Skip to Content
Course content

174: Content Security Policy Headers in PHP

Click on the "Edit" button in the top corner of the screen to edit your slide content.

A few years ago, I was reviewing a PR for a junior dev who had built a sleek user dashboard. He’d been diligent about using htmlspecialchars() on all user-generated output, so he felt safe. But during my audit, I found a tiny hole: a profile field that allowed a specific set of HTML tags for formatting. I managed to inject a simple <img src=x onerror="alert('Hacked')"> tag. Because the onerror attribute executes JavaScript directly in the browser, his output encoding didn't stop it. That's when I sat him down and explained that while input sanitization is vital, you need a second line of defense that lives in the browser itself. That's where Content Security Policy (CSP) comes in.

Defining Your Trust Boundaries

A Content Security Policy is essentially a set of instructions you send to the browser via an HTTP header. It tells the browser, "I only trust scripts from these specific domains, and I don't trust any inline scripts unless I explicitly sign off on them." If a hacker manages to inject a script tag pointing to a malicious server, the browser will check your CSP, see that the server isn't on the whitelist, and simply refuse to execute the code. It's a massive safety net.

In PHP, you implement this using the header() function. You want to send this before any HTML is rendered. Here is a basic example of a restrictive policy:

<?php
header("Content-Security-Policy: default-src 'self'; script-src 'self' https://trustedscripts.com; style-src 'self' https://fonts.googleapis.com;");
?>

Let's break that down. default-src 'self' is your fallback; it tells the browser that by default, images, fonts, and AJAX requests should only come from your own domain. script-src 'self' https://trustedscripts.com expands that specifically for JavaScript, allowing your own files and one external trusted source. Notice the single quotes around 'self'—that's a keyword, not a string, so the quotes are mandatory.

Handling Inline Scripts with Nonces

Here is the catch: a strict CSP blocks all inline scripts (like <script>alert('hi')</script>) and all inline event handlers (like onclick). While you should generally move your JS to external files, sometimes you just need a small bit of PHP-generated data available to a script on the page. You can't just use 'unsafe-inline' because that completely defeats the purpose of having a CSP—it's basically like leaving the front door unlocked because you're too lazy to find your keys.

The professional way to handle this is with a nonce (a "number used once"). You generate a cryptographically strong random string on every single page load, include it in your CSP header, and then add that same string as an attribute to your script tag. If the nonces match, the browser trusts the script.

<?php
// Generate a random nonce for this request
$nonce = base64_encode(random_bytes(16));

// Add the nonce to the CSP header
header("Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-$nonce';");
?>

<script nonce="<?php echo $nonce; ?>">
    console.log("This inline script is allowed because the nonce matches!");
</script>

<script>
    alert("I will be blocked by the browser!");
</script>

I've found that using nonces is the only way to maintain a high security posture without breaking your site's functionality. It forces you to be intentional about which scripts are actually running on your pages.




📋 Practical Task

Implementing a Nonce-Based CSP for a User Settings Page

You are tasked with securing a settings.php page. The page displays user settings and requires one specific inline script to initialize a JavaScript object with the current user's ID from PHP.

  • Create a PHP file that generates a cryptographically secure nonce.
  • Send a Content-Security-Policy header that:
    • Sets default-src to 'self'.
    • Allows scripts from 'self' and allows inline scripts that possess the correct nonce.
    • Allows styles from 'self' and https://cdn.example.com.
  • Include one <script> tag that uses the nonce to successfully print "User ID initialized" to the console.
  • Include a second <script> tag without a nonce that attempts to alert "I am a malicious script!".
  • Verify in your browser's developer console (F12) that the second script was blocked by the CSP while the first one executed.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.