本文只指针编码层次的SQL注入漏洞解决方法,例子代码是以java为主。
1,参数化的预编译查询语句
不安全例子
String query = "SELECT account_balance FROM user_data WHERE user_name = " + request.getParameter("customerName"); try { Statement statement = connection.createStatement( … ); ResultSet results = statement.executeQuery( query ); }
防止通过参数传不安全值,必须使用参数化的预编译查询语句
String custname = request.getParameter("customerName"); // This should REALLY be validated too // perform input validation to detect attacks String query = "SELECT account_balance FROM user_data WHERE user_name = ? "; PreparedStatement pstmt = connection.prepareStatement( query ); pstmt.setString( 1, custname); ResultSet results = pstmt.executeQuery( );
2,输入参数白名单
不建议将SQL语句关键部分作参数传递,如表名、字段名或排序符(ASC、DESC)等。建议设计通过标识来判断,如以下例子
String tableName; switch(PARAM): case "Value1": tableName = "fooTable"; break; case "Value2": tableName = "barTable"; break; ... default : throw new InputValidationException("unexpected value provided for table name");
public String someMethod(boolean sortOrder) { String SQLquery = "some SQL ... order by Salary " + (sortOrder ? "ASC" : "DESC"); ...
时间: 2024-10-07 21:57:45