logo

Insecure or unset HTTP headers - Content-Security-Policy - Elixir


Need

Prevent potential security threats by correctly setting Content-Security-Policy


Context

  1. Usage of Elixir for building scalable and fault-tolerant applications
  2. Usage of Plug Phoenix Framework for building web applications
  3. Usage of the application as a web server for handling HTTP responses

Description

Insecure Code Example

defmodule VulnerableController do
  use MyApp.Web, :controller

  def show(conn, _params) do
    render(conn, "show.html")
  end
end

The following Elixir code is vulnerable because it does not set the Content-Security-Policy HTTP header. This omission makes the application susceptible to potential security threats like Cross-Site Scripting (XSS).

Steps

  1. Use Plug to set the Content-Security-Policy HTTP header in every response.
  2. Ensure the policies set in the Content-Security-Policy HTTP header do not contain insecure values.

Secure Code Example

defmodule SecureController do
  use MyApp.Web, :controller

  plug :put_content_security_policy_header

  def show(conn, _params) do
    render(conn, "show.html")
  end

  defp put_content_security_policy_header(conn, _opts) do
    conn
    |> put_resp_header("content-security-policy", "default-src 'self'")
  end
end

The following Elixir code is secure because it sets the Content-Security-Policy HTTP header using Plug. This setting protects the application from potential security threats.


References

  • 043 - Insecure or unset HTTP headers - Content-Security-Policy

  • Last updated

    2023/09/18