Lack of data validation - Token - Elixir

Lack of data validation - Token - Elixir

Need

To ensure the integrity and validity of JWT access tokens used for authentication.

Context

  • Usage of Elixir (1.12.0 and above) for building scalable and fault-tolerant applications
  • Usage of Phoenix Framework for building web applications
  • Usage of JOSE JWT library for JSON Web Token handling

Description

Non compliant code

        defmodule MyAppWeb.TokenController do
  use MyAppWeb, :controller

  def verify_token(conn, %{"token" => token}) do
    {:ok, _} = JOSE.JWT.decode(token)
    send_resp(conn, 200, "Token is valid")
  end
end
        
        

In this insecure code example, the JWT token is decoded, but its signature is not validated. This means that an attacker could modify the payload of the token, or even remove the signature entirely, and the server would still accept it as valid.

Steps

  • Modify the verify_token function to validate the signature of the JWT token using the JOSE.JWT.verify function.
  • Ensure that the secret key used for verification is stored securely and is not exposed.

Compliant code

        defmodule MyAppWeb.TokenController do
  use MyAppWeb, :controller

  def verify_token(conn, %{"token" => token}) do
    case JOSE.JWT.verify_strict(token, ["HS256"], "secret") do
      {true, _, _} ->
        send_resp(conn, 200, "Token is valid")
      _ ->
        send_resp(conn, 401, "Invalid token")
    end
  end
end
        
        

In this secure code example, the application correctly verifies the JWT token using the JOSE.JWT.verify_strict function with the appropriate algorithm and secret key. This prevents attackers from modifying the token payload or removing the signature.

References