logo

Database

Lack of data validation - Header x-amzn-RequestId

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

1. Non compliant code

defmodule InsecureApp do
  use Plug.Router

  plug :match
  plug :dispatch

  get "/" do
    Logger.info "Received request with ID: #{x_amzn_request_id}"...

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.

2. 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

3. Secure code example

defmodule SecureApp do
  use Plug.Router
  import Plug.Conn

  plug :match
  plug :dispatch

    if String.length(header_value) > 1000,...

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.