提问人:ihsan karunia 提问时间:4/14/2023 最后编辑:James Zihsan karunia 更新时间:4/15/2023 访问量:424
如何防止该函数在 Golang 中遭到 SQL 注入攻击?
How do i prevent this function from SQL Injection attack in Golang?
问:
我是 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注入?
答:
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 安全性
评论