Skip to main content

Lack of data validation - HTML code

Need

To sanitize and validate input data to prevent HTML injection attacks.

Context

  • Usage of Elixir (1.12.0 and above) for building scalable and fault-tolerant applications
  • Usage of Phoenix Framework for building web applications
  • Usage of Plug for request handling

Description

Non compliant code

defmodule MyAppWeb.PageController do
use MyAppWeb, :controller

def show(conn, %{"data" => data}) do
render(conn, "show.html", data: data)
end
end

The above code is insecure as it directly uses the user-provided data in the 'data' parameter without any validation or sanitization. This allows an attacker to inject HTML code that will be rendered and potentially execute malicious scripts when viewed in a browser.

Steps

  • Never trust user input and always sanitize it.
  • Use server-side validation to ensure that user-provided data is safe to use.
  • Consider using libraries that automatically escape HTML in text.

Compliant code

defmodule MyAppWeb.PageController do
use MyAppWeb, :controller

def show(conn, %{"data" => data}) do
sanitized_data = Phoenix.HTML.html_escape(data)
render(conn, "show.html", data: sanitized_data)
end
end

The code is now secure as it uses the 'html_escape' function from the Phoenix.HTML module to sanitize the user-provided data before rendering it. This ensures that any HTML code provided by the user is escaped and rendered as plain text, preventing any potential HTML injection attacks.

References