首页 > 解决方案 > Request Parameter is causing SQL Injection with the preparedstatement

问题描述

I am seeing a a SQL injection

SELECT count(id) FROM user  WHERE code= 67 AND user.postal_code like  UPPER('%AL%')

I am setting this as a

 private int loaddGrantees(Long code, String value)
    {
     DBConnectionManager dBConnectionManager = null;
     Connection conn = null;
     PreparedStatement pstmt = null;
     ResultSet rs = null;
     dBConnectionManager = new DBConnectionManager();
     conn = dBConnectionManager.getConnectionObject(XXX,XXX);
     string sql =  SELECT count(id) FROM user  WHERE code= ? AND user.postal_code LIKE UPPER(?);
      pstmt = conn.prepareStatement(sql);
      pstmt.setLong(1, code);
      pstmt.setString(2, "%" +value+ "%");
       rs = pstmt.executeQuery();
            while (rs.next()) {
                 number = rs.getInt(1);
             }
     return number;
}

From HTTPRequest I see the value is getting from the String value= request.getParameter("Val");

Can I know how to avoid sql injection here for postal_code, I see code parameter is not being retrieved from httpRequest

> Vulnerability says:
> 
> /XX/XX/XXX/XX/XX/6769/XX/AL/XX page of the application has been found
> to be vulnerable to a SQL Injection attack in the path parameter
> :value.
> 
> The source code that uses this path parameter in the page is:
> 
> loadGrantees(Person.java:5036)
> org.apache.tomcat.dbcp.dbcp2.DelegatingPreparedStatement.executeQuery();
> 
>     ...   }   ... }
> 
> This code has generated the following query in order to interact with
> the database, using the path parameter value: Note: AL represents the
> value which I am passing in the preparedstatement
> 
> SELECT count(id) FROM user  WHERE code= ? AND user.postal_code LIKE
> UPPER(?); The path parameter searchString in the URL
> /XX/XX/XXX/XX/XX/6769/XX/AL/XX can be modified to contain SQL syntax
> hence changing the query structure, causing unexpected application
> behavior which could lead to information theft, privileges escalation
> and unauthorized actions performed by the attacker.

       

标签: javasqlspringprepared-statementsql-injection

解决方案


漏洞报告似乎在抱怨用户指定的value参数包含%_字符的可能性,这将被LIKE操作员解释为通配符而不是文字。如果这不是故意的,那么它可能确实为恶意用户提供了造成伤害的机会,或者至少可以提取您不打算让他们获取的数据,但这不是传统意义上的代码注入。(强制性 XKCD:https ://xkcd.com/327/ )

如果您必须从用户输入中形成表达式的右手运算符LIKE(请考虑您是否真的需要),并且您不打算允许用户在该输入中使用%or通配符作为通配符,那么您有一些备择方案。其中包括:_

  1. 在服务器端验证参数以确保它不包含任何%_字符,如果包含则拒绝它。理想情况下,也执行客户端验证。

  2. 根据您使用的 DBMS 的适当语法,修改参数以转义出现的任何value%字符。_这很讨厌,因为它引入了 DBMS 依赖性,并且依赖于驱动程序和数据库不够聪明,无法识别您在做什么(以免它逃脱转义)。这是使用准备好的语句通常可以避免的那种混乱。

  3. 确保应用程序可以安全地容纳提供包含通配符的值的用户,用作通配符,并告诉您的漏洞扫描程序填充它。


推荐阅读