logo

Database

Lack of data validation - Session Cookie

Need

Prevent unauthorized modification of session cookies

Context

• Usage of Elixir (1.12 and above) for building scalable and fault-tolerant applications

• Usage of Plug for request handling

• Usage of Plug.Session for HTTP session management

Description

1. Non compliant code

defmodule SessionController do
  use MyApp.Web, :controller

  def set_session(conn, %{'session' => session_params}) do
    conn
    |> put_session(:user_id, session_params["user_id"])
    |> send_resp(200, "Session has been set")
end...

In this code, the session value is set based on whatever value is received from the user, without any validation. This allows an attacker to set an arbitrary value for the user_id in the session, potentially impersonating another user.

2. Steps

• Validate the session parameters before using them to set the session.

• If the session parameters are not valid, return an error response.

3. Secure code example

defmodule SessionController do
  use MyApp.Web, :controller

  def set_session(conn, %{'session' => session_params}) do
    if valid_session_params?(session_params) do
      conn
      |> put_session(:user_id, session_params["user_id"])
    else...

In the secure code example, the session parameters are validated before they are used to set the session. If the parameters are not valid, an error response is returned. This prevents an attacker from setting an arbitrary session value.