SpringBoot如何避免SQL注入漏洞呢?

书欣 SpringBoot 发布时间:2022-08-06 21:49:10 阅读数:20274 1
下文笔者讲述SpringBoot避免SQL注入漏洞的方法分享,如下所示

SQL盲注,SQL注入简介

 SQL注入的风险:
     数据库中的数据被任意查看,修改,删除
 SQL注入的原因:
     未对用户输入进行正确的验证
 SQL注入如何避免
     对危险字符进行过滤或sql参数化

SQL注入避免示例

 添加SQL注入包装类 
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
/**
 * SQL注入包装类
 * 
 * @author java265
 *
 */
 
public class SqlInjectHttpServletRequestWrapper extends HttpServletRequestWrapper {
    public static final Logger log = LoggerFactory.getLogger(SqlInjectHttpServletRequestWrapper .class);
	/**
	 * 构造请求对象
	 * 
	 * @param request
	 */
	public SqlInjectHttpServletRequestWrapper(HttpServletRequest request) {
		super(request);
	}
 
	/**
	 * 获取头部参数
	 * 
	 * @param v 参数值
	 */
	@Override
	public String getHeader(String v) {
		String header = super.getHeader(v);
		if (header == null || "".equals(header)) {
			return header;
		}
		return sqlFilter(header);
	}
 
	/**
	 * 获取参数
	 * 
	 * @param v 参数值
	 */
	@Override
	public String getParameter(String v) {
		String param = super.getParameter(v);
		if (param == null || "".equals(param)) {
			return param;
		}
		return sqlFilter(param);
	}
 
	/**
	 * 获取参数值
	 * 
	 * @param v 参数值
	 */
	@Override
	public String[] getParameterValues(String v) {
		String[] values = super.getParameterValues(v);
		if (values == null) {
			return values;
		}
 
		int length = values.length;
		String[] resultValues = new String[length];
		for (int i = 0; i < length; i++) {
			// 过滤特殊字符
			resultValues[i] = sqlFilter(values[i]);
			if (!(resultValues[i]).equals(values[i])) {
				log.debug("SQL注入过滤器 => 过滤前:{} => 过滤后:{}", values[i], resultValues[i]);
			}
		}
		return resultValues;
	}
 
	/**
	 * 预编译SQL过滤正则表达式
	 */
	private Pattern sqlPattern = Pattern.compile(
			"(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|(\\b(select|update|and|or|delete|insert|trancate|char|into|substr|ascii|declare|exec|count|master|into|drop|execute)\\b)",
			Pattern.CASE_INSENSITIVE);
 
	/**
	 * SQL过滤
	 * 
	 * @param v 参数值
	 * @return
	 */
	private String sqlFilter(String v) {
		if (v != null) {
			String resultVal = v;
			Matcher matcher = sqlPattern.matcher(resultVal);
			if (matcher.find()) {
				resultVal = matcher.replaceAll("");
			}
			if (!resultVal.equals(v)) {
				return "";
			}
			return resultVal;
		}
		return null;
	}
}

3、配置文件添加配置
# sql 注入过滤url地址
security.sql.excludes=/images/*, /jquery/*, /layui/*

4、添加SQL注入过滤器
import java.io.IOException;
import java.util.list;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
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.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Value;
 
/**
 * SQL注入过滤器
 * 
 * @author java265
 *
 */
@Component
@WebFilter(filterName = "SqlInjectFilter", urlPatterns = "/*")
public class SqlInjectFilter implements Filter {
 
	/**
	 * 过滤器配置对象
	 */
	FilterConfig filterConfig = null;
 
	/**
	 * 是否启用(默认启用)
	 */
	private boolean enable = true;
 
 
	/**
	 * 忽略的URL
	 */
    @Value("${security.sql.excludes}")
	private String excludes;
 
 
	/**
	 * 初始化
	 */
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
	}
 
	/**
	 * 拦截
	 */
	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
 
		// 不启用或者已忽略的URL不拦截
		if (!enable || isExcludeUrl(request.getServletPath())) {
			filterChain.doFilter(servletRequest, servletResponse);
			return;
		}
		SqlInjectHttpServletRequestWrapper sqlInjectHttpServletRequestWrapper = new SqlInjectHttpServletRequestWrapper(
				request);
		filterChain.doFilter(sqlInjectHttpServletRequestWrapper, servletResponse);
	}
 
	/**
	 * 销毁
	 */
	@Override
	public void destroy() {
		this.filterConfig = null;
	}
 
	/**
	 * 判断是否为忽略的URL
	 * 
	 * @param urlPath URL路径
	 * @return true-忽略,false-过滤
	 */
	private boolean isExcludeUrl(String url) {
		if (excludes == null || excludes.isEmpty()) {
			return false;
		}
        List<String> urls = Arrays.asList(excludes.split(","));
		return urls .stream().map(pattern -> Pattern.compile("^" + pattern)).map(p -> p.matcher(url))
				.anyMatch(Matcher::find);
	}
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaFramework/SpringBoot/202208/4166.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者