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

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

Need

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

Context

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

Description

Non compliant code

        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

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

Compliant code

        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