Hibernate:当集合元素需要使用 `like` 运算符检查时,如何防止 SQL 注入?

Hibernate : How to prevent SQL injection when the collection elements needs to check with `like` operator?

我有一个 query 类似的东西。

StringBuilder sbQry = new StringBuilder();
sbQry.append("select * from tableName where 1=1");
if(!myCollection.isEmpty()){
    sbQry.append("  and (");
        for (int i = 0; i < myCollection.size(); i++) {
            final String module = myCollection.get(i);
            sbQry.append("column = '" + module
                    + "' or column like 'J_'||'"
                    + module.replaceAll("-", "%") + "'");
            if (!(i == (myCollection.size() - 1))) {
                sbQry.append(" or ");
            }
        }
        sbQry.append(") ");
 }

此处此查询 sbQry 容易受到 SQLInjection 的攻击,因为 myCollection 来自外部来源。

如果我的集合元素将基于 = 运算符进行比较,那么我使用准备好的语句,例如:

sbQry.append(column in (:collection));
Query query = session.createSQLQuery(sbQry.toString());
query.setParameterList("collection",myCollection);

任何人都可以建议我在这种情况下如何防止 SQL 注入。

任何帮助将不胜感激。

为了防止 SQL 注入,您应该使用绑定参数,而不是字符串插值。

StringBuilder sbQry = new StringBuilder();
List<String> params = new ArrayList<>();
sbQry.append("select * from tableName");
if(!myCollection.isEmpty()){
    sbQry.append(" where ");
    int size = myCollection.size;
    List<String> terms = new ArrayList<>();
    for (int i = 0; i < size; i++) {
        final String module = myCollection.get(i);
        terms.add("column = ? or column like ?");
        params.add(module);
        params.add("J_" + module.replaceAll("-", "%"));
    }
    sbQry.append(String.join(" or ", terms));
}

Query q = sess.createQuery(sbQry);
int size = params.size();
for (int i = 0; i < size; i++) {
    q.setString(i, params[i]);
}

我没有测试上面的代码,但它应该给了你大概的想法。

使用绑定参数而不是字符串连接是防止 SQL 注入的安全方法,它还使代码更易于编写和阅读。

还使用 ArrayList 作为术语,String.join() 意味着您不必为术语系列的开始或结束使用 1=1 或特殊条件代码。