java - 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.
解决方案
漏洞报告似乎在抱怨用户指定的value
参数包含%
或_
字符的可能性,这将被LIKE
操作员解释为通配符而不是文字。如果这不是故意的,那么它可能确实为恶意用户提供了造成伤害的机会,或者至少可以提取您不打算让他们获取的数据,但这不是传统意义上的代码注入。(强制性 XKCD:https ://xkcd.com/327/ )
如果您必须从用户输入中形成表达式的右手运算符LIKE
(请考虑您是否真的需要),并且您不打算允许用户在该输入中使用%
or通配符作为通配符,那么您有一些备择方案。其中包括:_
在服务器端验证参数以确保它不包含任何
%
或_
字符,如果包含则拒绝它。理想情况下,也执行客户端验证。根据您使用的 DBMS 的适当语法,修改参数以转义出现的任何
value
或%
字符。_
这很讨厌,因为它引入了 DBMS 依赖性,并且依赖于驱动程序和数据库不够聪明,无法识别您在做什么(以免它逃脱转义)。这是使用准备好的语句通常可以避免的那种混乱。确保应用程序可以安全地容纳提供包含通配符的值的用户,用作通配符,并告诉您的漏洞扫描程序填充它。
推荐阅读
- sql - 获取所有购买的订单以及 SQL 中的一组特定商品
- c# - 现有 asp.net mvc 应用程序中的 ADFS 实现
- java - Jackson JSONSerializer:在另一个上下文中写入值(从根)
- javascript - 具有选定下拉值的 jQuery 克隆表行
- python - 我想用 pyqt5 为按钮创建彩色动画
- gradle - 如何为 Gradle 依赖项 {} 块编写扩展方法
- angular - 如果我输入一个数字,我正在使用 ngx-bootstrap datepicker,它会自动格式化
- angular - (Angular 6) Angular Universal - 不等待内容 API 调用
- reactjs - 我应该在带有 SSL 的 Nginx 服务器上为 React 应用程序启用 Gzip 吗?
- python - Python pandas中列值(字符串)的反向连接