Insecure Session Management - CSRF Fixation - Elixir

Insecure Session Management - CSRF Fixation - Elixir

Need

To prevent CSRF attacks that can spoof an authenticated user and execute critical transactions

Context

  • Usage of Elixir 1.12 for functional programming and building scalable applications
  • Usage of Phoenix Framework 1.6 for web development
  • Usage of Plug.CSRFProtection for protecting against Cross-Site Request Forgery (CSRF) attacks

Description

Non compliant code

        defmodule TransactionController do
  use MyApp.Web, :controller

  def make_transaction(conn, %{'amount' => amount, 'recipient' => recipient}) do
    # perform transaction...
  end
end
        
        

In the insecure code example, the make_transaction function handles a transaction without validating a CSRF token. This allows an attacker to create a button with the content of a request and trick a user running a transaction to receive the app push notification and complete the request.

Steps

  • Enable CSRF protection using `Plug.CSRFProtection`
  • Generate a CSRF token for every form using `Plug.CSRFProtection.get_csrf_token/0` and include it as a hidden field in the form
  • In the function handling the form submission, validate the CSRF token

Compliant code

        defmodule TransactionController do
  use MyApp.Web, :controller

  def make_transaction(conn, %{'_csrf_token' => csrf_token, 'amount' => amount, 'recipient' => recipient}) do
    if Plug.CSRFProtection.check_csrf_token(conn, csrf_token) do
      # perform transaction...
    else
      send_resp(conn, 403, "Invalid CSRF token")
    end
  end
end
        
        

In the secure code example, the make_transaction function validates the CSRF token using Plug.CSRFProtection.check_csrf_token/2. This ensures that the request is made by a legitimate user, preventing CSRF attacks.

References