Search code examples
securityhttphttpshttp-headerscontent-security-policy

Can I use CSP to limit requests to both https: AND 'self'?


I originally had this in my CSP header: default-src 'self';, which limits sources to only my domain, but it says nothing about the scheme/protocol. From what I can gather, this will allow sources to be loaded over http if the page itself was loaded over http. I'm using HSTS and CDN redirects to try to keep all traffic on https, but I want to cover this case off anyway. (In truth, I'm trying to make this header checker give me all green ticks.) Edit: srcclr will happily give all green ticks when using 'self'. I just had to fix some typos.

Anyway, I tried changing the CSP directive to be default-src https: 'self';, but it would seem that adding the scheme allows resources to be loaded from any domain, as long as it's over https. I.e, if either of the rules (https or 'self') matches, then the request is allowed. I tested this by playing around with URLs in the chrome dev tools.

Is there a way to indicate:

  1. All resources should be loaded over https; AND
  2. Resources should only come from the original domain?

Something like default-src https://'self';, but I don't think that's valid, is it?

One solution is to hardcode the domain name, but I'd like to use 'self' if it's possible.


Solution

  • According to https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/Sources, the 'self' content source keyword:

    Refers to the origin from which the protected document is being served, including the same URL scheme and port number.

    If you serve the web page over https, then self only allow https request to the same domain.

    The CSP2 specification http://www.w3.org/TR/CSP2/#match-source-expression says the same thing:

    If the source expression is a case insensitive match for 'self' (including the quotation marks), then:

    Return does match if the origin of url matches the origin of protected resource’s URL.