[英]Prevent SQL injection from form-generated SQL - NO PreparedStmts
我有一個搜索表,用戶可以使用類型的過濾器過濾結果:
因此,用戶將能夠設置任意一組過濾器,這將基本上產生一個完全動態的WHERE子句。 將來我還需要實現更復雜的邏輯表達式,比如
Where(name = John OR name = Nick)AND(surname = Blake OR surname = Bourne),
在用戶可能過濾或不過濾的所有10個字段中,我不知道用戶將設置多少和哪些過濾器。 所以,我不能使用預准備語句(假設至少我們知道WHERE子句中的字段)。 這就是為什么准備好的語句不可避免的原因,我必須使用普通的舊生成的SQL來完成。
我可以采取哪些措施來保護應用程序免受SQL注入(REGEX方式或任何其他方式)?
Java,未經測試。
List<String> clauses = new ArrayList<String>();
List<String> binds = new ArrayList<String>();
if (request.name != null) {
binds.add(request.name);
clauses.add("NAME = ?");
}
if (request.city != null) {
binds.add(request.city);
clauses.add("CITY = ?");
}
...
String whereClause = "";
for(String clause : clauses) {
if (whereClause.length() > 0) {
whereClause = whereClause + " AND ";
}
whereClause = whereClause + clause;
}
String sql = "SELECT * FROM table WHERE " + whereClause;
PreparedStatement ps = con.prepareStatment(sql);
int col = 1;
for(String bind : binds) {
ps.setString(col++, bind);
}
ResultSet rs = ps.executeQuery();
如果向預准備語句添加參數,它們將自動轉義。
conn = pool.getConnection( );
String selectStatement = "SELECT * FROM User WHERE userId = ? ";
PreparedStatement prepStmt = con.prepareStatement(selectStatement);
prepStmt.setString(1, userId);
ResultSet rs = prepStmt.executeQuery();
動態構建where子句,但使用參數名稱來執行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.