1. Home
  2. Explore
  3. Computer Science
  4. Web Security: CSRF

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Web Security: CSRF

🌐 Cross-Site Request Forgery (CSRF)

Cross-Site Request Forgery (CSRF) is a significant, yet often lesser-known, web attack that exploits the trust a web browser has in a user's authenticated session. Unlike Cross-Site Scripting (XSS) or SQL Injection, CSRF focuses on tricking a user's browser into sending an unintended request to a legitimate web application where the user is already authenticated. This can lead to actions being performed without the user's explicit consent, such as transferring funds, changing passwords, or deleting accounts.


💻 Understanding Web Requests: GET vs. POST

Web browsers communicate with servers primarily through two types of requests: GET and POST. The distinction between these methods is crucial for understanding CSRF.

📥 GET Requests

  • Purpose: Primarily designed for fetching data.

  • Data Transmission: Data is appended to the URL as query parameters, visible in the browser's address bar.

    • Example: youtube.com/watch?v=dQw4w9WgXcQ where v=dQw4w9WgXcQ is the data.

  • Characteristics:

    • Can be bookmarked and shared (copied and pasted).

    • Should ideally be idempotent, meaning performing the request multiple times has the same effect as performing it once (e.g., fetching a page multiple times doesn't change server state).

    • Not suitable for sensitive data or actions that modify server state.

📤 POST Requests

  • Purpose: Designed for writing or submitting data to the server, often for actions that modify server state.

  • Data Transmission: Data is bundled within the body of the HTTP request and is not visible in the URL bar.

    • Example: Submitting a form (e.g., making a comment, transferring money).

  • Characteristics:

    • Typically used for actions that should happen once (e.g., posting a comment, processing a transaction).

    • Refreshing a page after a POST request usually prompts the user for confirmation to prevent duplicate actions.

    • More secure for sensitive operations as data isn't exposed in the URL.


😈 How CSRF Attacks Work

CSRF attacks leverage the browser's automatic inclusion of session cookies and other authentication credentials with requests to a domain where the user is currently logged in.

🏦 Scenario: Malicious Online Bank Transfer

  1. Vulnerable Application: Imagine a poorly designed online banking application where transferring money is handled via a POST request. The form to transfer money might look like this (simplified):

      <form action="https://mybank.com/transfer" method="POST">
          <input type="text" name="account_number" value="[Recipient Account]">
          <input type="number" name="amount" value="[Amount]">
          <input type="submit" value="Go">
      </form>
  2. User Authentication: A user logs into their online bank (mybank.com) in one browser tab. Their browser now holds authentication cookies for mybank.com.

  3. Malicious Website: The attacker creates a malicious website (e.g., "My Awesome Blog") and embeds a hidden form or JavaScript code that automatically triggers a POST request to the banking website.

      <!-- On attacker's "My Awesome Blog" -->
      <form action="https://mybank.com/transfer" method="POST" style="display:none;">
          <input type="hidden" name="account_number" value="ATTACKER_ACCOUNT_NUMBER">
          <input type="hidden" name="amount" value="1000">
          <input type="submit" value="Click Me!"> <!-- This button might be invisible or auto-submitted -->
      </form>
      <script>
          // JavaScript could automatically submit this form when the page loads
          document.forms[0].submit(); 
      </script>
  4. The Attack:

    • The user visits "My Awesome Blog" while still logged into their bank in another tab.

    • The malicious page either tricks the user into clicking an invisible button or uses JavaScript to automatically submit the hidden form to mybank.com.

    • Because the user is logged into mybank.com, their browser automatically attaches the authentication cookies to this request.

    • The bank's server receives the request, sees valid authentication, and processes the transfer of £1000 to the attacker's account, believing it was a legitimate request initiated by the logged-in user.

🗑️ Other Vulnerable Actions

CSRF isn't limited to financial transactions. Any action that modifies server state and doesn't adequately verify the request's origin can be vulnerable:

  • Deleting an account: A malicious site could trigger a /delete?confirm=true request.

  • Posting comments: Could post spam or inflammatory content.

  • Changing passwords or email addresses.

  • Making purchases.

Modern web technologies (like AJAX) can make these attacks even more insidious, as they can happen silently in the background without any page reload or user interaction, making them harder to detect.


🛡️ Defending Against CSRF

Several mechanisms exist to mitigate CSRF attacks.

❌ The Referer Header (Limited Effectiveness)

  • Concept: The HTTP Referer header is sent with requests and indicates the URL of the page that originated the request. A server could check if the Referer matches its own domain.

  • Problem:

    • The Referer header is not always reliably sent by browsers due to privacy settings, ad blockers, or network configurations.

    • Blocking requests where the Referer is missing or incorrect can lead to a poor user experience and legitimate requests being denied.

    • Attackers can sometimes manipulate or spoof the Referer header in specific scenarios.

🔑 CSRF Tokens (Nonces) - The Primary Defense

The most effective and widely adopted defense against CSRF is the use of CSRF tokens, often called "nonces" (number used once).

  1. Token Generation:

    • When a user requests a form (e.g., the bank transfer form), the web application generates a unique, random, unpredictable string of characters (the CSRF token).

    • This token is unique per user session and often per form request or has a short expiration time (e.g., a few minutes).

  2. Token Inclusion:

    • The generated token is embedded as a hidden field within the form itself.

    • The token is also stored server-side (e.g., in the user's session).

  3. Token Verification:

    • When the user submits the form, the server receives the request, including the token from the hidden field.

    • The server then compares the received token with the token it stored for that user's session.

    • If the tokens match, the request is considered legitimate and is processed.

    • If the tokens do not match (e.g., the token is missing, incorrect, expired, or used by a different user), the request is rejected.

💡 Why CSRF Tokens Work

  • Attacker's Limitation: A malicious website cannot know the correct CSRF token.

    • The token is randomly generated per legitimate form request.

    • It's not available in the browser's URL (like GET parameters).

    • The attacker cannot read the content of the legitimate form from another domain due to the Same-Origin Policy.

  • Request Origin Check: By requiring a valid, session-specific token, the server effectively verifies that the request originated from the intended application's own form and not from an external, malicious source.

⚠️ Importance for Developers

Many web developers are familiar with XSS and SQL Injection, but CSRF often goes unnoticed. Any web form that performs a permanent action (e.g., deleting data, posting content, authorizing actions, transferring funds) is a potential CSRF target if it doesn't implement a robust token-based defense. Developers must ensure their applications generate and validate CSRF tokens for all state-changing operations.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent