Prevent unauthorized or malicious data injection and Denial of Service (DoS) attacks through the x-amzn-RequestId Header
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.
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.