防止web端脚本攻击的过滤器(可过滤大部分脚本攻击)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了防止web端脚本攻击的过滤器(可过滤大部分脚本攻击)相关的知识,希望对你有一定的参考价值。

在后台进行攻击拦截是必要的,下面是我所使用的防止web端脚本攻击的过滤器工具。

1.配置文件:

1 <!-- 请求拦截 -->
2 <mvc:interceptors>
3         <mvc:interceptor>
4             <mvc:mapping path="/**"/>
5             <bean class="com.demo.filter.UserAuthorityInterceptor"></bean>   
6         </mvc:interceptor>
7 </mvc:interceptors>

2.拦截器:

  1 package com.demo.filter;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.InputStream;
  5 import java.io.InputStreamReader;
  6 import java.net.URLDecoder;
  7 import java.util.Enumeration;
  8 import java.util.HashMap;
  9 import java.util.Iterator;
 10 import java.util.LinkedHashMap;
 11 import java.util.List;
 12 import java.util.Map;
 13 
 14 import javax.annotation.Resource;
 15 import javax.servlet.http.HttpServletRequest;
 16 import javax.servlet.http.HttpServletResponse;
 17 import javax.servlet.http.HttpSession;
 18 
 19 import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; 25 
 31 public class UserAuthorityInterceptor extends HandlerInterceptorAdapter {
 32         
 33         @Override    
 34         public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {  
 35             
 36             Map mapReg = new HashMap();
 37             mapReg.put("script", ".*<.*script.*>.*");
 38             mapReg.put("alert", ".*alert\\(.*?\\).*");
 39 //            mapReg.put("href=", ".*<.*href=.*>.*");
 40             mapReg.put("textarea", ".*<.*textarea.*>.*");
 41             mapReg.put("onmouseover", ".*onmouseover.*");
 42             mapReg.put("iframe", ".*<.*iframe.*>.*");
 43             mapReg.put("object data=data:text/html", ".*object data=data:text/html.*");
 44             Map<String, Object> map =getRequestParamMap(request);
 45             Iterator<String> itfilter=  mapReg.keySet().iterator();
 46             for(String key:map.keySet()){
 47                 Object parString=map.get(key);
 48                 if(parString==null){
 49                     return true;
 50                 }
 51                     String b=parString.toString();
 52                     itfilter=  mapReg.keySet().iterator();
 53                    while(itfilter.hasNext()){
 54                        String a=(String)mapReg.get(itfilter.next());
 55                        if(b.matches(a)){
 56                           System.out.println(a.toUpperCase());
 57                           System.out.println(b.toUpperCase());
 58                           response.setContentType("text/html;charset=UTF-8");
 59                           response.getWriter().write("<html><body><script type=\"text/javascript\">alert(‘请勿进行非法操作!非法的参数是:"+a+"‘)</script></body></html>");
 60                            return false;
 61                       } 
 62                    
 63                }
 64            }
 65             return true;
 66         }    
 67         
 68         /**
 69          * 从请求中获取所有参数(当参数名重复时,用后者覆盖前者)
 70          */
 71         public static Map<String, Object> getRequestParamMap(HttpServletRequest request) {
 72             Map<String, Object> paramMap = new LinkedHashMap<String, Object>();
 73             try {
 74                 String method = request.getMethod();
 75                 if (method.equalsIgnoreCase("put") || method.equalsIgnoreCase("delete")) {
 76                     String queryString = URLDecoder.decode(getString(request.getInputStream()),"UTF-8");
 77                     if ("".equals(queryString)) {
 78                         String[] qsArray = queryString.split("&") ;//StringUtil.splitString(queryString, "&");
 79                         if (qsArray.length>0) {
 80                             for (String qs : qsArray) {
 81                                 String[] array = queryString.split("=") ;//StringUtil.splitString(qs, "=");
 82                                 if (array.length>0 && array.length == 2) {
 83                                     String paramName = array[0].trim();
 84                                     String paramValue = array[1].trim();
 85                                     if (checkParamName(paramName)) {
 86                                         if (paramMap.containsKey(paramName)) {
 87                                             paramValue = paramMap.get(paramName) + String.valueOf((char) 29) + paramValue;
 88                                         }
 89                                         paramMap.put(paramName, paramValue);
 90                                     }
 91                                 }
 92                             }
 93                         }
 94                     }
 95                 } else {
 96                     Enumeration<String> paramNames = request.getParameterNames();
 97                     while (paramNames.hasMoreElements()) {
 98                         String paramName = paramNames.nextElement();
 99                         if (checkParamName(paramName)) {
100                             String[] paramValues = request.getParameterValues(paramName);
101                             if (paramValues.length>0) {
102                                 if (paramValues.length == 1) {
103                                     paramMap.put(paramName, paramValues[0]);
104                                 } else {
105                                     StringBuilder paramValue = new StringBuilder("");
106                                     for (int i = 0; i < paramValues.length; i++) {
107                                         paramValue.append(paramValues[i]);
108                                         if (i != paramValues.length - 1) {
109                                             paramValue.append(String.valueOf((char) 29));
110                                         }
111                                     }
112                                     paramMap.put(paramName, paramValue.toString());
113                                 }
114                             }
115                         }
116                     }
117                 }
118             } catch (Exception e) {
119                 throw new RuntimeException(e);
120             }
121             return paramMap;
122         }
123 
124         /**
125          * 从输入流中获取字符串
126          */
127         public static String getString(InputStream is) {
128             StringBuilder sb = new StringBuilder();
129             try {
130                 BufferedReader reader = new BufferedReader(new InputStreamReader(is));
131                 String line;
132                 while ((line = reader.readLine()) != null) {
133                     sb.append(line);
134                 }
135             } catch (Exception e) {
136                 e.printStackTrace();
137                 throw new RuntimeException(e);
138             }
139             return sb.toString();
140         }
141         private static boolean checkParamName(String paramName) {
142             return !paramName.equals("_"); // 忽略 jQuery 缓存参数
143         }
144         public static void main(String[] args) {
145             String a="88888 onmouseover=prompt(42873) bad=";
146             String b=".*onmouseover.*";
147             System.out.println(a.matches(b));
148             
149             
150         }
151 }

 

以上是关于防止web端脚本攻击的过滤器(可过滤大部分脚本攻击)的主要内容,如果未能解决你的问题,请参考以下文章

如何防止跨站点脚本攻击

XSS过滤JAVA过滤器filter 防止常见SQL注入

Web安全之防止XSS跨站脚本攻击

php安全字段和防止XSS跨站脚本攻击过滤函数

SpringBoot使用mica-xss防止Xss攻击

SpringBoot过滤XSS脚本攻击