简体   繁体   English

如何防止针对keyup()jQuery事件的XSS?

[英]How can I prevent XSS for an keyup() jQuery event?

I am making a form with an keyup() event: every character the user types is immediately displayed into another div on the same page. 我正在用keyup()事件制作表单:用户键入的每个字符都会立即显示在同一页面上的另一个div中。

It's vulnerable to XSS. 它容易受到XSS的攻击。 How can I secure it using jQuery? 如何使用jQuery保护它?

Note: In my forms, I am using latin alphanumeric characters only, as well as commas, semi-colons, colons. 注意:在表单中,我仅使用拉丁字母数字字符以及逗号,分号,冒号。

I have searched the "Reform" tool from OWASP but is there a way that's better? 我已经从OWASP搜索了“改革”工具,但是有没有更好的方法?

Thanks in advance. 提前致谢。 Regards 问候

With the few details available: remember that you don't have to use jQuery's HTML "parsing" for everything. 提供一些细节:请记住,您不必为所有内容使用jQuery的HTML“解析”。 Instead of using .html() , use DOM manipulations and .text() (which are also usually faster). 除了使用.html() ,还可以使用DOM操作和.text() (通常也更快)。 For example, this: 例如,这:

$('#result').html('<span class="whatever">' + someInput + '</span>');

would become this: 会变成这样:

$('#result').text($('<span>').addClass('whatever').text(someInput));

If that's not possible, you can also do flawless HTML escaping by setting with .text() and then fetching it with .html() . 如果不可能,也可以通过设置.text()然后使用.html()进行完美的HTML转义。 For example, this: 例如,这:

var data = 'This text: **is bold**';

$('#result').html(data.replace(/\*\*(.+?)\*\*/g, '<b>$1</b>'));

would become this: 会变成这样:

var data = 'This text: **is bold**';

$('#result').html(data.replace(/\*\*(.+?)\*\*/g, function(x) {
    return '<b>' + $('<div>').text(x).html() + '</b>';
}));

I've found the xss cleaner included in node-validator to be comprehensive. 我发现node-validator包含的xss清洁程序很全面。 The code you're interested in is available here . 您感兴趣的代码在这里 You'll need to clean it up a little to use in the browser (remove the module.exports and wrap in a Javascript closure instead) but it should work pretty seamlessly. 您需要对其进行一些清理,以便在浏览器中使用(删除module.exports并包装为Javascript闭包),但是它应该可以无缝运行。 If you wanted to, you could make it directly into a JQuery plug-in as well. 如果愿意,也可以直接将其添加到JQuery插件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM