logo

Concurrent sessions - Elixir


Need

Prevent multiple simultaneous sessions from the same user account to maintain traceability and non-repudiation of user actions.


Context

  1. Usage of Elixir for building scalable and concurrent applications
  2. Usage of Plug and Cowboy for HTTP request and response handling
  3. Session management for user data

Description

Insecure Code Example

defmodule VulnerableApp do
  use Plug.Router

  plug :match
  plug :dispatch

  post '/login' do
    user = authenticate_user(conn.params['username'], conn.params['password'])
    if user do
      session = start_session(user)
      send_resp(conn, 200, 'Logged in')
    else
      send_resp(conn, 401, 'Unauthorized')
    end
  end
end

This code creates a new session for a user every time they log in, even if they already have an active session. This could lead to Concurrent Sessions.

Steps

  1. Track the number of active sessions for each user.
  2. If a user tries to create a new session while they already have one, end the existing session or deny the creation of a new one.
  3. Notify the user when a new session is created from a different location.

Secure Code Example

defmodule SecureApp do
  use Plug.Router

  plug :match
  plug :dispatch

  post '/login' do
    user = authenticate_user(conn.params['username'], conn.params['password'])
    if user do
      end_existing_session(user)
      session = start_session(user)
      send_resp(conn, 200, 'Logged in')
    else
      send_resp(conn, 401, 'Unauthorized')
    end
  end
end

This code prevents concurrent sessions by checking if a user already has an active session when they try to log in. If they do, it ends the existing session before creating a new one.


References

  • 062 - Concurrent sessions

  • Last updated

    2023/09/18