JeecgBoot抵禦XSS攻擊實現方案

scott發表於2022-05-13

1. 問題描述

jeecgboot後臺啟動後,在瀏覽器輸入地址

http://localhost:8080/jeecg-boot/jmreport/view/')%22οnmοuseοver=alert('hacking')%20%20(

彈出對話方塊

在這裡插入圖片描述

2. 試驗環境

jeecgboot 3.0

3. 增加配置類

  • 在jeecg-boot-module-system的config包下,新建xss包,並新增幾個類

在這裡插入圖片描述

  • 類的具體程式碼如下:
package org.jeecg.config.xss;
 
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
 
/**
 * Created by sunh on 2012/12/29.
 * xss 過濾器只能過濾form表單形式提交的引數
 */
public class XssFilter implements Filter {
 
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
 
    }
 
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("***********開始過濾");
        XssHttpServletRequestWrapper xssRequest =
                new XssHttpServletRequestWrapper((HttpServletRequest) servletRequest);
        filterChain.doFilter(xssRequest, servletResponse);
    }
 
    @Override
    public void destroy() {
 
    }
}
package org.jeecg.config.xss;
 
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
 
/**
 * Created by sunh on 2012/12/29.
 * xss 自動配置類
 */
@Configuration
public class XssFilterAtuoConfig {
 
    @Bean
    public FilterRegistrationBean xssFiltrRegister() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new XssFilter());
        registration.addUrlPatterns("/*");
        registration.setName("XssFilter");
        registration.setOrder(1);
        return registration;
    }
 
 
    @Bean
    @Primary
    public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
        SimpleModule module = new SimpleModule();
        module.addDeserializer(String.class, new XssStringJsonDeserializer());
        ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().build();
        objectMapper.registerModule(module);
        return new MappingJackson2HttpMessageConverter(objectMapper);
    }
}
package org.jeecg.config.xss;
 
import org.springframework.web.servlet.HandlerMapping;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
 
/**
 * Created by sunh on 2012/12/29.
 * xss 包裝
 */
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
 
    public XssHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
    }
 
    @Override
    public String getHeader(String name) {
        String value = super.getHeader(name);
        return XssUtil.cleanXSS(value);
    }
 
    @Override
    public String getParameter(String name) {
        String value = super.getParameter(name);
        return XssUtil.cleanXSS(value);
    }
 
    @Override
    public String[] getParameterValues(String name) {
        String[] values = super.getParameterValues(name);
        if (values != null) {
            int length = values.length;
            String[] escapseValues = new String[length];
            for (int i = 0; i < length; i++) {
                escapseValues[i] = XssUtil.cleanXSS(values[i]);
            }
            return escapseValues;
        }
        return super.getParameterValues(name);
    }
 
    /**
     * 主要是針對HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE 獲取pathvalue的時候把原來的pathvalue經過xss過濾掉
     */
    @Override
    public Object getAttribute(String name) {
        // 獲取pathvalue的值
        if (HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE.equals(name)) {
            Map uriTemplateVars = (Map) super.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
            if (Objects.isNull(uriTemplateVars)) {
                return uriTemplateVars;
            }
            Map newMap = new LinkedHashMap<>();
            uriTemplateVars.forEach((key, value) -> {
                if (value instanceof String) {
                    newMap.put(key, XssUtil.cleanXSS((String) value));
                } else {
                    newMap.put(key, value);
 
                }
            });
            return newMap;
        } else {
            return super.getAttribute(name);
        }
    }
}
package org.jeecg.config.xss;
 
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
 
/**
 * Created by sunh on 2012/12/29.
 * 建立xss的json轉換器
 */
public class XssObjectMapper extends ObjectMapper {
 
    public XssObjectMapper() {
        SimpleModule module = new SimpleModule("XSS JsonDeserializer");
        module.addDeserializer(String.class, new XssStringJsonDeserializer());
        this.registerModule(module);
    }
}
package org.jeecg.config.xss;
 
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import org.springframework.web.util.HtmlUtils;
 
import java.io.IOException;
 
/**
 * Created by sunh on 2012/12/29.
 * 基於xss的JsonDeserializer
 */
public class XssStringJsonDeserializer extends JsonDeserializer<String> {
 
 
    @Override
    public Class<String> handledType() {
        return String.class;
    }
 
    @Override
    public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        return HtmlUtils.htmlEscape(jsonParser.getValueAsString());
    }
}
package org.jeecg.config.xss;
 
 
import java.util.Objects;
 
/**
 * Created by sunh on 2012/12/29
 * xss工具類
 */
public class XssUtil {
 
    public static String cleanXSS(String value) {
        if (Objects.isNull(value)) {
            return value;
        }
        //You'll need to remove the spaces from the html entities below
        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;
    }
}

4. 測試結果

啟動後端,在瀏覽器訪問地址

http://localhost:8080/jeecg-boot/jmreport/view/')%22οnmοuseοver=alert('hacking')%20%20(

未彈出對話方塊

在這裡插入圖片描述

啟動前端,原來的服務能正常訪問。

相關文章