Disallowing unneeded HTTP headers for non-HTML resources - iis

The Sonar test suite makes the interesting point that it should be considered bad practice to send the HTTP headers
Content-Security-Policy
X-Content-Security-Policy
X-Frame-Options
X-UA-Compatible
X-WebKit-CSP
X-XSS-Protection
when sending non-HTML resources.
I currently configure my IIS server using web.config, namely
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Content-Security-Policy" value="default-src 'self' ; img-src 'self' data:; script-src 'self' cdnjs.cloudflare.com/ajax/libs/html5shiv/" />
<add name="X-Frame-Options" value="DENY" />
<add name="X-Content-Type-Options" value="nosniff" />
<add name="X-Permitted-Cross-Domain-Policies" value="none" />
<add name="X-UA-Compatible" value="IE=edge" />
<add name="X-Xss-Protection" value="1; mode=block" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
But that configuration sends those headers no matter the type of the resource send.
How to make IIS selectively add those headers to the right types of files?

You can use the IIS UrlRewrite module (an IIS extension) and add a custom headers only for html resources.
Check this old question.

Related

IIS Authentication Tab doesn't open on double click

This is the operation i'm doing:
Open IIS Console
Select the Website
Double click at Authentication Icon
When I click this error occurs, only at that site (I have many sites configured, and this is the only one that I'm getting this error)
And then the panel show me that, and don't let me change the Authentication type. I need to Allow Anonimous Authentication, but I can't because of this error.
When I click Enable or Edit, the same pop-up error came up.
And also, when I try to access the website in any browser, I get this message:
My web.config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="dotnet" arguments=".\IdentityServer.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="true" startupTimeLimit="3600" requestTimeout="23:00:00" hostingModel="InProcess">
<environmentVariables>
<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
<environmentVariable name="COMPLUS_ForceENC" value="1" />
<environmentVariable name="ASPNETCORE_HTTPS_PORT" value="44339" />
</environmentVariables>
</aspNetCore>
<security>
<requestFiltering>
<verbs>
<add verb="PUT" allowed="true" />
<add verb="DELETE" allowed="true" />
</verbs>
<requestLimits maxQueryString="4096" />
</requestFiltering>
</security>
<modules runAllManagedModulesForAllRequests="false">
<remove name="WebDAVModule" />
</modules>
<httpProtocol>
<customHeaders>
<remove name="X-Xss-Protection" />
<!--<add name="X-Xss-Protection" value="1; mode=block" />
<add name="X-Content-Type-Options" value="nosniff" />
<add name="Content-Security-Policy" value="script-src 'self' h.online-metrix.net 'unsafe-inline' 'unsafe-eval'; object-src 'self' h.online-metrix.net; frame-src 'self' h.online-metrix.net; default-src 'self' h.online-metrix.net;" />-->
</customHeaders>
</httpProtocol>
</system.webServer>
<system.web>
<httpCookies httpOnlyCookies="true" requireSSL="true" />
</system.web>
</configuration>
<!--ProjectGuid: 3ACFC0B0-4FDD-4549-AFBD-C3FF653F5886-->
Thanks in advance for any help

Cache-control headers not added on azure linux app service

I host an angular frontend inside an Azure App Service on Linux. Stack is Node 12.
In order to enable the response headers "Cache-Control" for the static files I have added the line
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="3.00:00:00" />
inside the Web.config file as suggested in the microsoft documentation here
The Web.config file looks like this:
<configuration>
<system.webServer>
<handlers>
<clear />
<add
name="StaticFile"
path="*" verb="*"
modules="StaticFileModule,DefaultDocumentModule,DirectoryListingModule"
resourceType="Either"
requireAccess="Read" />
</handlers>
<staticContent>
<mimeMap fileExtension=".json" mimeType="application/json" />
<mimeMap fileExtension=".*" mimeType="application/octet-stream" />
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="3.00:00:00" />
</staticContent>
<rewrite>
<rules>
<rule name="redirect all requests" stopProcessing="true">
<match url="^(.*)$" ignoreCase="false" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" pattern="" ignoreCase="false" />
</conditions>
<action type="Rewrite" url="index.html" appendQueryString="true" />
</rule>
</rules>
</rewrite>
</system.webServer>
Unfortunately the headers are not set correctly. Is there something wrong with the Web.config file? Does the Azure App Service on Linux have to do something with it?
The web.config file is only for IIS configuration system, but IIS is not for Linux.
So you could not set the cache-control header in web.config file.
If you have entity instance for Linux, you could use Apache .htaccess file:
<IfModule mod_headers.c>
Header set Cache-Control "no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires 0
</IfModule>
If you don't have entity instance for Linux, you could set the header in code:
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
response.setHeader("Expires", "0"); // Proxies.
I have tried using .htaccess file on Azure, but it did not work as Azure is a PaaS, which did not include a entity instance.

Setting up CORS in web.config (IIS) for non .NET app

I'm trying to allow CORS over a site, using the IIS CORS module (https://www.iis.net/downloads/microsoft/iis-cors-module), but I'm having troubles.
This is my web.config:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<cors enabled="true" failUnlistedOrigins="true">
<add origin="https://my.site" allowCredentials="false" maxAge="120">
<allowHeaders allowAllRequestedHeaders="true"></allowHeaders>
<allowMethods>
<add method="GET" />
<add method="POST" />
<add method="PUT" />
</allowMethods>
</add>
</cors>
</system.webServer>
</configuration>
with this setup, the OPTIONS (pre-flight) request works fine, but any further request (GET, POST) raise a browser exception because of missing Access-Control-Allow-Origin
I tryed to add the following to web.config:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="https:/my.site" />
</customHeaders>
</httpProtocol>
but in this way the OPTIONS fails because there're 2 instances of Access-Control-Allow-Origin
Using only custom header the pre-flight fails with code 500 (I think IIS doesn't support OPTIONS method without the CORS module).
IIS CORS module documentation is very poor and googling I only find info related to .NET code, but it's not my case. I can't modify code (and it's not .NET), I need to act on IIS.
How can I make IIS respond properly to CORS requests ?
From the code you have posted, it looks like you have not added your origin correctly.
The origin line should contain a (Fully Qualified Domain Name) FQDN or some regex that matches it.
A correct line would look like:
<add origin="https://my.site.com" allowCredentials="false" maxAge="120">
You can allow subdomains of your domain using:
<add origin="https://*.site.com" allowCredentials="false" maxAge="120">
From the sounds of it, you aren't receiving the headers you want back from the web server. This may be due to the webserver Only returning CORS safe headers.
Using the IIS CORS Blog from Microsoft, I've added in config that will expose the headers back in the request.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<cors enabled="true" failUnlistedOrigins="true">
<add origin="https://my.site" allowCredentials="false" maxAge="120">
<allowHeaders allowAllRequestedHeaders="true">
<add header="DNT" />
<add header="Host" />
<add header="Origin" />
<add header="Referrer" />
<add header="User-Agent" />
</allowHeaders>
<allowMethods>
<add method="GET" />
<add method="POST" />
<add method="PUT" />
</allowMethods>
<exposeHeaders>
<add header="DNT" />
<add header="Host" />
<add header="Origin" />
<add header="Referrer" />
<add header="User-Agent" />
</exposeHeaders>
</add>
</cors>
</system.webServer>
</configuration>
However, according to This CORS documentation OPTIONS requests don't get the Allow Headers or Expose Headers configuration applied to them. Hopefully that's not the issue here though.
Below I've added the most basic CORS request I can think of. If this request works, then it may be a client side problem you are encountering.
fetch('example.com', {
method: 'GET',
mode: 'cors',
credentials: 'include',
headers: { 'Authorization': authString }
}).then(
response => response.json()
); // parses JSON response into native JavaScript objects

web.config set headers for all html files

I want to set no cache headers for all html files in my project. I know how to do it for a specific file:
<location path="index.html">
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Cache-Control" value="no-cache, no-store, must-revalidate" />
<add name="Pragma" value="no-cache" />
<add name="Expires" value="0" />
</customHeaders>
</httpProtocol>
</system.webServer>
</location>
But how can I use it like a wildcard to target all html files?
Wildcard is not an option I'm afraid.
You may want to consider setting this from your Startup.cs instead:
app.Use((context, next) =>
{
context.Response.Headers[HeaderNames.CacheControl] = "no-cache, no-store, must-revalidate";
context.Response.Headers[HeaderNames.Expires] = "0";
context.Response.Headers[HeaderNames.Pragma] = "no-cache";
return next();
});
This is the ASP.Net core v3 example, see this gold star answer for more details and examples for any environment you can imagine: How do we control web page caching, across all browsers?

Remove cache HTTP response headers from Web Api in Azure

I am trying to remove unwanted Cache-Control, Pragma and Expires HTTP headers in responses from a Web Api 2 project hosted on an Azure website in Standard mode.
I have tried the following in Global.asax Application_PreSendRequestHeaders:
var headers = ((HttpApplication)sender).Context.Response.Headers;
headers.Remove("Cache-Control");
headers.Remove("Pragma");
headers.Remove("Expires");
This works when debugging in Visual Studio. But on Azure, the headers are only removed for GET requests and not HEAD or POST requests.
Grateful for any suggestions!
Azure Web Sites supports the request filtering module, so you can do this in your web.config:
<system.webServer>
<httpProtocol>
<customHeaders>
<remove name="Cache-Control" />
<remove name="Pragma" />
<remove name="Expires" />
</customHeaders>
</httpProtocol>
</system.webServer>
Disclaimer: I am not condoning the removal of these headers, which are an essential part of the HTTP protocol.
Removing cache headers says to clients "it is entirely up to you to decide how to cache this response", which may result in odd and hard-to-reproduce errors in production. If you want to disable caching, you should set these headers to values which explicitly disable caching:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Cache-Control" value="no-cache" />
<add name="Pragma" value="no-cache" />
<add name="Expires" value="-1" />
</customHeaders>
</httpProtocol>
</system.webServer>

Resources