Skip to content Skip to sidebar Skip to footer

Javascript Xss Prevention

There is a Node.js project that sanitizes data and there is an OWASP library for JavaScript that handles sanitization to prevent XSS. I have been benchmarking these libraries, and

Solution 1:

Here is a general encode procedure:

var lt = /</g, 
    gt = />/g, 
    ap = /'/g, 
    ic = /"/g;
value = value.toString().replace(lt, "&lt;").replace(gt, "&gt;").replace(ap, "&#39;").replace(ic, "&#34;");

If your user doesn't submit anything to your server you don't even need the above. If the user submits and you are using the user input then the above should be safe. As long as the '<' and '>' are globally sanitized and the parenthesis also are you are good to go.

Solution 2:

why not use encodeURIComponent before sending the data to the client?

varstring="<script>...</script>";
string=encodeURIComponent(string); // %3Cscript%3E...%3C/script%3

Solution 3:

Considering https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html

Here is an implementation of their recommendations :

functionescapeOutput(toOutput){
    return toOutput.replace(/\&/g, '&amp;')
        .replace(/\</g, '&lt;')
        .replace(/\>/g, '&gt;')
        .replace(/\"/g, '&quot;')
        .replace(/\'/g, '&#x27')
        .replace(/\//g, '&#x2F');
}

Also make sure you use this function only when necessary or you might break some stuff.

But I suggest you to take a look at already made libraries for sanatizing output :

https://github.com/ecto/bleach

Solution 4:

You can use a function like

functionhtmlEncode(str){
  returnString(str).replace(/[^\w. ]/gi, function(c){
     return'&#'+c.charCodeAt(0)+';';
  });
}

You would then use this function as follows:

<script>document.body.innerHTML = htmlEncode(untrustedValue)</script>

If your input is inside a JavaScript string, you need an encoder that performs Unicode escaping. Here is a sample Unicode-encoder:

functionjsEscape(str){
  returnString(str).replace(/[^\w. ]/gi, function(c){
     return'\\u'+('0000'+c.charCodeAt(0).toString(16)).slice(-4);
  });

}

You would then use this function as follows:

<script>document.write('<script>x="'+jsEscape(untrustedValue)+'";<\/script>')</script>

More info: https://portswigger.net/web-security/cross-site-scripting/preventing

Post a Comment for "Javascript Xss Prevention"