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
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
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.
Steps
- Validate the session parameters before using them to set the session.
- If the session parameters are not valid, return an error response.
Compliant code
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"])
|> send_resp(200, "Session has been set")
else
send_resp(conn, 400, "Invalid session parameters")
end
end
defp valid_session_params?(session_params) do
# Implement validation logic here
end
end
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.