Prevent unintended redirects due to manipulation of the host header
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.
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.