Skip to content

Content Security Policy support #93

Closed

Description

@benmccann

I don't see anything in the code related to CSP support, so I'm guessing that doesn't exist yet unless I missed it.

Sapper supports it via %sapper.cspnonce%: https://sapper.svelte.dev/docs#Content_Security_Policy_CSP

Activity

  1. added this to the 1.0 milestone on Oct 29, 2020
  2. acoyfellow commented on Mar 31, 2021

    @acoyfellow

    Hi - it looks like this (mostly) can be solved with hooks now, in the handle function.

    no nonce's yet but i'm working on it, maybe someone can see that solution

    https://gist.github.com/acoyfellow/d8e86979c66ebea25e1643594e38be73

  3. furudean commented on Mar 31, 2021

    @furudean
  4. seanlail commented on Apr 7, 2021

    @seanlail
    Contributor

    @acoyfellow Great work so far!

    I just want to highlight that it's really important that eval is not used in SvelteKit.
    Can we ensure that there is no unsafe use, as @dominikg has suggested.

    I've just been looking at an issue in Sapper here where the issue is that we have to allow unsafe-eval, which defeats the purpose of using CSP.

    cc/ @Conduitry (as we were talking about this in the other ticket).

  5. modified the milestones: 1.0, post-1.0 on May 1, 2021
  6. Rich-Harris commented on Aug 3, 2021

    @Rich-Harris
    Member

    Noting this, from Twitter:

    is there any way to move the inline script for SvelteKit to an external one? I’d like to enforce a stricter CSP, but currently need unsafe-inline to accommodate. Thanks!

    For server-rendered pages we could just use a nonce, I think? For pre-rendered pages that's no good, we would need to generate a hashed file (say /boot/xyz123.js) for each unique script.

  7. added
    p1-important
    on Aug 4, 2021
  8. Karlinator commented on Aug 14, 2021

    @Karlinator
    Contributor

    As far as I can see it's only the init script in the head, right? Nothing else is inline? Or does this depend on build configurations/adapters?

    In any case meta policies are allowed alongside HTTP policies. However, any source must pass all specified policies, meaning if you wanted to load scripts from a CDN it must be specified both places and the HTTP header must still send unsafe-inline. Basically, generating CSP in more than one place is kind of a mess.

    See: https://www.w3.org/TR/CSP3/#multiple-policies

    Putting the init script in a separate file is a much better option imo.

  9. pzuraq commented on Aug 14, 2021

    @pzuraq
    Contributor

    @Rich-Harris

    For pre-rendered pages that's no good, we would need to generate a hashed file (say /boot/xyz123.js) for each unique script.

    I think one of the advantages of nonces is that with them and strict-dynamic you can load arbitrary scripts (say, Google Analytics, or a some other source) and since they're trusted, they can load anything they need, without needing to allowlist them. This is helpful for scripts distributed and loaded via CDN where the hashes might change frequently, and reduces maintenance cost.

    I'm not an expert here, but I think if the page is guaranteed to be static, then a static nonce would also work and not pose a security risk. Alternatively, the pages could be build with a static, known nonce placeholder (ideally a build/deploy time secret) which could then be replaced on each request with a dynamic nonce. We've used this approach in our cloudflare workers app and it seems to be working pretty well so far.

  10. Karlinator commented on Aug 14, 2021

    @Karlinator
    Contributor

    @pzuraq Nonces must always be unique for each HTTP request. If you send the same one twice then an attacker can inject inline script with that nonce simply by checking the nonce themselves previously.

    Nonces also don't work for static hosts where you don't have the ability to generate them.

    Additionally, we have the problem described above that adding the nonce (or a hash) in a <meta> tag is hard to combine with a CSP set outside it (and is therefore hard to configure and use). If we set script-src nonce-randomString then any script-src policy defined in the HTTP header must include 'unsafe-inline'. If a resource fails either policy it will be blocked. I think this also means that any domains listed in the HTTP header must also be replicated.

    It'd be nice if CSPs were just combined additively, but according to the spec they're not.

    I think it would generally be a good idea to not rely on the adapters and/or runtime modification to avoid unsafe-inline. Moving the current inline script to a different file would work on all adapters without any extra work, and avoids adding any CSPs. If you need nonces to run Analytics you can still do that, but it doesn't seem like SvelteKit should need it honestly.

    Hashing the script would work, as it's all build-time (and therefore works for static as well), but we'd still need 'unsafe-inline' in any HTTP headers if we're adding it in a <meta> tag.

    Additionally, as discussed in #1776, using nonces and hashes don't work with manifest V3. It'd be a bit of a shame to not support writing browser extensions at all.

    The only downside to moving the script to an external file is in implementation. I've started looking at it (I'm writing an app that really should have a strict CSP), but I'm having a hard time figuring how to do it. Speaking of, if @benmccann or someone has a tip to how one could modify the page render pipeline to emit a script file I'm all ears. I've found the script itself in server/page/render.js, but I'm not sure how I would create a separate file and have it be served and stuff?

  11. pzuraq commented on Aug 14, 2021

    @pzuraq
    Contributor

    If you send the same one twice then an attacker can inject inline script with that nonce simply by checking the nonce themselves previously.

    Right, but that only works if the contents of the page itself are dynamic. If they are not, there is no way to attack, unless I'm missing something. The alternative that allows you to still use strict-dynamic and include external sources is to have a script dynamically add them inline and make that script safe with a hash: https://csp.withgoogle.com/docs/faq.html#static-content

    But that's unfortunate because the script has to start executing in order to begin loading all of the resources. Maybe it'll execute quickly enough that it wouldn't make a difference?

    Edit: I guess maybe you could MITM with a static nonce value?

  12. 27 remaining items

  13. Rich-Harris commented on Jan 21, 2022

    @Rich-Harris
    Member

    Thanks for the valuable feedback everyone. I think we're close to squaring all the various circles.

    Ideally I'd like to see a flag in config, based on which important (for performance) scripts and styles can be either inline or in external files. What do you think?

    Yeah, it probably makes sense for this to live in Kit rather than adapters having to jump through lots of hoops themselves. Something like this perhaps:

    // svelte.config.js
    export default {
      kit: {
        prerender: {
          externaliseScriptsAndStyles: true
        }
      }
    };

    That's something that could happen independently of the CSP work, even though it's motivated by it.

    One additional consideration would be supporting strict-dynamic

    Totally doable — at build time we can hash all the assets, and use the hashes at render time if 'strict-dynamic' is enabled:

    // svelte.config.js
    export default {
      kit: {
        csp: {
          directives: {
            'script-src': ['strict-dynamic']
          }
        }
      }
    };

    Some inspiration: https://github.com/josh-hemphill/csp-typed-directives

    Woah! This is very useful (I don't think I'd have been able to figure out how to get autocompletion for unsaf... while also supporting URLs etc).

    Agree re string[] rather than string | string[]. I think ['self'] is preferable to ["'self'"], even if it would be more 'correct' to do the pedantic thing — I don't think there's any real potential for ambiguity, and the author of csp-typed-directives appears to agree.

    Of course, by generating the hash at request time we are essentially bypassing that, making the function more or less identical with nonces, so really I think implementation concerns should decide here.

    To clarify, I was only proposing hashing the scripts that SvelteKit generates — not injecting hashes (or nonces, for that matter) in cases like this:

    <div class="comment">
      <p>someone forgot to escape user input <script>alert('lol')</script></p>
    </div>

    That would mean people were responsible for their own dynamic scripts (google analytics, etc), either by putting them in static and allowing self, or using strict-dynamic and a) generating the hash themselves, as suggested above, or b) creating the script dynamically when the app loads (right now that would probably happen in the root __layout, but we'll probably add a client-side equivalent of src/hooks.js at some point soon, where this sort of thing could happen).

    Then when we render dynamically we can use nonces instead.

    Yeah, I think this hybrid approach makes sense. Nonces for dynamic, hashes for static. And we could expose the nonce — %svelte.nonce% — for things like analytics snippets and external scripts with strict-dynamic, but disallow its usage during prerendering, perhaps.


    For posterity, I'm going to recap a discussion I had with @antony earlier since he raised a very reasonable question — rather than having Kit generate CSP headers based on config, what if it just gave you the tools you need to generate them yourself? For example this:

    <meta http-equiv="Content-Security-Policy" content="default-src 'self' %svelte.cspHashes% ">

    On the face of it this makes a lot of sense, since it allows Kit to get out of the way, and provides app authors with maximum flexibility. But after discussing it we concluded it probably wasn't the right direction:

    • headers are preferable to <meta http-equiv> in situations where you control them (i.e. not prerendering)
    • if using headers, we'd need to change the handle API and you'd need to implement a custom hook (and be careful to generate well-formed headers):
      const { response, hashes } = await resolve(request);
      if (hashes) { // only true for pages
       response.headers.set('content-security-policy': `script-src: ${hashes.script}`);
      }
    • prerendering would have to read the headers you'd generated in your custom hook, and inject them into the head using <meta http-equiv>. but this is tricky: normally the way to inject content into the head is to insert it right before </head, since otherwise you have to use brittle regexes, but with CSP the <meta> needs to go before your inline scripts and styles. So realistically we'd need to use cheerio or something to parse the HTML, which will slow prerendering down and make Kit heftier

    So there'd be a lot more hoop-jumping, for both authors and the framework, and you'd lose the benefits of typechecked directives etc. The result would be that way fewer people would end up enabling CSP, unless someone made them do it. All in all it feels like this is one of those places where it makes sense for the framework to step in and say 'I got this'.

  14. pzuraq commented on Jan 21, 2022

    @pzuraq
    Contributor

    Yeah, I think this hybrid approach makes sense. Nonces for dynamic, hashes for static. And we could expose the nonce — %svelte.nonce% — for things like analytics snippets and external scripts with strict-dynamic, but disallow its usage during prerendering, perhaps.

    @Rich-Harris Would this be optional, to allow people to choose between using hashes or nonces based on what makes more sense to their setup? I think we would prefer hashes for the reasons I mentioned above, would help us cache our responses more aggressively and not need to rerender just to update the nonce.

  15. Rich-Harris commented on Jan 21, 2022

    @Rich-Harris
    Member

    Yeah, perhaps we could have an option like this, where 'auto' is the default

    // svelte.config.js
    export default {
      kit: {
        csp: {
          mode: 'hash' // or 'nonce' or 'auto', meaning 'hash' for prerendered and 'nonce' for dynamic
        }
      }
    };
  16. Karlinator commented on Jan 21, 2022

    @Karlinator
    Contributor

    To clarify, I was only proposing hashing the scripts that SvelteKit generates — not injecting hashes (or nonces, for that matter) in cases like this:

    Absolutely! I was just saying the (admittedly minor) security differences between hashes and nonces kind of disappear for us. If you can compromise a nonced init script in Kit then you could do the same for a hashed script (though both would be difficult), when with only compile-time hashes you have a slight advantage.

    On hashes for external scripts: This is a feature of CSP 3, and annoyingly not yet implemented in Firefox. That's a bit of a bummer. As far as I can tell other browsers support this. This is problematic for using hashes generated at compile time to allow our static scripts, which is otherwise an idea I really like. I'm not sure how much we should let this affect us though, since this is Firefox simply not being in line with spec and is likely to be fixed at some point.

    And we could expose the nonce — %svelte.nonce% — for things like analytics snippets and external scripts with strict-dynamic, but disallow its usage during prerendering, perhaps.

    We would need to be careful about this, no? As @pzuraq mentions this can be a target for attacking the SSR, and we don't want this to get through:

    <div class="comment">
      <p>someone forgot to escape user input <script nonce="%svelte.nonce%">alert('lol')</script></p>
    </div>

    I forget exactly how Kit's render pipeline works, but I imagine we can search for this string in, say, only the static app.html before any other content is added?


    Suggestion so far (in auto mode):

    1. Kit builds all the static files, hashes them, and stores the hashes somewhere (manifest?)
    2. The adapter calls prerender. Kit renders the files, hashes the inline scripts, adds those to the manifest. All script links are given integrity attributes (required for hashes of external scripts to work)
    3. Runtime. If Kit serves a response from the prerender cache, it sends with the hash headers relevant (that page and relevant assets). If instead it renders the page, it works mostly like in my PR (adapter gives a nonce, inserted into all script tags).

    In nonce mode it would ignore hashes completely (basically my PR). In hash mode I guess it would dynamically hash the contents when rendering? Insert integrity attributes like during prerendering, hash the inline script, and send CSP headers with hashes.

    Do we hash/nonce all scripts even if we're not in sctrict-dynamic? I don't think it can hurt, and it saves us from another toggle.

  17. Karlinator commented on Jan 21, 2022

    @Karlinator
    Contributor

    Wait, I left out kit.externaliseScriptsAndStyles from that. That would only have effect during prerendering I think (we've discussed at length here how that's almost impossible to combine with SSR), and would cause the prerender to return separate html and js file which can be placed somewhere. Some predictable url is needed, which Kit can insert into the html at render and then later serve the JS file from. Anything rendered at runtime basically ignore this.

  18. pzuraq commented on Jan 21, 2022

    @pzuraq
    Contributor

    We would need to be careful about this, no? As @pzuraq mentions this can be a target for attacking the SSR, and we don't want this to get through:

    My understanding was that %svelte.nonce% would only be replaced in sections of the code that are known to be safe, e.g. before user content that has been SSR'd is inserted. That's a fine setup, because there's no user content added before the replacement.

    The problem comes if we want to cache the entire response, so we don't need to enter into SSR in the first place. When caching the response, we lose context so there's no way to tell which parts of the response are "safe" to replace in and which are not. Responses could potentially be cached in parts to avoid this, maybe even the nonce placeholder could be cached as part of the response and generated uniquely for each response 🤔 but that could be platform specific. Cloudflare uses the Cache API to cache responses, and it expects a full Response object, so you'd have to like, store this info in a header or something like that.

  19. Karlinator commented on Jan 21, 2022

    @Karlinator
    Contributor

    My understanding was that %svelte.nonce% would only be replaced in sections of the code that are known to be safe, e.g. before user content that has been SSR'd is inserted. That's a fine setup, because there's no user content added before the replacement.

    Yeah, that was my assumption too, just wanted to make it explicit.

  20. Rich-Harris commented on Jan 21, 2022

    @Rich-Harris
    Member

    %svelte.nonce% in rendered content wouldn't be replaced, because in production no string replacement happens. But I opened #3490 anyway because I'm a completionist

  21. pzuraq commented on Jan 22, 2022

    @pzuraq
    Contributor

    Thought I'd mention something that just popped up in the Discord that's a bit related. Currently, we have a few places where we need to use dynamic styles in our templates, as things like the background color of certain elements are theme-able. This currently does not work with our CSP, as we do not allow unsafe-inline for styles, so there's a brief pop-in flash as the page rerenders from JS taking over, at which point the styles are set via a trusted script and render properly.

    Not sure what the best way to solve this would be, and it's definitely an edge case so it doesn't necessarily have to be in the first pass. I believe style attributes can also be hashed, so maybe there could be a way for a user to indicate that a certain style tag should be hashed and included?

  22. Karlinator commented on Jan 22, 2022

    @Karlinator
    Contributor

    @pzuraq That seems like it touches on both Kit and Svelte itself, no? Svelte is responsible for generating those inline styles (this is one annoyance of CSP, that it often requires passing a nonce or a hash all the way through an application stack from "the thing that generates CSS" to "the thing that sets HTTP headers").

    Anyways, this is controlled by the style-src-attr directive, and allows hashing if you also specify unsafe-hashes. Noncing is not available for attribute styling. I'm not sure if I like adding unsafe-hashes (though I think it isn't as unsafe as the name implies).

  23. pzuraq commented on Jan 22, 2022

    @pzuraq
    Contributor

    Yeah, agreed re: unsafe-hashes. Another option would be to somehow allow SvelteKit to generate a stylesheet or style tag dynamically, and generate the hash for that. Will have to think about what would be the best way to do that.

  24. Rich-Harris commented on Jan 26, 2022

    @Rich-Harris
    Member

    Closed via #3499. Opened #3555, #3556, #3557 and #3558 to track follow-up tasks. I'm not going to be working on CSP stuff in the near term, so if anyone needs these and is up for a PR then please feel welcome!

  25. benmccann commented on Feb 26, 2022

    @benmccann
    MemberAuthor
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    p1-importantsecurity

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions