如何防止该函数在 Golang 中遭到 SQL 注入攻击?

How do i prevent this function from SQL Injection attack in Golang?

提问人:ihsan karunia 提问时间:4/14/2023 最后编辑:James Zihsan karunia 更新时间:4/15/2023 访问量:424

问:

我是 Golang 的新手。当我为显示详细数据产品编写函数此代码时,我遇到了问题。此代码容易受到 SQL 注入的攻击。我使用框架 Gin,Gorm

func Show(c *gin.Context) {
    var product models.Product
    id := c.Param("id")

    if err := models.DB.First(&product, id).Error; err != nil {
        switch err {
        case gorm.ErrRecordNotFound:
            c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"message": "Data not found"})
            return
        default:
            c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"message": err.Error()})
            return
        }
    }

    c.JSON(http.StatusOK, gin.H{"status": 200, "data": product})

}

如何防止此参数 ID 受到 SQL 注入攻击?或者我怎样才能只在参数中验证以防止SQL注入?

MySQL Go SQL注入

评论

2赞 Burak Serdar 4/14/2023
正如所写,此代码不容易受到攻击
0赞 Someone Special 4/14/2023
go.dev/doc/database/sql-injection
0赞 Mike 'Pomax' Kamermans 4/14/2023
不要发布文字图片。在您的帖子中包含文本,并具有适当的缩进和降价。
0赞 ihsan karunia 4/14/2023
但是当我给出单引号 (') 并尝试运行 SQLmap 以测试端点 localhost/api/products/id<inject point> 的 SQL 注入攻击时。这个代码仍然容易受到攻击,有什么建议吗?
0赞 Someone Special 4/14/2023
我认为您想要的只是检查 id 是否是一个数字 - stackoverflow.com/a/22593449/2822041

答:

0赞 riyas 4/15/2023 #1

这是带有内联条件的 gorm 查询,它容易发生 sql 注入。 根据 gorm 文档 - 使用主键检索对象

Objects can be retrieved using primary key by using Inline Conditions if the primary key is a number

假设攻击者使用以下输入

id := "1=1;drop table products;"

查询将翻译如下

db.First(&product, id)
SELECT * FROM products WHERE 1=1;drop table products;

这可以通过代码中的类型检查来简单地防止

input,err := strconv.Atoi(id)

if err != nil {
    return error
}

db.First(&user, input)

请关注 gorm 的参考资料以获取更多信息 gorm 安全性