Evaled JSON injection
suggest changeLet’s say that whenever someone visits a profile page in Bob’s website, the following URL is fetched:
https://example.com/api/users/1234/profiledata.json
With a response like this:
{
"name": "Bob",
"description": "Likes pie & security holes."
}
Then that data is parsed and inserted:
var data = eval("(" + resp + ")");
document.getElementById("name").innerText = data.name;
document.getElementById("description").innerText = data.description;
getElementById takes the id, not a CSS selector. "#name" looks up an element whose id is the four characters #name.
Seems good, right? Wrong.
What if someone’s description is Likes XSS."});alert(1);({"name":"Alice","description":"Likes XSS.? Seems weird, but if poorly done, the response will be:
{
"name": "Alice",
"description": "Likes pie & security holes."});alert(1);({"name":"Alice","description":"Likes XSS."
}
And this will be evaled:
({
"name": "Alice",
"description": "Likes pie & security holes."});alert(1);({"name":"Alice","description":"Likes XSS."
})
If you don’t think that’s a problem, paste that in your console and see what happens.
Mitigation
- Use
JSON.parseinstead ofeval.JSON.parserejects the payload above. Do notevaltext a user can influence. - Escape both
"and\in data you place inside a JSON string. Escaping only"turns a backslash-quote into a quote that still closes the string.JSON.stringifydoes both.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents