Skip to main content

Insecurely Generated Token

Need

Create secure, unpredictable session tokens to prevent reuse

Context

  • Usage of Elixir (v1.11+) for building scalable and fault-tolerant applications
  • Usage of Phoenix.Token for token generation and verification

Description

Non compliant code

defmodule InsecureToken do
def generate_token(user_id) do
user_id
|> Integer.to_string
|> String.reverse
end
end

The generate_token function is insecure because it simply reverses the user_id and uses it as a token. This approach is predictable and can easily be reverse-engineered, which could allow an attacker to reuse a session token after 14 days.

Steps

  • Install the Phoenix.Token package if it's not already installed.
  • Use Phoenix.Token.sign/3 to generate a secure token, providing the user_id as the salt.
  • Use Phoenix.Token.verify/4 to verify tokens before use.

Compliant code

defmodule SecureToken do
@secret_key_base "s3cr3t"

def generate_token(user_id) do
Phoenix.Token.sign(@secret_key_base, "user salt", user_id)
end

def verify_token(token, user_id) do
Phoenix.Token.verify(@secret_key_base, "user salt", token, max_age: 14 * 24 * 60 * 60)
end
end

The generate_token function now uses Phoenix.Token.sign/3 to generate a secure token, and verify_token uses Phoenix.Token.verify/4 to verify the token's integrity and timeliness. The token is cryptographically secure and unpredictable, and it cannot be reused after 14 days.

References