How to ensure that your script runs first in a webpage

David Bruant bruant.d at gmail.com
Wed Feb 1 14:41:26 PST 2012


Hi,

I have claimed here a couple of times, that in a JavaScript application
containing code from different parties, the first to run is the one that
is in position to make decisions about security of the overall
application (freezing the primordials for a defender or monkey-patching
them if you're an attacker). I still have no proof (I feel it's coming
though) about it, but a strong intuition.

Assuming this is true, then, on the web, one has to make sure that her
protecting script runs first. How to ensure this, though? There is
always a risk that with an XSS an attacker scripts runs before the
protecting one.
I think I have found an answer and it is: with Content Security Policy
(CSP) [1].

CSP introduces a "script-src" directive [2] allowing only a whitelist of
script URLs to be "fetchable" as script at src. Moreover, by default,
inline scripts (in scripts or as on* attributes) won't execute.

Consequently, in browsers that support the script-src CSP directive
(script whitelisting even reduced to one element and the "If
'unsafe-inline' is not in allowed script sources" rule), one can enforce
running her script first.
The restriction is even stronger, because the whitelisted script is just
the only one to run.

It has to be noted that it does not limit the scripts that /can/ be run
on the page since the unique script can still download other scripts and
eval them. If a raw eval sounds too unsafe, you can embed in your unique
script a JavaScript rewriter [3] ;-)

Browser support: Firefox 4+, Webkit-based browsers, IE10.

David

[1]
https://dvcs.w3.org/hg/content-security-policy/raw-file/tip/csp-specification.dev.html
[2]
https://dvcs.w3.org/hg/content-security-policy/raw-file/tip/csp-specification.dev.html#script-src
[3] http://code.google.com/p/google-caja/


More information about the es-discuss mailing list