X content type options nosniff как исправить

I am developing a web page using JavaScript and HTML, everything was working
good when I have received this list of errors from my HTML page:

The resource from “https://raw.githubusercontent.com/dataarts/dat.gui/master/build/dat.gui.min.js”
  was blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).
The resource from “https://raw.githubusercontent.com/mrdoob/three.js/dev/build/three.js” was
  blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).
The resource from “https://raw.githubusercontent.com/mrdoob/three.js/master/examples/js/renderers/CanvasRenderer.js”
  was blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).
The resource from “https://raw.githubusercontent.com/mrdoob/three.js/master/examples/js/renderers/Projector.js”
  was blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).
The resource from “https://raw.githubusercontent.com/mrdoob/three.js/dev/build/three.js” was
  blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).

These errors appeared after an automatic browser update (Mozilla Firefox), may
be something has been changed in the set up. Do you know any way to solve this
problem?

Zombo's user avatar

asked Nov 21, 2016 at 20:14

Sim81's user avatar

1

Check if the file path is correct and the file exists — in my case that was the issue — as I fixed it, the error disappeared

answered Dec 25, 2016 at 8:56

dav's user avatar

davdav

8,84115 gold badges76 silver badges139 bronze badges

3

This can be fixed by changing your URL to use a mirror/proxy. Instead of using GitHub:

https://raw.githubusercontent.com/svnpenn/bm/master/yt-dl/yt-dl.js
Content-Type: text/plain; charset=utf-8

Use a third-party cache:

https://cdn.rawgit.com/svnpenn/bm/master/yt-dl/yt-dl.js
content-type: application/javascript;charset=utf-8

rawgit.com was a caching proxy service for GitHub that has shut down since 2018. See its FAQ

Avindra Goolcharan's user avatar

answered Dec 24, 2016 at 1:07

Zombo's user avatar

2

We started facing this error in production after our devops team changed the webserver configuration by adding X-Content-Type-Options: nosniff. Now, due to this, browser was forced to interpret the resources as it was mentioned in content-type parameter of response headers.

Now, from the beginning, our application server was explicitly setting content-type of the js files as text/plain. Since, X-Content-Type-Options: nosniff was not set in webserver, browser was automatically interpreting the js files as JavaScript files although the content-type was mentioned as text/plain. This is called as MIME-sniffing. Now, after setting X-Content-Type-Options: nosniff, browser was forced to not do the MIME-sniffing and take the content-type as mentioned in response headers. Due to this, it did interpret js files as plain text files and denied to execute them or blocked them. The same is shown in your errors.

Solution: is to make your server set the content-type of JS files as

application/javascript;charset=utf-8

This way, it will load all JS files normally and issue will get resolved.

answered Oct 30, 2018 at 10:42

Manish Bansal's user avatar

Manish BansalManish Bansal

2,3602 gold badges20 silver badges37 bronze badges

4

check your path ,this error will come if file was not exist into given path.

answered Jul 14, 2017 at 12:58

Priyanka Acharya's user avatar

Are you using express?

Check your path(note the «/» after /public/):

app.use(express.static(__dirname + "/public/"));

//note: you do not need the «/» before «css» because its already included above:

rel="stylesheet" href="css/style.css

Hope this helps

JP. Aulet's user avatar

JP. Aulet

4,3654 gold badges26 silver badges39 bronze badges

answered Oct 6, 2017 at 17:20

JPaulino's user avatar

JPaulinoJPaulino

3,1971 gold badge8 silver badges7 bronze badges

It might be a wrong path.
Ensure in your main app file you have:

app.use(express.static(path.join(__dirname,"public")));

Example link to your css as:

<link href="/css/clean-blog.min.css" rel="stylesheet">

similar for link to js files:

<script src="/js/clean-blog.min.js"></script>

answered May 28, 2019 at 13:37

Mwongera808's user avatar

Mwongera808Mwongera808

88011 silver badges16 bronze badges

For WordPress

In my case i just missed the slash «/» after get_template_directory_uri() so resulted / generated path was wrong:

My Wrong code :

wp_enqueue_script( 'retina-js', get_template_directory_uri().'js/retina.min.js' ); 

My Corrected Code :

wp_enqueue_script( 'retina-js', get_template_directory_uri().'/js/retina.min.js' );

dav's user avatar

dav

8,84115 gold badges76 silver badges139 bronze badges

answered Jul 6, 2017 at 13:04

Sabir Hussain's user avatar

Sabir HussainSabir Hussain

2,7522 gold badges14 silver badges19 bronze badges

This might be because the browser cannot access a file. I stumbled with this type of error when creating application with node.js. You can try to directly request the script file (copying and pasting url) and see if you can retrieve it. You can see then what the real problem is. It can be because of permission of folder in which the file is located, or browser just cannot find it due to incorrect path to it. In node.js, after specifying route to file, all works.

answered Apr 26, 2017 at 9:53

Vadi's user avatar

VadiVadi

3,1992 gold badges13 silver badges30 bronze badges

2

I’ve solved this problem by changing charset in js-files from UTF-8 without BOM to simple UTF-8 in Notepad++

answered May 6, 2017 at 14:47

Sergey's user avatar

I had this error when i was using the azure storage as a static website, the js files that are copied had the content type as text/plain; charset=utf-8 and i changed the content type to application/javascript

It started working.

answered Apr 2, 2020 at 10:56

Karthikeyan VK's user avatar

Karthikeyan VKKarthikeyan VK

5,0343 gold badges36 silver badges49 bronze badges

It happened to me for wrong tag. By mistake I add the js file in link tag.

Example: (The Wrong One)

<link rel="stylesheet" href="plugins/timepicker/bootstrap-timepicker.min.js">

It solved by using the correct tag for javascript. Example:

<script src="plugins/timepicker/bootstrap-timepicker.min.js"></script>

answered Sep 7, 2020 at 20:51

smartrahat's user avatar

smartrahatsmartrahat

5,2916 gold badges46 silver badges68 bronze badges

See for the protocols HTTPS and HTTP

Sometimes if you are using mixed protocols [this happens mostly with JSONP callbacks ] you can end up in this ERROR.

Make sure both the web-page and the resource page have the same HTTP protocols.

answered Aug 23, 2018 at 7:32

Clain Dsilva's user avatar

Clain DsilvaClain Dsilva

1,6333 gold badges25 silver badges34 bronze badges

I got this problem, when having a function name in the url parameters (firefox 68).

E.g. https://.../test.html?concat() where test.html is

<!DOCTYPE html>
<html>
<script src="https://unpkg.com/mathjs/lib/browser/math.js"></script>
</html>

concat is a function in math.js.

I have no idea, why it happens at all. And it occurs least for this function, while some other functions have no effect.

A space between concat and the parenthesis https://.../test.html?concat () solves the problem.

answered Jun 2, 2022 at 8:53

Friedrich -- Слава Україні's user avatar

app.static() does not preserve the file directory. For example: If you use app.static('static/') and link to the file as <script src="/static/code.js"></script> then the file will not be found as it is looking in the long place. Changing the code to <script src="code.js"></script> solved the problem for me

answered Feb 4 at 14:09

Umar Zahid's user avatar

1

I got this error in a Vue 3 application after updating Vite from v2.9.9 to v4.1.4.

It was solved after I cleared the cache in Firefox (How to clear the Firefox cache)

answered Mar 29 at 7:16

Anna Madsen's user avatar

Anna MadsenAnna Madsen

3463 silver badges13 bronze badges

i also facing this same problem in django server.So i changed DEBUG = True in settings.py file its working

answered Jun 25, 2020 at 5:19

sathish kumar's user avatar

1

I am doing some penetration testing on my localhost with OWASP ZAP, and it keeps reporting this message:

The Anti-MIME-Sniffing header X-Content-Type-Options was not set to
‘nosniff’

This check is specific to Internet Explorer 8 and Google Chrome.
Ensure each page sets a Content-Type header and the
X-CONTENT-TYPE-OPTIONS if the Content-Type header is unknown

I have no idea what this means, and I couldn’t find anything online. I have tried adding:

<meta content="text/html; charset=UTF-8; X-Content-Type-Options=nosniff" http-equiv="Content-Type" />

but the I still get the alert.

What is the correct way of setting the parameter?

Antti Haapala -- Слава Україні's user avatar

asked Aug 20, 2013 at 14:27

Koffeehaus's user avatar

Description

Setting a server’s X-Content-Type-Options HTTP response header to nosniff instructs browsers to disable content or MIME sniffing which is used to override response Content-Type headers to guess and process the data using an implicit content type. While this can be convenient in some scenarios, it can also lead to some attacks listed below. Configuring your server to return the X-Content-Type-Options HTTP response header set to nosniff will instruct browsers that support MIME sniffing to use the server-provided Content-Type and not interpret the content as a different content type.

Browser Support

The X-Content-Type-Options HTTP response header is supported in Chrome, Firefox and Edge as well as other browsers. The latest browser support is available on the Mozilla Developer Network (MDN) Browser Compatibility Table for X-Content-Type-Options:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options

Attacks Countered

  1. MIME Confusion Attack enables attacks via user generated content sites by allowing users uploading malicious code that is then executed by browsers which will interpret the files using alternate content types, e.g. implicit application/javascript vs. explicit text/plain. This can result in a «drive-by download» attack which is a common attack vector for phishing. Sites that host user generated content should use this header to protect their users. This is mentioned by VeraCode and OWASP which says the following:

    This reduces exposure to drive-by download attacks and sites serving user uploaded content that, by clever naming, could be treated by MSIE as executable or dynamic HTML files.

  2. Unauthorized Hotlinking can also be enabled by Content-Type sniffing. By hotlinking to sites with resources for one purpose, e.g. viewing, apps can rely on content-type sniffing and generate a lot of traffic on sites for another purpose where it may be against their terms of service, e.g. GitHub displays JavaScript code for viewing, but not for execution:

    Some pesky non-human users (namely computers) have taken to «hotlinking» assets via the raw view feature — using the raw URL as the src for a <script> or <img> tag. The problem is that these are not static assets. The raw file view, like any other view in a Rails app, must be rendered before being returned to the user. This quickly adds up to a big toll on performance. In the past we’ve been forced to block popular content served this way because it put excessive strain on our servers.

Community's user avatar

answered May 13, 2016 at 4:43

Grokify's user avatar

GrokifyGrokify

14.7k6 gold badges59 silver badges79 bronze badges

1

# prevent mime based attacks
Header set X-Content-Type-Options "nosniff"

This header prevents «mime» based attacks. This header prevents Internet Explorer from MIME-sniffing a response away from the declared content-type as the header instructs the browser not to override the response content type. With the nosniff option, if the server says the content is text/html, the browser will render it as text/html.

http://stopmalvertising.com/security/securing-your-website-with-.htaccess/.htaccess-http-headers.html

answered Oct 21, 2015 at 19:27

Won Jun Bae's user avatar

Won Jun BaeWon Jun Bae

5,1046 gold badges43 silver badges49 bronze badges

1

For Microsoft IIS servers, you can enable this header via your web.config file:

<system.webServer>
    <httpProtocol>
      <customHeaders>
        <remove name="X-Content-Type-Options"/>
        <add name="X-Content-Type-Options" value="nosniff"/>
      </customHeaders>
    </httpProtocol>
</system.webServer>

And you are done.

Simon East's user avatar

Simon East

55.1k17 gold badges139 silver badges133 bronze badges

answered Mar 28, 2016 at 6:15

ComeIn's user avatar

ComeInComeIn

1,50916 silver badges12 bronze badges

2

The X-Content-Type-Options HTTP response header is a marker used by the server to indicate that the MIME types advertised in the Content-Type headers should not be changed and should be followed. This allows you to opt out of MIME type sniffing, or, in other words, it is a way to say that the webmasters knew what they were doing.

Syntax :

X-Content-Type-Options: nosniff

Directives :

nosniff
Blocks a request if the requested type is

  1. «style» and the MIME type is not «text/css», or
  2. «script» and the MIME type is not a JavaScript MIME type.

Note: nosniff only applies to «script» and «style» types. Also applying nosniff to images turned out to be incompatible with existing web sites.

Specification :

https://fetch.spec.whatwg.org/#x-content-type-options-header

iconoclast's user avatar

iconoclast

20.9k14 gold badges100 silver badges136 bronze badges

answered Oct 9, 2017 at 11:25

Sahil Aggarwal's user avatar

Sahil AggarwalSahil Aggarwal

1,2811 gold badge12 silver badges29 bronze badges

A really simple explanation that I found useful: the nosniff response header is a way to keep a website more secure.

From Security Researcher, Scott Helme, here:

It prevents Google Chrome and Internet Explorer from trying to mime-sniff the content-type of a response away from the one being declared by the server.

answered Jan 26, 2021 at 12:59

stevec's user avatar

stevecstevec

38.9k25 gold badges197 silver badges280 bronze badges

Just to elaborate a bit on the meta-tag thing. I’ve heard a talk, where a statement was made, one should always insert the «no-sniff» meta tag in the html to prevent browser sniffing (just like OP did):

<meta content="text/html; charset=UTF-8; X-Content-Type-Options=nosniff" http-equiv="Content-Type" />

However, this is not a valid method for w3c compliant websites, the validator will raise an error:

Bad value text/html; charset=UTF-8; X-Content-Type-Options=nosniff for attribute content on element meta: The legacy encoding contained ;, which is not a valid character in an encoding name.

And there is no fixing this. To rightly turn off no-sniff, one has to go to the server settings and turn it off there. Because the «no-sniff» option is something from the HTTP header, not from the HTML file which is attached at the HTTP response.

To check if the no-sniff option is disabled, one can enable the developer console, networks tab and then inspect the HTTP response header:

Visualization of enabled no-sniff option

answered Jan 23, 2021 at 15:23

Hans T's user avatar

Hans THans T

1231 silver badge13 bronze badges

Prevent content sniffing where no mimetype is sent

Configuration on Ubuntu 20.04 — apache 2.4.41:

Enable the headers module
$ sudo a2enmod headers

Edit file /etc/apache2/conf-available/security.conf and add:

Header always set X-Content-Type-Options: nosniff

Enable Configuration $ sudo a2enconf security.conf

Restart Apache
$ sudo systemctl restart apache2

$ curl -I localhost

HTTP/1.1 200 OK
Date: Fri, 23 Oct 2020 06:12:16 GMT
Server:  
X-Content-Type-Options: nosniff
Last-Modified: Thu, 22 Oct 2020 08:06:06 GMT

answered Oct 23, 2020 at 6:35

blessed's user avatar

blessedblessed

7451 gold badge11 silver badges15 bronze badges

1

This article is a part of our Web Security Knowledge Base
(back to index)

Why “X-Content-Type-Options Header Missing” can be dangerous

The missing «X-Content-Type-Options» http header enables a browser (mostly Internet Explorer) to perform MIME sniffing when the Content-Type header is not set or its value seems inappropriate. In other words, when the browser gets the response from the web server it tries to figure out on its own what is the type of the content and how to handle it. In certain circumstances that can lead to serious security issues (a cross site scripting attack).

For example, if we have an application that allows user uploaded content of jpg files, an attacker may upload a file with jpg extension being in fact an html file with malicious js script inside. Some other user may want to display the image in his browser. The browser gets the file with Content-Type=image/jpg and finds out that declared content type is inappropriate. If the MIME type sniffing is enabled, the browser handles the file as html and executes the malicious js script. On the other hand, if the MIME type sniffing is disabled by setting the «X-Content-Type-Options» header, the browser displays an error message and the script is not executed.

Your server should be configured to include the anti MIME sniffing header

X-Content-Type-Options=nosniff

How does ScanRepeat report “X-Content-Type-Options Header Missing”

ScanRepeat reports listing all instances of URL resources returned without the header or with the header value different than nosniff along with additional information on what should be set to fix this problem.

Would you like to test your application now against this problem? Sign up for our
free trial

Scan Your Web App Now

Я разрабатываю веб-страницу с использованием JavaScript и HTML, все работает
хорошо, когда я получил этот список ошибок с моей HTML-страницы:

The resource from "https://raw.githubusercontent.com/dataarts/dat.gui/master/build/dat.gui.min.js"
  was blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).
The resource from "https://raw.githubusercontent.com/mrdoob/three.js/dev/build/three.js" was
  blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).
The resource from "https://raw.githubusercontent.com/mrdoob/three.js/master/examples/js/renderers/CanvasRenderer.js"
  was blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).
The resource from "https://raw.githubusercontent.com/mrdoob/three.js/master/examples/js/renderers/Projector.js"
  was blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).
The resource from "https://raw.githubusercontent.com/mrdoob/three.js/dev/build/three.js" was
  blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).

Эти ошибки появились после автоматического обновления браузера (Mozilla Firefox), возможно
что-то было изменено в настройке. Вы знаете какой-либо способ решить эту проблему?
проблема?

4b9b3361

Ответ 1

Проверьте правильность пути к файлу и файл — в моем случае это было проблемой — поскольку я исправил его, ошибка исчезла

Ответ 2

Это можно устранить, изменив URL-адрес, например bad:

https://raw.githubusercontent.com/svnpenn/bm/master/yt-dl/yt-dl.js
Content-Type: text/plain; charset=utf-8

Пример:

https://cdn.rawgit.com/svnpenn/bm/master/yt-dl/yt-dl.js
content-type: application/javascript;charset=utf-8

rawgit.com — это кеширующий прокси-сервис для github. Вы также можете пойти туда и в интерактивном режиме получить соответствующий URL-адрес для вашего исходного URL-адреса raw.githubusercontent.com. См. FAQ

Ответ 3

проверьте свой путь, эта ошибка появится, если файл не существует в указанном пути.

Ответ 4

В моем случае я просто пропустил слэш «/» после get_template_directory_uri(), поэтому приведенный/сгенерированный путь был неправильным:

Мой неправильный код:

wp_enqueue_script( 'retina-js', get_template_directory_uri().'js/retina.min.js' ); 

Мой исправленный код:

wp_enqueue_script( 'retina-js', get_template_directory_uri().'/js/retina.min.js' );

Ответ 5

Возможно, это связано с тем, что браузер не может получить доступ к файлу. Я наткнулся на эту ошибку при создании приложения с помощью node.js. Вы можете попробовать напрямую запросить файл script (копировать и вставлять URL-адрес) и посмотреть, сможете ли вы его загрузить. Вы можете видеть, в чем проблема. Это может быть из-за разрешения папки, в которой находится файл, или браузер просто не может найти его из-за неправильного пути к нему. В node.js, после указания пути к файлу, все работает.

Ответ 6

Я решил эту проблему, изменив charset в js файлах из UTF-8 без спецификации на простой UTF-8 в Notepad ++

Ответ 7

Вы используете экспресс?

Проверьте свой путь (обратите внимание на «/» после /public/ ):

app.use(express.static(__dirname + "/public/"));

//обратите внимание: вам не нужно «/» перед «css», потому что оно уже включено выше:

rel="stylesheet" href="css/style.css

Надеюсь, что это поможет

Ответ 8

Мы начали сталкиваться с этой ошибкой в производственном процессе после того, как наша команда разработчиков изменила конфигурацию веб-сервера, добавив X-Content-Type-Options: nosniff. Теперь из-за этого браузер был вынужден интерпретировать ресурсы, как это было упомянуто в параметре content-type заголовков ответа.

Теперь с самого начала наш сервер приложений явно устанавливал тип содержимого файлов js как text/plain. Поскольку X-Content-Type-Options: nosniff не был установлен в веб-сервере, браузер автоматически интерпретировал js файлы как файлы JavaScript, хотя тип содержимого упоминался как text/plain. Это называется MIME-сниффинг. Теперь, после установки X-Content-Type-Options: nosniff, браузер был вынужден не выполнять MIME-сниффинг и принимать тип контента, как указано в заголовках ответов. Из-за этого он интерпретировал файлы js как простые текстовые файлы и отказывался выполнять их или блокировал их. То же самое показано в ваших ошибках.

Решение: заставить ваш сервер установить content-type файлов JS как

application/javascript;charset=utf-8

Таким образом, все файлы JS будут загружены нормально, и проблема будет решена.

Ответ 9

Смотрите протоколы HTTPS и HTTP

Иногда, если вы используете смешанные протоколы [это происходит в основном с обратными вызовами JSONP], вы можете оказаться в этой ОШИБКЕ.

Убедитесь, что и веб-страница, и страница ресурса имеют одинаковые протоколы HTTP.

Ответ 10

у меня та же проблема, это ошибка

El recurso de "http://localhost:9000/styles/main.css" 
se bloqueó debido a la falta de coincidencia del tipo MIME ("text/html")
(X-Content-Type-Options: nosniff).[Saber más]

The X-Content-Type-Options header is an HTTP header that allows developers to specify that their content should not be MIME-sniffed. This header is designed to mitigate MIME-Sniffing attacks. For each page that could contain user controllable content, you must use the HTTP Header X-Content-Type-Options:nosniff. 

Add the below header in the web.config file if the application is hosted by Internet Information Services (IIS) 7 onwards.

<system.webServer>

   <httpProtocol>

     <customHeaders>

      <add name=»X-Content-Type-Options» value=»nosniff»/>

      </customHeaders>

    </httpProtocol>

</system.webServer>

Please refer to the Link to know more about this particular response header. 

The script and styleSheet elements will reject responses with incorrect MIME types if the server sends the response header «X-Content-Type-Options: nosniff». This is a security feature that helps prevent attacks based on MIME-type confusion. This is been explained in this article.

Recently, I was working on an issue where I was getting below error while calling AJAX functions. 

Refused to execute script from ‘http://localhost:8081/ajax/common.ashx’ because its MIME type (‘text/plain’) is not executable, and strict MIME type checking is enabled.
Sample.aspx:1 Refused to execute script from ‘http://localhost:8081/ajax/Ajax_Sample_.Sample,Ajax(Sample).ashx’ because its MIME type (‘text/plain’) is not executable, and strict MIME type checking is enabled.

I see the below code in my application. 

<script type="text/javascript" src="/ajax/common.ashx"></script><script type="text/javascript" src="/ajax/Ajax_Sample_.Sample,Ajax(Sample).ashx"></script>

It means that my application is expecting a javascript response from.ashx file but unfortunately, IIS sends the content-type “text/plain” response as it’s a default HTTP handler.  

As it would take some time to change the application code and deploy the code to IIS, I added an outbound URL rewrite rule in IIS as a workaround to fix the issue. Below are the steps followed. 

  • Download and install the URL rewrite module in IIS using https://www.iis.net/downloads/microsoft/url-rewrite
  • Add below outbound rule in web.config file inside <system.webServer> tag

  <rewrite>

            <outboundRules>

                <remove name=»Test» />

                <rule name=»Test»>

                    <match serverVariable=»RESPONSE_CONTENT_TYPE» pattern=»text/plain» />

                    <conditions>

                        <add input=»{REQUEST_URI}» pattern=».ashx» />

                    </conditions>

                    <action type=»Rewrite» value=»text/javascript» />

                </rule>

            </outboundRules>

        </rewrite>

Refer: https://docs.microsoft.com/en-us/iis/extensions/url-rewrite-module/creating-outbound-rules-for-url-r…

Note: This is just a workaround to resolve the issue but the permanent solution would be to to change the MIME type in your application code as per the requirement. 

Hope this helps :smiling_face_with_smiling_eyes:

Понравилась статья? Поделить с друзьями:
  • Как составить уравнение касательной неявно заданной функции
  • Как найти свою сберкнижку в сбербанке онлайн
  • Как найти объем когда известна плотность
  • Как найти каменщика в московской области
  • Как найти категорию риска предприятия