Lack of data validation - Header x-amzn-RequestId - Elixir

Lack of data validation - Header x-amzn-RequestId - Elixir

Need

Prevent unauthorized or malicious data injection and Denial of Service (DoS) attacks through the x-amzn-RequestId Header

Context

  • Usage of Elixir (1.10 and above) for building scalable and fault-tolerant applications
  • Usage of Plug and Cowboy for request handling and server management

Description

Non compliant code

        defmodule InsecureApp do
  use Plug.Router

  plug :match
  plug :dispatch

  get "/" do
    x_amzn_request_id = get_req_header(conn, "x-amzn-requestId")
    Logger.info "Received request with ID: #{x_amzn_request_id}"
    send_resp(conn, 200, "Hello, World!")
  end

  run InsecureApp
end
        
        

This insecure code snippet represents a REST API endpoint written in Elixir. The code is vulnerable because it lacks input validation for the x-amzn-RequestId header. It directly takes the value from the header and logs it. An attacker can inject harmful strings or very long strings to cause injection attacks or service denial by exhausting system resources.

Steps

  • Import and use 'Plug.Conn' for better handling of the request context
  • Create a new function to validate the x-amzn-RequestId header
  • In the validation function, check the length of the header and sanitize it to escape any dangerous characters
  • In the GET handler, call this validation function before using the header value

Compliant code

        defmodule SecureApp do
  use Plug.Router
  import Plug.Conn

  plug :match
  plug :dispatch

  defp validate_header(header_value) do
    if String.length(header_value) > 1000,
      do: {:error, "Header too long"}
    sanitized_value = String.replace(header_value, ~r/[<>"';()&]/, "")
    {:ok, sanitized_value}
  end

  get "/" do
    case get_req_header(conn, "x-amzn-requestId") |> validate_header do
      {:ok, valid_request_id} ->
        Logger.info "Received request with ID: #{valid_request_id}"
        send_resp(conn, 200, "Hello, World!")
      {:error, _reason} ->
        send_resp(conn, 400, "Invalid header")
    end
  end

  run SecureApp
end
        
        

This secure code snippet represents a REST API endpoint written in Elixir with data validation for the x-amzn-RequestId header. The 'validate_header' function checks the length of the header value and uses 'String.replace' function to escape dangerous characters. This way, the possibility of injection attacks or service denial is significantly mitigated.

References