java 如何避免应用程序受到 XSS 攻击?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5769847/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to avoid apps from XSS attacks?
提问by Ravi
How to safe guard our web applications from XSS attacks? One app is vulnearable to attack, if it does not do any conversion of a special charecters.
如何保护我们的 Web 应用程序免受 XSS 攻击?一个应用程序很容易受到攻击,如果它不做任何特殊字符的转换。
采纳答案by WhiteFang34
You should HTML escape any input before outputting it back to the user. Some references:
在将任何输入输出回用户之前,您应该对它进行 HTML 转义。一些参考:
回答by eduardohl
HTML escaping inputs works very well. But in some cases business rules might require you NOT to escape the HTML. Using REGEX is not fit for the task and it is too hard to come up with a good solution using it.
HTML 转义输入效果很好。但在某些情况下,业务规则可能要求您不要转义 HTML。使用 REGEX 不适合这项任务,而且使用它想出一个好的解决方案太难了。
The best solution I found was to use: http://jsoup.org/cookbook/cleaning-html/whitelist-sanitizer
我发现的最佳解决方案是使用:http: //jsoup.org/cookbook/cleaning-html/whitelist-sanitizer
It builds a DOM tree with the provided input and filters any element not previosly allowed by a Whitelist. The API also has other functions for cleaning up html.
它使用提供的输入构建一个 DOM 树,并过滤以前白名单不允许的任何元素。该 API 还具有用于清理 html 的其他功能。
回答by Cuga
Just to add to WhiteFang34' list:
只是添加到 WhiteFang34' 列表中:
It has several whitelists built-in to choose from, such as allowing some HTML, no HTML, etc.
它有几个内置的白名单可供选择,例如允许使用一些 HTML、不允许使用 HTML 等。
I chose this over Apache Commons's StringEscapeUtils.escapeHtml()
because of how it handles apostrophes. I.e. if our users type in:
我选择它而不是 Apache Commons 是StringEscapeUtils.escapeHtml()
因为它处理撇号的方式。即如果我们的用户输入:
Alan's mom had a good brownie recipe.
艾伦的妈妈有一个很好的布朗尼食谱。
JSoup will leave the apostrophe alone, whereas Apache Commons would escape that string as:
JSoup 将不理会撇号,而 Apache Commons 会将该字符串转义为:
Alan\'s mom had a good brownie recipe.
艾伦的妈妈有一个很好的布朗尼食谱。
Which I wouldn't want to have to worry about unescaping before displaying to the user.
在向用户显示之前,我不想担心转义。