当前位置:   article > 正文

Springboot结合ESAPI——配置XSS防御过滤_spring boot owasp esapi

spring boot owasp esapi

本文来源与几篇优秀文章的整合,但整合后真实可用, 在此记录以便往后使用
文章地址: https://blog.csdn.net/frog4/article/details/81876462
https://blog.csdn.net/julycaka/article/details/78467291       https://blog.csdn.net/fengyao1995/article/details/81290547

框架:前后端分离、Spring Boot + mybatis 

1. 使用的是maven项目;在pom.xml 中加入依赖:

  1. <!-- 预防XSS攻击工具 -->
  2. <dependency>
  3. <groupId>org.owasp.esapi</groupId>
  4. <artifactId>esapi</artifactId>
  5. <version>2.1.0</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.jsoup</groupId>
  9. <artifactId>jsoup</artifactId>
  10. <version>1.9.2</version>
  11. </dependency>

2. 在classpath下加入配置文件:validation.properties和ESAPI.properties

ESAPI.properties

  1. # 是否要打印配置属性,默认为true
  2. ESAPI.printProperties=true
  3. ESAPI.AccessControl=org.owasp.esapi.reference.DefaultAccessController
  4. ESAPI.Authenticator=org.owasp.esapi.reference.FileBasedAuthenticator
  5. ESAPI.Encoder=org.owasp.esapi.reference.DefaultEncoder
  6. ESAPI.Encryptor=org.owasp.esapi.reference.crypto.JavaEncryptor
  7. ESAPI.Executor=org.owasp.esapi.reference.DefaultExecutor
  8. ESAPI.HTTPUtilities=org.owasp.esapi.reference.DefaultHTTPUtilities
  9. ESAPI.IntrusionDetector=org.owasp.esapi.reference.DefaultIntrusionDetector
  10. ESAPI.Logger=org.owasp.esapi.reference.JavaLogFactory
  11. ESAPI.Randomizer=org.owasp.esapi.reference.DefaultRandomizer
  12. ESAPI.Validator=org.owasp.esapi.reference.DefaultValidator
  13. #===========================================================================
  14. # ESAPI Encoder
  15. Encoder.AllowMultipleEncoding=false
  16. Encoder.AllowMixedEncoding=false
  17. Encoder.DefaultCodecList=HTMLEntityCodec,PercentCodec,JavaScriptCodec
  18. #===========================================================================
  19. # ESAPI 加密模块
  20. Encryptor.PreferredJCEProvider=
  21. Encryptor.EncryptionAlgorithm=AES
  22. Encryptor.CipherTransformation=AES/CBC/PKCS5Padding
  23. Encryptor.cipher_modes.combined_modes=GCM,CCM,IAPM,EAX,OCB,CWC
  24. Encryptor.cipher_modes.additional_allowed=CBC
  25. Encryptor.EncryptionKeyLength=128
  26. Encryptor.ChooseIVMethod=random
  27. Encryptor.fixedIV=0x000102030405060708090a0b0c0d0e0f
  28. Encryptor.CipherText.useMAC=true
  29. Encryptor.PlainText.overwrite=true
  30. Encryptor.HashAlgorithm=SHA-512
  31. Encryptor.HashIterations=1024
  32. Encryptor.DigitalSignatureAlgorithm=SHA1withDSA
  33. Encryptor.DigitalSignatureKeyLength=1024
  34. Encryptor.RandomAlgorithm=SHA1PRNG
  35. Encryptor.CharacterEncoding=UTF-8
  36. Encryptor.KDF.PRF=HmacSHA256
  37. #===========================================================================
  38. # ESAPI Http工具
  39. HttpUtilities.UploadDir=C:\\ESAPI\\testUpload
  40. HttpUtilities.UploadTempDir=C:\\temp
  41. # Force flags on cookies, if you use HttpUtilities to set cookies
  42. HttpUtilities.ForceHttpOnlySession=false
  43. HttpUtilities.ForceSecureSession=false
  44. HttpUtilities.ForceHttpOnlyCookies=true
  45. HttpUtilities.ForceSecureCookies=true
  46. # Maximum size of HTTP headers
  47. HttpUtilities.MaxHeaderSize=4096
  48. # File upload configuration
  49. HttpUtilities.ApprovedUploadExtensions=.zip,.pdf,.doc,.docx,.ppt,.pptx,.tar,.gz,.tgz,.rar,.war,.jar,.ear,.xls,.rtf,.properties,.java,.class,.txt,.xml,.jsp,.jsf,.exe,.dll
  50. HttpUtilities.MaxUploadFileBytes=500000000
  51. # Using UTF-8 throughout your stack is highly recommended. That includes your database driver,
  52. # container, and any other technologies you may be using. Failure to do this may expose you
  53. # to Unicode transcoding injection attacks. Use of UTF-8 does not hinder internationalization.
  54. HttpUtilities.ResponseContentType=text/html; charset=UTF-8
  55. # This is the name of the cookie used to represent the HTTP session
  56. # Typically this will be the default "JSESSIONID"
  57. HttpUtilities.HttpSessionIdName=JSESSIONID
  58. #===========================================================================
  59. # ESAPI Executor
  60. Executor.WorkingDirectory=
  61. Executor.ApprovedExecutables=
  62. #===========================================================================
  63. # ESAPI Logging
  64. # Set the application name if these logs are combined with other applications
  65. Logger.ApplicationName=ExampleApplication
  66. # If you use an HTML log viewer that does not properly HTML escape log data, you can set LogEncodingRequired to true
  67. Logger.LogEncodingRequired=false
  68. # Determines whether ESAPI should log the application name. This might be clutter in some single-server/single-app environments.
  69. Logger.LogApplicationName=true
  70. # Determines whether ESAPI should log the server IP and port. This might be clutter in some single-server environments.
  71. Logger.LogServerIP=true
  72. # LogFileName, the name of the logging file. Provide a full directory path (e.g., C:\\ESAPI\\ESAPI_logging_file) if you
  73. # want to place it in a specific directory.
  74. Logger.LogFileName=ESAPI_logging_file
  75. # MaxLogFileSize, the max size (in bytes) of a single log file before it cuts over to a new one (default is 10,000,000)
  76. Logger.MaxLogFileSize=10000000
  77. #===========================================================================
  78. # ESAPI Intrusion Detection
  79. IntrusionDetector.Disable=false
  80. IntrusionDetector.event.test.count=2
  81. IntrusionDetector.event.test.interval=10
  82. IntrusionDetector.event.test.actions=disable,log
  83. IntrusionDetector.org.owasp.esapi.errors.IntrusionException.count=1
  84. IntrusionDetector.org.owasp.esapi.errors.IntrusionException.interval=1
  85. IntrusionDetector.org.owasp.esapi.errors.IntrusionException.actions=log,disable,logout
  86. IntrusionDetector.org.owasp.esapi.errors.IntegrityException.count=10
  87. IntrusionDetector.org.owasp.esapi.errors.IntegrityException.interval=5
  88. IntrusionDetector.org.owasp.esapi.errors.IntegrityException.actions=log,disable,logout
  89. IntrusionDetector.org.owasp.esapi.errors.AuthenticationHostException.count=2
  90. IntrusionDetector.org.owasp.esapi.errors.AuthenticationHostException.interval=10
  91. IntrusionDetector.org.owasp.esapi.errors.AuthenticationHostException.actions=log,logout
  92. #===========================================================================
  93. # ESAPI 校验器
  94. #校验器的配置文件
  95. Validator.ConfigurationFile=validation.properties
  96. # Validators used by ESAPI
  97. Validator.AccountName=^[a-zA-Z0-9]{3,20}$
  98. Validator.SystemCommand=^[a-zA-Z\\-\\/]{1,64}$
  99. Validator.RoleName=^[a-z]{1,20}$
  100. #the word TEST below should be changed to your application
  101. #name - only relative URL's are supported
  102. Validator.Redirect=^\\/test.*$
  103. # Global HTTP Validation Rules
  104. # Values with Base64 encoded data (e.g. encrypted state) will need at least [a-zA-Z0-9\/+=]
  105. Validator.HTTPScheme=^(http|https)$
  106. Validator.HTTPServerName=^[a-zA-Z0-9_.\\-]*$
  107. Validator.HTTPParameterName=^[a-zA-Z0-9_]{1,32}$
  108. Validator.HTTPParameterValue=^[a-zA-Z0-9.\\-\\/+=@_ ]*$
  109. Validator.HTTPCookieName=^[a-zA-Z0-9\\-_]{1,32}$
  110. Validator.HTTPCookieValue=^[a-zA-Z0-9\\-\\/+=_ ]*$
  111. # Note that max header name capped at 150 in SecurityRequestWrapper!
  112. Validator.HTTPHeaderName=^[a-zA-Z0-9\\-_]{1,50}$
  113. Validator.HTTPHeaderValue=^[a-zA-Z0-9()\\-=\\*\\.\\?;,+\\/:&_ ]*$
  114. Validator.HTTPContextPath=^\\/?[a-zA-Z0-9.\\-\\/_]*$
  115. Validator.HTTPServletPath=^[a-zA-Z0-9.\\-\\/_]*$
  116. Validator.HTTPPath=^[a-zA-Z0-9.\\-_]*$
  117. Validator.HTTPQueryString=^[a-zA-Z0-9()\\-=\\*\\.\\?;,+\\/:&_ %]*$
  118. Validator.HTTPURI=^[a-zA-Z0-9()\\-=\\*\\.\\?;,+\\/:&_ ]*$
  119. Validator.HTTPURL=^.*$
  120. Validator.HTTPJSESSIONID=^[A-Z0-9]{10,30}$
  121. # Validation of file related input
  122. Validator.FileName=^[a-zA-Z0-9!@#$%^&{}\\[\\]()_+\\-=,.~'` ]{1,255}$
  123. Validator.DirectoryName=^[a-zA-Z0-9:/\\\\!@#$%^&{}\\[\\]()_+\\-=,.~'` ]{1,255}$
  124. # Validation of dates. Controls whether or not 'lenient' dates are accepted.
  125. # See DataFormat.setLenient(boolean flag) for further details.
  126. Validator.AcceptLenientDates=false

validation.properties

  1. # 校验某个字段的正则表达式
  2. Validator.SafeString=^[.\\p{Alnum}\\p{Space}]{0,1024}$
  3. Validator.Email=^[A-Za-z0-9._%'-]+@[A-Za-z0-9.-]+\\.[a-zA-Z]{2,4}$
  4. Validator.IPAddress=^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$
  5. Validator.URL=^(ht|f)tp(s?)\\:\\/\\/[0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*(:(0-9)*)*(\\/?)([a-zA-Z0-9\\-\\.\\?\\,\\:\\'\\/\\\\\\+=&amp;%\\$#_]*)?$
  6. Validator.CreditCard=^(\\d{4}[- ]?){3}\\d{4}$
  7. Validator.SSN=^(?!000)([0-6]\\d{2}|7([0-6]\\d|7[012]))([ -]?)(?!00)\\d\\d\\3(?!0000)\\d{4}$

 

过滤器:在项目包下创建类 XssFilter实现Filter接口

  1. import java.io.IOException;
  2. import javax.servlet.Filter;
  3. import javax.servlet.FilterChain;
  4. import javax.servlet.FilterConfig;
  5. import javax.servlet.ServletException;
  6. import javax.servlet.ServletRequest;
  7. import javax.servlet.ServletResponse;
  8. import javax.servlet.annotation.WebFilter;
  9. import javax.servlet.http.HttpServletRequest;
  10. import org.slf4j.Logger;
  11. import org.slf4j.LoggerFactory;
  12. /**
  13. * 描述 : 跨站请求防范
  14. *
  15. * @author
  16. *
  17. */
  18. @WebFilter(filterName = "xssFilter", urlPatterns = "/*", asyncSupported = true)
  19. public class XssFilter implements Filter {
  20. /**
  21. * 描述 : 日志
  22. */
  23. private static final Logger LOGGER = LoggerFactory.getLogger(XssFilter.class);
  24. @Override
  25. public void init(FilterConfig filterConfig) throws ServletException {
  26. }
  27. @Override
  28. public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
  29. throws IOException, ServletException {
  30. XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request);
  31. //System.out.println("进入XSS过滤器............");
  32. chain.doFilter(xssRequest, response);
  33. //System.out.println("过滤器XSS执行完......................");
  34. }
  35. @Override
  36. public void destroy() {
  37. }
  38. }

敏感字符转换类:HttpServletRequestWrapper

  1. import java.util.regex.Pattern;
  2. import javax.servlet.http.HttpServletRequest;
  3. import javax.servlet.http.HttpServletRequestWrapper;
  4. import org.owasp.esapi.ESAPI;
  5. public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
  6. public XssHttpServletRequestWrapper(HttpServletRequest servletRequest) {
  7. super(servletRequest);
  8. }
  9. public String[] getParameterValues(String parameter) {
  10. String[] values = super.getParameterValues(parameter);
  11. if (values == null) {
  12. return null;
  13. }
  14. int count = values.length;
  15. String[] encodedValues = new String[count];
  16. for (int i = 0; i < count; i++) {
  17. encodedValues[i] = cleanXSS(values[i]);
  18. }
  19. return encodedValues;
  20. }
  21. public String getParameter(String parameter) {
  22. String value = super.getParameter(parameter);
  23. if (value == null) {
  24. return null;
  25. }
  26. return cleanXSS(value);
  27. }
  28. public String getHeader(String name) {
  29. String value = super.getHeader(name);
  30. if (value == null)
  31. return null;
  32. return cleanXSS(value);
  33. }
  34. // private String cleanXSS(String value) {
  35. //
  36. // //You'll need to remove the spaces from the html entities below
  37. //
  38. // value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;");
  39. //
  40. // value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;");
  41. //
  42. // value = value.replaceAll("'", "& #39;");
  43. //
  44. // value = value.replaceAll("eval\\((.*)\\)", "");
  45. //
  46. // value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
  47. //
  48. // value = value.replaceAll("script", "");
  49. //
  50. // return value;
  51. //
  52. // }
  53. private String cleanXSS(String value) {
  54. if (value != null) {
  55. // 推荐使用ESAPI库来避免脚本攻击
  56. value = ESAPI.encoder().canonicalize(value);
  57. // 避免空字符串
  58. value = value.replaceAll("\\s", "");
  59. // 避免script 标签
  60. Pattern scriptPattern = Pattern.compile("<script>(.*?)</script>", Pattern.CASE_INSENSITIVE);
  61. value = scriptPattern.matcher(value).replaceAll("");
  62. // 避免src形式的表达式
  63. scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\'(.*?)\\\'", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
  64. value = scriptPattern.matcher(value).replaceAll("");
  65. scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\"(.*?)\\\"", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
  66. value = scriptPattern.matcher(value).replaceAll("");
  67. // 删除单个的 </script> 标签
  68. scriptPattern = Pattern.compile("</script>", Pattern.CASE_INSENSITIVE);
  69. value = scriptPattern.matcher(value).replaceAll("");
  70. // 删除单个的<script ...> 标签
  71. scriptPattern = Pattern.compile("<script(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
  72. value = scriptPattern.matcher(value).replaceAll("");
  73. // 避免 eval(...) 形式表达式
  74. scriptPattern = Pattern.compile("eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
  75. value = scriptPattern.matcher(value).replaceAll("");
  76. // 避免 e­xpression(...) 表达式
  77. scriptPattern = Pattern.compile("expression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
  78. value = scriptPattern.matcher(value).replaceAll("");
  79. // 避免 javascript: 表达式
  80. scriptPattern = Pattern.compile("javascript:", Pattern.CASE_INSENSITIVE);
  81. value = scriptPattern.matcher(value).replaceAll("");
  82. // 避免 vbscript: 表达式
  83. scriptPattern = Pattern.compile("vbscript:", Pattern.CASE_INSENSITIVE);
  84. value = scriptPattern.matcher(value).replaceAll("");
  85. // 避免 onload= 表达式
  86. scriptPattern = Pattern.compile("onload(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
  87. value = scriptPattern.matcher(value).replaceAll("");
  88. // 避免 onXX= 表达式
  89. scriptPattern = Pattern.compile("on.*(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
  90. value = scriptPattern.matcher(value).replaceAll("");
  91. }
  92. return value;
  93. }
  94. }

创建配置类:XSSFilterConfig

  1. import com.gdtel.common.xssfilter.XssFilter;
  2. import org.springframework.boot.web.servlet.FilterRegistrationBean;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import javax.servlet.Filter;
  6. /**
  7. * @author jxwen
  8. * @create 2018-10-19 9:14
  9. * @desc
  10. **/
  11. @Configuration
  12. public class XSSFilterConfig {
  13. @Bean
  14. public FilterRegistrationBean filterRegistrationBean() {
  15. FilterRegistrationBean registration = new FilterRegistrationBean();
  16. registration.setFilter(xssFilter());
  17. registration.addUrlPatterns("/*");
  18. registration.addInitParameter("paramName", "paramValue");
  19. registration.setName("xssFilter");
  20. return registration;
  21. }
  22. /**
  23. * 创建一个bean
  24. * @return
  25. */
  26. @Bean(name = "xssFilter")
  27. public Filter xssFilter() {
  28. return new XssFilter();
  29. }
  30. }

配置完成, 架构如下:

END!!!!!!!

 

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/150457
推荐阅读
相关标签
  

闽ICP备14008679号