Search code examples
c#wcfsslhsts

SSL error on implementing HSTS


I'm trying to implement HSTS on my website(eg. www.example.com) which has been moved from http to https recently, and is at the default port. And I have a WCF Service running at the same domain but different port(eg. www.example.com:8000).

What I've tried doing is adding the following code in the Web.config file

<system.webServer>
    <httpProtocol>
        <customHeaders>
            <add name="Strict-Transport-Security" value="max-age=31536000"/>
        </customHeaders>
    </httpProtocol>
</system.webServer>

And then later I tried this code from here (because it said above implementation was incorrect)

<system.webServer>
    <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>
</system.webServer>

My website at www.example.com works fine. But once I access www.example.com, the response header Strict-Transport-Security get cached, and then trying to access the WCF service page redirects to https causing 'SSL Error' as the service is running on 8000 port.

Note: Clearing the cache and accessing the same service page shows the page.

How do I stop redirecting calls made on port 8000 to https?


Solution

  • HSTS applies to all HTTP calls on the domain and not just those on port 80.

    From the rfc:

    The UA MUST replace the URI scheme with "https" [RFC2818], and

    if the URI contains an explicit port component of "80", then the UA MUST convert the port component to be "443", or

    if the URI contains an explicit port component that is not equal to "80", the port component value MUST be preserved; otherwise,

    if the URI does not contain an explicit port component, the UA MUST NOT add one.

    NOTE: These steps ensure that the HSTS Policy applies to HTTP over any TCP port of an HSTS Host.

    So you need to do one of the following:

    1. Switch your WCF service to https too.
    2. Switch the domain for your WCF service so it is not affected by your HSTS policy.
    3. Stop using HSTS.