Skip to main content
Ben Nadel at the jQuery Conference 2010 (Boston, MA) with: Stephen Tang
Ben Nadel at the jQuery Conference 2010 (Boston, MA) with: Stephen Tang

Reviewing My Content Security Policy (CSP) After The Optimizely Hack

By
Published in

Earlier this week, Optimizely — a popular web experimentation script — was compromised and started embedding malicious code in close to 200 prime-time websites. I don't use Optimizely personally; but when I was at InVision, we used Optimizely on several different web properties for years. So this hit close to home for me. None of my sites were compromised; but it felt much more like luck of the draw than it did like preparedness. As such, I'm trying to learn from this hack in an effort to help guard myself against future, similar attacks.

Over the summer, I wrote about how I still manually code all my personal projects despite using AI all day at work. I'm not anti-AI — I just treat my personal projects as a "brain teaser". That said, I still use AI to help me do research and to perform adversarial reviews of my code. In fact, it was an adversarial review that raised Apple's Intelligent Tracking Prevention (ITP) in yesterday's theme picker write-up.

So when the Optimizely hack happened, I asked Claude Code to research the malicious vector and then review my site's Content Security Policy (CSP) to see where it might be hardened:

(In Claude Code): Earlier this week, Optimizely was hacked and started embedding malicious scripts. See this article for more detail. Do some web research to see what attack vectors were used. Then look at my @ContentSecurityPolicy.cfc to find gaps in my implementation. Do not change the code - just present me with the findings so we can discuss.

My Content Security Policy was already in pretty good shape. But Claude Code found several places it could be improved.

Narrow the script-src Directive

I removed the 'strict-dynamic' aspect of this directive, making it nonce-only. The 'strict-dynamic' value means that the host site grants implicit trust to all scripts loaded by an explicitly trusted script. In this case, Optimizely was the explicitly trusted script that then loaded the implicitly trusted malicious code.

To be clear though, this change is relatively cosmetic. This change blocks the way the Optimizely hack happened to work. But if the malicious actor had just embedded the malicious code directly inside the Optimizely script instead of loading it from a remote domain, the 'strict-dynamic' removal wouldn't have mattered.

Once an embedded script is compromised, there's little we can really do to stop it; we can only hope to limit the damage, which is where the other directives come into play.

Add the connect-src Directive

Part of how the Optimizely hack worked is that the malicious code captured sensitive user information (credit cards, cookies, screenshots) and then sent that data to an external site using features such as the sendBeacon API. The connect-src directive creates an explicit list of trusted domains that the browser can connect to when using various APIs (such as sendBeacon, fetch(), XMLHttpRequest, and WebSockets). I created a small list of domains that I know my site connects to.

To be clear though, this change is only a partial fix — it closes one exfiltration path, but not all of them. There are still other ways to send data to a remote host such as through a dynamically constructed new Image().src URL or an iframe URL (see the next section on frame-src). Again, this would have only prevented part of the way that the Optimizely hack happened to work.

Add the frame-src Directive

The frame-src directive creates an explicit list of trusted domains that can be used in an embedded iframe. For example, my list includes Vimeo and YouTube, which is how I embed video players; as well as Apple and RedCircle, which is how I embed podcast players. Allow-listing iframe sources helps to prevent data exfiltration through the src attribute; and helps to prevent malicious user interfaces from being rendered.

My Current Content Security Policy

Here's a truncated look at my now current ContentSecurityPolicy.cfc ColdFusion component. I've omitted the code that deals with reporting of violations since this write-up is primarily concerned with the policy directives.

component {

	// Define properties for dependency-injection.
	property name="config" ioc:type="config";
	property name="router" ioc:type="core.lib.web.Router";
	property name="secureRandom" ioc:type="core.lib.util.SecureRandom";

	// ColdFusion language extensions (global functions).
	include "/core/cfmlx.cfm";

	// ---
	// PUBLIC METHODS.
	// ---

	/**
	* I return the Content Security Policy (CSP) configuration, including the inline
	* nonce and the relevant HTTP Headers.
	*/
	public struct function getCspConfig() {

		// When CSP violations are blocked by the browser, the browser will (eventually)
		// report those violations to this end-point.
		var reportToUrl = router.externalUrlForParts( "api.csp.report" );
		// The nonce (N-once) is a unique value that is generated fresh for each page
		// request. It's then included in the CSP header and must match "nonce" attributes
		// in scripts tags as a means to denote the script tags as trusted. You can think
		// of it kind of like a reverse CSRF-Token.
		var nonce = secureRandom.getEncodedBytes( 16, "base64" );
		// Define which URLs are safe to connect / send data to.
		var connectDomains = [
			// For JavaScript debugging purposes, I need to include my CDN as this is
			// where the compiled source-maps are stored.
			config.cdnOrigin,
			"https://notify.bugsnag.com",
			"https://sessions.bugsnag.com",
		];
		var frameDomains = [
			"https://embed.podcasts.apple.com",
			"https://player.vimeo.com",
			"https://redcircle.com",
			"https://www.youtube.com",
		];

		var directives = [
			// Limit script tags to those with a "nonce" attribute that matches the given
			// "nonce-{token}" value.
			"script-src 'nonce-#nonce#'",
			// Limit where scripts can send data when using fetch, XHR, sendBeacon, and
			// WebSocket. This blocks exfiltration of data through those channels.
			"connect-src 'self' #connectDomains.toList( ' ' )#",
			// Limit iframe sources to the known embed providers.
			"frame-src #frameDomains.toList( ' ' )#",
			// Deny all object media loads (such as Flash/SWF plugins).
			"object-src 'none'",
			// Block injected <base> tags from being applied, which a malicious actor
			// could use to change the loading of relative-path script tags.
			"base-uri 'none'",
			// Only allow this site to embed pages in a frame (clickjacking protection).
			// This supersedes the legacy X-Frame-Options header.
			"frame-ancestors 'self'",
			// Only allow forms to submit to this site. This prevents injected markup from
			// exfiltrating data to a third-party end-point.
			"form-action 'self'",
			// Upgrade "http:" sub-resource requests to "https:". Old blog posts contain
			// insecure image and embed URLs that would otherwise be mixed-content.
			"upgrade-insecure-requests",
			// Report CSP violations to the following end-point. Older browsers use the
			// report-uri directive while newer browsers use the report-to directive
			// (which references the Reporting-Endpoints header).
			"report-uri #reportToUrl#",
			"report-to csp-endpoint",
		];

		// Note: While the Reporting-Endpoints HTTP header is broader in scope than the
		// Content-Security-Policy HTTP header, I have no other use for it at this time.
		// As such, I'm defining it as part of the CSP configuration (especially since the
		// two headers have to agree on the endpoint name). This may change in the future
		// if I ever need an additional reporting end-point. This header supersedes the
		// deprecated (JSON-based) Report-To header.
		var result = {
			nonce: nonce,
			header: {
				name: "Content-Security-Policy",
				value: directives.toList( "; " ),
			},
			reportingEndpointsHeader: {
				name: "Reporting-Endpoints",
				value: 'csp-endpoint="#reportToUrl#"',
			},
		};

		return result;

	}

	// ... rest of ColdFusion component ...
}

Note that I'm including my blog's CDN (Content Delivery Network) domain in the connect-src. This allows the browser's DevTools to pull down the source-maps for my compiled JavaScript bundles. My site's actual JavaScript files are loaded securely by way of the script-src directive and its nonce attribute, not the connect-src directive.

Security Is a Best Effort (With Trade-Offs)

Security is a best effort cat-and-mouse game. The changes that I've made to my CSP make it stronger than it was before; and these changes would have prevented the way the Optimizely hack occurred; but they aren't perfect. And, if the Optimizely hack had been constructed in a slightly different way, none of these changes would have mattered.

And, of course, everything in security is a trade-off. For example, my narrowed script-src directive now makes it harder for HTMX to execute <script> tags in a swap operation. And my existing lack of unsafe-eval makes it harder for frameworks like Alpine.js to wire-up interactivity (though I'm super excited that the CSP build of Alpine.js is now quite robust).

All we can do is keep trying to harden our web properties against threats.

Want to use code from this post? Check out the license.

Reader Comments

Post A Comment — I'd Love To Hear From You!

I believe in love. I believe in compassion. I believe in human rights. I believe that we can afford to give more of these gifts to the world around us because it costs us nothing to be decent and kind and understanding. And, I want you to know that when you land on this site, you are accepted for who you are, no matter how you identify, what truths you live, or whatever kind of goofy shit makes you feel alive! Rock on with your bad self!
— Ben Nadel
Managed ColdFusion hosting services provided by:
xByte Cloud Logo