Reputation: 2677
I have a webapi post method which accepts a json and returns a record.
public ProductResponse Post(ProductRequest reqObj){
//search the record
//var responseObject = //search in db using ProductRequest.Name
return responseObject;
}
public class ProductRequest{
public string Name {get;set;}
}
so if the request comes in like {"Name": "iPhone"}
it looks it up and return the response {"Name": "iPhone", "price": "25.00", "Description":"lorem ipsum"}
, if the product doesn't exist then it returns {"Name": "iPhone", "error": "product doesn't exists"}
.
I've been told that the api is prone to XSS attack, because when the user sends {"Name": "iPhone<script>alert(1);</script>"}
then response he is getting is {"Name": "iPhone<script>alert(1);</script>", "error": "product doesn't exists"}
. The expectation is that the tags should have been encoded.
Question 1: Is it vulnerable to XSS when I am not rendering the content directly to the browser?
Question 2: If I am encoding the response, then I have to put a decoder when I get the request too?
Upvotes: 0
Views: 318
Reputation: 15570
It does not matter how you intended to render or use the response, the thing with these attacks is what is possible for an attacker, like for example sending a link to a victim user, displaying your api response in a browser.
However, this is likely not exploitable in recent browsers and given some circumstances. Most importantly, a fairly recent browser only renders a response as html (and runs scripts) if the content type of your response is html (eg. text/html
). A json response should have its content type set to application/json
, in which case javascript would not be run, and it is not vulnerable to xss. (Well, except in very old browsers, but nobody should be using those anymore, a browser from the past ~10 years should be ok.)
Encoding values in json responses is usually wrong. The reason is that it is not the responsibility of the backend to figure out how the value will be used in the frontend, and for that, what encoding is needed. The frontend might want to render it in html, or in a html attribute, or create an xml, or a csv, all needing a potentially different kind of encoding... So appropriate, context-aware encoding should be performed on the client (most modern client-side frameworks take care of this mostly, but not entirely).
You do need to take care though to encode values in the response for the json itself (meaning dealing with quotes for example, so the response is not corrupted due to a quote in the value). But this has nothing to do with xss, and is likelt already managed by the framework you use to generate the json response.
Upvotes: 1