douliao7354 2019-01-09 20:25 采纳率: 0%
浏览 321
已采纳

如何防止PostgreSQL JSON / JSONB字段中的SQL注入?

How can I prevent SQL injection attacks in Go while using "database/sql"?

This solves the single value field problem because you can remove the quotes, but I can't do that filtering a JSON/JSONB field, like in the following because the $1 is considered a string:

`SELECT * FROM foo WHERE bar @> '{"baz": "$1"}'`

The following works but it's prone to SQL Injection:

`SELECT * FROM foo WHERE bar @> '{"baz": "` + "qux" + `"}'`

How do I solve this?


EDITED after @mkopriva's comment:

How would I build this json [{"foo": $1}] with the jsonb_* functions? Tried the below without success:

jsonb_build_array(0, jsonb_build_object('foo', $1::text))::jsonb

There's no sql error. The filter just doesn't work. There's a way that I can check the builded sql? I'm using the database/sql native lib.

  • 写回答

1条回答 默认 最新

  • duanhuang7591 2019-01-10 07:32
    关注

    Is this what you're looking for?

    type MyStruct struct {
        Baz string
    }
    
    func main() {
        db, err := sql.Open("postgres", "postgres://...")
        if err != nil {
            log.Panic(err)
        }
    
        s := MyStruct{
            Baz: "qux",
        }
    
        val, _ := json.Marshal(s)
        if err != nil {
            log.Panic(err)
        }
    
        if _, err := db.Exec("SELECT * FROM foo WHERE bar @> ?", val); err != nil {
            log.Panic(err)
        }
    }
    

    As a side note, Exec isn't for retrieval (although I kept it for you so the solution would match your example). Check out db.Query (Fantastic tutorial here: http://go-database-sql.org/retrieving.html)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么