Session Fixation - Elixir

Session Fixation - Elixir

Need

Prevent session hijacking by securing session cookies.

Context

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

Description

Non compliant code

        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

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

Compliant code

        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