w3c / webappsec-csp

WebAppSec Content Security Policy
https://w3c.github.io/webappsec-csp/
Other
209 stars 78 forks source link

Does `strict-dynamic` allow dynamically adding inline scripts? #426

Open bakkot opened 4 years ago

bakkot commented 4 years ago

For example, if I have

<script nonce="asdf">
x = document.createElement('script');
x.textContent = 'console.log(0)';
document.head.appendChild(x);
</script>

on a page with a CSP of script-src 'strict-dynamic' 'nonce-asdf', does it log 0 or not?

As best I can tell, the CSP spec says no. In particular,

(Does element match source list for type and source? makes no mention of strict-dynamic except to turn off unsafe-inline.)

But Firefox and Chrome both allow it. (Safari does not support strict-dynamic at all.)

The section on the usage of strict-dynamic is not helpful; it says that "Script requests which are triggered by non-"parser-inserted" script elements are allowed", which implies it only applies to external scripts, but also says "scripts created at runtime will be allowed to execute", which implies it would apply to inline ones as well.

arturjanc commented 4 years ago

The intent is definitely for 'strict-dynamic' to allow the execution of inline scripts added via programmatic APIs, such as createElement (which don't set the parser-inserted flag on the script).

This could possibly be a bug in the spec text, unless @mikewest says otherwise :)

mikewest commented 4 years ago

The intent is, as @arturjanc suggests, to allow this snippet to cause script execution. I'm pretty sure we've locked that in with tests (and implementations), but I can totally believe I screwed up the specification. I expect I intended to add something like step 1.4 of https://w3c.github.io/webappsec-csp/#script-pre-request to the https://w3c.github.io/webappsec-csp/#match-element-to-source-list algorithm. You're correct that the spec, as written, doesn't do what I expect it to do.

bakkot commented 4 years ago

@mikewest Since I can't refer to the spec on this point: is the intent also to allow dynamically inserted inline styles? (Created with createElement, not document.write.)

arturjanc commented 4 years ago

No, 'strict-dynamic' applies only to scripts and there is no equivalent for styles. It wouldn't be unreasonable to implement something similar for styles (it could help with resources loaded by stylesheets with an @import), but it would be a new feature request for CSP.