当前位置:   article > 正文

Java防止XSS攻击_xss java

xss java
方法一:转义存储:添加XssFilter 
1.在web.xml添加过滤器:
  1. <!-- 解决xss漏洞 -->
  2. <filter>
  3. <filter-name>xssFilter</filter-name>
  4. <filter-class>XXXXXX.XssFilter</filter-class>
  5. </filter>
  6. <!-- 解决xss漏洞 -->
  7. <filter-mapping>
  8. <filter-name>xssFilter</filter-name>
  9. <url-pattern>*</url-pattern>
  10. </filter-mapping>

2.添加XssFilter

  1. public class XssFilter implements Filter{
  2. @Override
  3. public void init(FilterConfig filterConfig) {
  4. }
  5. @Override
  6. public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
  7. //使用包装器
  8. XssFilterWrapper xssFilterWrapper=new XssFilterWrapper((HttpServletRequest) servletRequest);
  9. filterChain.doFilter(xssFilterWrapper,servletResponse);
  10. }
  11. @Override
  12. public void destroy() {
  13. }
  14. }

3、添加 XssFilterWrapper.java类

  1. public class XssFilterWrapper extends HttpServletRequestWrapper {
  2. public XssFilterWrapper(HttpServletRequest request) {
  3. super(request);
  4. }
  5. @Override
  6. public String getHeader(String name) {
  7. return StringEscapeUtils.escapeHtml4(super.getHeader(name));
  8. }
  9. @Override
  10. public String getQueryString() {
  11. return StringEscapeUtils.escapeHtml4(super.getQueryString());
  12. }
  13. @Override
  14. public String getParameter(String name) {
  15. return StringEscapeUtils.escapeHtml4(super.getParameter(name));
  16. }
  17. @Override
  18. public String[] getParameterValues(String name) {
  19. String[] values = super.getParameterValues(name);
  20. if(values != null) {
  21. int length = values.length;
  22. String[] escapseValues = new String[length];
  23. for(int i = 0; i < length; i++){
  24. escapseValues[i] = StringEscapeUtils.escapeHtml4(values[i]);
  25. }
  26. return escapseValues;
  27. }
  28. return super.getParameterValues(name);
  29. }
  30. }

自此,即能实现,

假如在网站的文本框输入<script>alert("OK");</script>,

提交到数据库后保存的数据为:&lt;script&gt;alert(&quot;OK&quot;);&lt;/script&gt;

方法二、

1.添加XssFilter ,(同上)

2..添加XssHttpServletRequestWrapper.java类

  1. import java.io.BufferedReader;
  2. import java.io.ByteArrayInputStream;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.InputStreamReader;
  6. import java.nio.charset.Charset;
  7. import java.util.HashMap;
  8. import java.util.Map;
  9. import java.util.regex.Pattern;
  10. import javax.servlet.ReadListener;
  11. import javax.servlet.ServletInputStream;
  12. import javax.servlet.http.HttpServletRequest;
  13. import javax.servlet.http.HttpServletRequestWrapper;
  14. import org.apache.commons.lang.StringUtils;
  15. import com.alibaba.fastjson.JSON;
  16. public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
  17. /**
  18. * Constructs a request object wrapping the given request.
  19. *
  20. * @param request The request to wrap
  21. * @throws IllegalArgumentException if the request is null
  22. */
  23. public XssHttpServletRequestWrapper(HttpServletRequest request) {
  24. super(request);
  25. }
  26. @Override
  27. public String getHeader(String name) {
  28. String value = super.getHeader(name);
  29. if(StringUtils.isEmpty(value)){
  30. return value;
  31. }
  32. else{
  33. return cleanXSS(value);
  34. }
  35. }
  36. @Override
  37. public String getParameter(String name) {
  38. String value = super.getParameter(name);
  39. if(StringUtils.isEmpty(value)){
  40. return value;
  41. }
  42. else{
  43. return cleanXSS(value);
  44. }
  45. }
  46. @Override
  47. public String[] getParameterValues(String name) {
  48. String[] values = super.getParameterValues(name);
  49. if (values != null) {
  50. int length = values.length;
  51. String[] escapseValues = new String[length];
  52. for (int i = 0; i < length; i++) {
  53. escapseValues[i] = cleanXSS(values[i]);
  54. }
  55. return escapseValues;
  56. }
  57. return super.getParameterValues(name);
  58. }
  59. @Override
  60. public ServletInputStream getInputStream() throws IOException {
  61. String str=getRequestBody(super.getInputStream());
  62. Map<String,Object> map= JSON.parseObject(str,Map.class);
  63. Map<String,Object> resultMap=new HashMap<>();
  64. for(String key:map.keySet()){
  65. Object val=map.get(key);
  66. if(map.get(key) instanceof String){
  67. resultMap.put(key,cleanXSS(val.toString()));
  68. }
  69. else{
  70. resultMap.put(key,val);
  71. }
  72. }
  73. str=JSON.toJSONString(resultMap);
  74. final ByteArrayInputStream bais = new ByteArrayInputStream(str.getBytes());
  75. return new ServletInputStream() {
  76. @Override
  77. public int read() throws IOException {
  78. return bais.read();
  79. }
  80. @Override
  81. public boolean isFinished() {
  82. return false;
  83. }
  84. @Override
  85. public boolean isReady() {
  86. return false;
  87. }
  88. @Override
  89. public void setReadListener(ReadListener listener) {
  90. }
  91. };
  92. }
  93. private String getRequestBody(InputStream stream) {
  94. String line = "";
  95. StringBuilder body = new StringBuilder();
  96. int counter = 0;
  97. // 读取POST提交的数据内容
  98. BufferedReader reader = new BufferedReader(new InputStreamReader(stream, Charset.forName("UTF-8")));
  99. try {
  100. while ((line = reader.readLine()) != null) {
  101. body.append(line);
  102. counter++;
  103. }
  104. } catch (IOException e) {
  105. e.printStackTrace();
  106. }
  107. return body.toString();
  108. }
  109. private String cleanXSS(String value) {
  110. if(StringUtils.isEmpty(value)){
  111. return value;
  112. }
  113. else{
  114. if (value != null) {
  115. if (value != null) {
  116. // NOTE: It's highly recommended to use the ESAPI library and uncomment the following line to
  117. // avoid encoded attacks.
  118. // value = ESAPI.encoder().canonicalize(value);
  119. // Avoid null characters
  120. value = value.replaceAll("", "");
  121. // Avoid anything between script tags
  122. Pattern scriptPattern = Pattern.compile("<script>(.*?)</script>", Pattern.CASE_INSENSITIVE);
  123. value = scriptPattern.matcher(value).replaceAll("");
  124. // Avoid anything in a src="http://www.yihaomen.com/article/java/..." type of e­xpression
  125. // 会误伤百度富文本编辑器
  126. // scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\'(.*?)\\\'", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
  127. // value = scriptPattern.matcher(value).replaceAll("");
  128. // scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\"(.*?)\\\"", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
  129. // value = scriptPattern.matcher(value).replaceAll("");
  130. // Remove any lonesome </script> tag
  131. scriptPattern = Pattern.compile("</script>", Pattern.CASE_INSENSITIVE);
  132. value = scriptPattern.matcher(value).replaceAll("");
  133. // Remove any lonesome <script ...> tag
  134. scriptPattern = Pattern.compile("<script(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
  135. value = scriptPattern.matcher(value).replaceAll("");
  136. // Avoid eval(...) e­xpressions
  137. scriptPattern = Pattern.compile("eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
  138. value = scriptPattern.matcher(value).replaceAll("");
  139. // Avoid e­xpression(...) e­xpressions
  140. scriptPattern = Pattern.compile("e­xpression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
  141. value = scriptPattern.matcher(value).replaceAll("");
  142. // Avoid javascript:... e­xpressions
  143. scriptPattern = Pattern.compile("javascript:", Pattern.CASE_INSENSITIVE);
  144. value = scriptPattern.matcher(value).replaceAll("");
  145. // Avoid vbscript:... e­xpressions
  146. scriptPattern = Pattern.compile("vbscript:", Pattern.CASE_INSENSITIVE);
  147. value = scriptPattern.matcher(value).replaceAll("");
  148. // Avoid onload= e­xpressions
  149. scriptPattern = Pattern.compile("onload(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
  150. value = scriptPattern.matcher(value).replaceAll("");
  151. }
  152. }
  153. return value;
  154. }
  155. }
  156. }

两种方法,原理一致只是写法不一样,

第二种写法保存到数据库为:scriptalert("OK");/script

原文地址:Java防止XSS攻击 - Sky—yong - 博客园

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

闽ICP备14008679号