欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-03-26 18:45:30
背景前阵子做了几个项目,终于开发完毕,进入了测试阶段,信心满满将项目部署到测试环境,然后做了安全测评之后..... ​(什么!你竟然说我代码不安全???)然后测出了 xss漏洞 安全的问题...

背景

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

Springboot实现XSS漏洞过滤的示例代码 ​(什么!你竟然说我代码不安全???)

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

解决方案

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

问题演示

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

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

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

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

总共包含以下四部分

  • xssutil
  • xssfilterautoconfig
  • xsshttpservletrequestwrapper
  • xssstringfjsondeserializer

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

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

最后我们需要在全局过滤器中使用我们实现的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() {
  }

} 

到此这篇关于springboot实现xss漏洞过滤的示例代码的文章就介绍到这了,更多相关springboot xss漏洞过滤内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!