Skip to main content

Insecure Functionality - Session Management

Need

Prevent reuse of expired session tokens to ensure session integrity

Context

  • Usage of Elixir 1.12 for building scalable and concurrent applications
  • Usage of Phoenix Framework 1.6 for web development
  • Usage of Guardian library for authentication and authorization

Description

Non compliant code

defmodule MyAppWeb.Endpoint do
use Guardian.Plug.VerifyHeader, realm: "Bearer"
def call(conn, _) do
case Guardian.Plug.current_token(conn) do
nil -> conn
token ->
if MyApp.Auth.Token.is_expired?(token) do
MyApp.Auth.Token.extend_expiration(token)
end
conn
end
end
end

This example depicts an API endpoint in a Phoenix application that authenticates the user using JWT tokens generated with the Guardian library. The problem lies in the token validation mechanism, where the code checks the token's expiration date against the current time but does not verify if the token itself is expired.

Steps

  • Remove the token extension functionality
  • Ensure that expired tokens cannot be reused

Compliant code

defmodule MyAppWeb.Endpoint do
use Guardian.Plug.VerifyHeader, realm: "Bearer"
def call(conn, _) do
case Guardian.Plug.current_token(conn) do
nil -> conn
token ->
if MyApp.Auth.Token.is_expired?(token) do
conn
|> put_status(:unauthorized)
|> Phoenix.Controller.json(%{error: "Expired token"})
|> halt()
end
conn
end
end
end

In the fixed code, the token extension functionality has been removed. Therefore, once a token has expired, it can no longer be used, ensuring the integrity of the session.

References