使用springMVC通過Filter實現防止xss註入

springMVC Filter防止xss註入

跨站腳本工具(cross 斯特scripting),為不和層疊樣式表(cascading style sheets,CSS)的縮寫混淆,故將跨站腳本攻擊縮寫為XSS。

惡意攻擊者往web頁面裡插入惡意scriptScript代碼,當用戶瀏覽該頁之時,嵌入其中Web裡面的Script代碼會被執行,從而達到惡意攻擊用戶的目的。

防止XSS攻擊簡單的預防就是對Request請求中的一些參數去掉一些比較敏感的腳本命令。

原本是打算通過springMVC的HandlerInterceptor機制來實現的,通過獲取request然後對request中的參數進行修改,結果雖然值修改瞭,但在Controller中獲取的數值還是沒有修改的。沒辦法就是要Filter來完成。

簡單來說就是創建一個新的httpRequest類XsslHttpServletRequestWrapper,然後重寫一些get方法(獲取參數時對參數進行XSS判斷預防)。

@WebFilter(filterName="xssMyfilter",urlPatterns="/*") 
public class MyXssFilter implements Filter{ 
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {		
	}
 
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
	        throws IOException, ServletException {
		XsslHttpServletRequestWrapper xssRequest = new XsslHttpServletRequestWrapper((HttpServletRequest)request);
		chain.doFilter(xssRequest , response); 
	}
	
	@Override
	public void destroy() {		
	}	
}

XSS代碼的過濾是在XsslHttpServletRequestWrapper中實現的,主要是覆蓋實現瞭getParameter,getParameterValues,getHeader這幾個方法,然後對獲取的value值進行XSS處理。

public class XsslHttpServletRequestWrapper extends HttpServletRequestWrapper { 
  HttpServletRequest xssRequest = null;  
 public XsslHttpServletRequestWrapper(HttpServletRequest request) {
  super(request);
  xssRequest = request;
 } 
 
  @Override  
  public String getParameter(String name) {  
       String value = super.getParameter(replaceXSS(name));  
         if (value != null) {  
             value = replaceXSS(value);  
         }  
         return value;  
  }  
  
  @Override
 public String[] getParameterValues(String name) {
   String[] values = super.getParameterValues(replaceXSS(name));
   if(values != null && values.length > 0){
    for(int i =0; i< values.length ;i++){
     values[i] = replaceXSS(values[i]);
    }
   }
  return values;
  }
  
  @Override  
  public String getHeader(String name) {  
   
         String value = super.getHeader(replaceXSS(name));  
         if (value != null) {  
             value = replaceXSS(value);  
         }  
         return value;  
     } 
  /**
   * 去除待帶script、src的語句,轉義替換後的value值
   */
 public static String replaceXSS(String value) {
     if (value != null) {
         try{
          value = value.replace("+","%2B");   //'+' replace to '%2B'
          value = URLDecoder.decode(value, "utf-8");
         }catch(UnsupportedEncodingException e){
         }catch(IllegalArgumentException e){
     }
         
   // Avoid null characters
   value = value.replaceAll("\0", "");
 
   // Avoid anything between script tags
   Pattern scriptPattern = Pattern.compile("<script>(.*?)</script>", Pattern.CASE_INSENSITIVE);
   value = scriptPattern.matcher(value).replaceAll("");
 
   // Avoid anything in a src='...' type of e­xpression
   scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\'(.*?)\\\'", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
   value = scriptPattern.matcher(value).replaceAll("");
 
   scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\"(.*?)\\\"", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
   value = scriptPattern.matcher(value).replaceAll("");
 
   // Remove any lonesome </script> tag
   scriptPattern = Pattern.compile("</script>", Pattern.CASE_INSENSITIVE);
   value = scriptPattern.matcher(value).replaceAll("");
 
   // Remove any lonesome <script ...> tag
   scriptPattern = Pattern.compile("<script(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
   value = scriptPattern.matcher(value).replaceAll("");
 
   // Avoid eval(...) e­xpressions
   scriptPattern = Pattern.compile("eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
   value = scriptPattern.matcher(value).replaceAll("");
 
   // Avoid e­xpression(...) e­xpressions
   scriptPattern = Pattern.compile("e­xpression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
   value = scriptPattern.matcher(value).replaceAll("");
 
   // Avoid javascript:... e­xpressions
   scriptPattern = Pattern.compile("javascript:", Pattern.CASE_INSENSITIVE);
   value = scriptPattern.matcher(value).replaceAll("");
   // Avoid alert:... e­xpressions
   scriptPattern = Pattern.compile("alert", Pattern.CASE_INSENSITIVE);
   value = scriptPattern.matcher(value).replaceAll("");
   // Avoid οnlοad= e­xpressions
   scriptPattern = Pattern.compile("onload(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
   value = scriptPattern.matcher(value).replaceAll("");
   scriptPattern = Pattern.compile("vbscript[\r\n| | ]*:[\r\n| | ]*", Pattern.CASE_INSENSITIVE);  
   value = scriptPattern.matcher(value).replaceAll("");
  }         
     return filter(value);
 }  
  /**
   * 過濾特殊字符
   */
  public static String filter(String value) {
         if (value == null) {
             return null;
         }        
         StringBuffer result = new StringBuffer(value.length());
         for (int i=0; i<value.length(); ++i) {
             switch (value.charAt(i)) {
              case '<':
                  result.append("<");
                  break;
              case '>': 
                  result.append(">");
                  break;
              case '"': 
                  result.append(""");
                  break;
              case '\'': 
                  result.append("'");
                  break;
              case '%': 
                  result.append("%");
                  break;
              case ';': 
                  result.append(";");
                  break;
           case '(': 
                  result.append("(");
                  break;
              case ')': 
                  result.append(")");
                  break;
              case '&': 
                  result.append("&");
                  break;
              case '+':
                  result.append("+");
                  break;
              default:
                  result.append(value.charAt(i));
                  break;
          }  
         }
         return result.toString();
     } 
}

SpringMVC 防止XSS 工具(常規方式)

要求:

xss過濾請求的參數:Content-Type為 json(application/json)

SpringMVC 對於application/json 轉換處理說明:

spring mvc默認使用MappingJackson2HttpMessageConverter轉換器,

而它是使用jackson來序列化對象的,如果我們能 將jackson的序列化和反序列化過程修改,加入過濾xss代碼,並將其註冊到MappingJackson2HttpMessageConverter中

具體實現功能代碼:

import java.io.IOException;
import org.apache.commons.text.StringEscapeUtils;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
 
/**
 * 反序列化
 *
 */
public class XssDefaultJsonDeserializer extends StdDeserializer<String> { 
 public XssDefaultJsonDeserializer(){
  this(null);
 }
 
 public XssDefaultJsonDeserializer(Class<String> vc) {
  super(vc);
 }
 
 @Override
 public String deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
  // TODO Auto-generated method stub
  //return StringEscapeUtils.escapeEcmaScript(jsonParser.getText());
  return StringEscapeUtils.unescapeHtml4(jsonParser.getText());
 } 
}

SpringMVC 配置對象:

@Configuration
@EnableWebMvc
public class SpingMVCConfig extends WebMvcConfigurerAdapter {
 @Override
 public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
  super.configureMessageConverters(converters);
  // TODO Auto-generated method stub
  SimpleModule module = new SimpleModule();
  // 反序列化
  module.addDeserializer(String.class, new XssDefaultJsonDeserializer());
  // 序列化
  module.addSerializer(String.class, new XssDefaultJsonSerializer());
  ObjectMapper mapper = Jackson2ObjectMapperBuilder.json().build();
  // 註冊自定義的序列化和反序列化器
  mapper.registerModule(module);
  MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(mapper);
  converters.add(converter);
          }
}

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: