防止XSS攻击的方式

本文介绍了一种全面的XSS攻击防护策略,包括GET请求、FORM表单提交和JSON格式数据提交的过滤替换非法符号方法。通过使用XssHttpServletRequestWrapper和自定义的XSSMappingJackson2HttpMessageConverter,确保了各种请求数据的安全处理。
摘要由CSDN通过智能技术生成

主要有三种请求方式,进行过滤替换非法符号

1.普通的GET请求数据:

2.FORM表单提交数据:

3.Json格式数据提交:

把下面5个文件放入项目中即可

 1 package com.joppay.admin.security.xss;
 2 
 3 import org.springframework.util.StringUtils;
 4 import org.springframework.web.util.HtmlUtils;
 5 
 6 import javax.servlet.http.HttpServletRequest;
 7 import javax.servlet.http.HttpServletRequestWrapper;
 8 
 9 /**
10  * XSS转义
11  *
12  * @author leroy
13  * @date 2019/3/6 18:08
14  */
15 public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
16 
17     /**
18      * Constructs a request object wrapping the given request.
19      *
20      * @param request The request to wrap
21      * @throws IllegalArgumentException if the request is null
22      */
23     public XssHttpServletRequestWrapper(HttpServletRequest request) {
24         super(request);
25     }
26 
27     @Override
28     public String getParameter(String name) {
29         String value = super.getParameter(name);
30         if (!StringUtils.isEmpty(value)) {
31             value = HtmlUtils.htmlEscape(value);
32         }
33         return value;
34 
35     }
36 
37     @Override
38     public String[] getParameterValues(String name) {
39         String[] parameterValues = super.getParameterValues(name);
40         if (parameterValues == null) {
41             return null;
42         }
43         for (int i = 0; i < parameterValues.length; i++) {
44             String value = parameterValues[i];
45             parameterValues[i] = HtmlUtils.htmlEscape(value);
46         }
47         return parameterValues;
48 
49     }
50 
51 }
View Code
package com.joppay.admin.security.xss;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import java.io.IOException;
import java.lang.reflect.Type;

public class XSSMappingJackson2HttpMessageConverter extends
        MappingJackson2HttpMessageConverter {

    private ObjectMapper mapper = new ObjectMapper();

    public XSSMappingJackson2HttpMessageConverter() {
        super();
        mapper.getFactory().setCharacterEscapes(new HTMLCharacterEscapes());
    }

    @Override
    public Object read(Type type, Class<?> contextClass,
                       HttpInputMessage inputMessage) throws IOException,
            HttpMessageNotReadableException {
        JavaType javaType = getJavaType(type, contextClass);
        // 下面的程式碼 將 @RequestBody 中的資料 做 XSS過濾
        try {
            // json字串转实体
            Object object = mapper.readValue(inputMessage.getBody(), javaType);

            // 实体转字串
            String jsonString = mapper.writeValueAsString(object);

            // json字串转实体
            object = mapper.readValue(jsonString, javaType);
            return object;
        } catch (IOException ex) {
            throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex);
        }

    }
}
View Code
 1 package com.joppay.admin.security.xss;
 2 
 3 import com.fasterxml.jackson.core.JsonGenerator;
 4 import com.fasterxml.jackson.databind.JsonSerializer;
 5 import com.fasterxml.jackson.databind.SerializerProvider;
 6 import org.springframework.web.util.HtmlUtils;
 7 
 8 import java.io.IOException;
 9 
10 /**
11  * json XSS过滤(Form表单对象)
12  * @author leroy
13  * @date 2019/3/6 18:15
14  */
15 public class XssStringJsonSerializer extends JsonSerializer<String> {
16     @Override
17     public Class<String> handledType() {
18         return String.class;
19     }
20 
21     @Override
22     public void serialize(String value, JsonGenerator jsonGenerator,
23                           SerializerProvider serializerProvider) throws IOException {
24         if (value != null) {
25             String encodedValue = HtmlUtils.htmlEscape(value);
26             jsonGenerator.writeString(encodedValue);
27         }
28     }
29 
30 }
View Code
package com.joppay.admin.security.xss;

import com.fasterxml.jackson.core.SerializableString;
import com.fasterxml.jackson.core.io.CharacterEscapes;
import com.fasterxml.jackson.core.io.SerializedString;
import org.apache.commons.lang3.StringEscapeUtils;

public class HTMLCharacterEscapes  extends CharacterEscapes {

    private final int[] asciiEscapes;

    public HTMLCharacterEscapes() {
        // start with set of characters known to require escaping (double-quote, backslash etc)
        asciiEscapes = CharacterEscapes.standardAsciiEscapesForJSON();
        // and force escaping of a few others:
        asciiEscapes['<'] = CharacterEscapes.ESCAPE_CUSTOM;
        asciiEscapes['>'] = CharacterEscapes.ESCAPE_CUSTOM;
        asciiEscapes['&'] = CharacterEscapes.ESCAPE_CUSTOM;
        asciiEscapes['"'] = CharacterEscapes.ESCAPE_CUSTOM;
        asciiEscapes['\''] = CharacterEscapes.ESCAPE_CUSTOM;
    }

    @Override
    public int[] getEscapeCodesForAscii() {
        return asciiEscapes;
    }

    // and this for others; we don't need anything special here
    @Override
    public SerializableString getEscapeSequence(int ch) {
        return new SerializedString(StringEscapeUtils.escapeHtml4(Character.toString((char) ch)));
    }
}
View Code
package com.joppay.admin.security.xss;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * XSS过滤
 *
 * @author leroy
 * @date 2019/3/6 18:13
 */
@WebFilter
@Component
public class XssFilter implements Filter {
    FilterConfig filterConfig = null;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        XssHttpServletRequestWrapper xssRequestWrapper = new XssHttpServletRequestWrapper(req);
        chain.doFilter(xssRequestWrapper, response);
    }

    @Override
    public void destroy() {
        this.filterConfig = null;
    }

    @Bean
    public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
        return new XSSMappingJackson2HttpMessageConverter();
    }
    @Bean
    public XssStringJsonSerializer xssStringJsonSerializer(){
        return new XssStringJsonSerializer();
    }
}
View Code

 

转载于:https://www.cnblogs.com/dwb91/p/10490331.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值