Prevent injection of malicious scripts into dynamically generated web content
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.
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.