Skip to main content

Lack of Data Validation - Input Length

Need

Prevent overlong content in user input, which can lead to resource exhaustion or other vulnerabilities

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 create(conn, %{"body" => body}) do
# No input length validation
MyApp.create_item(body)
send_resp(conn, 200, "Item created")
end
end

This code is vulnerable because it doesn't validate the length of the 'body' parameter. An attacker can provide a very long input, potentially causing resource exhaustion or other vulnerabilities.

Steps

  • Use the 'String.length' function to validate the length of the user input.
  • Before passing the 'body' parameter to 'MyApp.create_item', check whether the length of 'body' exceeds the acceptable limit. If it does, return an error response.

Compliant code

defmodule MyAppWeb.MyController do
use MyAppWeb, :controller

def create(conn, %{"body" => body}) do
if String.length(body) > 1000 do
send_resp(conn, 400, "Body is too long")
else
MyApp.create_item(body)
send_resp(conn, 200, "Item created")
end
end
end

This code is safe because it checks the length of the 'body' parameter before using it. If the length exceeds 1000, it returns an error response instead of passing the overlong input to 'MyApp.create_item'.

References