Javascript 清理:插入可能的 XSS html 字符串的最安全方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11292147/
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
Javascript sanitization: The most safe way to insert possible XSS html string
提问by Somebody
Currently i'm using this method with jQuery solution, to clean string from possible XSS attacks.
目前我正在将此方法与 jQuery 解决方案一起使用,以清除可能的 XSS 攻击中的字符串。
sanitize:function(str) {
// return htmlentities(str,'ENT_QUOTES');
return $('<div></div>').text(str).html().replace(/"/gi,'"').replace(/'/gi,''');
}
But i have a feeling it's not safe enough. Do i miss something?
但我有一种感觉,它不够安全。我想念什么吗?
I have tried htmlentities from phpjs project here: http://phpjs.org/functions/htmlentities:425/
我在这里尝试了来自 phpjs 项目的 htmlentities:http://phpjs.org/functions/htmlentities:425/
But it's kinda bugged and returns some additional special symbols. Maybe it's an old version?
但它有点问题并返回一些额外的特殊符号。也许是旧版本?
For example:
例如:
htmlentities('test"','ENT_QUOTES');
Produces:
产生:
test&quot;
But should be:
但应该是:
test"
How are you handling this via javascript?
你如何通过javascript处理这个问题?
回答by Oleg V. Volkov
If your string is supposed to be plain text without HTML formatting, just use .createTextNode(text)
/assigning to .data
property of existing text node. Whatever you put there will always be interpreted as text and needs no additional escaping.
如果您的字符串应该是没有 HTML 格式的纯文本,只需将.createTextNode(text)
/assigning 用于.data
现有文本节点的属性。无论你在那里放什么都会被解释为文本,不需要额外的转义。
回答by penartur
Yes dynamically using javascript. String comes from untrusted source.
是动态使用 javascript。字符串来自不受信任的来源。
Then you don't need to sanitize it manually. With jQuery you can just write
那么您就不需要手动对其进行消毒。使用 jQuery,您只需编写
?var str = '<div>abc"def"ghi</div>?????????????????????????????????';
?$?('test').text(str);
$('test').attr('alt', str);
Browser will separate the data from the code for you.
浏览器将为您将数据与代码分开。
Example: http://jsfiddle.net/HNQvd/
回答by some_coder
You should quote other characters too: ' " < > ( ) ; They all can be used for XSS attacsk.
你也应该引用其他字符: ' " < > ( ) ; 它们都可以用于 XSS 攻击。