Security model

This page collects the protections that are in Karta's code, so that operators know what they can rely on and reviewers know where to look. To report a vulnerability, follow the security policy: report privately, never in a public issue.

Tenants are kept apart

  • Every lookup is scoped by server or organisation: a message, recipient, credential, suppression or domain of another tenant is simply not found. Ids that are not UUIDs, or that belong to another server, give the same "not found" as ids that do not exist. Tests check this for every API.
  • A domain name can be verified for one organisation only, and only verified domains can appear as author or envelope sender, or be signed for. Verification needs a TXT record with the domain's random 160-bit token, which only someone who controls the domain's DNS can publish, or an administrator of the instance; a second organisation's record does not take a verified name over. A failed DNS lookup never verifies or unverifies a domain.

Sender authorisation on parsed addresses

From, Sender and the envelope sender are checked on addresses parsed by a strict RFC 5322/6532 parser (Karta.Mail.Address, Karta.Mail.Authorisation), never by matching text: a comment or display name that contains an address cannot choose the domain that is checked. Messages with several From fields, several Sender fields or groups are refused. See Sending rules and limits.

Secrets

SecretStored as
API key secretArgon2id hash (16 MiB, 3 passes, 1 lane), found by an 8-character prefix
SMTP passwordSCRAM-SHA-256 stored and server keys (PBKDF2-SHA-256, 100,000 iterations, 16-byte salt); the password is not recoverable
DKIM private keysAES-256-GCM under the vault key
Local login passwordsArgon2id hash (16 MiB, 3 passes, 1 lane)
TOTP secretsAES-256-GCM under the vault key
Webhook secrets (Standard Webhooks, Mailgun's signing keys, the private keys of SendGrid's key pairs) and the passwords of webhook URLsAES-256-GCM under the vault key; shown once (secrets), or never (SendGrid's private keys, whose public keys are shown; passwords)
The RSA key that signs one organisation's requests in Postal's format, and the extra authentication header of a webhook or inbound endpointAES-256-GCM under the vault key; only the key's public parts (its JWK set) and the header's name are shown; the header's value is shown once, when it is set
Session tokensSHA-256 hash; the token is only in the user's session cookie
Message bodiesAES-256-GCM, a key per message derived from the vault key
  • Postal-format signing keys belong to one organisation each: a receiver of one organisation cannot verify a request signed for another with its own key. The JWK set's address holds an unguessable token and serves public keys only; it names no organisation.
  • A webhook's or an inbound HTTP endpoint's extra authentication header is sent beside the format's signature, never instead of it. It does not protect the body's integrity or a request sent again.
  • Keys and passwords are generated by Karta from the operating system's random source, shown once, and use only a-z and 2-7.
  • Unknown SMTP user names and revoked credentials take the same work as a wrong password, and a SCRAM exchange for them uses a made-up salt that is the same every time, so neither timing nor the exchange reveals whether a user name exists. Unknown API key prefixes run a dummy Argon2id verification.
  • The API key cache keeps only a SHA-256 hash of each key, and every request still reads the credential from the database, so revocation is immediate.
  • Secrets are redacted from Ecto structs' inspection and from crash reports of SMTP connections.
  • Encryption uses AES-256-GCM through Erlang's :crypto, with a fresh random 96-bit IV per value, and authenticates the key id, so a value cannot be relabelled as another key's. Stored bodies bind their key to the object name, so one message's body cannot be swapped for another's.

SMTP

  • AUTH is offered only over TLS; credentials are never accepted in clear.
  • Only TLS 1.2 and 1.3 with forward-secret AEAD suites; no renegotiation by the client.
  • After STARTTLS, input sent before the handshake is discarded and the session starts over (no command injection across the upgrade).
  • SMTP smuggling: a bare CR or LF in a command, or in the data, is refused (500 5.5.2, 554 5.6.0), and the end of data is recognised only as CRLF.CRLF. Regression tests feed known smuggling payloads and check that at most one message results and that it is refused (test/karta/smtp/regression_test.exs). Outbound, a stored message with bare line endings is never sent (5.6.0).
  • Every input is bounded: line length, header size, message size, recipients, errors, rejections, AUTH failures, connections per client and per minute, idle time, connection lifetime and the memory of each connection process (SMTP listeners).
  • The Received: field writes the HELO name and the recipient only when they are valid and printable, so a client cannot inject header lines through it.
  • The PROXY protocol header is read only from configured trusted proxies.
  • IP range credentials are not an open relay. A range is checked against the connection's own peer address (or the PROXY header of a trusted proxy), never against anything in a message; it must be no wider than the instance's minimum prefix (/16 of IPv4 and /48 of IPv6 by default), and the whole address space (0.0.0.0/0, ::/0) is refused always. A client in a range may send only from the verified domains of that server's organisation, under the credential's rate limit and the server's suspension, exactly as an authenticated client. The mx listener relays only when the operator sets KARTA_SMTP_MX_IP_RELAY=true; with it off, port 25 refuses every client that is not routing mail for a server, range or no range. Overlapping ranges are resolved by the most specific prefix; two active credentials cannot name the same range.
  • Outbound TLS is never weakened by an attacker in the path: under DANE, MTA-STS enforce, configured verified TLS or REQUIRETLS, a missing STARTTLS, a failed handshake or a certificate that does not check out defers the message instead of sending it in clear, and DANE trusts only the TLSA records from a validated DNS answer (the AD bit is believed only from a resolver on a trusted path, see DNS resolver). TLS-Required: No relaxes the recipient's policies only for the message that carries it, at its sender's request.

Checking the senders of received mail

The mx listener checks SPF, DKIM, DMARC and ARC on every message it receives (Checking the sender). The checks look up names that strangers choose, so they are bounded:

  • Work. SPF stops at 10 terms that look up DNS, 2 lookups that find nothing (both permerror), 10 MX records per mx and 10 PTR names per ptr (RFC 7208 §4.6.4). DKIM evaluates at most 8 signatures. The DMARC tree walk makes at most 8 queries per name however many labels it has (RFC 9989 §4.10), and only identifiers under the author's own organisational domain are walked, so a stranger's slow DNS cannot slow down or change the verdict on someone else's domain. An ARC chain has at most 50 sets (more, or more than 150 ARC fields, fail before any lookup); each key is looked up once per message, so a chain costs at most 100 lookups and 100 signature checks, and the body is canonicalised at most twice. ARC runs after DMARC, so a long chain cannot delay the DMARC verdict. All lookups go through the DNS cache.
  • Time. All checks of a message share 20 seconds; after that no lookup starts (SPF, DKIM, DMARC or ARC), and a check still running a second later is stopped. The checks also stop when the connection that asked for them is gone. RCPT never waits for them: they run once, after the data.
  • Failures. A check that cannot finish is a temperror, and a temperror never refuses a message (mail is not lost when DNS fails). Only a DMARC fail for a domain whose owner asks for rejection, or a message naming more than five author domains, is refused (550 5.7.1).
  • Header injection. The Authentication-Results: field Karta adds holds only fixed words and values it checked: domain names in their normalised form, a DKIM selector and the start of a signature, each written as a MIME token or a quoted string of printable ASCII; the field is built by the same code as every field Karta writes, which refuses line breaks and control characters. Local parts are never reported (SPF does not authenticate them).
  • Forged results. Every Authentication-Results: field that claims Karta's authserv-id (compared as a reader would: after comments, without case or a final dot, quoted or not) is removed from a received message before it is stored (RFC 8601 §5). Applications should trust only the fields with Karta's id.
  • ARC is evidence, not trust. A valid chain says who handled the message, not that they are honest (RFC 8617 §9.4). Its results change a verdict only for a sealer the operator names (KARTA_ARC_TRUSTED_SEALERS, none by default), only as the newest sealer, and only when that sealer's own results say DMARC passed for the author's domain. Results claiming Karta's authserv-id are never read as Karta's, in an ARC-Authentication-Results: field either; the ARC fields themselves are kept, as the chain needs them.
  • ARC seals. Karta seals only forwards of mail it received and checked itself, never mail submitted to it, with the receiving domain's own DKIM key (kept encrypted, rotated and published with it; it is never written out). The set's results are copied from Karta's own Authentication-Results: field of the stored message, which arriving mail cannot forge (above), and written by the same code as every field Karta writes.
  • Organisational domains. DMARC finds them by the DNS tree walk; the Public Suffix List, refreshed every night, keeps a record published at a public suffix from making all the domains under it aligned with each other.

Scanning received mail

Spam and virus scanning (Karta.Scan) talks to two services the operator names, never to an address a sender or an application chose, so it does not go through Karta.NetGuard (which guards the requests whose addresses strangers write). The boundaries are elsewhere:

  • How much is read. The message is streamed from the spool file: rspamd receives it as the body of one HTTP request read in chunks from disk, and clamd in INSTREAM chunks of 64 KiB; neither Karta nor the scanners' clients ever hold a second copy of it. The answer is bounded too (rspamd's at 1 MiB, clamd's at 4 KiB), so a scanner cannot make the receiving process grow.
  • How long. One budget (KARTA_SCAN_TIMEOUT, 5 seconds) covers both scanners; a scan that has not finished is stopped in a process of its own and reported as failed, so an SMTP connection is never held longer.
  • What reaches a message. The X-Spam-* and X-Virus-* fields hold only what Karta formats itself: scores as numbers, one of rspamd's actions (anything else becomes unknown), symbol names of letters, digits, _, . and - with a score, and a virus name reduced to the same alphabet. No text a scanner sends reaches a field as it is, and each field is capped, so a scanner cannot add a line to a message.
  • Fail-closed. A scanner that is configured but cannot answer (down, slow, an answer Karta cannot read, a message larger than the scan size) refuses the message with 451 4.7.1 unless every recipient's route is fail_closed: false; then it is accepted and marked X-Spam-Scanned: no. A scanner that is not configured is not a failure: a fresh installation does not refuse mail because nobody set up rspamd.
  • Releasing held messages is scoped like every other operation on received mail: only a message of the caller's own server is found, and only its held deliveries move, in one conditional statement, so two releases queue each delivery's job at most once.

DMARC reports

A DMARC report (aggregate or failure) or a TLS report arrives over SMTP from anyone who can reach the address, so it is read as hostile input (Karta.Reports.Ingest):

  • The message is at most 10 MiB, and what it carries is unpacked to at most 32 MiB: a gzip stream, or one zip archive read from the archive's own directory, whose file's CRC and size are checked. A stream that would grow past the limit is stopped as soon as it does, so a small archive cannot expand without bound.
  • The XML is read by OTP's SAX parser with entity declarations refused, external entities never read and undeclared references an error: no document type declaration, no entity, no file or URL outside the document. At most 2,000,000 elements, 50,000 records, 10 reasons and 100 authentication results per record, and 1,024 bytes per field. Nothing is looked up while a report is read.
  • A failure report is read with Karta.Complaints.ARF's bounds (65,536 bytes, 100 fields) and keeps only the reporter's fields, at most 255 characters each, and the quoted message's Message-ID: the quoted message is a stranger's and is not stored. A TLS report is JSON of at most 8 MiB with at most 200 policies, 1,000 failure details, 100 policy lines and 100 MX hosts a policy, strings cut at 255 characters and counts below 10^12; one with more policies is refused. Nothing in a report makes Karta fetch anything.
  • A report is attributed to a verified domain of the receiving server's organisation, or to none, and it is never authority for anything: it cannot verify a domain, change a policy, suppress an address or make Karta accept mail. The pages of one organisation never show another's reports.

No server-side requests from user input

No endpoint fetches a URL taken from a request or a message: not the APIs, not the tracking host, not Postal's image proxy path (which is not served). Tests check this for every API (test/karta_web/no_url_fetching_test.exs). Five components make HTTP requests. Three talk only to URLs in the instance's configuration, which may well be on a private network: the blob store (Karta.Storage), to its configured endpoint; the DNS providers (Karta.PowerDNS, Karta.RFC2136), to the server in the operator's configuration (below); the Public Suffix List's nightly refresh (Karta.PublicSuffix.Refresh), without redirects, at most 4 MB, the answer used only once it passes the list's checks. Two connect to hosts that someone else names, so they treat them as hostile: outbound delivery, which fetches a recipient domain's MTA-STS policy from https://mta-sts.<domain>/.well-known/mta-sts.txt (a fixed GET over verified TLS, bounded in time (60 s) and size (64 KiB); nothing of the answer is used but the policy), and webhooks, whose URLs the servers' owners set (Karta.NetGuard.HTTP: a signed POST, bounded in time (15 s), at most 1 KB of the answer kept).

Every connection to a host someone else names goes through the NetGuard (Karta.NetGuard): webhook requests, the MTA-STS fetch, the SMTP connections of outbound delivery to the recipient's mail servers (Delivery), and the STARTTLS check of the MX hosts before an MTA-STS policy Karta serves is set to enforce (Karta.MTASTS.Probe: EHLO, STARTTLS, the certificate checked, QUIT; no mail). Karta resolves the name itself, refuses private, loopback, link-local, carrier-grade NAT, unique local, NAT64 (64:ff9b::/96, 64:ff9b:1::/48), 6to4 (2002::/16), Teredo, documentation, multicast, reserved and other special addresses (an address written in a URL or an address literal too), and connects to the address it checked, with the original name in Host and in TLS: a second answer from DNS cannot point the connection elsewhere (DNS rebinding). No redirect is followed. An operator who needs a private network reachable (a webhook receiver on the instance's own network) allows it with KARTA_NET_GUARD_ALLOWED_NETWORKS; nothing is allowed by default.

Received mail goes to hosts that the servers' owners name too: an HTTP endpoint's URL and an SMTP endpoint's host go through the NetGuard exactly as webhooks do (resolved once, every address checked, the checked address connected to, no redirects). The mx listener is no open relay: it takes only addresses that a route of a verified domain names, and a route can name only a domain verified by the server's own organisation. An SRS address takes only bounces, and only with a valid tag (HMAC under the vault key, at most 21 days old). Karta never bounces received mail after accepting it (no backscatter): it refuses at RCPT or at the end of the message, and records failures for the owners. A route's address cannot contain +; plus addressing can be switched off per route, so that name+anything is not received as name. One message is relayed, or forwarded, once per SMTP or address endpoint, however many of its recipients route there: a stranger cannot multiply one message into hundreds of outgoing copies.

Received mail in Postal's formats is signed with the instance's one Postal key, as webhooks in Postal's format are (below): one organisation's receiver can pass a signed RawMessage or Hash on to another organisation's Postal-format endpoint, which verifies it. Receivers should drop delivery ids (id) they have seen and check that the recipient is theirs; Karta's own formats (karta, raw), signed with a secret per endpoint and with the time, are the better choice where the receiver can change.

Received mail in the providers' inbound formats is enough for the provider's receiver to work, and no more. Mailgun's format is signed with a signing key of the endpoint's own, but (as Mailgun's own is) over a timestamp and a random token, not over the body: a receiver must check that the token has not been used before and that the recipient is theirs. SendGrid's and Postmark's formats are not signed at all: only a user name and password in the URL (over https://) authenticate Karta, and the message itself is in the request (email, RawEmail), so a receiver must not treat it as verified mail. A parsed format sends only the delivery's own address in recipient, rcpt_to, OriginalRecipient and the envelope; the message's own To and Cc fields are those of the message, as the provider sent them.

Webhook signatures in the providers' formats are weaker than Karta's own. Standard Webhooks signs the event's id and the time with the body under a secret of the webhook. Postal's format signs the body only, with one RSA key of the instance: a request can be sent to its receiver again later, and a receiver of one organisation could pass a request on to another organisation's receiver, which verifies it too. Mailgun's format signs a timestamp and a random token, not the body. SendGrid's format signs the time and the body, but not an event id, and SendGrid's libraries do not check the time. Postmark's format is not signed at all: only a user name and password in the URL (over https://) authenticate Karta. They exist so that applications written for those providers work unchanged; their receivers should drop requests they have seen (uuid, token, sg_event_id, X-PM-Webhook-Trace-Id) and check that the message is theirs. Mailgun's webhooks API gives the webhooks it makes one signing key, shared as Mailgun shares one per account. Every receiver of a webhook that shares it can sign requests the others accept, as with Mailgun; give the webhooks of one server only to receivers you trust alike, or add the others over the Karta API, where each webhook has its own key. A user name and password in a webhook URL are allowed over https:// only, kept apart from the URL and encrypted, sent as Basic authentication, never shown again; request parameters named url are left out of logs and error reports.

Content that organisations upload

  • BIMI logos are SVG, a format that can carry scripts and links. Karta stores one only when it meets SVG Tiny PS (Karta.BIMI.SVG): parsed by OTP's SAX parser with entity declarations refused, external entities never read and no atoms made from the file; no document type declaration or processing instruction; only the profile's elements and attributes (no scripts, event handlers, styles, raster images, links or foreign namespaces); references only to elements of the file; at most 32 KB. Karta serves it from the tracking host as image/svg+xml with X-Content-Type-Options: nosniff and a content security policy that allows no scripts; the admin page shows it in an <img> (as a data: URI, which the admin pages' policy allows), where an SVG runs no script and loads nothing.
  • MTA-STS policies Karta serves are written by Karta from the mode, the host names (checked as host names) and max_age; nothing typed reaches the file as it was typed. A policy is served only at mta-sts.<domain> of a verified domain whose CNAME record points to Karta.

Publishing DNS records

  • The server's URL (and, for PowerDNS, its key), and the TSIG key's name and secret, come from the operator's configuration (KARTA_DNS_PROVIDER with KARTA_POWERDNS_* or KARTA_DNS_RFC2136_*), never from a request: no organisation can point Karta at another server. Redirects are not followed (one could carry the key elsewhere); errors never include the request; the key and the secret are redacted when the configuration is inspected and are never logged.
  • Karta writes only in the zones the operator lists, and only for verified domains: an organisation that adds a name in such a zone cannot make Karta publish the ownership record that would verify it.
  • Karta replaces and removes only RRsets it wrote (a marker naming the domain: a PowerDNS comment of the account karta, or an entry in the RFC 2136 provider's inventory record), at the names and types it publishes for that domain; another organisation's domain, even a subdomain in the same zone, has its own marker. Records someone else wrote are taken over only when they already hold exactly Karta's records.
  • An RFC 2136 update carries a prerequisite per RRset (it still holds the records Karta read, or does not exist yet) and its signature is checked in every answer, so a stale change is refused and an answer cannot be spoofed.
  • What is written comes from Karta's own records: the ownership token, the public keys Karta generated, the tracking host's name under the domain, the configured CNAME target, and the MTA-STS policy's id, the TLS reports' address and the BIMI record that owners and admins of the verified domain set (each checked as above).

Signed tokens

Tracking tokens, VERP return paths and Mailgun paging tokens are HMACs with keys derived from the vault key (HKDF-SHA256, a different label for each use), compared in constant time, and checked before anything is looked up. A click redirects only to the URL stored when the message was sent; nothing in the request can change the target. The kind of a tracking token is signed, so the open pixel cannot be used as an unsubscribe link.

Signing in

  • Through an OpenID Connect provider: authorization code flow with PKCE (S256), state and nonce, the ID token verified by oidcc, and only addresses the provider has verified. The flow is kept in the encrypted session cookie for ten minutes and used once.
  • A provider account is never linked to an existing Karta user by its e-mail address alone (providers let users change their address), unless KARTA_OIDC_LINK_BY_EMAIL=true; an operator links them explicitly.
  • Local login is off by default. Its failures all get the same answer after the same Argon2id work; attempts are limited per address and per client, TOTP codes per user, and a code is accepted once.
  • Sessions live on the server for 12 hours; signing in issues a new cookie, signing out and disabling a user end sessions at once, and open pages check their session every minute. Forms are protected by CSRF tokens.
  • A page to return to after sign-in is always a path on Karta's own host.
  • The admin pages decide on the server what a user sees and may do: every page and every action on it checks the user's role in the database at that moment, events a page does not declare are refused, and records an action names are looked up within the page's organisation or server. A page the user may not see answers 404, as one that does not exist.
  • New API keys and SMTP passwords are shown once, on the page that made them, and never again: they are not put in the flash, the URL or the database. A webhook's new signing secret is shown once in the same way (Karta keeps it encrypted, to sign with); the webhook pages keep no secret of a webhook in their state, show SendGrid's public keys but never their private keys, and show a webhook URL's user name but never its password. Only owners and admins change webhooks there; a webhook's URL is checked as over the API, and its requests go through the NetGuard.
  • See Sign-in and access.

Security headers

The admin pages send a content security policy that allows scripts, styles, images and fonts from Karta only, no inline scripts or styles, no framing (frame-ancestors 'none', X-Frame-Options: DENY) and no plugins; Referrer-Policy: no-referrer, a permissions policy that turns off camera, microphone, location, payment and USB, Cross-Origin-Opener-Policy and Cross-Origin-Resource-Policy: same-origin, and Cache-Control: no-store. In production both HTTP endpoints redirect to HTTPS and send Strict-Transport-Security.

Message bodies

A message is the sender's content, so the admin pages treat everything in it as hostile. Header fields, the plain text and file names are shown as escaped text. The HTML part never enters an admin page; three layers stand between it and the browser:

  1. Made safe on the server (Karta.Mail.SafeHTML): the part is parsed as a browser parses it (an HTML5 parser) and written again from elements and attributes on a list of harmless ones. Scripts, frames, plugins, forms and their controls, link, meta, base, SVG and MathML are removed, event handlers and every attribute that names a resource too; links lose their target (it becomes their title); images keep only data: URIs and the message's own cid: images, inlined; CSS loses @import, escapes and every url() other than a data: image. Nothing remote is even requested.
  2. A document of its own, from its own route, which checks access as the message page does (a 404 for anyone who may not see the message) and sends Content-Security-Policy: default-src 'none'; img-src data:; style-src 'unsafe-inline'; frame-ancestors 'self'; base-uri 'none'; form-action 'none'; sandbox, X-Frame-Options: SAMEORIGIN, Referrer-Policy: no-referrer, X-Content-Type-Options: nosniff and Cache-Control: no-store. The sandbox directive applies even when the document is opened on its own.
  3. A sandboxed frame on the message page: <iframe sandbox> with no exceptions, so no scripts, no forms, no pop-ups, no navigation of the page and an origin of its own.

The raw message is a download (application/octet-stream, Content-Disposition: attachment, nosniff), never shown inline. Bodies are decrypted for each request and not cached.

Client addresses behind proxies

X-Forwarded-For and X-Forwarded-Proto are believed only from the ranges in KARTA_TRUSTED_PROXIES (KartaWeb.ClientIP); X-Forwarded-Host never. Limits per client count an IPv4 address or an IPv6 /64. The APIs read a request's body only after its key has been accepted.

The tracking host

The tracking links are served by a separate endpoint on its own port, with no API, no cookies, no sessions and no request body parsing; every answer forbids scripts, caching, indexing and referrers (Tracking and unsubscribe). Unsubscribing takes a POST, so link scanners cannot unsubscribe anyone.

Header handling

Headers given through the APIs are checked: names of printable ASCII, no line breaks or control characters in values, and the fields Karta writes itself (From, To, Date, Message-ID, the MIME fields, Received, DKIM-Signature, ...) cannot be set again. DKIM signatures oversign the author, subject, date and recipient fields, so they cannot be added after signing. Addresses given as text (Postmark's From, To, ReplyTo, ...) are parsed and written anew, so nothing of the text as sent reaches the header; an attachment's name and content type are checked as header values are.

The replacements of a Karta API batch are plain text put in once: nothing is evaluated and a value is never searched again. They go into the subject, the text and the HTML only, never into header fields or addresses; a value for the subject may hold no line break or control character, and in the HTML every value is escaped, so a recipient's values cannot add a header field or markup.

Privacy

  • Opens and clicks store the client's network (IPv4 /24, IPv6 /48), not its address, and a shortened user agent; they are deleted with the message.
  • Log messages about storage and delivery failures carry no message content.

Hardening checklist

  • Keep the vault key, SECRET_KEY_BASE and the database and S3 credentials in a secret store; give the S3 key access to Karta's bucket only.
  • Keep the metrics port (9568) and the database off the public network.
  • Run the resolver on the loopback address or a private sidecar network; set KARTA_DNS_TRUST_AD only for such a network.
  • Run the image as built: unprivileged, read-only root, a tmpfs at /tmp and a private volume for the spool.
  • Serve the API and the tracking host only over HTTPS; production redirects HTTP and sends HSTS.
  • Use KARTA_SMTP_TRUSTED_PROXIES and KARTA_TRUSTED_PROXIES only with the exact ranges of your load balancers and reverse proxies.
  • Prefer sign-in through your identity provider; turn local login on only where you need it.
  • Watch CHANGELOG.md: every security fix has an entry under Security.

Dependency checks

mix precommit runs hex.audit and deps.audit (known advisories) and sobelow (Phoenix security checks); CI also runs trivy fs on every pull request. See Development.