前言
在项目中,很多时候如使用MyBatis等我们用sql拼接或者直接使用sql语句操作数据库时,就有可能遇到sql盲注的问题
例如,如果我们的sql语句为select * from menu where name= #{name,jdbc=varchar}
此时,如果我们传过来的name参数为‘’ or 1=1
,此时就可以无视条件查询所有的menu
通过在参数中插入非法的字符实现对数据库表和条目进行非法的查看、修改或删除操作,这就是SQL盲注
解决办法
我们可以通过Filter来过滤非法的参数,从而实现阻止SQL盲注,代码如下
@WebFilter("/*")
public class sqlFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse resp = (HttpServletResponse)response;
PrintWriter writer = null;
Enumeration params = req.getParameterNames();
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];
}
}
if(sqlValidate(sql)) {
System.out.println("发现sql注入");
response.setCharacterEncoding("GBK");
writer = response.getWriter();
writer.print("发现sql注入");
return;
}
chain.doFilter(req,resp);
}
private boolean sqlValidate(String str) {
str = str.toLowerCase();// 统一转为小写
String badStr = "'|exec|execute|insert|select|delete|update|drop|%|master|truncate|"
+ "declare|sitename|net user|xp_cmdshell|like'|exec|execute|insert|create|drop|"
+ "table|grant|use|group_concat|column_name|information_schema.columns|table_schema|"
+ "select|delete|update|master|truncate|declare|-- |like|//|%";// 过滤掉的sql关键字,可以手动添加
String[] badStrs = badStr.split("\\|");
for (int i = 0; i < badStrs.length; i++) {
if (str.indexOf(badStrs[i]) >= 0) {
return true;
}
}
return false;
}
@Override
public void destroy() {
}
}