SpringBoot2.x防止SQL注入、XSS攻击、CROS恶意访问

SQL注入:

把SQL命令插入到Web表单递交或输入域名或页面请求的查询字符串,最终达到欺骗服务器执行恶意的SQL命令

例如:http://localhost:8180/webapp2/testSql1?userName=1&passWord=1 or 1=1
解决方案:
1)无论是直接使用数据库还是使用如mybatis组件,使用sql的预编译,不要用拼接字符串
2)后台过滤检测:使用正则表达式过滤传入的参数**;**.字符串过滤
3)前端检测sql常见关键字,如or and drop之类的

XSS攻击:

其原理是攻击者向有XSS漏洞的网站中输入(传入)恶意的HTML代码,
当其它用户浏览该网站时,这段HTML代码会自动执行,从而达到攻击的目的
如:盗取用户Cookie、破坏页面结构、重定向到其它网站等

例如:http://localhost:8180/webapp2/testXss?userName=1&passWord=
解决方案:
1)对用户输入的表单数据进行校验

CSRF/CROS恶意访问:
简介:https://www.cnblogs.com/lailailai/p/4528092.html

CSRF - Cross-Site Request Forgery - 跨站请求伪造:
攻击可以在受害者毫不知情的情况下以受害者名义伪造请求发送给受攻击站点,从而在未授权的情况下执行在权限保护之下的操作
CORS - Cross Origin Resourse-Sharing - 跨站资源共享:
恶意访问内网敏感资源

解决方法:有效的解决办法是通过多种条件屏蔽掉非法的请求,例如HTTP头、参数等
1)不信任未经身份验证的跨域请求,应该首先验证Session ID或者Cookie
2)对于请求方来说验证接收的数据有效性,服务方仅暴露最少最必须的功能
3)通过多种条件屏蔽掉非法的请求,例如HTTP头、参数等

SpringBoot服务器端代码实现:
利用filter过滤器实现前端参数的过滤:
XssHttpServletRequestWrapper类:继承HttpServletRequestWrapper,重写部分获取参数的方法
代码如下:

/**
 * @Description 防止sql注入,xss攻击
 * @Date 2020/5/20 9:48
 */
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {

    private static Logger logger = LoggerFactory.getLogger(XssHttpServletRequestWrapper.class);
    private static String key = "and|exec|insert|select|delete|update|count|*|%|chr|mid|master|truncate|char|declare|;|or|-|+";
    private static Set<String> notAllowedKeyWords = new HashSet<String>(0);
    private static String replacedString = "INVALID";
    private final byte[] body; //用于保存读取body中数据
    private String currentUrl;

    static {
        String keyStr[] = key.split("\\|");
        for (String str : keyStr) {
            notAllowedKeyWords.add(str);
        }
    }

    public XssHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
        currentUrl = request.getRequestURI();
        body = StreamUtils.copyToByteArray(request.getInputStream());
    }

    /**
     * @Description 覆盖getParameter方法,将参数和参数值做xss过滤
     * @Date 2020/5/20 9:57
     */
    @Override
    public String getParameter(String name) {
        String value = super.getParameter(name);
        if(StringUtils.isEmpty(value)){
            return null;
        }
        return cleanXss(value);
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        Map<String,String[]> values = super.getParameterMap();
        if(null == values){
            return null;
        }
        Map<String,String[]> result = new HashMap<>();
        for (String key : values.keySet()) {
            String encodedKey = cleanXss(key);
            int count = values.get(key).length;
            String[] encodedValues = new String[count];
            for(int i = 0;i < count;i++){
                encodedValues[i] = cleanXss(values.get(key)[i]);
            }
            result.put(encodedKey,encodedValues);
        }
        return result;
    }

    @Override
    public String getHeader(String name) {
        String value = super.getHeader(name);
        if(StringUtils.isEmpty(value)){
            return null;
        }
        return cleanXss(value);
    }

    @Override
    public String[] getParameterValues(String name) {
        String[] values = super.getParameterValues(name);
        if(StringUtils.isEmpty(values)){
            return null;
        }
        int count = values.length;
        String[] encodedValues = new String[count];
        for (int i = 0;i < count;i++) {
            encodedValues[i] = cleanXss(values[i]);
        }
        return encodedValues;
    }
	
	@Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream bais = new ByteArrayInputStream(body);
        return new ServletInputStream() {

            @Override
            public int read() throws IOException {
                return bais.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener arg0) {

            }
        };
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }
    
    /**
     * @Description 解析参数
     * @Date 2020/5/20 10:01
     */
    private String cleanXss(String valueP){
        String value = valueP.replaceAll("<","<").replaceAll(">",">");
        value = value.replaceAll("<","& lt;").replaceAll(">","& gt;");
        value = value.replaceAll("\\(","& #40;").replaceAll("\\)","& #41;");
        value = value.replaceAll("'","& #39;");
        value = value.replaceAll("eval\\((.*)\\)","");
        value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']","\"\"");
        value = value.replaceAll("script","");
        value = cleanSqlKeyWords(value);
        return value;
    }

    /**
     * @Description 解析参数SQL关键字
     * @Date 2020/5/20 10:01
     */
    private String cleanSqlKeyWords(String value){
        String paramValue = value;
        for (String keyWord : notAllowedKeyWords) {
            if(paramValue.length() > keyWord.length() + 4
                    && (paramValue.contains(" " + keyWord)
                    || paramValue.contains(keyWord + " ")
                    || paramValue.contains(" " + keyWord + " "))){
                paramValue = StringUtils.replace(paramValue,keyWord,replacedString);
                logger.error( this.currentUrl + "已被过滤,因为参数中包含不允许sql的关键词(" + keyWord + ");参数:" + value + ";过滤后的参数:" + paramValue);
            }
        }
        return paramValue;
    }

	public boolean checkSqlKeyWords(String value){
        String paramValue = value;
        for (String keyword : notAllowedKeyWords) {
            if (paramValue.length() > keyword.length() + 4
                    && (paramValue.contains(" "+keyword)||paramValue.contains(keyword+" ")||paramValue.contains(" "+keyword+" "))) {
                logger.error(this.getRequestURI()+ "参数中包含不允许sql的关键词(" + keyword
                        + ")");
                return true;
            }
        }
        return false;
    }
}

可以看出,我们重写了getParameter、getParameterMap、getHeader、getParameterValues四个获取参数的方法,对几个方法进行了SQL检测、xss匹配等

CrosXssFilter类:实现Filter拦截器

 * @Description CrosXss拦截过滤
 * @Date 2020/5/20 9:33
 */
@WebFilter("/*")
@Component
public class CrosXssFilter implements Filter {

    private static Logger logger = LoggerFactory.getLogger(CrosXssFilter.class);

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //跨域设置
        if(response instanceof HttpServletResponse){
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            //通过在响应header中设置‘*’来允许来自所有域的跨域请求
            httpResponse.setHeader("Access-Control-Allow-Origin","*");
            //设置请求方式
            httpResponse.setHeader("Access-Control-Allow-Methods","*");
            httpResponse.setHeader("Access-Control-Max-Age", "86400");
            httpResponse.setHeader("Access-Control-Allow-Headers", "*");
        }
        //sql、xss过滤
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        logger.info("CrosXssFilter----->orignal url:{},ParameterMap:{}",httpRequest.getRequestURI(), JSONObject.toJSONString(httpRequest.getParameterMap()));
        XssHttpServletRequestWrapper xssHttpServletRequestWrapper = new XssHttpServletRequestWrapper(httpRequest);
        String param = getBodyString(xssHttpServletRequestWrapper.getReader());
        if(xssHttpServletRequestWrapper.checkSqlKeyWords(param)){
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.write("参数中不允许存在sql关键字");
            return;
        }
        chain.doFilter(xssHttpServletRequestWrapper,response);
        logger.info("CrosXssFilter..........doFilter url:{},ParameterMap:{}",xssHttpServletRequestWrapper.getRequestURI(), JSONObject.toJSONString(xssHttpServletRequestWrapper.getParameterMap()));
    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

    @Override
    public void destroy() {

    }
    
	public static String getBodyString(BufferedReader br) {
        String inputLine;
        String str = "";
        try {
            while ((inputLine = br.readLine()) != null) {
                str += inputLine;
            }
            br.close();
        } catch (IOException e) {
            logger.error("过滤参数异常:{}",e.getMessage());
        }
        return str;
    }
}

在这里我们设置了cros跨域访问

最后我们只需要在启动类上添加注解@ServletComponentScan,启动自动扫描装配即可完成

你可能感兴趣的:(SpringBoot)