spring boot / cloud (一) 使用filter防止XSS

spring boot / cloud (一) 使用filter防止XSS

前言

XSS(跨站腳本攻擊)

跨站腳本攻擊(Cross Site Scripting),爲不和層疊樣式表(Cascading Style Sheets, CSS)的縮寫混淆,故將跨站腳本攻擊縮寫爲XSS。惡意攻擊者往Web頁面裏插入惡意Script代碼,當用戶瀏覽該頁之時,嵌入其中Web裏面的Script代碼會被執行,從而達到惡意攻擊用戶的目的。html

思路

基於filter攔截,將特殊字符替換爲html轉意字符 (如: "<" 轉意爲 "&lt;") , 須要攔截的點以下:

  • 請求頭 requestHeaderjava

  • 請求體 requestBodygit

  • 請求參數 requestParameterweb

實現

1.建立XssHttpServletRequestWrapper類

在獲取請求頭,請求參數的這些地方,將目標值使用HtmlUtils.htmlEscape方法轉意爲html字符,而避免惡意代碼參與到後續的流程中spring

/**
 * XssHttpServletRequestWrapper.java
 * Created at 2016-09-19
 * Created by wangkang
 * Copyright (C) 2016 egridcloud.com, All rights reserved.
 */
package org.itkk.udf.core.xss;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.springframework.web.util.HtmlUtils;

/**
 * 描述 : 跨站請求防範
 *
 * @author wangkang
 *
 */
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {

  /**
   * 描述 : 構造函數
   *
   * @param request 請求對象
   */
  public XssHttpServletRequestWrapper(HttpServletRequest request) {
    super(request);
  }

  @Override
  public String getHeader(String name) {
    String value = super.getHeader(name);
    return HtmlUtils.htmlEscape(value);
  }

  @Override
  public String getParameter(String name) {
    String value = super.getParameter(name);
    return HtmlUtils.htmlEscape(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] = HtmlUtils.htmlEscape(values[i]);
      }
      return escapseValues;
    }
    return super.getParameterValues(name);
  }

}

2.建立XssStringJsonSerializer類

其次是涉及到json轉換的地方,也同樣須要進行轉意,好比,rerquestBody,responseBodyjson

/**
 * XssStringJsonSerializer.java
 * Created at 2016-09-19
 * Created by wangkang
 * Copyright (C) 2016 egridcloud.com, All rights reserved.
 */
package org.itkk.udf.core.xss;

import java.io.IOException;

import org.springframework.web.util.HtmlUtils;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

/**
 * 描述 : 基於xss的JsonSerializer
 *
 * @author wangkang
 *
 */
public class XssStringJsonSerializer extends JsonSerializer<String> {

  @Override
  public Class<String> handledType() {
    return String.class;
  }

  @Override
  public void serialize(String value, JsonGenerator jsonGenerator,
      SerializerProvider serializerProvider) throws IOException {
    if (value != null) {
      String encodedValue = HtmlUtils.htmlEscape(value);
      jsonGenerator.writeString(encodedValue);
    }
  }

}

3.建立Bean

在啓動類中,建立XssObjectMapper的bean,替換spring boot原有的實例,用於整個系統的json轉換.app

/**
   * 描述 : xssObjectMapper
   *
   * @param builder builder
   * @return xssObjectMapper
   */
  @Bean
  @Primary
  public ObjectMapper xssObjectMapper(Jackson2ObjectMapperBuilder builder) {
    //解析器
    ObjectMapper objectMapper = builder.createXmlMapper(false).build();
    //註冊xss解析器
    SimpleModule xssModule = new SimpleModule("XssStringJsonSerializer");
    xssModule.addSerializer(new XssStringJsonSerializer());
    objectMapper.registerModule(xssModule);
    //返回
    return objectMapper;
  }

4.建立XssFilter

首先是攔截全部的請求,而後在doFilter方法中,將HttpServletRequest強制類型轉換成XssHttpServletRequestWrapper框架

而後傳遞下去.ssh

/**
 * XssFilter.java
 * Created at 2016-09-19
 * Created by wangkang
 * Copyright (C) 2016 egridcloud.com, All rights reserved.
 */
package org.itkk.udf.core.xss;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 描述 : 跨站請求防範
 *
 * @author wangkang
 *
 */
@WebFilter(filterName = "xssFilter", urlPatterns = "/*", asyncSupported = true)
public class XssFilter implements Filter {

  /**
   * 描述 : 日誌
   */
  private static final Logger LOGGER = LoggerFactory.getLogger(XssFilter.class);

  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
  
  }

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

  @Override
  public void destroy() {
  }

}

代碼倉庫 (博客配套代碼)

結束

本文雖基於spring boot實現主題,可是思路是一致的,不限於任何框架.


想得到最快更新,請關注公衆號

想得到最快更新,請關注公衆號

相關文章
相關標籤/搜索