CSRF 全称Cross-Site Request Forgery,是用户伪造了一个自动提交的url,导致其他用户点击URL时会自动执行一些危险操作。CSRF一般可以通过两种手段防御:1.只允许POST提交数据。2.提交数据时加上token。
XSS 全称Cross-site Scripting,是用户提交了非法的脚本内容到网站,导致其他用户访问页面时非法脚本会被执行。XSS一般提供对请求参数进行过滤防御。两种攻击的详情内容可以参考:
https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)#Examples CSRF攻击原理
https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)#Examples XSS攻击原理
幸运的是owasp(open web application secutiry project)已经提供了一系列完善的安全框架来解决这类问题。(owasp项目列表:https://www.owasp.org/index.php/OWASP_Project_Inventory#tab=Flagship_Projects)这里介绍一下owasp antisamy的使用。
maven依赖:
<dependency> <groupId>org.owasp.antisamy</groupId> <artifactId>antisamy</artifactId> <version>1.5.3</version> </dependency>
import org.owasp.validator.html.AntiSamy; import org.owasp.validator.html.Policy; import org.owasp.validator.html.PolicyException; public class XSSChecker { protected Policy policy; /** * relative to japa python root */ protected String policyPath = "WEB-INF/ebay.xml"; protected AntiSamy as = null; public void setPolicyPath(String policyPath) { if (policyPath != null) { this.policyPath = policyPath; } } public void init() throws PolicyException { policy = Policy.getInstance(policyPath); as = new AntiSamy(policy); } public String scan(String html) { if (html == null) { return ""; } try { return as.scan(html, AntiSamy.SAX).getCleanHTML(); } catch (RuntimeException e) { return html; } catch (Exception e) { return html; } } }
在servlet中这样使用:
class XSSFilter(object): def scan(self, request): if request.GET: request.GET0 = request.GET ret = {} for k, v in request.GET.items(): ret[k] = self.xssfilter.scan(v) request.GET = ret if request.POST: request.POST0 = request.POST ret = {} for k, v in request.POST.items(): ret[k] = self.xssfilter.scan(v) request.POST = ret router: xssfilter = XSSFilter(config.getServletContext().getRealPath('')) xssfilter.scan(request)
owasp AntiSamy参考资料:
http://www.owasp.org.cn/owasp-project/download/owasp-antisamy-java/view
https://www.owasp.org/index.php/AntiSamy
更多安全参考:
http://www.freebuf.com/articles/web/9977.html 防御XSS的七条原则
http://www.freebuf.com/articles/web/9928.html XSS解决方案系列之一:淘宝、百度、腾讯的解决方案之瑕疵
http://blog.csdn.net/kkdelta/article/details/17374927 一个反射型XSS例子的解析
http://www.howtocreate.co.uk/crosssite.html
https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet
http://stackoverflow.com/questions/2113984/is-replacing-and-with-lt-and-gt-enough-to-prevent-xss-injection
http://blog.csdn.net/kaosini/article/details/8778775http://blog.csdn.net/kaosini/article/details/8778775
http://blog.csdn.net/kaosini/article/details/8778775
案例:
<DIV » STYLE="background-image: » url(javascript:alert('XS » S'))">