Java防SQL注入,最簡單的辦法是杜絕SQL拼接,SQL注入攻擊能得逞是因為在原有SQL語句中加入了新的邏輯,如果使用PreparedStatement來代替Statement來執行SQL語句,其後只是輸入參數,SQL注入攻擊手段將無效,這是因為PreparedStatement不允許在不同的插入時間改變查詢的邏輯結構,大部分的SQL注入已經擋住了,在WEB層我們可以過濾用戶的輸入來防止SQL注入比如用Filter來過濾全局的表單參數。
- import Java.io.IOException;
- import Java.util.Iterator;
- import Javax.servlet.Filter;
- import Javax.servlet.FilterChain;
- import Javax.servlet.FilterConfig;
- import Javax.servlet.ServletException;
- import Javax.servlet.ServletRequest;
- import Javax.servlet.ServletResponse;
- import Javax.servlet.http.HttpServletRequest;
- import Javax.servlet.http.HttpServletResponse;
- /**
- * 通過Filter過濾器來防SQL注入攻擊
- *
- */
- public class SQLFilter implements Filter {
- private String inj_str = "'|and|exec|insert|select|delete|update|count|*|%|chr|mid|master|truncate|char|declare|; |or|-|+|,";
- protected FilterConfig filterConfig = null;
- /**
- * Should a character encoding specified by the clIEnt be ignored?
- */
- protected boolean ignore = true;
- public void init(FilterConfig config) throws ServletException {
- this.filterConfig = config;
- this.inj_str = filterConfig.getInitParameter("keyWords");
- }
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
- HttpServletRequest req = (HttpServletRequest)request;
- HttpServletResponse res = (HttpServletResponse)response;
- Iterator values = req.getParameterMap().values().iterator();//獲取所有的表單參數
- while(values.hasNext()){
- String[] value = (String[])values.next();
- for(int i = 0;i < value.length;i++){
- if(sql_inj(value[i])){
- //TODO這裡發現sql注入代碼的業務邏輯代碼
- return;
- }
- }
- }
- chain.doFilter(request, response);
- }
- public boolean sql_inj(String str)
- {
- String[] inj_stra=inj_str.split("\\|");
- for (int i=0 ; i < inj_stra.length ; i++ )
- {
- if (str.indexOf(" "+inj_stra[i]+" ")>=0)
- {
- return true;
- }
- }
- return false;
- }
- }
也可以單獨在需要防范SQL注入的JavaBean的字段上過濾:
- /**
- * 防止sql注入
- *
- * @param sql
- * @return
- */
- public static String TransactSQLInjection(String sql) {
- return sql.replaceAll(".*([';]+|(--)+).*", " ");