字符過濾器和防止XSS攻擊,SQL注入的過濾器

1.字符過濾器

public class CharacterEncodingFilter implements Filter
{
  private String encoding;
  private boolean forceEncoding = false;

  public void setEncoding(String encoding) {
    this.encoding = encoding;
  }

  public void setForceEncoding(boolean forceEncoding) {
    this.forceEncoding = forceEncoding;
  }

  public void destroy()
  {
  }

  public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
    throws IOException, ServletException
  {
    if ((this.encoding != null) && ((this.forceEncoding) || (request.getCharacterEncoding() == null)))
    {
      request.setCharacterEncoding(this.encoding);
      if (this.forceEncoding) {
        response.setCharacterEncoding(this.encoding);
      }
    }
    filterChain.doFilter(request, response);
  }

  public void init(FilterConfig filterConfig) throws ServletException
  {
    this.encoding = filterConfig.getInitParameter("encoding");
    String value = filterConfig.getInitParameter("forceEncoding");
    if ("true".equalsIgnoreCase(value))
      this.forceEncoding = true;
  }
}

web.xml的配置

<filter>
      <filter-name>CharacterEncoding</filter-name>
      <filter-class>CharacterEncodingFilter</filter-class>
      <init-param>
         <param-name>encoding</param-name>
         <param-value>GBK</param-value>
      </init-param>
      <init-param>
         <param-name>forceEncoding</param-name>
         <param-value>true</param-value>
      </init-param>
   </filter>
   <filter-mapping>
      <filter-name>CharacterEncoding</filter-name>
      <url-pattern>/*</url-pattern>
    </filter>

2.XSS攻擊和SQL注入的過濾器

public class XSSFilter implements Filter
{
  private String error_url;
  private Logger logger = YGLogger.getLogger("xss.trc");

  private String[] invalidCharacters = { ">", "<", "'", "\"", "&", "\\", "#" };

  private String[] invalidUrlCharacters = { ">", "<", "'", "\"", "&", "\\", "#" };

  private String[] excludeUrl = null;

  public void init(FilterConfig filterConfig) throws ServletException
  {
    String fileName = filterConfig.getInitParameter("config");
    if (fileName == null)
    {
      return;
    }
    InputStream is = filterConfig.getServletContext().getResourceAsStream(fileName);
    Properties props = new Properties();
    try {
      props.load(is);
    } catch (IOException e) {
      throw new ServletException("load file:" + fileName + " failure", e);
    } finally {
      IOUtils.closeQuietly(is);
    }
    String tmp = props.getProperty("invalid_character");
    if (tmp != null) {
      this.invalidCharacters = StringUtils.split(tmp, ", ");
    }
    tmp = props.getProperty("invalid_url_character");
    if (tmp != null) {
      this.invalidUrlCharacters = StringUtils.split(tmp, ", ");
    }

    tmp = props.getProperty("exclude_url");
    if (tmp != null) {
      this.excludeUrl = StringUtils.split(tmp, ",");
    }

    this.error_url = props.getProperty("error_url");
    if (this.error_url == null)
      throw new ServletException("xss error_url not config");
  }

  public void destroy()
  {
  }

  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException
  {
    HttpServletRequest httpRequest = (HttpServletRequest)request;
    String url = httpRequest.getRequestURL().toString();
    boolean flag = false;
    if (this.excludeUrl != null) {
      for (String s : this.excludeUrl) {
        if (url.indexOf(s) != -1) {
          flag = true;
          break;
        }
      }
    }
    if (flag) {
      chain.doFilter(request, response);
      return;
    }

    if (isContainsXssChar(url)) {
      this.logger.info("request url:[" + url + "] contains xss character");
      httpRequest.getRequestDispatcher(this.error_url).forward(request, response);
      return;
    }

    Enumeration en = httpRequest.getParameterNames();
    while (en.hasMoreElements()) {
      String name = (String)en.nextElement();
      String[] values = httpRequest.getParameterValues(name);
      for (String value : values) {
        if (isContainsXss2Char(value)) {
          this.logger.info("request url:[" + url + "],parameter:[" + name + "=" + value + "] contains xss character");

          httpRequest.getRequestDispatcher(this.error_url).forward(request, response);

          return;
        }
      }
    }

    chain.doFilter(request, response);
  }

  private boolean isContainsXssChar(String s) {
    if ((s == null) || (s.equals("")) || (isBase64Str(s))) {
      return false;
    }

    for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);
      for (String c1 : this.invalidUrlCharacters) {
        if (c1.charAt(0) == c) {
          return true;
        }
      }
    }
    return false;
  }

  public static boolean isBase64Str(String value) {
    if (value == null) {
      return true;
    }
    if (value.length() % 4 != 0) {
      return false;
    }

    for (int i = 0; i < value.length(); i++) {
      char c = value.charAt(i);
      if ((c < 'A') && (c > 'Z') && (c < 'a') && (c > 'z') && (c < '0') && (c > '9') && (c != '+') && (c != '/') && (c != '='))
      {
        return false;
      }
    }
    return true;
  }
  private boolean isContainsXss2Char(String s) {
    if ((s == null) || (s.equals(""))) {
      return false;
    }
    for (String c1 : this.invalidCharacters) {
      if (s.indexOf(c1) != -1) {
        return true;
      }
    }
    return false;
  }
}

web.xml配置

<filter>
        <filter-name>XSSFilter</filter-name>
        <filter-class>com.yuangou.ecp.bp.web.controller.filter.XSSFilter</filter-class>
        <init-param>
            <param-name>config</param-name>
            <param-value>/WEB-INF/conf/xss_config.properties</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>XSSFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping

xss_config.properties

#攔截參數
invalid_character=>,<,',",&,#,:,%,--,/*,*/,',;,net localgroup administrators,net user,exec master,select,update,insert,delete,or,and,from,truncate,drop,xp_cmdshell
#攔截url
invalid_url_character=>,<,',",\,#
#排除的url
exclude_url=/login.do
#錯誤url
error_url=/xss.jsp
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章