可以通过$()注入恶意的javascript代码吗? [英] Can malicious javascript code be injected through $()?

查看:93
本文介绍了可以通过$()注入恶意的javascript代码吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:

if($('#' + untrusted_js_code).length) > 0
  ....`

通常,"untrusted_js_code"应该是表示项目ID的简单字符串.变量的值来自iframe(通过postMessage),这就是为什么它不受信任的原因.而且我只是在检查当前页面中是否存在该项目,然后再对其进行处理.

Normally "untrusted_js_code" should be a simple string representing the ID of an item. The value of the variable comes from an iframe (trough postMessage), this is why it's untrusted. And I'm just checking if that item exists in the current page, and only then do stuff with it.

推荐答案

截至2012年10月22日,jQuery 1.8.2:

是的,可能会发生XSS攻击.

var input = "<script>alert('hello');</script>"
$(input).appendTo("body");

参见演示.看来jQuery团队有

See demo. It seems the jQuery team has acknowledged this and has plans to address it in jQuery 1.9.

从jQuery 1.8开始,如果您希望用户输入的内容为html,请使用 $.parseHTML :

As of jQuery 1.8, use $.parseHTML if you expect user input to be html:

var input = "<script>alert('hello');</script>"
$($.parseHTML(input)).appendTo("body");​

参见演示,没有警报.

但是,在OP描述的情况下,以下内容:

In the case OP describes however, the following:

var untrusted_js_code = 'alert("moo")';
$('#' + untrusted_js_code).show();

将翻译为:

$('#alert("moo")').show();

由于字符串中的前面的#号,jQuery将其解释为CSS选择器,与html相反,它不能包含内联JS代码,因此相对安全.上面的代码只会告诉jQuery通过该ID查找DOM元素,从而导致jQuery无法找到该元素,因此不执行任何操作.

This is intrepreted by jQuery as a CSS selector, thanks to the preceding # in the string, which as oppposed to html cannot have in-line JS code, so it is relatively safe. The code above would only tell jQuery to look for a DOM element by that ID, resulting in jQuery failing to find the element and thus not performing any action.

这篇关于可以通过$()注入恶意的javascript代码吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆