1. 程式人生 > >Java Filter過濾xss註入非法參數的方法

Java Filter過濾xss註入非法參數的方法

nbsp rst let efi fin author ssa html 空串

http://blog.csdn.NET/feng_an_qi/article/details/45666813

Java Filter過濾xss註入非法參數的方法

web.xml:

[html] view plain copy
  1. <filter>
  2. <filter-name>XSSFiler</filter-name>
  3. <filter-class>
  4. com.paic.mall.web.filter.XssSecurityFilter
  5. </filter-class>
  6. </filter>
  7. <filter-mapping>
  8. <filter-name>XSSFiler</filter-name>
  9. <url-pattern>*.jsp</url-pattern>
  10. </filter-mapping>
  11. <filter-mapping>
  12. <filter-name>XSSFiler</filter-name>
  13. <url-pattern>*.do</url-pattern>
  14. </filter-mapping>
  15. <filter-mapping>
  16. <filter-name>XSSFiler</filter-name>
  17. <url-pattern>*.screen</url-pattern>
  18. </filter-mapping>
  19. <filter-mapping>
  20. <filter-name>XSSFiler</filter-name>
  21. <url-pattern>*.shtml</url-pattern>
  22. </filter-mapping>
  23. <filter-mapping>
  24. <filter-name>XSSFiler</filter-name>
  25. <servlet-name>dispatcher</servlet-name>
  26. </filter-mapping>

XssSecurityFilter.Java

[java] view plain copy
  1. public class XssSecurityFilter implements Filter {
  2. protected final Logger log = Logger.getLogger(this.getClass());
  3. public void init(FilterConfig config) throws ServletException {
  4. if(log.isInfoEnabled()){
  5. log.info("XSSSecurityFilter Initializing ");
  6. }
  7. }
  8. /**
  9. * 銷毀操作
  10. */
  11. public void destroy() {
  12. if(log.isInfoEnabled()){
  13. log.info("XSSSecurityFilter destroy() end");
  14. }
  15. }
  16. public void doFilter(ServletRequest request, ServletResponse response,
  17. FilterChain chain) throws IOException, ServletException {
  18. HttpServletRequest httpRequest = (HttpServletRequest)request;
  19. XssHttpRequestWrapper xssRequest = new XssHttpRequestWrapper(httpRequest);
  20. httpRequest = XssSecurityManager.wrapRequest(xssRequest);
  21. chain.doFilter(xssRequest, response);
  22. }
  23. }

XssHttpRequestWrapper.Java

[java] view plain copy
  1. /**
  2. * @author
  3. * @date
  4. * @describe 主要是對參數進行xss過濾,替換原始的request的getParameter相關功能
  5. * 線程不安全
  6. *
  7. */
  8. public class XssHttpRequestWrapper extends HttpServletRequestWrapper {
  9. protected Map parameters;
  10. /**
  11. * 封裝http請求
  12. *
  13. * @param request
  14. */
  15. public XssHttpRequestWrapper(HttpServletRequest request) {
  16. super(request);
  17. }
  18. @Override
  19. public void setCharacterEncoding(String enc)
  20. throws UnsupportedEncodingException {
  21. super.setCharacterEncoding(enc);
  22. //當編碼重新設置時,重新加載重新過濾緩存。
  23. refiltParams();
  24. }
  25. void refiltParams(){
  26. parameters=null;
  27. }
  28. @Override
  29. public String getParameter(String string) {
  30. String strList[] = getParameterValues(string);
  31. if (strList != null && strList.length > 0)
  32. return strList[0];
  33. else
  34. return null;
  35. }
  36. @Override
  37. public String[] getParameterValues(String string) {
  38. if (parameters == null) {
  39. paramXssFilter();
  40. }
  41. return (String[]) parameters.get(string);
  42. }
  43. @Override
  44. public Map getParameterMap() {
  45. if (parameters == null) {
  46. paramXssFilter();
  47. }
  48. return parameters;
  49. }
  50. /**
  51. *
  52. * 校驗參數,若含xss漏洞的字符,進行替換
  53. */
  54. private void paramXssFilter() {
  55. parameters = getRequest().getParameterMap();
  56. XssSecurityManager.filtRequestParams(parameters, this.getServletPath());
  57. }
  58. }

XssSecurityManager.java

[java] view plain copy
    1. /**
    2. * @author
    3. * @date
    4. * @describe 安全過濾配置管理類,統一替換可能造成XSS漏洞的字符為中文字符
    5. */
    6. public class XssSecurityManager {
    7. private static Logger log = Logger.getLogger(XssSecurityManager.class);
    8. // 危險的javascript:關鍵字j av a script
    9. private final static Pattern[] DANGEROUS_TOKENS = new Pattern[] { Pattern
    10. .compile("^j\\s*a\\s*v\\s*a\\s*s\\s*c\\s*r\\s*i\\s*p\\s*t\\s*:",
    11. Pattern.CASE_INSENSITIVE) };
    12. // javascript:替換字符串(全角中文字符)
    13. private final static String[] DANGEROUS_TOKEN_REPLACEMENTS = new String[] { "JAVASCRIPT:" };
    14. // 非法的字符集
    15. private static final char[] INVALID_CHARS = new char[] { ‘<‘, ‘>‘, ‘\‘‘,
    16. ‘\"‘, ‘\\‘ };
    17. // 統一替換可能造成XSS漏洞的字符為全角中文字符
    18. private static final char[] VALID_CHARS = new char[] { ‘<‘, ‘>‘, ‘’‘, ‘“‘,
    19. ‘\‘ };
    20. // 開啟xss過濾功能開關
    21. public static boolean enable=false;
    22. // url-patternMap(符合條件的url-param進行xss過濾)<String ArrayList>
    23. public static Map urlPatternMap = new HashMap();
    24. private static HashSet excludeUris=new HashSet();
    25. private XssSecurityManager() {
    26. // 不可被實例化
    27. }
    28. static {
    29. init();
    30. }
    31. private static void init() {
    32. try {
    33. String xssConfig = "/xss_security_config.xml";
    34. if(log.isDebugEnabled()){
    35. log.debug("XSS config file["+xssConfig+"] init...");
    36. }
    37. InputStream is = XssSecurityManager.class
    38. .getResourceAsStream(xssConfig);
    39. if (is == null) {
    40. log.warn("XSS config file["+xssConfig+"] not found.");
    41. }else{
    42. // 初始化過濾配置文件
    43. initConfig(is);
    44. log.info("XSS config file["+xssConfig+"] init completed.");
    45. }
    46. }
    47. catch (Exception e) {
    48. log.error("XSS config file init fail:"+e.getMessage(), e);
    49. }
    50. }
    51. private static void initConfig(InputStream is) throws Exception{
    52. DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
    53. DocumentBuilder builder=factory.newDocumentBuilder();
    54. Element root = builder.parse(is).getDocumentElement();
    55. //-------------------
    56. NodeList nl=root.getElementsByTagName("enable");
    57. Node n=null;
    58. if(nl!=null && nl.getLength()>0){
    59. n=((org.w3c.dom.Element)nl.item(0)).getFirstChild();
    60. }
    61. if(n!=null){
    62. enable = new Boolean(n.getNodeValue().trim()).booleanValue();
    63. }
    64. log.info("XSS switch="+enable);
    65. //-------------------------
    66. nl=root.getElementsByTagName("filter-mapping");
    67. NodeList urlPatternNodes=null;
    68. if(nl!=null && nl.getLength()>0){
    69. Element el=(Element)nl.item(0);
    70. urlPatternNodes=el.getElementsByTagName("url-pattern");
    71. //-----------------------------------------------------
    72. NodeList nl2=el.getElementsByTagName("exclude-url");
    73. if(nl2!=null && nl2.getLength()>0){
    74. for(int i=0;i<nl2.getLength();i++){
    75. Element e=(Element)urlPatternNodes.item(i);
    76. Node paramNode=e.getFirstChild();
    77. if(paramNode!=null){
    78. String paramName=paramNode.getNodeValue().trim();
    79. if(paramName.length()>0){
    80. excludeUris.add(paramName.toLowerCase());
    81. }
    82. }
    83. }
    84. }
    85. }
    86. //----------------------
    87. if(urlPatternNodes!=null && urlPatternNodes.getLength()>0){
    88. for(int i=0;i<urlPatternNodes.getLength();i++){
    89. Element e=(Element)urlPatternNodes.item(i);
    90. String urlPattern=e.getAttribute("value");
    91. if(urlPattern!=null && (urlPattern=urlPattern.trim()).length()>0){
    92. List filtParamList = new ArrayList(2);
    93. if(log.isDebugEnabled()){
    94. log.debug("Xss filter mapping:"+urlPattern);
    95. }
    96. //-------------------------------
    97. NodeList temp=e.getElementsByTagName("include-param");
    98. if(temp!=null && temp.getLength()>0){
    99. for(int m=0;m<temp.getLength();m++){
    100. Node paramNode=(temp.item(m)).getFirstChild();
    101. if(paramNode!=null){
    102. String paramName=paramNode.getNodeValue().trim();
    103. if(paramName.length()>0){
    104. filtParamList.add(paramName);
    105. }
    106. }
    107. }
    108. }
    109. //一定得將url轉換為小寫
    110. urlPatternMap.put(urlPattern.toLowerCase(), filtParamList);
    111. }
    112. }
    113. }
    114. //----------------------
    115. }
    116. public static HttpServletRequest wrapRequest(HttpServletRequest httpRequest){
    117. if(httpRequest instanceof XssHttpRequestWrapper){
    118. // log.info("httpRequest instanceof XssHttpRequestWrapper");
    119. //include/forword指令會重新進入此Filter
    120. XssHttpRequestWrapper temp=(XssHttpRequestWrapper)httpRequest;
    121. //include指令會增加參數,這裏需要清理掉緩存
    122. temp.refiltParams();
    123. return temp;
    124. }else{
    125. // log.info("httpRequest is not instanceof XssHttpRequestWrapper");
    126. return httpRequest;
    127. }
    128. }
    129. public static List getFiltParamNames(String url){
    130. //獲取需要xss過濾的參數
    131. url = url.toLowerCase();
    132. List paramNameList = (ArrayList) urlPatternMap.get(url);
    133. if(paramNameList==null || paramNameList.size()==0){
    134. return null;
    135. }
    136. return paramNameList;
    137. }
    138. public static void filtRequestParams(Map params,String servletPath){
    139. long t1=System.currentTimeMillis();
    140. //得到需要過濾的參數名列表,如果列表是空的,則表示過濾所有參數
    141. List filtParamNames=XssSecurityManager.getFiltParamNames(servletPath);
    142. filtRequestParams(params, filtParamNames);
    143. }
    144. public static void filtRequestParams(Map params,List filtParamNames){
    145. // 獲取當前參數集
    146. Set parameterNames = params.keySet();
    147. Iterator it = parameterNames.iterator();
    148. //得到需要過濾的參數名列表,如果列表是空的,則表示過濾所有參數
    149. while (it.hasNext()) {
    150. String paramName = (String) it.next();
    151. if(filtParamNames==null || filtParamNames.contains(paramName) ){
    152. String[] values = (String[])params.get(paramName);
    153. proceedXss(values);
    154. }
    155. }
    156. }
    157. /**
    158. * 對參數進行防止xss漏洞處理
    159. *
    160. * @param value
    161. * @return
    162. */
    163. private static void proceedXss(String[] values) {
    164. for (int i = 0; i < values.length; ++i) {
    165. String value = values[i];
    166. if (!isNullStr(value)) {
    167. values[i] = replaceSpecialChars(values[i]);
    168. }
    169. }
    170. }
    171. /**
    172. * 替換非法字符以及危險關鍵字
    173. *
    174. * @param str
    175. * @return
    176. */
    177. private static String replaceSpecialChars(String str) {
    178. for (int j = 0; j < INVALID_CHARS.length; ++j) {
    179. if (str.indexOf(INVALID_CHARS[j]) >= 0) {
    180. str = str.replace(INVALID_CHARS[j], VALID_CHARS[j]);
    181. }
    182. }
    183. str=str.trim();
    184. for (int i = 0; i < DANGEROUS_TOKENS.length; ++i) {
    185. str = DANGEROUS_TOKENS[i].matcher(str).replaceAll(
    186. DANGEROUS_TOKEN_REPLACEMENTS[i]);
    187. }
    188. return str;
    189. }
    190. /**
    191. * 判斷是否為空串,建議放到某個工具類中
    192. *
    193. * @param value
    194. * @return
    195. */
    196. private static boolean isNullStr(String value) {
    197. return value == null || value.trim().length()==0;
    198. }
    199. public static void main(String args[]) throws Exception{
    200. Map datas=new HashMap();
    201. String paramName="test";
    202. datas.put(paramName,new String[]{ "Javascript:<script>alert(‘yes‘);</script>"});
    203. filtRequestParams(datas,"/test/sample.do");
    204. System.out.println(((String[])datas.get(paramName))[0]);
    205. }
    206. }

Java Filter過濾xss註入非法參數的方法