Categories: Security

A Faster Content Security Policy (CSP)

With the establishment of CSP Level 2, Mozilla shifted gears and reimplemented CSP in C++. This security feature first shipped in Firefox 4 (2011), and until now was implemented in a combination of JavaScript and C++. The new implementation is based solely on C++ and without the need to connect two languages, which increases performance and simplifies the implementation. This allows us faster turnaround when deploying new features established by future layers of the CSP standard.

We’re thrilled to report that CSP in Firefox now works faster than ever.

Performance measurements:
We measured performance with a standard consumer laptop: we ran all csp mochitests in our testsuite (content/base/test/csp/) on a 2.5 GHz Intel Core i5 MacBook Pro with 8 GB RAM running Mac OS X 10.9.4 and an optimized build of Firefox (like the releases). In addition, we run the testsuite using nice -n -20 to minimize operating system scheduler effects. We performed 10 repetitions for each test to get stable results and report the geometric mean of these repetitions to remove outliers.

The three operations we tested were “APPENDPOLICY” (how long it takes to set a CSP for a site), “SHOULDLOAD” (how long it takes to check each requested resource for CSP compliance) and “ALLOWS” (how long it takes to check each inline script or stylesheet computation for CSP compliance).

Operation OLD CSP time (ms) NEW CSP time (ms) Improvement factor
APPENDPOLICY 1.0942 0.0704 15.54x
SHOULDLOAD 0.5081 0.0220 23.09x
ALLOWS 0.0767 0.0178 4.30x

Example:
Consider a hypothetical site with an active CSP, ten resource loads (images, script files, etc), and three inline scripts. That’s one APPENDPOLICY, ten SHOULDLOADs, and three ALLOW calls. The old implementation of CSP would spend 1.0942ms in APPENDPOLICY, 5.081ms in SHOULDLOAD and 0.2301ms in ALLOWS, or 6.4053ms time in CSP. The same page with our new implementation would spend about 0.3438ms in CSP, which is about a 95% speedup.

Because most sites load many resources, SHOULDLOAD performance is critical. While each site may trigger APPENDPOLICY once, the SHOULDLOAD code path is triggered for all images and external file loads that the site performs and is especially critical on sites with CSS image widgets, backgrounds, custom bullets, and more complicated graphics. Our tests show that the biggest improvement happens with SHOULDLOAD, suggesting this reimplementation targeted the most critical part of page execution performance.

What’s next:
We have seen CSP gradually adopted as a useful security tool on Web pages and we will continue working in the W3C to simplify usage and make CSP more powerful. We believe CSP has the potential to provide an even greater security benefit once adopted by more of the Web.

Christoph Kerschbaumer & Sid Stamm
Mozilla Security Engineering