Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 48 ยท Real-World Elixir

Security Basics

Learn the main security traps in Elixir and Phoenix: atom exhaustion, unsafe deserialization, SQL fragments, CSRF, XSS and keeping secrets out of code.

Elixir removes whole classes of bugs, such as null pointer crashes and shared-memory races, but it cannot make your application secure by itself. Security problems come from how you treat data that arrives from outside: query strings, form fields, cookies, uploaded files and binary blobs. The rule behind almost every item in this lesson is the same: never trust input, and never let input choose something the runtime keeps forever or executes.

This lesson covers atom exhaustion, deserializing untrusted data, SQL injection through fragments, CSRF and XSS in Phoenix, and handling secrets and configuration. The code is read-only Elixir. Two editors use JavaScript stand-ins to show the shape of the problems. For the framework basics, see Phoenix: Web Applications and Ecto.

Where attacks enter

Params Query strings and form fields.
Cookies Sessions and tokens.
Binaries Stored or received terms.
Config Secrets in the wrong place.

Everything from outside is untrusted until checked.

1 / 2

Atom exhaustion

Atoms are never garbage collected. Each unique atom is stored in a global table, and the table has a fixed limit (about a million by default). When it fills up, the whole VM crashes, not only one process.

That makes this call dangerous when the string comes from outside:

ELIXIR
# DANGEROUS: every new value from a user creates a permanent atom
role = String.to_atom(params["role"])

An attacker only needs to send enough different values. The safe options are:

ELIXIR
# Only converts if the atom already exists; raises otherwise
role = String.to_existing_atom(params["role"])

# Best: map allowed strings explicitly, with a pattern-matching function
def parse_role("admin"), do: {:ok, :admin}
def parse_role("editor"), do: {:ok, :editor}
def parse_role("viewer"), do: {:ok, :viewer}
def parse_role(_other), do: {:error, :unknown_role}

String.to_existing_atom/1 is a good second line of defense, but an explicit allow-list is clearer, because it also documents the valid values. The same advice applies to List.to_atom/1, :erlang.binary_to_atom/2 and to JSON libraries: decode keys as strings (the default in Jason) and do not enable atom keys for untrusted input. Ecto casts and changesets handle this for you, by casting to declared types.

JS Why an allow-list beats creating atoms (JavaScript stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The allow-list version never grows the table, however much junk arrives. The naive version creates a permanent entry for every new string until it hits the limit.

Untrusted deserialization

:erlang.binary_to_term/1 turns a binary back into any Erlang term. If an attacker controls the binary, they can create atoms (same exhaustion problem) and, in some cases, build terms that include functions (anonymous function values), which is dangerous if your code later calls them.

ELIXIR
# Never do this with data from users, cookies, queues you do not control, or files you did not write
term = :erlang.binary_to_term(payload)

# If you must decode external terms, restrict it
term = :erlang.binary_to_term(payload, [:safe])

The :safe option refuses to create new atoms, references or function values that do not already exist. It reduces the risk, but the best approach is to not use Erlang's term format for external data at all. Use JSON (with explicit parsing into known shapes) or another data format designed for exchange, as in Files, JSON and Serialization. Phoenix signs and encrypts cookies and tokens with Plug.Crypto and Phoenix.Token, so use those rather than hand-made schemes. Signed data cannot be forged without your secret_key_base.

SQL injection and fragments

Ecto's query DSL turns values into parameters, sent separately from the SQL text, so ordinary queries are safe from injection:

ELIXIR
# Safe: the value is a bound parameter, not pasted into the SQL
from(u in User, where: u.email == ^email)

The risk returns when you build SQL text yourself. Ecto's fragment/1 lets you write a piece of raw SQL; values inside it must still be passed through ? placeholders:

ELIXIR
# Safe: ? is a parameter
from(p in Post, where: fragment("lower(?) = ?", p.title, ^title))

# DANGEROUS: string interpolation builds SQL from user input
from(p in Post, where: fragment("title = '#{title}'"))

Ecto actually refuses string interpolation in a fragment at compile time, but the same mistake is possible with Ecto.Adapters.SQL.query/3, where a string you build is executed as-is:

ELIXIR
# DANGEROUS
Repo.query("SELECT * FROM users WHERE name = '#{name}'")

# Safe: parameters
Repo.query("SELECT * FROM users WHERE name = $1", [name])

Another trap is dynamic sort fields. You cannot bind a column name as a parameter, so do not splice one in from the query string. Map allowed values explicitly, as in the role example, and use order_by(query, ^[asc: field]) only with an atom you obtained from an allow-list.

CSRF, XSS and other web basics

CSRF (cross-site request forgery) tricks a logged-in user's browser into sending a request to your site. Phoenix includes Plug.CSRFProtection in the :browser pipeline, and forms generated with <.form> include a token that the server checks on POST, PUT, PATCH and DELETE. Do not remove :protect_from_forgery from browser pipelines. JSON APIs authenticated by an Authorization header (not cookies) are not exposed to this attack in the same way, so they use a different pipeline.

XSS (cross-site scripting) happens when untrusted text is inserted into a page as HTML. HEEx escapes values by default: {@comment} is rendered as text, so <script> becomes harmless characters. The danger is the explicit opt-out, raw/1 or Phoenix.HTML.raw/1. Use it only on content you generated or sanitized yourself.

Other items for a checklist:

  • Set secure cookie options: secure: true, http_only: true, a sensible same_site and a short session lifetime. Phoenix sessions are signed (and can be encrypted) cookies.
  • Force HTTPS in production (force_ssl in the endpoint) and send security headers; Phoenix's put_secure_browser_headers adds several.
  • Hash passwords with a dedicated library such as bcrypt_elixir, argon2_elixir or pbkdf2_elixir, never with plain :crypto.hash. The mix phx.gen.auth generator sets up a full flow with these defaults.
  • Compare secrets and tokens in constant time with Plug.Crypto.secure_compare/2, not ==.
  • Limit upload size and type, and never use user input as a file path without checking it (path traversal such as ../../etc/passwd). Path.safe_relative/2 helps.
  • Validate everything with changesets, even for internal forms, and authorize on the server for every action, including LiveView events, because the client can send any event name.
JS Constant-time comparison idea (JavaScript stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The naive loop does more work the more leading characters are right, which an attacker with a precise clock can exploit. The constant-time one always does the same work. Real implementations are written to resist this at a lower level, so use the library function, not your own.

Secrets and configuration

  • Never commit secrets (API keys, database passwords, secret_key_base) to the repository. Read them in config/runtime.exs from environment variables or a secrets manager, as shown in Releases, Config and Deployment.
  • Rotate keys that may have leaked. Changing secret_key_base invalidates all signed sessions, which is the intended effect.
  • Do not log secrets. Mark sensitive schema fields with redact: true, and filter parameters such as passwords with the :filter_parameters setting, so they appear as [FILTERED] in logs.
  • Keep dependencies updated. Run mix deps.audit (from the mix_audit package) and mix hex.audit to check for known-vulnerable or retired packages, and mix sobelow to scan Phoenix code for common mistakes.
  • Least privilege. The database user for the app should not own the schema, and the cookie for the Erlang cluster must be long and random, with distribution kept on a private network.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is String.to_atom/1 on user input dangerous?

    The atom table is global and has a fixed limit. An attacker can fill it with unique strings.
  2. 2. Which is the safest way to turn a role string into a known value?

    An allow-list never creates atoms, rejects unknown values and documents what is valid.
  3. 3. How should user input appear in an Ecto fragment?

    Placeholders send values as parameters, separate from the SQL text, which prevents injection.
  4. 4. What does the :safe option of binary_to_term/2 do?

    :safe reduces the risks of decoding untrusted binaries, but a data format like JSON is still preferable for external input.
  5. 5. Which Phoenix feature protects form posts from CSRF?

    Forms carry a CSRF token, and unsafe requests without a valid one are rejected.

Summary

  • Never create atoms from untrusted strings; use allow-lists or String.to_existing_atom/1.
  • Avoid binary_to_term/1 on external data; prefer JSON, signed tokens and [:safe] where needed.
  • Ecto parameters prevent SQL injection; keep user input out of SQL strings, and do not splice column names.
  • Keep CSRF protection on, let HEEx escape output, and treat raw/1 as a loaded gun.
  • Hash passwords with a dedicated library, and compare secrets in constant time.
  • Keep secrets in runtime configuration, redact logs and audit dependencies.

Next up: Project: Todo List with Pure Functions.