【问题标题】:How do make safe query builder and prevent sql injection如何制作安全的查询构建器并防止 sql 注入
【发布时间】:2021-11-29 22:35:33
【问题描述】:

这是我的代码:

type mysqlRepository struct {
    Conn *sql.DB
}

func (dbconn *mysqlRepository) GetAll(param map[string]string) (response []models.Subject, err error) {
    var result models.Subject

    c := 0
    q := `
        SELECT id, name, teacher, uuid
        FROM subject
    `

    for i, x := range param {
        if x != "" {
            if c > 0 {
                q += ` AND ` + i + ` = ` + x
            } else {
                q += ` WHERE ` + i + ` = ` + x
            }
            c++
        }
    }

    query, err := dbconn.Conn.Query(q)

    if err != nil {
        utils.QueryErrorException(err)
        return
    }

    defer query.Close()

    for query.Next() {
        errorScanningDataHistory := query.Scan(
            &result.ID,
            &result.Name,
            &result.Teacher,
            &result.UUID,
        )

        utils.QueryErrorException(errorScanningDataHistory)

        response = append(response, result)
    }

    return
}

我尝试像这样使用邮递员并运行良好:http://localhost/public/api/v1/subject?name=robert。它只显示以罗伯特为老师的科目

但是,如果我注入 sql 命令,它也可以工作:http://localhost/public/api/v1/subject?name=robert OR 1=1。但是,它返回所有数据。

我怎样才能更安全?

【问题讨论】:

  • 通过已知/允许列的映射过滤i。不要连接 x,而是使用占位符 ? 并将 x 附加到然后传递给查询的参数片段。
  • Sql 注入是由于您如何处理用户提供给您的输入数据而发生的。避免这种情况的最好方法是限制输入数据类型和用户想要的内容。因此,您不应允许用户输入整数或 1=1 类型的“名称”

标签: mysql database go


【解决方案1】:

@mkopriva 评论的实现

通过已知/允许列的映射过滤 i。代替 连接 x 使用占位符 ?并将 x 附加到切片 然后传递给查询的参数

    safeFields := map[string]bool{"name": true}
    args := []interface{}{}
    where := "WHERE 1"
    for i, x := range param {
        if _, ok := safeFields[i]; ok && x != "" {
            where += fmt.Sprintf(" AND %s=?", i)
            args = append(args, x)
        }
    }

    query, err := dbconn.Conn.Query(q+where, args...)

【讨论】:

    猜你喜欢
    • 2021-04-08
    • 1970-01-01
    • 1970-01-01
    • 2020-09-16
    • 1970-01-01
    • 2015-04-25
    • 2017-07-24
    • 1970-01-01
    • 2020-05-01
    相关资源
    最近更新 更多