Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
621 views
in Technique[技术] by (71.8m points)

jquery - Can malicious javascript code be injected through $()?

Example:

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As of 22/10/2012, jQuery 1.8.2:

Yes, XSS attacks are possible.

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

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

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");?

See demo, no alerts.


In the case OP describes however, the following:

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

Will translate to this:

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...