5

I'm trying to wrap my head around, why it is advised to validate the content-type, sent by a client to a REST API.

OWASP states in their REST Security Cheat Sheet:

When POSTing or PUTting new data, the client will specify the Content-Type (e.g. application/xml or application/json) of the incoming data. The server should never assume the Content-Type; it should always check that the Content-Type header and the content are the same type. A lack of Content-Type header or an unexpected Content-Type header should result in the server rejecting the content with a 406 Not Acceptable response.

They never really state how a missing validation may be exploited. Of course it's better to validate the input, for the data parser's sake, but the header can be faked anyways by an attacker, right?

Why is the content-type validation suggested and how could a missing validation be exploited?

Anders
  • 64,406
  • 24
  • 178
  • 215
SaAtomic
  • 989
  • 2
  • 15
  • 27

1 Answers1

4

First, the attacker can't always spoof the content type. For example, if your REST API supports a web app that uses cookies to hold session tokens, an attacker may try using CORS (cross-origin XHR) or auto-submitting HTML forms to attack users of your service when the victim visits the attacker's page. If making a cross-site request from the attacker's site (which doesn't have CORS permission for Access-Control-Allow-Header: Content-Type), the attacker can't set the Content-Type header. However, if the application just assumes that the content type is something CORS disallows by default (like JSON) and doesn't verify the header, then an attacker can send a request using one of the non-preflighted / allowed-by-default / allowed-in-forms content types such that it will be accepted by a JSON (or whatever) parser. Of course, ideally you'd have anti-CSRF protections, too, but sometimes people think "I only allow JSON and don't let third-party sites send me JSON, so I'm safe" when in practice they also allow other content types so long as the request body is also valid JSON.

Other times it matters come when doing things like letting a user upload files (always something to do cautiously); if you limit allowed file types, but don't actually verify that uploaded file's type is what it's supposed to be, you could experience a variety of types of problems (depending on what you do with the uploaded files). If you do different things with different file types, you may need to both verify that the user specified a file of one of the allowed types, and that the uploaded file is valid for that type.

CBHacking
  • 40,303
  • 3
  • 74
  • 98
  • Yep. The pivotal point here is that cross-domain XHR is pre-flighted with non-standard content types (eg., application/json). Verifying this provides a definite layer to the depth of defense. – katrix Mar 22 '17 at 18:30