简体   繁体   中英

Javascript sanitization: The most safe way to insert possible XSS html string

Currently i'm using this method with jQuery solution, to clean string from possible XSS attacks.

sanitize:function(str) {
    // return htmlentities(str,'ENT_QUOTES');
    return $('<div></div>').text(str).html().replace(/"/gi,'&quot;').replace(/'/gi,'&apos;');   
}

But i have a feeling it's not safe enough. Do i miss something?

I have tried htmlentities from phpjs project here: http://phpjs.org/functions/htmlentities:425/

But it's kinda bugged and returns some additional special symbols. Maybe it's an old version?

For example:

htmlentities('test"','ENT_QUOTES');

Produces:

test&amp;quot;

But should be:

test&quot;

How are you handling this via javascript?

If your string is supposed to be plain text without HTML formatting, just use .createTextNode(text) /assigning to .data property of existing text node. Whatever you put there will always be interpreted as text and needs no additional escaping.

Yes dynamically using javascript. String comes from untrusted source.

Then you don't need to sanitize it manually. With jQuery you can just write

​var str = '<div>abc"def"ghi</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​';

​$​('test').text(str);
$('test').attr('alt', str);

Browser will separate the data from the code for you.

Example: http://jsfiddle.net/HNQvd/

You should quote other characters too:

'
"
<
>
(
)
;

They all can be used for XSS attacks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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