CSRF

CSRF (Cross-Site Request Forgery) is a web vulnerability that tricks a user into making unintended actions on a site where they are authenticated.

Cross-Site Request Forgery (CSRF) is a type of web security vulnerability that tricks a user into unintentionally performing actions on a website where they are authenticated. Attackers exploit the trust that a website has in the user’s browser by making unauthorized requests on behalf of the user.

How CSRF Works

  1. The victim logs into a trusted website (e.g., banking site) and receives a session cookie.
  2. Without logging out, the victim visits a malicious website.
  3. The malicious site triggers a hidden request (form submission, image, script) to the trusted site.
  4. Since the browser automatically includes cookies, the request looks legitimate to the server.

Example of a CSRF Attack

<!-- Malicious website code -->
<img src="https://bank.com/transfer?amount=1000&to=attacker" style="display:none">

Here, the victim’s browser sends a request to the bank to transfer money, including the valid session cookie. The server assumes the request was intentional.

CSRF Protection Techniques

  • CSRF Tokens: Unique, unpredictable tokens embedded in forms and verified on submission.
  • SameSite Cookies: Restricts cookies from being sent on cross-site requests.
  • Double Submit Cookies: Token stored both in a cookie and request, compared on the server.
  • Re-authentication: For sensitive actions (like password change or payments).

CSRF in PHP Frameworks

  • Laravel: Automatically provides CSRF protection via hidden _token field.
  • Symfony: Uses CSRF tokens in forms and API requests.
  • WordPress: Uses nonces (wp_nonce) to secure requests.

Difference Between CSRF and XSS

  • CSRF: Exploits the trust a site has in the user’s browser.
  • XSS: Exploits the trust a user has in a website.

Summary

CSRF is a critical web vulnerability that can lead to unauthorized actions like fund transfers, email changes, or account takeovers. By implementing CSRF tokens, SameSite cookies, and framework security features, developers can effectively prevent CSRF attacks.