Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is jQuery .text() method XSS safe?

I have unescaped data from users.

So is it safe to use like this:

var data = '<test>a&f"#</test>'; // example data from ajax response if (typeof(data) === 'string')     $('body').text(data); 

Can I use like this or there is some problems like encoding or some specific symbols that I should be careful and add more strict validation?

like image 933
Vytautas Avatar asked Mar 16 '12 09:03

Vytautas


People also ask

Does jQuery prevent XSS?

The Editor itself cannot protect you from XSS attacks because malicious users can manually edit form fields and post forged requests to the server. To protect your users from these attacks, clean the posted content on the server through an HTML parsing and a whitelist of allowed tags.

Is innerText vulnerable to XSS?

One example of an attribute which is thought to be safe is innerText. Some papers or guides advocate its use as an alternative to innerHTML to mitigate against XSS in innerHTML. However, depending on the tag which innerText is applied, code can be executed.

What is a best practice for avoiding an XSS attack?

How to prevent XSS attacks. To prevent XSS attacks, your application must validate all the input data, make sure that only the allowlisted data is allowed, and ensure that all variable output in a page is encoded before it is returned to the user.

Is HTML encoding enough to prevent XSS?

Encoding is probably the most important line of XSS defense, but it is not sufficient to prevent XSS vulnerabilities in every context. You should also validate input as strictly as possible at the point when it is first received from a user.


2 Answers

When you set the text of an element using the text method, jQuery uses createTextNode internally, which escapes all special characters.

From the jQuery docs:

We need to be aware that this method escapes the string provided as necessary so that it will render correctly in HTML. To do so, it calls the DOM method .createTextNode(), which replaces special characters with their HTML entity equivalents (such as &lt; for <)

So yes, it should be safe. Here's your example in jsfiddle. Notice how the tags appear as literal text.

like image 126
James Allardice Avatar answered Sep 25 '22 13:09

James Allardice


Because XSS attacks rely on being able to insert DOM nodes (<img />, <script />) etc, and jQuery.fn.text() does not support this, it is entirely XSS safe.

As you can see in this basic example, all would-be-HTML tags are encoded as a result of jQuery using createTextNode internally:

jQuery('div').text('<test>a&f"#</test>');​ 

So that what is actually inserted is more equivilant to;

jQuery('div').html('&lt;test&gt;a&f"#&lt;/test&gt;');​ 
like image 30
Matt Avatar answered Sep 23 '22 13:09

Matt