Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it 100% safe to do the following?

Is it 100% safe to do the following?:

var untrusted_input_from_3rd_party = '<script>alert("xss")<\/script>';
document.getElementsByTagName('body')[0].appendChild(document.createTextNode(untrusted_input_from_3rd_party));

Considering that the third party can input anything (HTML, CSS, etc.), can I be sure it won't do any harm if I pass it through createTextNode and then add it to the dom?

like image 815
Polar Avatar asked Oct 10 '11 08:10

Polar


3 Answers

This is a fine way to prevent XSS. DOM manipulation via createTextNode is widely used to safely embed third party text.

That said, there are problems besides XSS. It doesn't do anything to stop social engineering attempts if the untrusted input is something like:

ALERT: We have detected malware on your computer. Copy and paste http://evil.org/ into your browser URL bar to fix the problem.

The best way to prevent social engineering (besides not including third-party content) is to make it clear that the content comes from a third party.

like image 163
Mike Samuel Avatar answered Sep 21 '22 18:09

Mike Samuel


Tested it now. Seems to be correct. If something goes wrong - it should be browser bug, not yours.
As usual server should make a correct html view of all user inputs and then give it back to user.

But to lower server loading (and if it's acceptable) you can use this for sure.

like image 31
Sergey Avatar answered Sep 20 '22 18:09

Sergey


I dont see this being executed in any standard modern browsers as its being rendered as a text node. Good read: http://www.educatedguesswork.org/2011/08/guest_post_adam_barth_on_three.html

like image 40
naveen Avatar answered Sep 21 '22 18:09

naveen