by simonw · 7mo ago · 0 comments
A useful thing I learned recently is that, while CSP headers are usually set using HTTP headers, you can also reliably set them directly in HTML - for example for HTML generated directly on a page where HTTP headers don't come into play:
<iframe sandbox="allow-scripts" srcdoc="
<meta http-equiv='Content-Security-Policy'
content='default-src none; script-src unsafe-inline; style-src unsafe-inline;'>
<!-- untrusted content here -->
"></iframe>
It feels like this shouldn't work, because JavaScript in the untrusted content could use the DOM to delete or alter that meta tag... but it turns out all modern browsers specifically lock that down, treating those CSP rules as permanent as soon as that meta tag has loaded before any malicious code has the chance to subvert them.I had Claude Code run some experiments to help demonstrate this a few weeks ago: https://github.com/simonw/research/tree/main/test-csp-iframe...
This should be in addition to heavily restricting CSP on user content. (Hmm, surely all images should be served with the CSP header set.)
A better approach here would be to just serve svg with Content-security-policy: script-src 'none'; sandbox
I suppose an actual exception is Content-Disposition. If you want the user to save a file, you need to serve it with dest == document as far as I know.
I've been just using plain typescript/html and it's so easy to say "yeah all of that rendered content goes into an iframe", I've got all of d3 entirely sandboxed away with a strict CSP and no origin.
I do hope that iframe sandboxing grows some new primitives. It's still quite hacky - null origins suck and I want a virtual/sandbox origin primitive as well as better messaging primitives.
For something like this that's security critical I'd really like to see each of the browser vendors publishing detailed, trustworthy documentation about their implementations.
The technology itself is very widely deployed due to banner ads, so it's at least thoroughly exercised.
Right now if I want to render untrusted content and if I use React I have to escape from using React to leverage this, using https://react.dev/reference/react-dom/server/renderToString
And using null origins has tons of UX problems - virtual / sandbox origins would solve this. https://gist.github.com/ddworken/309363b5d140bcc5ff6b39fa4a8...
There's just a lot more work to do before I expect to see this. It would solve so many problems though. I personally put d3, markdown rendering, etc, all into iframe sandboxes, which means the entire library could be malicious and it won't matter. But it requires way more effort than I'd like.
But for all my self righteous bluster the inline version was news to me. Hacker news. Awesome. Thank you.