KIM COMPUTER


CSRF (Cross-Site Request Forgery)

CSRF (Cross-Site Request Forgery) is an attack that forces an end user to execute unwanted actions on a web application in which they are currently authenticated.

The core of the attack is exploiting the user's trusted, authenticated state to compromise the integrity of data or actions.


1. How the Attack Works

A CSRF attack typically involves three entities:

  1. Victim Site: A trusted site (like a bank or e-commerce store) where the user is currently logged in, and authentication information (session cookies) is stored in the browser.
  2. Attacker Site: A malicious website containing code planted by the attacker.
  3. Victim: The authenticated user who visits the attacker's site.

Attack Scenario Example

  1. The victim logs into their banking website. (Session cookie is saved).
  2. The victim then visits a malicious website (Attacker Site).
  3. The malicious site contains hidden code, such as: html <img src="[https://bank.com/transfer?to=attacker&amount=100000](https://bank.com/transfer?to=attacker&amount=100000)" style="display:none;">
  4. The browser attempts to load this hidden resource (<img>) and automatically sends a request to the trusted domain (bank.com).
  5. Crucially, the browser attaches the valid session cookie for bank.com.
  6. The bank server sees the valid cookie and assumes the request is legitimate and initiated by the logged-in user, executing the transfer.

2. CSRF Defense Strategies (Developer Perspective)

CSRF is best mitigated by verifying the origin of the request.

  1. Use of CSRF Tokens (Synchronizer Token Pattern):
    • The most standard defense. The server generates a unique, one-time, random token and embeds it in a hidden field (hidden input) within the form sent to the client.
    • The client must send this token back with the request. The server verifies that the received token matches the token stored in the session.
  2. SameSite Cookie Attribute:
    • By setting the SameSite attribute (e.g., to Strict or Lax), the browser is instructed not to send the cookie automatically with cross-site requests, effectively blocking the attack vector.
  3. Referer Header Check:
    • Checking the HTTP request header's Referer field to ensure the request is originating from the site's own domain.