Overview
Routing is what the proxy does between accepting a client connection and joining it to a backend. The same sequence applies to every interactive protocol. This page describes that shared sequence, and the mechanisms that every protocol uses. The protocol pages (mail protocols, SMTP and submission and HTTP) describe what differs.
Connection sequence
Section titled “Connection sequence”A connection of an interactive protocol (IMAP, POP3, ManageSieve or submission) goes through these stages:
- Before authentication. The proxy sends its greeting and capabilities, negotiates STARTTLS where requested, and reads the client’s authentication command. The proxy answers this dialogue itself, because the backend is not chosen yet.
- Routing identifier. The proxy derives a routing identifier from the credentials, normalises it and removes a master user suffix.
- Resolution. The identifier is looked up in the mapping store, which returns a destination, or the default destination when the account has no mapping.
- Backend connection. The proxy connects to the destination’s endpoint for the protocol, announces the client as configured, and negotiates TLS with the backend.
- Authentication replay. The proxy replays the client’s authentication to the backend and reads the result.
- Bridging. On success the two connections are joined, and the session continues between client and backend until either side closes it or it stays idle for longer than
server.bridge_idle.
Two kinds of traffic depart from this sequence. SMTP and LMTP pass-through sessions skip stages 1, 2, 3 and 5: they are passed to one fixed destination as an uninterpreted stream, as described under SMTP and submission. HTTP requests are routed one by one, by route rules.
Every listener requires a [routing] section with a default_destination; a configuration that declares listeners without it is refused with listener.<name>: a listener requires a [routing] section with default_destination. A proxy started with only the management API, as proxy init creates it, needs no [routing] until the first listener is added.
Routing identifier
Section titled “Routing identifier”The routing identifier is the account name that the proxy looks up. It is taken from the authentication, in a way that depends on the mechanism:
- For password authentication (SASL
PLAINandLOGIN, the IMAPLOGINcommand and the POP3USERcommand), the identifier is the user name the client supplies. An authorisation identity inPLAINis ignored. - For
OAUTHBEARERandXOAUTH2, the identifier comes from the user name in the frame (thea=authorisation identity ofOAUTHBEARER, theuser=field ofXOAUTH2) or from the token, as described below. - For an HTTP bearer token, which carries no user name, the identifier comes from the token.
Tokens come in two forms, and the proxy reads the identifier from each differently:
- A Stalwart access token is recognised by its
sw1.prefix. It carries the account name in a readable part, which the proxy uses. The rest of the token is encrypted, and is not read. - Any other token is read as a JSON Web Token. The identifier is the first claim whose value contains
@, trying the configuredjwt_username_claimfirst, and thenemail,preferred_username,upn,unique_nameandsub.
A JSON Web Token payload is accepted with or without = padding. The proxy does not validate tokens. Their signature, expiry and audience are checked by the backend that receives them.
An OAuth login can carry an identity in two places, the frame and the token, and the proxy tries the candidates in a fixed order:
- The user name in the frame, when it contains
@. - The account name of a Stalwart access token.
- The first matching claim of a JSON Web Token.
- The user name in the frame without
@, such as an unqualified login of a legacy server.
A user name that is a full address therefore takes precedence over the token, which matters for XOAUTH2 clients whose tokens are opaque to the proxy (for example Google and Microsoft consumer tokens). A bare user name is used only when the token yields nothing. A candidate that is not a valid identifier is skipped, and the next one is tried.
Logins that yield no identifier at all, such as a token without an account name and a frame without a user name, use the default destination for mail protocols, and the rule’s fallback destination for HTTP. Older Stalwart servers issue such tokens, as described in the migration troubleshooting.
The identifier is then normalised as configured in the mapping store, and a master user suffix is removed, as described under Master users.
An identifier is limited to 320 bytes, measured after normalisation and after the master user suffix is removed. For the mail protocols, an identifier that is longer, or that contains control characters, spaces or double quotes, is rejected before any lookup: the client receives the backend-unavailable response, and the connection is closed. This keeps malformed identifiers out of the lookup cache, the mapping store and the announcement sent to the backend. For HTTP, such an identifier is treated like a missing one.
The password or token is used only to derive the identifier, and is passed to the backend unchanged.
Authentication replay
Section titled “Authentication replay”The proxy does not verify credentials. After connecting to the destination, the proxy rebuilds the client’s authentication command in the form the backend expects, sends it, and reads the backend’s reply.
On success, the proxy passes the reply to the client and joins the connections. On failure, it returns the backend’s reply to the client (or a generic one when the destination sets hide_auth_errors), closes the backend connection, and continues its own dialogue with the client. The client may then authenticate again on the same connection. Each attempt is routed on its own, so a second attempt for another account reaches that account’s destination. Rejections by the backend count towards the listener’s max_auth_attempts, as do malformed commands during the pre-authentication dialogue; when the limit is reached, the connection is closed. The listener’s preauth_timeout starts again after each failed login.
The proxy holds the credentials only during this exchange, and never writes them anywhere. Before replaying credentials over a mail protocol, it checks that the connection to the backend is encrypted. The exception is a destination that sets allow_plaintext_auth, for a backend reached over a connection that is protected by other means.
Some mechanisms are converted on the way. The proxy conducts a SASL LOGIN exchange itself, sending the Base64 Username: and Password: prompts, and rebuilds the result as a PLAIN authentication. The IMAP LOGIN command and the POP3 USER and PASS commands are rebuilt the same way. The backend therefore only ever receives PLAIN, OAUTHBEARER or XOAUTH2.
A client may send the Base64 user name as the initial response of LOGIN. A client may cancel any exchange, whatever the mechanism, by answering a continuation with *. LOGIN is offered only when it is in the protocol’s sasl list and cleartext authentication is permitted on the connection, as described under Authentication mechanisms.
A backend may also be unavailable: it cannot be reached, its destination is marked down by the circuit breaker, or it does not complete the authentication exchange (an error, or no verdict within server.backend_timeout). The client then receives the protocol’s temporary failure response, and the connection is closed, so that the client retries later instead of reporting an authentication error. The responses are:
NO [UNAVAILABLE] backend unavailablein IMAP-ERR backend unavailablein POP3421 4.3.0 backend unavailablein submissionNO "backend unavailable"in ManageSieve
Forwarding the client address
Section titled “Forwarding the client address”The backend sees a connection from the proxy, not from the client. The proxy therefore announces the client’s address, with one of two mechanisms. The mechanism is selected per destination, by the forwarding key described under Destinations.
PROXY protocol
Section titled “PROXY protocol”With forwarding = "proxy", the proxy starts the backend connection with a PROXY protocol version 2 header, before any protocol data and before TLS. The header carries the client’s and the proxy’s socket addresses. The backend reads it, and attributes the session to the client.
The mechanism is independent of the protocol, and is used for Stalwart and other backends that understand the PROXY protocol. When the client’s address and the proxy’s own address on that connection belong to different address families, the proxy writes the IPv4 one as an IPv4-mapped IPv6 address (::ffff:192.0.2.10), so that the backend still receives the client’s address. Stalwart treats a mapped address as the IPv4 address it contains.
XCLIENT and IMAP ID
Section titled “XCLIENT and IMAP ID”With forwarding = "xclient", the proxy announces the client inside the protocol. Dovecot and Postfix support these extensions.
For submission, POP3 and ManageSieve, the proxy sends an XCLIENT command. It carries the client’s address and port, the proxy’s address and port, a session identifier, the forwarding time-to-live and the transport security. For submission, it also carries the client’s HELO name and protocol.
IMAP has no XCLIENT command, so for IMAP the proxy sends an ID command instead. It carries the same information in fields such as x-originating-ip and x-connected-ip, together with the forwarding time-to-live.
The proxy sends these commands only to a backend that advertises them. When a backend does not, the proxy logs a warning once for that destination (and again after a configuration reload) and continues without announcing the client. For submission, it also sends only the attributes that the backend’s XCLIENT announcement lists, because some servers reject unknown attributes. The LOGIN attribute of XCLIENT is never sent. The proxy always replays the authentication, so pre-authenticating the session through XCLIENT is neither needed nor safe.
HTTP headers
Section titled “HTTP headers”For HTTP, a destination with forwarded = true also receives the client’s address in the Forwarded and X-Forwarded-For request headers. These come in addition to the PROXY header, when forwarding resolves to proxy. Headers sent by the client are kept or removed according to the listener’s forwarded setting, as described under HTTP routing.
TLS on both legs
Section titled “TLS on both legs”The connection to the client and the connection to the backend are encrypted independently. The client side follows the listener’s tls mode and the inbound certificates. The backend side follows the tls mode of the destination’s endpoint, and the destination’s verification settings. The two need not match: a client may connect with implicit TLS while the proxy reaches the backend with STARTTLS, or the reverse.
On the backend side, each mode behaves as follows:
- With an
implicitendpoint, the proxy starts TLS as soon as it connects. - With a
starttlsendpoint, the proxy connects without TLS, checks that the backend advertises STARTTLS, issues the command, and then starts TLS. When the backend does not advertise or accept STARTTLS, the connection is closed; it never continues without encryption. Data that arrives after the backend’s STARTTLS reply but before the handshake also closes the connection, because it could have been injected by an attacker on the network between proxy and backend. After the upgrade, the proxy discards the capabilities it learned in cleartext and asks for them again over TLS. - With a
plainendpoint, the connection is not encrypted, and the proxy does not replay credentials over it unless the destination setsallow_plaintext_auth.
Loop prevention
Section titled “Loop prevention”A misconfigured destination could make the proxy connect to itself. Three checks guard against such loops. They compare destinations against every listener bind and against the bind of the management API, including its loopback or wildcard twin on the same port.
The first check runs before connecting. A destination whose host is an IP address is refused when that address, together with the endpoint’s port, equals one of the proxy’s own binds exactly. The refusal reads proxying loop: destination is one of our own listeners.
The second check runs after the TCP connection is established, for destinations given by host name and whenever one of the binds is a wildcard address. The proxy compares the address it actually reached with its binds: a peer equal to a bind, or a peer on the proxy’s own host (a loopback address or the local address of the connection) on the port of a bind that accepts it, is refused with proxying loop: backend connection reached one of our own listeners. A host name that resolves to the proxy itself is caught this way, and so is a destination on the same host as a listener bound to 0.0.0.0 or ::. The connection is closed before anything is sent on it.
The third check uses a forwarding time-to-live. For backends announced with XCLIENT or IMAP ID, the proxy sends a forwarding time-to-live of server.proxy_ttl minus one. It refuses such connections with proxying loop: forwarded TTL exhausted when server.proxy_ttl is 1 or less. The proxy does not read a time-to-live from incoming connections, so it does not detect a chain of several proxies that loops.
A refused connection is a configuration error rather than a backend failure: it is not retried and does not count towards the destination’s circuit breaker. In the log the text carries a configuration error: prefix, at warning level for the mail protocols (the backend unavailable line) and at debug level for HTTP and SMTP pass-through. The mail client receives the backend-unavailable response, an HTTP client receives 502 Bad Gateway, and a pass-through connection is closed without a reply.