In this chapter, we added the protection against XSS attacks. If you have any questions, please contact me at [email protected]. Ask for directions of various gods, thank you


One: What is XSS

XSS attack, full name for cross-site scripting attack, is a computer security vulnerability in Web applications that allows malicious Web users to insert code into pages intended for use by other users.

For (var I =0; var I =0; var I =0; var I =0; i<1000; I ++){alert(” kill you “+ I); }, save it to the database; 2. Create a div element on the page that displays the value stored in the first step, and you will see a pop-up box appear.

The above two examples are just hoaxes. Malicious users can do much more, such as obtaining user information and conducting “phishing” attacks.

One way to deal with XSS attacks is to filter input directly from the back end, such as

Add Jsoup dependencies

Jsoup uses the mechanism of tag whitelist to prevent XSS attacks. If only P tags are allowed in the whitelist, only P tags can exist in an HTML code, and other tags will be cleared to keep only the contents wrapped by tags. Of course, Jsoup can not only be used for filtering, but also for crawlers. Here is not to explain, later will write a single article to explain.

<dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.10.2</version>Copy the code

Three: Create a filter

Create the Filter folder under core

1. Create a filtering rule

package com.example.demo.core.filter; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.safety.Whitelist; /** * @author * @description: * @date 2018/5/16 20:03 */ public class XssFilterUtil {/** * Use basicWithImages whitelist * Allow notes with a, b, blockquote, br, cite, code, dd, dl, dt, em, I, li, ol, p, the pre, q, small, the span, * strike, strong, sub, sup, u, ul, img href * and a label, img SRC labels, align, Alt, height, width, the title attribute * / private static final Whitelist  whitelist = Whitelist.basicWithImages(); */ private static final Document.OutputSettings OutputSettings = new Document.OutputSettings().prettyPrint(false); Static {// Rich text editing is implemented with style, such as the red font style="color:red;"// Add the style attribute whitelist.addattributes (":all"."style");
    }

    public static String clean(String content) {
        return Jsoup.clean(content, "", whitelist, outputSettings); }}Copy the code

2. Rewrite the request parameter processing function, which is the key to realize XSS filtering. Rewrite getParameter, getParameterValues, getHeader and other methods in it to filter the parameters in the HTTP request.

package com.example.demo.core.filter; import org.apache.commons.lang3.StringUtils; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; / * * * to rewrite the request parameter handler * / public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {it orgRequest = null; private boolean isIncludeRichText =false; public XssHttpServletRequestWrapper(HttpServletRequest request, boolean isIncludeRichText) { super(request); orgRequest = request; this.isIncludeRichText = isIncludeRichText; } /** * override the getParameter method to XSS filter both parameter names and parameter values. By super. GetParameterValues (name) to get * getParameterNames, getParameterValues and getParameterMap may need to Override * / @ Override public String getParameter(String name) {if (("content".equals(name) || name.endsWith("WithHtml")) && !isIncludeRichText) {
            return super.getParameter(name);
        }
        name = XssFilterUtil.clean(name);
        String value = super.getParameter(name);
        if (StringUtils.isNotBlank(value)) {
            value = XssFilterUtil.clean(value);
        }
        return value;
    }

    @Override
    public String[] getParameterValues(String name) {
        String[] arr = super.getParameterValues(name);
        if(arr ! = null) {for(int i = 0; i < arr.length; i++) { arr[i] = XssFilterUtil.clean(arr[i]); }}returnarr; } /** * override the getHeader method to XSS filter both parameter names and parameter values. <br/> * If you want to get the original value, <br/> getHeaders(name) <br/> * getHeaderNames */ @override public String getHeader(String name) {name = XssFilterUtil.clean(name); String value = super.getHeader(name);if (StringUtils.isNotBlank(value)) {
            value = XssFilterUtil.clean(value);
        }
        returnvalue; } /** * get the original request ** @return
     */
    public HttpServletRequest getOrgRequest() {
        returnorgRequest; } /** * static method to get the original request ** @return
     */
    public static HttpServletRequest getOrgRequest(HttpServletRequest req) {
        if (req instanceof XssHttpServletRequestWrapper) {
            return ((XssHttpServletRequestWrapper) req).getOrgRequest();
        }
        returnreq; }}Copy the code

3, add filter XSS the entry of the request, through the XssHttpServletRequestWrapper will it here for encapsulation, filterChain. DoFilter (xssRequest, response); To ensure the subsequent code execution request. The getParameter, request. GetParameterValues, request. Are to be called by the getHeader XssHttpServletRequestWrapper rewriting method, The obtained parameters are tags that have been filtered to eliminate sensitive information.

package com.example.demo.core.filter; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author * @description: * @date 2018/5/16 20:04 */ public class XssFilter implements Filter {// Whether rich text content is filtered private static boolean IS_INCLUDE_RICH_TEXT =true;

    public List<String> excludes = new ArrayList<>();

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        if (handleExcludeURL(req, resp)) {
            filterChain.doFilter(request, response);
            return;
        }
        XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request, IS_INCLUDE_RICH_TEXT);
        filterChain.doFilter(xssRequest, response);
    }

    private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) {
        if (excludes == null || excludes.isEmpty()) {
            return false;
        }
        String url = request.getServletPath();
        for (String pattern : excludes) {
            Pattern p = Pattern.compile("^" + pattern);
            Matcher m = p.matcher(url);
            if (m.find()) {
                return true; }}return false;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String isIncludeRichText = filterConfig.getInitParameter("isIncludeRichText");
        if (StringUtils.isNotBlank(isIncludeRichText)) {
            IS_INCLUDE_RICH_TEXT = BooleanUtils.toBoolean(isIncludeRichText);
        }
        String temp = filterConfig.getInitParameter("excludes");
        if(temp ! = null) { String[] url = temp.split(",");
            for(int i = 0; url ! = null && i < url.length; i++) { excludes.add(url[i]); } } } @Override public voiddestroy() {}}Copy the code

Four: register filter

To create the core – configurer – XssFilterConfigurer

package com.example.demo.core.configurer; import com.example.demo.core.filter.XssFilter; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.HashMap; import java.util.Map; /** * @author @description: XSS filter interceptor Configuration file * @time 2018/5/16 20:47 */ @configuration public class XssFilterConfigurer {/** * XSS filter interceptor */ @bean public FilterRegistrationBeanxssFilterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new XssFilter());
        filterRegistrationBean.setOrder(Integer.MAX_VALUE-1);
        filterRegistrationBean.setEnabled(true);
        filterRegistrationBean.addUrlPatterns("/ *"); Map<String, String> initParameters = new HashMap(); // Excludes Used to configure request URL initparameters.put ("excludes"."/favicon.ico,/img/*,/js/*,/css/*"); //isIncludeRichText is mainly used to set whether rich text content should be filtered initparameters.put ("isIncludeRichText"."true");
        filterRegistrationBean.setInitParameters(initParameters);
        returnfilterRegistrationBean; }}Copy the code

5: test

Path to the localhost: 8080 / the userInfo/selectById

ssssss

Results:

We can see that <script></script> has been filtered out


The project address

Code cloud address: gitee.com/beany/mySpr…

GitHub address: github.com/MyBeany/myS…

Writing articles is not easy, if it is helpful to you, please help click star

At the end

Adding the function of preventing XSS attacks has been completed, and the subsequent functions will be updated successively. If you have any questions, please contact me at [email protected]. Ask for directions from various gods, thank you.