標籤:next int cas 說明 err 實戰 服務 res exce
原文出自:https://blog.csdn.net/seesun2012
前言
淺談SQL注入:
所謂SQL注入,就是通過把SQL命令插入到Web表單提交或輸入欄位名或頁面請求的查詢字串,最終達到欺騙伺服器執行惡意的SQL命令,達到一定的非法用途。
解決辦法
1、配置WEB-INF/web.xml
<web-app> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> <!-- 防SQL注入過濾 --> <filter> <filter-name>SqlInjectFilter</filter-name> <filter-class>com.seesun2012.web.core.filter.SqlInjectFilter</filter-class> <!-- 過濾前台傳入的參數,可手動添加或刪減,以“|”分割 --> <init-param> <param-name>sqlInjectStrList</param-name> <param-value>‘|or|and|;|-|--|+|,|like|//|/|*|%|#</param-value> </init-param> </filter> <filter-mapping> <filter-name>SqlInjectFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
2、過濾器SqlInjectFilter.java類
package com.seesun2012.web.core.filter;import java.io.IOException;import java.util.Enumeration;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;/** * SQL注入過濾器 * @author CSDN:seesun2012 * @version 0.0.1-SNAPSHOT * @Date 2018-01-14 */public class SqlInjectFilter implements Filter{ public FilterConfig config; @Override public void destroy() { this.config = null; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httprequest = (HttpServletRequest) request; // 獲得所有請求參數名 Enumeration<?> params = httprequest.getParameterNames(); String sql = ""; while (params.hasMoreElements()) { // 得到參數名 String name = params.nextElement().toString(); // 得到參數對應值 String[] value = httprequest.getParameterValues(name); for (int i = 0; i < value.length; i++) { sql = sql + value[i]; } } // 過濾掉的SQL關鍵字,可以手動添加 String sqlInjectStrList = config.getInitParameter("sqlInjectStrList"); if (sqlValidate(sql, sqlInjectStrList)) { throw new IOException("請輸入有效字元"); // 重新導向或跳轉,略... } else { chain.doFilter(request, response); } } // 校正SQL protected static boolean sqlValidate(String str, String sqlInjectStrList) { // 統一轉為小寫 str = str.toLowerCase(); // 轉換為數組 String[] badStrs = sqlInjectStrList.split("\\|"); for (int i = 0; i < badStrs.length; i++) { // 檢索 if (str.indexOf(badStrs[i]) >= 0) { return true; } } return false; } @Override public void init(FilterConfig filterConfig) throws ServletException { config = filterConfig; }}
備忘
- 相關說明文檔:SQL注入(百度知道)
- 相關測試案例:SQL注入實戰(僅供測試學習)
- 本文僅供Java相關學習交流與Web防禦,如果用於非法攻擊或非法操作以及商業攻擊,後果自負!
Java 防SQL注入過濾器(攔截器)代碼