Skip to main content

Lack of Data Validation - Host Header Injection

Need

Prevent unintended redirects due to manipulation of the host header

Context

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

Description

Non compliant code

defmodule MyApp.HeaderController do
use MyAppWeb, :controller

def redirect(conn, _params) do
redirect_to = Map.get(conn.req_headers, "host")
redirect(conn, external: redirect_to)
end
end

This code is vulnerable because it directly uses the 'host' header from the user request to construct the redirection URL without any validation. This can lead to Host Header Injection attacks if a user provides a malicious website as the 'host' header.

Steps

  • Define a whitelist of trusted domains in your application configuration.
  • In the redirect function, validate the 'host' header against the whitelist before using it to construct the redirection URL.

Compliant code

defmodule MyApp.HeaderController do
use MyAppWeb, :controller

def redirect(conn, _params) do
redirect_to = Map.get(conn.req_headers, "host")
trusted_domains = Application.get_env(:my_app, :trusted_domains)
if redirect_to in trusted_domains do
redirect(conn, external: redirect_to)
else
conn
end
end
end

This code is secure because it validates the 'host' header against a whitelist of trusted domains before using it to construct the redirection URL. If the 'host' header is not in the trusted domains, it simply returns the connection without redirecting.

References