-
-
Save zhang-ning/f42bb1d7d9abde3cb5fec0ac20de2fed to your computer and use it in GitHub Desktop.
xss escaping and parsing html entities
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var entityMap = { | |
"&": "&", | |
"<": "<", | |
">": ">", | |
'"': '"', | |
"'": ''', | |
"/": '/' | |
}; | |
var htmlMap = { | |
"&": "&", | |
"<": "<", | |
">": ">", | |
'"': '"', | |
''': "'", | |
'/': "/" | |
}; | |
function escapeHtml(string) { | |
return String(string).replace(/[&<>"'\/]/g, function (s) { | |
return entityMap[s]; | |
}); | |
} | |
function parseHtml(string) { | |
return String(string).replace(/&|<|>|"|'|//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