Making full use of X-Content-Type-Options for web security

What are X-Content-Type-Options?

X-Content-Type-Options is an HTTP response header that controls whether browsers should attempt MIME type sniffing. If X-Content-Type-Options is enabled, the browser will follow the MIME type provided by the server to prevent the browser from executing a response body with a MIME type error.

If the Content-Type specified in the HTTP response header is inconsistent with the MIME type returned by the actual response body, in this case the browser may ignore the Content-Type specified in the response header and execute the MIME type of the actual response body, causing security risks , and setting X-Content-Type-Options is to avoid this type of security risk.

How to set X-Content-Type-Options?

On the server side (in the scenario where the front and back ends are separated, you only need to configure the server where the front-end site is located, if the front and back ends are together, add X-Content-Type- to the code or reverse proxy service configuration) The Options header will do.

Take nginx as an example, add the following lines to the nginx.conf file:

add_header X-Content-Type-Options nosniff;

Taking apache as an example, add the following lines to the .htaccess file:

Header set X-Content-Type-Options "nosniff"

The response header key is X-Content-Type-Options, and the value is nosniff. This configuration is to tell the browser to prohibit the execution of response content inconsistent with the type specified by Content-Type, and not to try to infer the file type from the file extension or file content, thereby avoiding the security risk caused by content sniffing.

Application scenarios of X-Content-Type-Options

It is mainly used to prevent XSS (cross-site scripting attack) and snippet-injection attack. A snippet-injection attack refers to embedding HTML code into non-HTML content, which is read and parsed by the browser. This can lead to XSS attacks or be misdirected to sites containing malicious code.

see an example

Here is a piece of code that uses the X-Content-Type-Options response header:

HTTP/1.1 200 OK
Content-Type: text/html;charset=utf-8
X-Content-Type-Options: nosniff

<html>
<head>
<title>路多辛的博客</title>
</head>
<body>
<script>
alert("nosniff warning");
</script>
</body>
</html>

By adding X-Content-Type-Options: nosniff in the response header, tell the browser to only execute the response content whose MIME is text/html, which will prevent the browser from executing JavaScript code.

Guess you like

Origin blog.csdn.net/luduoyuan/article/details/131196398