SpringMVC处理脚本,SQL注入问题

SpringMVC处理脚本,SQL注入问题(写的不好勿喷,互相学习)

使用 Filter 来过滤浏览器发出的请求,对每个URI参数请求过滤些关键字,替换成安全的字符。所有请求的 getParameter 会被替换,如果参数里面含有敏感词会被替换掉。

 

对于类似:>"<script>alert('XSS');</script>

一、过滤些敏感的脚本

 

1、编写XssHttpServletRequestWrapper

import javax. servlet. http. HttpServletRequest;
import javax. servlet. http. HttpServletRequestWrapper;

public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
    public XssHttpServletRequestWrapper (HttpServletRequest servletRequest) {
        super(servletRequest);
    }
    public String [] getParameterValues (String parameter) {
        String [] values = super. getParameterValues(parameter);
        if (values == null) {
            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;
    }
    public String getParameter (String parameter) {
        String value = super. getParameter(parameter);
        if (value == null) {
            return null;
        }
        return cleanXSS(value);
    }
    public String getHeader (String name) {
        String value = super. getHeader(name);
        if (value == null)
            return null;
        return cleanXSS(value);
    }
    private String cleanXSS (String value) {
    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", "");
        return value;
    

2添加一个过滤器 XssFilter

import java.io.IOException;

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;

publicclass XSSFilter implements Filter {

    FilterConfig filterConfig = null;

    publicvoid init (FilterConfig filterConfig) throws ServletException {

        this. filterConfig = filterConfig;

    }

    publicvoid destroys () {

        this. filterConfig = null;

    }

    publicvoid doFilter (ServletRequest request, ServletResponse response, FilterChain chain)

             throws IOException, ServletException {

        chain. doFilter (new XssHttpServletRequestWrapper((HttpServletRequest) request), response);

    }

}

3web中配置

<filter>

    <filter-name>XssSqlFilter</filter-name>

    <filter-class>com. Controller.XSSFilter</filter-class>

</filter>

<filter-mapping>

    <filter-name>XssSqlFilter</filter-name>

    <url-pattern>/*</url-pattern>

    <dispatcher>REQUEST</dispatcher>

</filter-mapping>

4基于springMVC的配置使用

编写SqlInjectInterceptor

import org.springframework.web. servlet.HandlerInterceptor;

import org.springframework.web. servlet.ModelAndView;

import javax. servlet. http. HttpServletRequest;

import javax. servlet. http. HttpServletResponse;

import java. util. Enumeration;

/** * 防止SQL注入的拦截器  */

publicclass SqlInjectInterceptor implements HandlerInterceptor {

    publicboolean preHandle(HttpServletRequest request,HttpServletResponse response, Object o) throws Exception {

        Enumeration names = request.getParameterNames ();

        while (names. hasMoreElements()) {

             String name = (String) names.nextElement();

             String[] values = request.getParameterValues(name);

             for (String value: values) {

                 value = clearXss(value);

             }

        }

        returntrue;

    }

    publicvoid postHandle(HttpServletRequest request,HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {

 

   }

    publicvoidafterCompletion(HttpServletRequest request,HttpServletResponse response, Object o, Exception e)

             throws Exception {

    }

    /** * 处理字符转义 * * @param value * @return */

    private String clearXss (String value) {

        if (value == null || "".equals(value)) {

             returnvalue;

        }

        System.err.println("=========>:处理字符转义");

        value = value. replaceAll ("<", "<"). replaceAll (">", ">");

        value = value.replaceAll("\\(", "(").replace("\\)", ")");

        value = value. replaceAll ("'", "'");

        value = value.replaceAll("eval\\((.*)\\)", "");

        value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");

        value = value.replace("script", "");

        returnvalue;

    }

}

二、对含有敏感的脚本,直接处理掉。

1编写SX_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;

import javax. servlet. http. HttpServletResponse;

publicclass SX_Filterimplements Filter {

    private FilterConfig config;

    privatestatic String errorPath;// 出错跳转的目的地

    privatestatic String[] excludePaths;// 不进行拦截的url

    privatestatic String [] safeless = { // 需要拦截的字符关键字、url编码

             "<script",

             "</script",

             "<iframe",

             "</iframe",

             "<frame",

             "</frame",

             "set-cookie",

             "%3cscript",

             "%3c/script",

             "%3ciframe",

             "%3c/iframe",

             "%3cframe",

             "%3c/frame",

             "src=\"javascript:",

             "<body",

        "</body",

             "%3cbody",

             "%3c/body",

             "<", ">","</","/>","%3c","%3e","%3c/","/%3e"};

publicvoid doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain)

             throws IOException, ServletException {

        Enumeration params = req. getParameterNames ();

        HttpServletRequest request = (HttpServletRequest) req;

        HttpServletResponse response = (HttpServletResponse)resp;

        booleanisSafe = true;

        String requestUrl = request. getRequestURI ();

        if (isSafe(requestUrl)) {

             requestUrl = requestUrl.substring(requestUrl.indexOf("/"));

             if (! excludeUrl(requestUrl)) {

                 while (params. hasMoreElements ()) {

                 String cache = req.getParameter((String) params.nextElement());

                     if (null != cache && cache.length() > 0) {

                         if (!isSafe(cache)) {

                             isSafe = false;

                             break;

                         }

                     }

                 }

             }

        }else{

             isSafe = false;

        }

        if (! isSafe) {

             request.setAttribute("error", "您输入的参数有非法字符!");

             response. sendRedirect ("http://... ");

             return;

        }

        filterChain.doFilter(req, resp);

    }

    privatestaticboolean isSafe (String str) {

        if (null! = str && str. length () > 0) {

             for (String s: safeless) {

                 if (str. toLowerCase ().contains(s)) {

                     returnfalse;

                 }

             }

        }

        returntrue;

    }

    privateboolean excludeUrl (String url) {

        if (excludePaths != null && excludePaths.length > 0) {

             for (String path : excludePaths) {

                 if (url. toLowerCase (). equals(path)) {

                     returntrue;

                 }

             }

        }

        returnfalse;

    }

    publicvoid destroy() {

    }

    publicvoid init(FilterConfig config) throws ServletException {

        this.config = config;

        errorPath = config. getInitParameter("errorPath");

        String excludePath = config.getInitParameter("excludePaths");

        if (null != excludePath && excludePath.length() > 0) {

             excludePaths = excludePath.split(",");

        }

    }

}

2web中配置

<filter>

    <filter-name>XssSqlFilter</filter-name>

    <filter-class>com. Controller. SX_Filter </filter-class>

</filter>

<filter-mapping>

    <filter-name>XssSqlFilter</filter-name>

    <url-pattern>/*</url-pattern>

    <dispatcher>REQUEST</dispatcher>

</filter-mapping>

 

Spring MVC处理脚本和SQL注入

使用 Filter 来过滤浏览器发出的请求,对每个URI参数请求过滤些关键字,替换成安全的字符。所有请求的 getParameter 会被替换,如果参数里面含有敏感词会被替换掉。

对于类似:>"<script>alert('XSS');</script>

一、过滤些敏感的脚本

1、编写XssHttpServletRequestWrapper

import javax. servlet. http. HttpServletRequest;

import javax. servlet. http. HttpServletRequestWrapper;

 

publicclassXssHttpServletRequestWrapper extendsHttpServletRequestWrapper{

    public XssHttpServletRequestWrapper (HttpServletRequest servletRequest) {

        super(servletRequest);

    }

    public String [] getParameterValues (String parameter) {

        String [] values = super. getParameterValues(parameter);

        if (values == null) {

             returnnull;

        }

        intcount = values. length;

        String [] encodedValues = new String[count];

        for (inti = 0; i < count; i++) {

             encodedValues[i] = cleanXSS(values[i]);

        }

        returnencodedValues;

    }

    public String getParameter (String parameter) {

        String value = super. getParameter(parameter);

        if (value == null) {

             returnnull;

        }

        return cleanXSS(value);

    }

    public String getHeader (String name) {

        String value = super. getHeader(name);

        if (value == null)

             returnnull;

        return cleanXSS(value);

    }

    private String cleanXSS (String value) {

    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", "");

        returnvalue;

    }

}

2添加一个过滤器 XssFilter

import java.io. IOException;

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;

 

publicclass XSSFilter implements Filter {

    FilterConfig filterConfig = null;

    publicvoid init (FilterConfig filterConfig) throws ServletException {

        this. filterConfig = filterConfig;

    }

    publicvoid destroys () {

        this. filterConfig = null;

    }

    publicvoid doFilter (ServletRequest request, ServletResponse response, FilterChain chain)

             throws IOException, ServletException {

        chain. doFilter (new XssHttpServletRequestWrapper((HttpServletRequest) request), response);

    }

}

3web中配置

<filter>

    <filter-name>XssSqlFilter</filter-name>

    <filter-class>com. Controller.XSSFilter</filter-class>

</filter>

<filter-mapping>

    <filter-name>XssSqlFilter</filter-name>

    <url-pattern>/*</url-pattern>

    <dispatcher>REQUEST</dispatcher>

</filter-mapping>

 

 

4基于springMVC的配置使用

编写SqlInjectInterceptor

import org.springframework.web. servlet. HandlerInterceptor;

import org.springframework.web. servlet. ModelAndView;

import javax. servlet. http. HttpServletRequest;

import javax. servlet. http. HttpServletResponse;

import java. util. Enumeration;

 

/** * 防止SQL注入的拦截器  */

publicclass SqlInjectInterceptor implements HandlerInterceptor {

    publicboolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        Enumeration names = request. getParameterNames ();

        while (names. hasMoreElements ()) {

             String name = (String) names.nextElement();

             String[] values = request.getParameterValues(name);

             for (String value: values) {

                 value = clearXss(value);

             }

        }

        returntrue;

    }

    publicvoid postHandle(HttpServletRequest request, HttpServletResponse response, Object o,

             ModelAndView modelAndView) throws Exception {

    }

    publicvoid afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e)

             throws Exception {

    }

    /** * 处理字符转义 * * @param value * @return */

    private String clearXss (String value) {

        if (value == null || "".equals(value)) {

             returnvalue;

        }

        System.err.println("=========>:处理字符转义");

        value = value. replaceAll ("<", "<"). replaceAll (">", ">");

        value = value.replaceAll("\\(", "(").replace("\\)", ")");

        value = value. replaceAll ("'", "'");

        value = value.replaceAll("eval\\((.*)\\)", "");

        value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");

        value = value.replace("script", "");

        returnvalue;

    }

}

springMVC.xml文件中配置SqlInjectInterceptor

<! -- 拦截器:SQL注入拦截 -->

    <mvc: interceptors>

        <mvc: interceptor>

             <mvc: mapping path="/**" />

             <bean class="com. Controller.SqlInjectInterceptor"></bean>

        </mvc: interceptor>

    </mvc: interceptors>

 

二、对含有敏感的脚本,直接处理掉。

1编写SX_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;

import javax. servlet. http. HttpServletResponse;

 

publicclass SX_Filter implements Filter {

 

    private FilterConfig config;

    privatestatic String errorPath;// 出错跳转的目的地

    privatestatic String[] excludePaths;// 不进行拦截的url

    privatestatic String [] safeless = { // 需要拦截的字符关键字、url编码

             "<script",

             "</script",

             "<iframe",

             "</iframe",

             "<frame",

             "</frame",

             "set-cookie",

             "%3cscript",

             "%3c/script",

             "%3ciframe",

             "%3c/iframe",

             "%3cframe",

             "%3c/frame",

             "src=\"javascript:",

             "<body", "</body",

             "%3cbody",

             "%3c/body",

             "<", ">","</","/>","%3c","%3e","%3c/","/%3e"};

publicvoid doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain)

             throws IOException, ServletException {

        Enumeration params = req. getParameterNames ();

        HttpServletRequest request = (HttpServletRequest) req;

        HttpServletResponse response = (HttpServletResponse) resp;

        booleanisSafe = true;

        String requestUrl = request. getRequestURI ();

        if (isSafe(requestUrl)) {

             requestUrl = requestUrl.substring(requestUrl.indexOf("/"));

             if (! excludeUrl(requestUrl)) {

                 while (params. hasMoreElements ()) {

                 String cache = req.getParameter((String) params.nextElement());

                     if (null != cache && cache.length() > 0) {

                         if (!isSafe(cache)) {

                             isSafe = false;

                             break;

                         }

                     }

                 }

             }

        } else {

             isSafe = false;

        }

        if (! isSafe) {

             request.setAttribute("error", "您输入的参数有非法字符!");

             response. sendRedirect ("http://... ");

             return;

        }

        filterChain.doFilter(req, resp);

    }

    privatestaticboolean isSafe (String str) {

        if (null! = str && str. length () > 0) {

             for (String s: safeless) {

                 if (str. toLowerCase (). contains(s)) {

                     returnfalse;

                 }

             }

        }

        returntrue;

    }

    privateboolean excludeUrl (String url) {

        if (excludePaths != null && excludePaths.length > 0) {

             for (String path : excludePaths) {

                 if (url. toLowerCase (). equals(path)) {

                     returntrue;

                 }

             }

        }

        returnfalse;

    }

    publicvoid destroy() {

    }

    publicvoid init(FilterConfig config) throws ServletException {

        this.config = config;

        errorPath = config. getInitParameter("errorPath");

        String excludePath = config.getInitParameter("excludePaths");

        if (null != excludePath && excludePath.length() > 0) {

             excludePaths = excludePath.split(",");

        }

    }

}

2web中配置

<filter>

    <filter-name>XssSqlFilter</filter-name>

    <filter-class>com. Controller. SX_Filter </filter-class>

</filter>

<filter-mapping>

    <filter-name>XssSqlFilter</filter-name>

    <url-pattern>/*</url-pattern>

    <dispatcher>REQUEST</dispatcher>

</filter-mapping>

 

 

posted @ 2016-06-15 15:46  逍遥叹!!  阅读(4833)  评论(0编辑  收藏  举报