5 ms·
Why would you ever be escaping HTML in client-side JS? You should be using appropriate DOM APIs (which don't include innerHTML) to manipulate the document.
by Sephr 7y ago
Why would you ever be escaping HTML in client-side JS? You should be using appropriate DOM APIs (which don't include innerHTML) to manipulate the document.
- tracker1 7y agoIf the JSON itself contains strings with markup included, and you're injecting directly into a script tag in the HTML document. Though, if you're dealing with a typed object server-side and/or loading into a .js file request, it's less of an issue, if you aren't supporting html markup in the object to begin with. In my own use case, both are true.
- Sephr 7y agoHence why I said "You should be using appropriate DOM APIs"... The appropriate DOM APIs don't take HTML strings in the first place. You shouldn't be passing HTML strings to JS.
- IggleSniggle 7y agoI think you’ve missed the vulnerability. You can use appropriate DOM APIs all you want and be hit by a malicious escaper if you don’t serialize in the right way. At some point, your js is inserted into the document via a script tag. If you use the JSON parser to initialize your data more quickly, and your data has user input anywhere within it, then if you aren’t careful about encoding/decoding your string, the attacker’s can abruptly interrupt your own script simply by inserting `</script>//attacker script here`. It is comparable to an SQL injection attack, but instead it is HTML injection that is made possible if you use JSON.stringify without taking the differing character specification into account (the example in the write up shows one good way to do this). The attacker is escaping JSON.parse to escape HTML.
- Sephr 7y agoHence why I said "You should be using appropriate DOM APIs"... The appropriate DOM APIs don't take HTML strings in the first place. You shouldn't be passing HTML strings to JS.