Uncontrolled External Site Redirect - Elixir

Uncontrolled External Site Redirect - Elixir

Need

Prevent unauthorized redirection to potentially malicious external sites

Context

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

Description

Non compliant code

        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

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

Compliant code

        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