← 返回课程: PHP from scratch

CSRF protection and week 5 review

视频即将上线

There is another important web attack besides XSS: CSRF (Cross-Site Request Forgery). It happens when a malicious page makes the browser of a victim, who is already logged in to your site, send a request the victim did not intend: change their email, transfer money, delete an account. The browser attaches cookies automatically, so the server believes the request is legitimate. The standard defense is a secret, unpredictable token that the legitimate form includes and the attacker cannot know.

The CSRF token step by step

The mechanism has four steps. First, when showing the form you generate a random token with random_bytes and store it in the user's session (session_start creates that session; we will study it in depth in week 7). Second, you include it in the form as a hidden field. Third, when you receive the POST you compare the submitted token with the session one using hash_equals, which compares in constant time so it does not leak information. Fourth, if they do not match, you reject the request with a 403 code. Never use random or rand for this: they are not cryptographically secure.

php
<?php
// File: csrf.php
declare(strict_types=1);

function csrfToken(): string
{
    if (session_status() !== PHP_SESSION_ACTIVE) {
        session_start();
    }
    if (empty($_SESSION['csrf'])) {
        $_SESSION['csrf'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf'];
}

function csrfIsValid(?string $sent): bool
{
    if (session_status() !== PHP_SESSION_ACTIVE) {
        session_start();
    }
    $expected = $_SESSION['csrf'] ?? '';
    return is_string($sent) && $expected !== '' && hash_equals($expected, $sent);
}
php
<?php
// File: change-email.php
declare(strict_types=1);

require_once __DIR__ . '/csrf.php';

$notice = '';
$token = csrfToken(); // starts the session before any output

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrfIsValid($_POST['csrf'] ?? null)) {
        http_response_code(403);
        exit('Invalid request.');
    }
    $email = filter_var($_POST['email'] ?? '', FILTER_VALIDATE_EMAIL);
    $notice = $email === false ? 'Invalid email.' : 'Email updated.';
}
?>
<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8"><title>Change email</title></head>
<body>
<?php if ($notice !== ''): ?>
    <p><?= htmlspecialchars($notice, ENT_QUOTES, 'UTF-8') ?></p>
<?php endif; ?>
<form method="post">
    <input type="hidden" name="csrf" value="<?= htmlspecialchars($token, ENT_QUOTES, 'UTF-8') ?>">
    <input type="email" name="email" required>
    <button type="submit">Save</button>
</form>
</body>
</html>

The token does not replace other defenses; it completes them. Configure session cookies with SameSite=Lax or Strict, which prevents the browser from sending them on requests started from other sites, and with HttpOnly so JavaScript cannot read them. Always use POST for actions that modify data: a delete action behind a GET link can be triggered just by loading an image. And regenerate the session on login, something we will see in week 7.

An example to fix the idea: imagine your bank has the URL /transfer?to=123&amount=500 and that it works just by visiting it while logged in. A foreign page can include that URL in an invisible image and your browser, with its cookie, would run it. With a token in a POST, the foreign page cannot guess the value nor read it from another domain, because the browser prevents it. That is the reason the token works.

检验所学

第 1 / 6

What does hash_equals compare and why is it used for tokens?

✎ 我的笔记

仅保存在此浏览器中。登录后可保存到账号。0/5000 字符

← 上一节下一节 →