Javascript Xss Prevention
Solution 1:
Here is a general encode procedure:
var lt = /</g,
gt = />/g,
ap = /'/g,
ic = /"/g;
value = value.toString().replace(lt, "<").replace(gt, ">").replace(ap, "'").replace(ic, """);
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, '&')
.replace(/\</g, '<')
.replace(/\>/g, '>')
.replace(/\"/g, '"')
.replace(/\'/g, ''')
.replace(/\//g, '/');
}
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 :
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"