Cross-Site Request Forgery (CSRF) Tutorial
Introduction
Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious website, email, or program causes a user's web browser to perform an unwanted action on a trusted site for which the user is currently authenticated. This can lead to unauthorized actions such as changing account details, making transactions, or other unwanted operations.
How CSRF Works
CSRF exploits the trust that a web application has in the user's browser. Here’s a simple example to illustrate how CSRF works:
Suppose you are logged into a banking website. An attacker creates a malicious website with a hidden form that submits a funds transfer request to your bank:
<form action="https://yourbank.com/transfer" method="POST"> <input type="hidden" name="amount" value="1000"> <input type="hidden" name="recipient" value="attacker_account"> </form>
Preventing CSRF Attacks
To prevent CSRF attacks, developers can implement several strategies:
- CSRF Tokens: Generate a unique token for each session and include it in every form submission. The server then verifies this token, ensuring the request is legitimate.
- SameSite Cookie Attribute: Use the SameSite attribute in cookies to prevent browsers from sending cookies along with cross-site requests.
- Referer Header Check: Verify that the request's Referer header matches the expected origin.
Implementing CSRF Protection in PHP
Let's implement CSRF protection using tokens in a PHP application.
1. Generating a CSRF Token
Generate a unique CSRF token and store it in the user's session:
<?php session_start(); if (empty($_SESSION['csrf_token'])) { $_SESSION['csrf_token'] = bin2hex(random_bytes(32)); } ?>
2. Including the CSRF Token in Forms
Include the CSRF token as a hidden input field in your forms:
<form action="submit.php" method="POST"> <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>"> <!-- Other form fields --> <input type="submit" value="Submit"> </form>
3. Verifying the CSRF Token
Verify the token in your form handling script:
<?php session_start(); if ($_SERVER['REQUEST_METHOD'] === 'POST') { if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) { die('Invalid CSRF token'); } // Process the form data } ?>
Conclusion
CSRF is a serious security threat that can lead to unauthorized actions on behalf of authenticated users. By understanding how CSRF works and implementing appropriate protection mechanisms, such as CSRF tokens, developers can mitigate the risk of CSRF attacks and secure their web applications.