logo

Session Fixation - Elixir


Need

Prevent session hijacking by securing session cookies.


Context

  1. Usage of Elixir (1.12.0 and above) for building scalable and fault-tolerant applications
  2. Usage of Phoenix framework for web request handling
  3. Usage of Plug.Session for session management

Description

Insecure Code Example

defmodule MyApp.SessionController do
  use MyApp, :controller

  def create(conn, %{"user" => user_params}) do
    case MyApp.Authenticator.authenticate(user_params) do
      {:ok, user} ->
        conn
        |> put_session(:user_id, user.id)
        |> redirect(to: "/welcome")
      {:error, reason} ->
        render(conn, "login.html", error: reason)
    end
  end
end

This Elixir/Phoenix code does not handle session cookies securely. The session cookie is not regenerated after login, which allows an attacker to fixate a session, and then hijack the user session once the victim logs in.

Steps

  1. Regenerate the session cookie after login to prevent session fixation.
  2. This can be done by deleting the old session and creating a new one.

Secure Code Example

defmodule MyApp.SessionController do
  use MyApp, :controller

  def create(conn, %{"user" => user_params}) do
    case MyApp.Authenticator.authenticate(user_params) do
      {:ok, user} ->
        conn
        |> configure_session(renew: true)
        |> put_session(:user_id, user.id)
        |> redirect(to: "/welcome")
      {:error, reason} ->
        render(conn, "login.html", error: reason)
    end
  end
end

This secure Elixir/Phoenix code example regenerates the session cookie after a successful login. The call to 'configure_session(renew: true)' ensures a new session is created, preventing session fixation.


References

  • 280 - Session Fixation

  • Last updated

    2023/09/18