问题背景:
生产有个老项目使用的是jsp+servlet写的,对安全方面几乎没有,对执行的sql使用的是
Statement.executeUpdate(sql),没有使用PreparedStatement.executeUpdate(sql)
容易造成恶意攻击
解决思想:
1)配置全局过滤器,通过关键字匹配来拦截恶意请求
2)写sql的时候用PreparedStatement
本次使用的是配置全局过滤器
1.在web.xml中加入以下配置
<!-- 防止SQL注入的过滤器 -->
<filter>
<filter-name>SqlInjectionFilter</filter-name>
<filter-class>org.oct.attachment.secure.SqlInjectFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SqlInjectionFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2.创建全局过滤器
package org.oct.attachment.secure;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.util.Enumeration;
/**
* @author xiaoss
* @since 1.0, 2022年08月22日 12:06:13
*/
public class SqlInjectFilter implements Filter {
// Logger logger= LoggerFactory.getLogger(SqlInjectFilter.class);
private static final Logger logger = Logger.getLogger(SqlInjectFilter.class);
private static final String SQL_REGX = ".*(\\b(select|update|and|or|delete|insert|trancate|char|into|substr|ascii|declare|exec|count|master|drop|execute)\\b).*";
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
logger.error("进入全局过滤器==================================");
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
//获得所有请求参数名
Enumeration params = req.getParameterNames();
logger.error("url=================================="+req.getRequestURI()+ req.getQueryString());
String sql = "";
while (params.hasMoreElements()) {
//得到参数名
String name = params.nextElement().toString();
//得到参数对应值
String[] value = req.getParameterValues(name);
for (int i = 0; i < value.length; i++) {
sql = sql + value[i];
}
}
//有sql关键字,跳转到error.html
if (sqlValidate(sql)) {
logger.error("您发送请求中的参数中含有非法字符"+sql);
//throw new IOException("您发送请求中的参数中含有非法字符");
} else {
logger.error("执行完全局过滤器"+sql);
chain.doFilter(req, res);
}
}
//效验
protected static boolean sqlValidate(String str) {
str = str.toLowerCase();//统一转为小写
if(str.matches(SQL_REGX)){
return true;
}
return false;
}
public void init(FilterConfig filterConfig) throws ServletException {
}
public void destroy() {
}
}
测试:
浏览器上直接访问项目
http://localhost:8080/oct_attachment_war/DeleteServlet?id=-1%20SELECT%202+983-983-1=0+0+0+1--