123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 |
- package com.system.filter;
- import java.io.IOException;
- import java.util.Enumeration;
- 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.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.log4j.Logger;
- /**
- * 非法字符过滤器
- * 1.所有非法字符配置在web.xml中,如需添加新字符,请自行配置
- * 2.请注意请求与相应的编码格式设置
- * @author lee
- *
- */
- public class XSSFilter implements Filter{
- private static final Logger log = Logger.getLogger(XSSFilter.class);
- private String encoding;
- private String[] illegalChars;
- private final String str="<,>";
- @Override
- public void destroy() {
- // TODO Auto-generated method stub
- encoding = null;
- illegalChars = null;
- }
- @Override
- public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
- throws IOException, ServletException {
- // TODO Auto-generated method stub
- HttpServletRequest req = (HttpServletRequest)request;
- HttpServletResponse res = (HttpServletResponse) response;
-
- //必须手动指定编码格式
- req.setCharacterEncoding(encoding);
- String tempURL = req.getRequestURI();
- log.info(tempURL);
- Enumeration params = req.getParameterNames();
-
- //是否执行过滤 true:执行过滤 false:不执行过滤
- boolean executable = true;
-
- //非法状态 true:非法 false;不非法
- boolean illegalStatus = false;
- String illegalChar = "";
- //对参数名与参数进行判断
- w:while(params.hasMoreElements()){
-
- String paramName = (String) params.nextElement();
-
- executable = true;
-
- //密码不过滤
- if(paramName.toLowerCase().contains("password")){
- executable = false;
- }
-
- if(executable){
- String[] paramValues = req.getParameterValues(paramName);
-
- f1:for(int i=0;i<paramValues.length;i++){
-
- String paramValue = paramValues[i];
-
- f2:for(int j=0;j<illegalChars.length;j++){
-
- illegalChar = illegalChars[j];
- if(paramValue.indexOf(illegalChar) != -1){
- illegalStatus = true;//非法状态
- break f2;
- }
- }
-
- if(illegalStatus){
- break f1;
- }
-
- }
- }
-
- if(illegalStatus){
- break w;
- }
- }
- if(illegalStatus){
- //必须手动指定编码格式
- res.setContentType("text/html;charset="+encoding);
- res.setCharacterEncoding(encoding);
- res.getWriter().print("<script>window.alert('当前链接中存在非法字符');window.history.go(-1);</script>");
- }else{
- filterChain.doFilter(request, response);
- }
- }
- @Override
- public void init(FilterConfig filterConfig) throws ServletException {
- // TODO Auto-generated method stub
- encoding = filterConfig.getInitParameter("encoding");
- illegalChars = str.split(",");
- }
- }
|