亲宝软件园·资讯

展开

Springboot XSS漏洞过滤 Springboot实现XSS漏洞过滤的代码实例

善良的小黑哥 人气:0

背景

前阵子做了几个项目,终于开发完毕,进入了测试阶段,信心满满将项目部署到测试环境,然后做了安全测评之后.....

​(什么!你竟然说我代码不安全???)

然后测出了 Xss漏洞 安全的问题

解决方案

场景:可以在页面输入框输入JS脚本, 攻击者可以利用此漏洞执行恶意的代码

问题演示

所以我们要对于前端传输的参数做处理,做统一全局过滤处理

既然要过滤处理,我们首先需要实现一个自定义过滤器

总共包含以下四部分

最后我们需要在全局过滤器中使用我们实现的Xss自定义过滤器

代码实现

XssFilterAtuoConfig实现代码

 import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import net.greatsoft.overallbudget.filter.SimpleCORSFilter;
import org.springframework.boot.context.embedded.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 wjy on 2020/11/5.
 * xss 自动配置类
 */
@Configuration
public class XssFilterAtuoConfig {

  /**
   * 注册自定义过滤器
   * @return
   */
  @Bean
  public FilterRegistrationBean xssFiltrRegister() {
    FilterRegistrationBean registration = new FilterRegistrationBean();
    //设置系统过滤器 (setFilter就是你所定义的过滤器filter类)
    registration.setFilter(new SimpleCORSFilter());
    //过滤所有路径
    registration.addUrlPatterns("/*");
    //过滤器名称
    registration.setName("XssFilter");
    //优先级
    registration.setOrder(1);
    return registration;
  }

  /**
   *  过滤JSON数据
   * @return
   */
  @Bean
  @Primary
  public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
    SimpleModule module = new SimpleModule();
    //自定义序列化过滤配置(XssStringJsonDeserializer), 对入参进行转译
    module.addDeserializer(String.class, new XssStringJsonDeserializer());
    // 注册解析器
    ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().build();
    objectMapper.registerModule(module);
    return new MappingJackson2HttpMessageConverter(objectMapper);
  }
}

XssHttpServletRequestWrapper实现代码

/**
 * Created by wjy on 2020/11/5.
 * xss 包装
 */
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {

  public XssHttpServletRequestWrapper(HttpServletRequest request) {
    super(request);
  }

  /**
   * 对header处理
   * @param name
   * @return
   */
  @Override
  public String getHeader(String name) {
    String value = super.getHeader(name);
    return XssUtil.cleanXSS(value);
  }

  /**
   * 对参数处理
   * @param name
   * @return
   */
  @Override
  public String getParameter(String name) {
    String value = super.getParameter(name);
    return XssUtil.cleanXSS(value);
  }

  /**
   * 对数值进行处理
   * @param name
   * @return
   */
  @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);
    }
  }
} 

XssStringJsonDeserializer代码实现

 /**
 * Created by wjy on 2020/11/5.
 * 基于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 XssUtil.cleanXSS(jsonParser.getValueAsString());
  }
} 

XssUtil代码实现

 /**
 * Created by wjy on 2020/11/5.
 * xss工具类
 */
public class XssUtil {

  public static String cleanXSS(String value) {
    if (Objects.isNull(value)) {
      return 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;
  }
} 

全局过滤器实现

 @Component
public class SimpleCORSFilter implements Filter {

  @Override
  public void doFilter(ServletRequest req, ServletResponse res,
      FilterChain chain) throws IOException, ServletException {
    // 在这里,使用我们实现的XSS过滤器
    XssHttpServletRequestWrapper request =
        new XssHttpServletRequestWrapper((HttpServletRequest) req);

    HttpServletResponse response = (HttpServletResponse) res;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods",
        "POST, GET, PUT, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers",
        "Origin, X-Requested-With, Content-Type, Accept, token");
    
    chain.doFilter(request, response);
    
  }

  public void init(FilterConfig filterConfig) {
  }

  public void destroy() {
  }

} 

加载全部内容

相关教程
猜你喜欢
用户评论