logo

Reflected Cross-Site Scripting (XSS) - Elixir


Need

Prevent injection of malicious scripts into dynamically generated web content


Context

  1. Usage of Elixir 1.13.0 for building scalable and fault-tolerant applications
  2. Usage of Plug for request management
  3. Dynamic content generation

Description

Insecure Code Example

defmodule VulnerableController do
  use Plug.Router

  plug :match
  plug :dispatch

  get "/search" do
    results = Search.query(conn.params["query"])
    send_resp(conn, 200, "Search results for: #{conn.params["query"]}")
  end
end

The '/search' endpoint uses user-provided input directly in the output content. If an attacker provides a script as part of the 'query' parameter, this script will be reflected back in the response and executed by the user's browser, resulting in a reflected XSS vulnerability.

Steps

  1. Use the functions provided by the Phoenix.HTML package to sanitize user input before including it in dynamic content.
  2. Replace string interpolation with the 'h' function from Phoenix.HTML when generating dynamic content.

Secure Code Example

defmodule SecureController do
  use Plug.Router
  use Phoenix.HTML

  plug :match
  plug :dispatch

  get "/search" do
    results = Search.query(conn.params["query"])
    safe_query = Phoenix.HTML.raw(h(conn.params["query"]))
    send_resp(conn, 200, "Search results for: #{safe_query}")
  end
end

This solution introduces the use of the 'h' function from the Phoenix.HTML package to sanitize user-provided input. It ensures that any HTML special characters in the input are escaped, preventing them from being interpreted as part of the HTML markup. This prevents scripts from being executed in the user's browser, mitigating the reflected XSS vulnerability.


References

  • 008 - Reflected Cross-Site Scripting (XSS)

  • Last updated

    2023/09/18