Lack of Data Validation - Headers - Elixir

Lack of Data Validation - Headers - Elixir

Need

Prevent potential attacks via HTTP headers by validating the data received

Context

  • Usage of Elixir (v1.10+) for building scalable and fault-tolerant applications
  • Usage of Phoenix Framework for request handling

Description

Non compliant code

        defmodule MyAppWeb.MyController do
  use MyAppWeb, :controller

  def show(conn, _params) do
    # No header validation
    user_token = get_req_header(conn, "user-token")
    item = MyApp.get_item(user_token)
    json(conn, item)
  end
end
        
        

This code is vulnerable because it doesn't validate the 'user-token' header. An attacker can inject potentially harmful content into this header to exploit potential vulnerabilities or achieve an XSS attack.

Steps

  • Add a function to validate the 'user-token' header against a set of allowed patterns or values.
  • Before passing the 'user-token' header to 'MyApp.get_item', call this validation function. If the validation fails, return an error response.

Compliant code

        defmodule MyAppWeb.MyController do
  use MyAppWeb, :controller

  def show(conn, _params) do
    user_token = get_req_header(conn, "user-token")
    if validate_token(user_token) do
      item = MyApp.get_item(user_token)
      json(conn, item)
    else
      send_resp(conn, 400, "Invalid user-token header")
    end
  end

  defp validate_token(token) do
    # Implement your validation logic here
  end
end
        
        

This code is safe because it validates the 'user-token' header before using it. If the header contains invalid data, it returns an error response instead of passing the harmful content to 'MyApp.get_item'.

References