Springboot實現XSS漏洞過濾的示例代碼

背景

前陣子做瞭幾個項目,終於開發完畢,進入瞭測試階段,信心滿滿將項目部署到測試環境,然後做瞭安全測評之後…..

​(什麼!你竟然說我代碼不安全???)

然後測出瞭 Xss漏洞 安全的問題

解決方案

場景:可以在頁面輸入框輸入JS腳本, 攻擊者可以利用此漏洞執行惡意的代碼

問題演示

所以我們要對於前端傳輸的參數做處理,做統一全局過濾處理

既然要過濾處理,我們首先需要實現一個自定義過濾器

總共包含以下四部分

  • XssUtil
  • XssFilterAutoConfig
  • XssHttpServletRequestWrapper
  • XssStringfJsonDeserializer

最後我們需要在全局過濾器中使用我們實現的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漏洞過濾內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: