How to fix Security Misconfiguration
in Plug
Executive Summary
Plug is the backbone of the Elixir web stack. A default or lazy configuration is a playground for attackers. Security misconfigurations in Plug typically manifest as missing security headers, insecure session cookies, and lack of transport layer enforcement. Harden your pipeline or prepare for session hijacking and XSS.
The Vulnerable Pattern
defmodule MyApp.Router do use Plug.Router plug :match plug :dispatchVULNERABLE: No SSL enforcement, missing cookie flags, no security headers
plug Plug.Session, store: :cookie, key: “_my_app_key”, signing_salt: “secret_salt”
get ”/” do send_resp(conn, 200, “Welcome”) end end
The Secure Implementation
The vulnerable configuration fails on three fronts: transport, session, and browser-side protections. The secure implementation fixes this by: 1. Using Plug.SSL to force HTTPS and set Strict-Transport-Security (HSTS). 2. Hardening Plug.Session with 'http_only' (blocks JS access to cookies), 'secure' (ensures cookies travel only over HTTPS), and 'same_site' (mitigates CSRF). 3. Injecting a custom pipeline to set critical headers like CSP to prevent XSS, X-Frame-Options to stop Clickjacking, and X-Content-Type-Options to prevent MIME-sniffing attacks.
defmodule MyApp.Router do use Plug.RouterSECURE: Enforce SSL and HSTS
plug Plug.SSL, rewrite_on: [:x_forwarded_proto], hsts: true
plug :match plug :put_secure_browser_headers plug :dispatch
SECURE: Hardened session cookies
plug Plug.Session, store: :cookie, key: “_secure_session”, signing_salt: ”${SESSION_SIGNING_SALT}”, http_only: true, secure: true, same_site: “Lax”
defp put_secure_browser_headers(conn, _opts) do conn |> put_resp_header(“content-security-policy”, “default-src ‘self’”) |> put_resp_header(“x-frame-options”, “DENY”) |> put_resp_header(“x-content-type-options”, “nosniff”) |> put_resp_header(“referrer-policy”, “strict-origin-when-cross-origin”) end
get ”/” do send_resp(conn, 200, “Welcome”) end end
Your Plug API
might be exposed to Security Misconfiguration
74% of Plug apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.