logo

Insecure Session Management - CSRF Fixation - Elixir


Need

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


Context

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

Description

Insecure Code Example

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

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

Secure Code Example

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

  • 337 - Insecure Session Management - CSRF Fixation

  • Last updated

    2023/09/18