Thursday 20 October 2016

Setting HTTP Strict Transport Security (HSTS) in ASP.NET Application

Setting HSTS on a website application is one way to avoid Man in the Middle attack which modifies server response to use insecure connection to gain user information.
One online tool that can be used to check whether our website has HSTS or not is https://www.ssllabs.com/ssltest . If on the report, it shows that:
'Strict Transport Security (HSTS) : No'
then it means that it is not set.

To set HSTS in web.config file, add these configurations below inside <system.webServer> node:
<rewrite>
 <rules>
  <rule name="HTTP to HTTPS redirect" stopProcessing="true">
   <match url="(.*)" />
   <conditions>
    <add input="{HTTPS}" pattern="off" ignoreCase="true" />
   </conditions>
   <action type="Redirect" url="https://{HTTP_HOST}/{R:1}"
    redirectType="Permanent" />
  </rule>
 </rules>
 <outboundRules>
  <rule name="Add Strict-Transport-Security when HTTPS" enabled="true">
   <match serverVariable="RESPONSE_Strict_Transport_Security"
    pattern=".*" />
   <conditions>
    <add input="{HTTPS}" pattern="on" ignoreCase="true" />
   </conditions>
   <action type="Rewrite" value="max-age=31536000" />
  </rule>
 </outboundRules>
</rewrite>

However if we do not have URL Rewrite module installed in IIS, we will have a 500 internal server error. This is because IIS does not understand <rewrite> node in the codes.

We can download URL Rewrite module from https://www.iis.net/downloads/microsoft/url-rewrite


References:
http://www.hanselman.com/blog/HowToEnableHTTPStrictTransportSecurityHSTSInIIS7.aspx
http://serverfault.com/questions/417173/enable-http-strict-transport-security-hsts-in-iis-7/629594
https://www.tbs-certificates.co.uk/FAQ/en/hsts-iis.html
https://www.iis.net/learn/extensions/url-rewrite-module/creating-rewrite-rules-for-the-url-rewrite-module