Skip to Content
Course content

66: CSRF Protection Techniques

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

A few years ago, I worked with a developer who had built a sleek, one-click "Delete Account" feature for a member portal. He’d tested it thoroughly—clicked the button, saw the account vanish, and felt proud of the efficiency. But a week after launch, users started reporting that their accounts were disappearing spontaneously. It turned out a disgruntled former member had posted a hidden image tag on a popular community forum. The src attribute of that image wasn't a picture at all; it was a URL pointing directly to the portal's delete_account.php script. Because the users were already logged into the portal in another tab, their browsers automatically attached their session cookies to the request. The server saw a valid session, assumed the user wanted to delete their account, and complied. The developer hadn't written a single bug in his logic—he had just forgotten that the browser is far too helpful for its own good.

The Mechanical Flaw of Cookies

The core of the problem is that browsers are designed to send all cookies associated with a domain every time a request is made to that domain, regardless of where that request originated. If you are logged into your-bank.com and you visit evil-site.net, that malicious site can trigger a POST request to your bank. Since your browser holds the session cookie for the bank, it attaches it to the request. To the server, this looks like a legitimate action performed by you.

This is why we can't rely on session cookies alone to prove intent. We need a way to verify that the request was actually initiated from our own frontend, not a hidden form on some random corner of the web.

Implementing a Cryptographic Handshake

The most reliable way to stop this is the Synchronizer Token Pattern. Essentially, we generate a unique, random string for the user's session and require that this string be sent back with every state-changing request (POST, PUT, DELETE). If the token in the request doesn't match the one in the session, we kill the request immediately.

// Generating the token and storing it in the session
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$token = $_SESSION['csrf_token'];

// In your HTML form
echo '';

When the form is submitted, your verification logic should look something like this:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        // This is a potential CSRF attack
        http_response_code(403);
        die('Invalid CSRF token');
    }
    // Proceed with the actual logic (e.g., updating a password)
}

I used hash_equals() here instead of a standard == comparison. This is a small but vital detail: hash_equals is timing-attack safe. It prevents an attacker from guessing the token by measuring how long the server takes to reject a wrong answer.

Adding Layers with SameSite Cookie Attributes

While tokens are the gold standard, modern browsers have introduced a powerful defense-in-depth mechanism: the SameSite attribute for cookies. By setting this attribute, you tell the browser whether it's okay to send the cookie when the request comes from a different site.

You have three main options: Strict, Lax, and None. I almost always recommend Lax for general applications. It prevents the cookie from being sent on cross-site POST requests (the primary CSRF vector) but still allows the cookie to be sent when a user clicks a link from an external site to yours, so they don't arrive at your landing page logged out.

// Setting a session cookie with SameSite=Lax
session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'domain' => $_SERVER['HTTP_HOST'],
    'secure' => true,     // Only send over HTTPS
    'httponly' => true,   // Prevent JavaScript access
    'samesite' => 'Lax'   // The CSRF defense
]);
session_start();

Don't treat SameSite as a replacement for tokens, though. Older browsers don't support it, and some edge cases can still leave you vulnerable. Think of it as a seatbelt—it's a great safety measure, but you still need a sturdy car (your tokens) to survive the crash.




📋 Practical Task

Exercise: Securing a User Profile Update Form against Cross-Site Forgery

You are provided with a simple PHP page that allows a user to update their email address. Currently, it only checks if the user is logged in, making it vulnerable to CSRF.

Your Task:

  • Modify the script to generate a secure, random CSRF token and store it in the $_SESSION upon page load.
  • Inject this token into the email update form as a hidden input field.
  • Implement a verification check at the top of the POST processing logic that uses hash_equals() to validate the submitted token against the session token.
  • Configure the session cookie settings using session_set_cookie_params to include the SameSite=Lax attribute.
  • Ensure that if the token is missing or invalid, the script terminates with a 403 Forbidden header.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.