logo

Insecure Object Reference - Session Management - Elixir


Need

To prevent unauthorized users from closing sessions of other users


Context

  1. Usage of Elixir 1.12 for building scalable and fault-tolerant applications
  2. Usage of Phoenix Framework 1.6 for web development

Description

Insecure Code Example

defmodule SessionManager do
  def logout_user(conn, email) do
    # Clearing the session
    conn
    |> put_flash(:info, "Logged out successfully.")
    |> configure_session(drop: true)
    |> redirect(to: "/")
  end
end

In this insecure code, the `logout_user` function logs out a user based on the email provided. This is insecure because if an attacker knows a user's email, they can log out the user's session.

Steps

  1. Use a secure identifier, like a session token, to identify the user for the logout operation
  2. Implement checks to validate that the session being terminated matches the user performing the operation

Secure Code Example

defmodule SessionManager do
  def logout_user(conn, session_token) do
    user = get_user_from_session_token(session_token)
    if conn.assigns.current_user == user do
      # Clearing the session
      conn
      |> put_flash(:info, "Logged out successfully.")
      |> configure_session(drop: true)
      |> redirect(to: "/")
    else
      # Do not allow logging out other users' sessions
    end
  end

  defp get_user_from_session_token(session_token) do
    # Logic to get the user from the session token
  end
end

In the secure version of the code, the system checks whether the session being terminated belongs to the user initiating the logout operation.


References

  • 328 - Insecure Object Reference - Session Management

  • Last updated

    2023/09/18