xss漏洞和csrf漏洞防御

来源:互联网 发布:软件销售代理商 编辑:程序博客网 时间:2024/05/01 09:46

xss防御:

1、尽量少将域名的domain设为域名的根下面,减少分站xss漏洞对主站的影响;

2、对输入的数据进行过滤检查:

  1. public static String htmlSpecialChars(final String s) { 
  2.       String result = s; 
  3.       result = regexReplace("&", "&", result); 
  4.       result = regexReplace("\"", """, result); 
  5.       result = regexReplace("<", "&lt;", result); 
  6.       result = regexReplace(">", "&gt;", result); 
  7.       return result; 
  8.   } 

注意:CSS的行为方式也会有JavaScript的执行:

<style type="text/css" >
#content { height: expression(alert('test xss') ); }
</style>

如果要支持html可以使用这个过滤器(附件,开源的)

  1. 例子 
  2. final ArrayList<Attribute> span_atts = new ArrayList<Attribute>(); 
  3. Map<String, Pattern> allowedAttrValues = new HashMap<String, Pattern>(); 
  4. allowedAttrValues.put(“color”, Pattern.compile(“(#([0-9a-fA-F]{6}|[0-9a-fA-F]{3}))”)); 
  5. allowedAttrValues.put(“font-weight”, Pattern.compile(“bold”)); 
  6. allowedAttrValues.put(“text-align”, Pattern.compile(“(center|right|justify)”)); 
  7. allowedAttrValues.put(“font-style”, Pattern.compile(“italic”)); 
  8. allowedAttrValues.put(“text-decoration”, Pattern.compile(“underline”)); 
  9. allowedAttrValues.put(“margin-left”, Pattern.compile(“[0-9]+px”)); 
  10. allowedAttrValues.put(“text-align”, Pattern.compile(“center”)); 
  11. span_atts.add(new Attribute(“style”, allowedAttrValues)); 
  12. vAllowed.put(“span”, span_atts); 
  13. final ArrayList<Attribute> div_atts = new ArrayList<Attribute>(); 
  14. div_atts.add(new Attribute(“class”)); 
  15. div_atts.add(new Attribute(“align”)); 
  16. vAllowed.put(“div”, div_atts); 
  17. * 2. 调用类似这样的函数String outHtml = HetaoBlogXssHTMLFilter.filter(sourceHtmlString); 

3、针对图片的上传需要检测是否是正确的图片格式是否是伪格式 ,图片服务器尽量不开启程序(java,php,.net)功能或对图片格式不做程序解析;

防御CSRF:

    在Web应用程序侧防御CSRF漏洞,一般都是利用referer判断输入端的url来源、或使用token或者使用JavaScript看不见的验证码;

本文出自 “林清杨--技术博客” 

原创粉丝点击