logo

Uncontrolled External Site Redirect - Elixir


Need

Prevent unauthorized redirection to potentially malicious external sites


Context

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

Description

Insecure Code Example

def handle_req(%Plug.Conn{params: params} = conn, _) do
  redirect_to = Map.get(params, "redirect_to")
  conn |> redirect(external: redirect_to)
end

The code above is vulnerable as it takes a 'redirect_to' parameter from the request and uses it directly to redirect the user. An attacker can manipulate the 'redirect_to' parameter to redirect users to a malicious website.

Steps

  1. Do not use user-provided inputs to set the 'external' option in the redirect function.
  2. If you have to redirect based on user inputs, maintain a whitelist of allowed URLs and check against it.
  3. Regularly update your dependencies to include patches for security vulnerabilities.

Secure Code Example

def handle_req(%Plug.Conn{params: params} = conn, _) do
  redirect_to = Map.get(params, "redirect_to")
  allowed_urls = ["http://safe1.com", "http://safe2.com"]
  if redirect_to in allowed_urls, do: conn |> redirect(external: redirect_to)
end

The secure code checks the 'redirect_to' parameter against a list of allowed URLs before making the redirection. This ensures that the user can't be redirected to a malicious website even if they manipulate the 'redirect_to' parameter.


References

  • 156 - Uncontrolled External Site Redirect

  • Last updated

    2023/09/18