Skip to main content

Reflected Cross-Site Scripting (XSS)

Need

Prevent injection of malicious scripts into dynamically generated web content

Context

  • Usage of Elixir 1.13.0 for building scalable and fault-tolerant applications
  • Usage of Plug for request management
  • Dynamic content generation

Description

Non compliant code

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

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

Compliant code

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