Search code examples
iisheadercontent-security-policyiis-10

IIS set header with url rewrite for 3xx response


after a pentest, they found that

The web server does not provide the Content-Security-Policy header on HTTP responses with status code belonging to the 4xx class and on HTTP responses with status codes belonging to the 3xx class for subpaths of the following URLs:

For the 4xx i had create a custom page and set IIS to use it in case, but for the 3xx i dont know how to use the url rewrite, i look on SO and on web but not found a working solution, someone can help me giving an example? Thanks in advance


Solution

  • Here’s an approach you can take:

    1. Ensure the CustomHeaders module is enabled in IIS. If not, you can enable it in the IIS Manager by going to the server’s Features and enabling the HTTP Response Headers feature.

    2. Modify the web.config file to add the necessary rules and headers.

    Here's an example of how to configure the web.config:

    <configuration>
     <system.webServer>
       <rewrite>
        <rules>
          <rule name="Rewrite 3xx Responses" stopProcessing="true">
            <match url=".*" />
              <conditions>
               <add input="{RESPONSE_STATUS}" pattern="^3\d\d$" />
              </conditions>
             <action type="Rewrite" url="{R:0}" />
           </rule>
         </rules>
      </rewrite>
    
      <!-- Custom Headers for 3xx Responses -->
      <httpProtocol>
        <customHeaders>
          <add name="Content-Security-Policy" value="default-src 'self';" />
        </customHeaders>
      </httpProtocol>
     </system.webServer>
    </configuration>
    

    The URL Rewrite rule matches all URLs (url=".*") and applies only if the response status code is in the 3xx range (using pattern="^3\d\d$"). the Rewrite action rewrites the URL, ensuring that the rule is applied and processed.the customHeaders section ensures that the Content-Security-Policy header is added to all responses, including 3xx.

    The Rewrite action doesn't change the URL but ensures that the rule is processed. the Content-Security-Policy header is applied globally here, so it will be present in both 2xx and 3xx responses.