Challenge 1 — Solution Task: Write a complete CSRF-protected form flow: a page generating and embedding a token, and a processing script that rejects the request with a 403 status if the token is missing or doesn't match, using hash_equals(). Test it conceptually by describing what would happen if an attacker's page tried to submit the same form action directly, without the token. ---- settings.php (generates and embeds the token) ----
---- update_settings.php (processing script) ---- ---- What would happen if an attacker's page submitted the form action directly ---- If a malicious page on a different site auto-submitted a hidden form directly to update_settings.php (e.g. with only a display_name field, no csrf_token field at all, or a guessed/made-up token value), the request would still arrive at the server carrying the visitor's real session cookie automatically - but $_POST['csrf_token'] would either be completely missing (defaulting to '' via the ?? operator) or would contain a value the attacker could not possibly have known (since it's a 32-byte random value stored server-side in the visitor's own session, never exposed anywhere the attacker's page could read it). hash_equals() would then compare the real, session-stored token against this missing-or-wrong submitted value, return false, and the script would respond with a 403 Forbidden status and stop immediately - the settings update never happens, regardless of the visitor's otherwise-valid session. Notes: - The token is generated once per session (only if it doesn't already exist), not regenerated on every single page load - so the same token value remains valid across multiple legitimate form submissions within one session. - hash_equals() is used specifically instead of === for the token comparison, matching the chapter's own timing-safe-comparison guidance for security tokens. - The ?? '' defaults on both sides of the comparison ensure a completely missing token (either in the session or in the POST data) is treated as a non-matching empty string rather than triggering an undefined-key warning.