A frequent recommendation for hardening Web App response headers is "X-Content-Type-Options: nosniff" with the reasoning that preventing mime-sniffing reduces exposure to drive-by download attacks.
Can anyone explain the reasoning behind this?
Scanning the content of a file allows web browsers to detect the format of a file. This regardless of the specified Content-Type
by the web server. For example, a browser requests scripts from a web server. That web server sends that script using a Content-Type
of image/jpg
. The browser will detect the actual application/javascript
format and will execute the script.
This is “MIME sniffing”. It compensates for incorrect, or absence of metadata browsers need to interpret the contents of a page resource. Browsers uses contextual clues (the HTML element that triggered the fetch) or inspects the initial bytes of media type loads to determine the correct content type. MIME sniffing increases the web experience for the majority of users. But it also opens up an attack vector known as MIME confusion attack.
Consider a web application which allows users to upload image files. But it does not verify that the user actually uploaded a valid image. The web application only checks for a valid file extension. This lack of verification allows an attacker to craft and upload an image. But this image contains scripting content. The browser renders the content as HTML, opening the possibility for XSS.
Some files can even be polyglots. It means their content satisfies two or more content types. You can craft a GIF in a way to be valid image and also valid JavaScript. The correct interpretation of the file depends on the browser context.
With this XSS an attacker may craft and triger file(s) download(s) from an internal or external server.
Many sites allow some sort of user-generated content which is served as a non-HTML, non-JavaScript MIME type. For example, a site might allow storing PDFs or raster images for future download by the same or other user. Without MIME sniffing, this content can't be rendered normally in a web browser, and isn't subject to many of the potential security hazards of user-generated content in a web browser.
However, if MIME sniffing is enabled, then a user can craft a malicious file of an accepted type that the sniffer thinks is HTML or JavaScript and then load it in the browser, which can cause security problems when the browser renders it, including allowing the user to cause downloads of malicious software.