Files
leaf/docs/configuration.md
eric 7899cadebc feat(failover): let the deployer choose where health checks go
Every failover health check connected to www.google.com:443 and asked
1.1.1.1:53 about www.google.com, through every actor, direct ones
included, on a timer. That is a fixed pattern an observer can match,
direct DNS in the clear, and where Google is blocked a direct actor was
always marked down. The TLS check also sent "GET / HTTP/1.1" with no Host
header, which no browser does.

healthCheckTcpDestination (host:port) and healthCheckUdpDestination
(ip:port), health-check-tcp-destination and health-check-udp-destination
in .conf, now set them; the defaults are unchanged. The DNS check asks
for the TCP destination's name, or the root zone when that is an
address, and the HTTP request carries a Host header, with the port when
it is not 443. An IPv6 address must be in brackets. A malformed value
fails at startup.

A test runs real checks through a direct actor against local listeners.
2026-12-04 09:55:40 +08:00

966 lines
41 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Configuration reference
Every option leaf reads: what it does, what it accepts, and what happens when it
is left out. Choices that decide whether traffic stays behind the proxy --
certificate checks, name resolution, the default route, logging -- are marked
**Security**, and [security.md](security.md) explains them in context. Read that
before deploying anything to people who depend on it.
- [Files and formats](#files-and-formats)
- [Top level](#top-level): [`log`](#log), [`env`](#env), [`dns`](#dns)
- [Inbounds](#inbounds)
- [Outbounds](#outbounds)
- [Router](#router)
- [Environment variables](#environment-variables)
- [Command line](#command-line)
- [The `.conf` format](#the-conf-format)
## Files and formats
leaf reads a configuration file named by `-c` (default `config.conf`). The
extension picks the parser: `.json` or `.conf`. Anything else is refused.
The JSON format is the complete one and is what the rest of this page
describes. The `.conf` format is a shorter syntax for common setups; it is
translated into the same structure, and [its own section](#the-conf-format)
lists what each of its keys becomes.
JSON keys are camelCase. Where a key has two words, the snake_case spelling
(`server_name` for `serverName`) is accepted too, except where noted. Unknown
keys are ignored, except in the settings of `socks`, `shadowsocks`, `trojan`
and `ws` inbounds, `amux`, `chain` and `mptp` inbounds, and `trojan` and
`chain` outbounds, which refuse them.
A setting that is left out takes the default listed for it. Many string
settings have no default and are effectively required; an empty value often
fails only when the outbound is first used, not when leaf starts.
`leaf -T -c <file>` checks that a file parses, without starting anything; it
does not build the outbounds, so it does not catch those.
## Top level
```json
{
"log": { ... },
"env": { ... },
"dns": { ... },
"inbounds": [ ... ],
"outbounds": [ ... ],
"router": { ... }
}
```
Every section is optional. With no `inbounds` leaf accepts nothing; with no
`outbounds` it has nowhere to send what it accepts.
### `log`
| Key | Values | Omitted |
|---|---|---|
| `level` | `trace`, `debug`, `info`, `warn`, `error`, `none` (any case) | `info`. An unrecognised value is `warn`. |
| `output` | `console`, or a path to append to | `console` |
| `format` | `full`, `compact` | `full` |
**Security.** At `info` and above, a connection is logged as its protocol, the
inbound and outbound it used and how long it took to connect. At `debug` and
`trace` the line also carries the source address, the destination, the domain
sniffed from it and, in builds with process rules, the process name -- which
together are a record of where every user went. Use `debug` or `trace` only to
diagnose a problem, and treat the file they write as sensitive: limit who can
read it and delete it afterwards. `warn` is a reasonable level for a
deployment. Plugins log through the same levels.
On macOS, `output: "console"` with `LOG_CONSOLE_OUT=true` writes to the system
log rather than standard output, where other software on the machine can read
it.
### `env`
A map of environment variables to set before anything else is read:
```json
"env": { "DNS_TIMEOUT": "2", "TCP_DOWNLINK_TIMEOUT": "5" }
```
It is the same as setting them in leaf's environment, and any variable in
[Environment variables](#environment-variables) can be set this way. Each is
read once, when it is first needed, so changing `env` and reloading the
configuration does not change a value that is already in use. An empty name is
ignored.
### `dns`
leaf's own resolver. It is used when leaf itself needs an address: to reach a
proxy given by name, to connect a `direct` outbound to a name, for
`router.domainResolve`, and for ECH. It is not involved when an application
hands leaf a name and the outbound passes that name on to a remote proxy: the
proxy resolves it.
| Key | Values | Omitted |
|---|---|---|
| `servers` | List of servers, below | `["1.1.1.1"]` |
| `hosts` | Map of name to a list of IP addresses | none |
A server is one of:
| Form | Meaning |
|---|---|
| `1.1.1.1`, `2606:4700::1111` | Plain DNS over UDP, port 53. No other port can be given. |
| `doh:resolver.example` | DNS over HTTPS: `POST https://resolver.example/dns-query`, certificate checked against the bundled public roots. |
| `doh:resolver.example@192.0.2.53` | The same, connecting to the IP given instead of looking the resolver's name up. |
| `system` | The operating system's resolver. |
Any form can be prefixed with `direct:`, as in `direct:1.1.1.1` or
`direct:doh:resolver.example@192.0.2.53`. An invalid entry is skipped with a
warning; if none is left, leaf refuses to start.
How a query travels depends on the prefix:
- A server **without** `direct:` is reached through the router, like any other
traffic, as a session from an inbound tagged `dnsclient`. With a rule that
sends everything to the proxy, the query goes through the proxy.
- A server **with** `direct:` is contacted over the local network, bypassing
the router.
- `system` always asks the operating system, whatever the prefix. The query
then goes wherever the system's resolver sends it, outside leaf.
Which servers answer a given name depends on where that name would be routed.
A name routed to a `direct` outbound is resolved with the `direct:` servers; any
other name with the servers that have no prefix. If the matching group is
empty, the other group is used.
The address of a proxy server given by name is always looked up directly: a
plain server is sent the query over the local network, without the router,
since the proxy cannot carry the query that finds the proxy.
When several servers are listed, one is used at a time and the others are
fallbacks, tried in order when it fails or is slow. The
[DNS variables](#dns-1) tune this. Answers are cached.
`hosts` answers before any server is asked:
```json
"hosts": { "proxy.example": ["192.0.2.10"] }
```
**Security.**
- The default, `1.1.1.1`, is plain DNS. Through the router the query reaches the
proxy encrypted, but a query that is sent directly -- the proxy's own name, a
name routed to `direct`, or every query when all servers carry `direct:` --
crosses the local network in the clear.
- Give the proxy as an IP address, or pin its name in `hosts`, so leaf never
looks it up. Configure DoH with the `@ip` form, so leaf does not ask the
operating system for the resolver's own address before it can connect.
- `system` hands the name to the operating system, which sends it wherever its
own configuration says. Avoid it where lookups must not leave the proxy.
- If every server in the list carries `direct:`, names routed to the proxy are
resolved directly too.
## Inbounds
An inbound accepts traffic. Each one is:
| Key | Meaning | Omitted |
|---|---|---|
| `protocol` | One of the protocols below | required |
| `tag` | Name used by `inboundTag` rules and in logs | empty |
| `address` | Address to listen on | `127.0.0.1` |
| `port` | Port to listen on | none. Required for every listener except `tun`, `nf` and `cat`. |
| `settings` | Protocol settings | see each protocol |
**Security.** `127.0.0.1` keeps a local proxy to the machine it runs on.
Listening on `0.0.0.0` or a public address lets anyone who can reach the port
use the proxy, and the `http` inbound has no authentication at all.
### `http`
An HTTP proxy (`CONNECT` and plain requests). No settings, no authentication.
### `socks`
A SOCKS5 proxy, TCP `CONNECT` and `UDP ASSOCIATE`, and SOCKS4/4a `CONNECT`
when no username is set.
| Setting | Meaning | Omitted |
|---|---|---|
| `username` | Require username/password authentication | no authentication |
| `password` | The password | empty, when `username` is set; leaf refuses a `password` without a `username` |
With a username set, SOCKS4 clients are refused, since SOCKS4 has no password,
and the UDP relay drops datagrams from any IP address that does not hold an
open, authenticated `UDP ASSOCIATE` connection. The association ends when that
connection closes.
**Security.** The UDP check is by IP address: other users on an authenticated
client's host, or behind the same NAT, can use its association while it is
open. The credentials cross the network in the clear. Keep a SOCKS inbound on
loopback, or behind something that encrypts.
### `shadowsocks`
A Shadowsocks server.
| Setting | Values | Omitted |
|---|---|---|
| `method` | `chacha20-ietf-poly1305` (also `chacha20-poly1305`), `aes-256-gcm`, `aes-128-gcm` | `chacha20-ietf-poly1305` |
| `password` | The shared key | required |
### `trojan`
A Trojan server. It does not do TLS itself: put it behind a `tls` inbound in a
`chain`.
| Setting | Meaning |
|---|---|
| `passwords` | List of accepted passwords |
### `ws`
A WebSocket transport, for use in a `chain`. `websocket` is accepted as the
protocol name too.
| Setting | Meaning | Omitted |
|---|---|---|
| `path` | Request path to accept | `/` |
### `tls`
A TLS transport, for use in a `chain`.
| Setting | Meaning |
|---|---|
| `certificate` | Certificate chain: a path, or PEM text inline |
| `certificateKey` | Private key: a path, or PEM text inline |
| `rawCertificate` | The certificate as a list of PEM lines; overrides `certificate` |
| `rawCertificateKey` | The key as a list of PEM lines; overrides `certificateKey` |
| `echConfig`, `echKey` | Not supported. Setting either is refused. |
A relative path is taken relative to the asset directory (`ASSET_LOCATION`).
### `quic`
A QUIC transport.
| Setting | Meaning |
|---|---|
| `certificate`, `certificateKey`, `rawCertificate`, `rawCertificateKey` | As for `tls` |
| `alpn` | ALPN protocols to offer |
### `amux`
leaf's own multiplexing transport.
| Setting | Meaning |
|---|---|
| `actors` | Tags of the inbound transports to run under it, in order |
### `chain`
Runs inbound transports one inside the other: `["tls", "ws", "trojan"]` accepts
Trojan inside WebSocket inside TLS.
| Setting | Meaning |
|---|---|
| `actors` | Inbound tags, outermost first |
### `mptp`
The multi-path transport. No settings. See [mptp_usage.md](mptp_usage.md).
### `tun`
Captures the operating system's traffic through a TUN device (Linux, macOS,
Windows, iOS, Android).
| Setting | Meaning | Omitted |
|---|---|---|
| `fd` | An already open TUN file descriptor, from the platform (iOS, Android) | none |
| `auto` | Create the device and take over the default route | `false` |
| `name`, `address`, `gateway`, `netmask` | Create a device with these values (when neither `fd` nor `auto` is used) | |
| `mtu` | MTU of a device leaf creates | `1500` |
| `fakeDnsInclude` | Domains to answer with FakeDNS addresses; nothing else is | FakeDNS off |
| `fakeDnsExclude` | Domains *not* to answer with FakeDNS; everything else is | FakeDNS off |
Each entry covers that domain and every name under it, compared label by
label and ignoring case: `example.com` covers `www.example.com`, not
`notexample.com` or `example.com.evil.net`. `*` covers every name. Entries
used to match anywhere in the name; a keyword such as `google` now matches
only a domain called `google`.
| `wintun` | Path to `wintun.dll` (Windows) | |
| `dnsServers` | DNS servers to assign to the device (Windows) | |
| `tun2socks` | Accepted and ignored | |
`fd` takes precedence over `auto`, and `auto` over the explicit device. With
`auto` the device is `DEFAULT_TUN_NAME` with the `DEFAULT_TUN_*` addresses
below.
FakeDNS answers a DNS query that arrives through the TUN device with an address
from `198.18.0.0/16` and remembers the name, so that a connection to that
address can be routed and proxied by name. It answers `A` queries; `AAAA` and
`HTTPS` queries get an empty answer. Queries it does not answer pass through as
ordinary UDP traffic. Set one of the two lists, not both. An entry matches any
name that *contains* it, so `example.com` also matches `notexample.com.evil`;
`*` matches everything.
**Security.**
- `auto` takes over the IPv4 default route. It takes over IPv6 only when
`ENABLE_IPV6=true`; otherwise IPv6 traffic leaves through the original
interface, outside leaf. Where the network has IPv6, either enable it or
make sure the host has no IPv6 route.
- Traffic the operating system sends elsewhere -- other routes, other
interfaces, software that binds to an interface directly -- does not reach
leaf. Check from outside what the device actually sends.
- FakeDNS addresses are reused from a fixed pool and forgotten when leaf
restarts. An application that caches one past that point connects to a
different name or to nothing.
- `TUN_REJECT_IPV6=true` refuses IPv6 inside the stack instead.
### `nf`
Captures traffic on Windows through the NetFilter SDK driver.
| Setting | Meaning | Omitted |
|---|---|---|
| `driverName` | The driver's name | required |
| `nfapi` | Path to `nfapi.dll` | `nfapi.dll` |
| `fakeDnsInclude`, `fakeDnsExclude` | As for `tun` | FakeDNS off |
### `cat`
Connects standard input and output to one destination through the router: a
command-line tool, not a listener.
| Setting | Meaning | Omitted |
|---|---|---|
| `network` | `tcp` or `udp` | `tcp` |
| `address`, `port` | The destination | required |
### `hc`
A health-check endpoint over HTTP, for a load balancer in front of a server.
| Setting | Meaning | Omitted |
|---|---|---|
| `path` | Path to answer | required |
| `request` | A body the request must carry; with it the request must be a `POST` | the request is a `GET` |
| `response` | The body to answer with | required |
## Outbounds
An outbound sends traffic somewhere. Each one is:
| Key | Meaning |
|---|---|
| `protocol` | One of the protocols below |
| `tag` | Name used by rules and other outbounds |
| `settings` | Protocol settings |
Two outbounds with the same protocol and settings share one handler. An
outbound whose protocol is unknown, or not built into this leaf, is skipped
without an error, and so is a composite outbound naming one that does not
exist.
**Security.** With no rule matching, traffic goes to the *first* outbound in the
list, or to the target of a `FINAL` rule (see [Router](#router)). Put the proxy
first, or use `FINAL`, so that traffic nobody wrote a rule for is proxied rather
than sent directly.
Outbounds come in three kinds:
- **Endpoints** connect to a server of their own: `direct`, `redirect`,
`socks`, `shadowsocks`, `trojan`, `vmess`, `vless`, `quic`, `amux`, `mptp`,
and `plugin` with `host` and `port`.
- **Transports** wrap whatever comes before them in a `chain`: `tls`, `ws`,
`obfs`, `reality`, and `plugin` without `host` and `port`.
- **Composites** choose between, or combine, other outbounds: `chain`,
`tryall`, `static`, `failover`, `select`.
### `direct`
Connects to the destination itself. A name is resolved with [`dns`](#dns). No
settings.
### `drop`
Refuses the connection. No settings.
### `redirect`
Sends every connection to one fixed address instead of its destination.
| Setting | Meaning |
|---|---|
| `address`, `port` | Where to send it |
### `socks`
A SOCKS5 proxy.
| Setting | Meaning | Omitted |
|---|---|---|
| `address`, `port` | The proxy | required |
| `username`, `password` | Credentials. With a username set, username/password is the only method offered, and a server that picks "no authentication" is refused. A password without a username is a configuration error. | no authentication |
UDP is relayed through the address in the server's `UDP ASSOCIATE` reply, or
the server's own address when that reply is unspecified, and the association
lasts until the outbound datagram is closed. A UDP reply that cannot be parsed
is dropped.
**Security.** SOCKS5 has no encryption. The destination and any username and
password cross the network in the clear, so use it to reach a proxy on the same
machine or inside a protected transport, never across a network that is
watched.
### `shadowsocks`
| Setting | Values | Omitted |
|---|---|---|
| `address`, `port` | The server | required |
| `method` | `chacha20-ietf-poly1305` (also `chacha20-poly1305`), `aes-256-gcm`, `aes-128-gcm` | `chacha20-ietf-poly1305` |
| `password` | The shared key | required |
| `prefix` | Bytes to start every stream's salt with, percent-encoded (`%16%03%01` for three bytes). At most the key length. TCP only. | random salt |
**Security.** Shadowsocks is designed to look like random bytes from the first
packet. Censors have learned to look for exactly that; see
[security.md](security.md#choosing-a-protocol). `prefix` makes the start of
the stream match some other protocol, but it is the same on every connection,
so it is a fixed pattern of its own and leaves less of the salt random.
### `obfs`
The simple-obfs transport, normally in a chain in front of `shadowsocks`.
| Setting | Values |
|---|---|
| `method` | `http` or `tls` (required) |
| `host` | Host name to present |
| `path` | Request path, for `http` |
**Security.** This dresses the start of a connection up as HTTP or TLS without
being either, which is easy to tell apart from the real thing.
### `trojan`
| Setting | Meaning |
|---|---|
| `address`, `port` | The server (required) |
| `password` | The password (required) |
Trojan sends its password and destination without encrypting them: it expects
to run inside TLS. Put a `tls` outbound in front of it in a `chain`, as in
[the examples](../examples/tls-cabi/README.md).
### `vmess`
| Setting | Values | Omitted |
|---|---|---|
| `address`, `port` | The server | required |
| `uuid` | The user id | required |
| `security` | `chacha20-ietf-poly1305` (also `chacha20-poly1305`) or `aes-128-gcm`. Any other value is a configuration error. | `chacha20-ietf-poly1305` |
### `vless`
| Setting | Meaning |
|---|---|
| `address`, `port` | The server (required) |
| `uuid` | The user id (required) |
VLESS does not encrypt. Run it inside `tls` or `reality`.
### `reality`
The Xray REALITY transport, in a chain in front of `vless`.
| Setting | Meaning |
|---|---|
| `serverName` | The site whose name the handshake presents (required) |
| `publicKey` | The server's public key (required) |
| `shortId` | The short id |
### `tls`
The TLS transport.
| Setting | Meaning | Omitted |
|---|---|---|
| `serverName` | Name to send as SNI and to verify the certificate against | the address of the next hop: the endpoint after it in the chain |
| `alpn` | ALPN protocols to offer, e.g. `["http/1.1"]` | none offered |
| `certificate` | Trust these CA certificates (path or inline PEM) *instead of* the bundled public roots | bundled public roots |
| `rawCertificate` | The same as a list of PEM lines | |
| `certificateKey`, `rawCertificateKey` | Refused: there is no client certificate, and a key would only look like one | |
| `insecure` | Skip certificate verification | `false` |
| `ech` | Use Encrypted Client Hello, with the config list looked up in DNS (`HTTPS` record) | `false` |
| `echConfigList` | A fixed ECH config list (base64), used when the lookup fails or is disabled | none |
| `echDisableDnsLookup` | Use only `echConfigList`, never look one up | `false` |
ECH needs a leaf built with the `aws-lc` TLS backend (the default); with `ring`
it is refused.
**Security.**
- `insecure: true` turns off the only check that the server is the one you meant
to reach. Anyone in the path can then read and change everything inside the
connection, the Trojan password and the destinations included. It exists for
test fixtures; never ship it.
- The bundled roots are a fixed copy of the public web's. A private CA has to be
given with `certificate`, and then *only* that CA is trusted.
- Without `serverName` and with the proxy given as an IP address, no SNI is sent
and the certificate must name the IP. Set `serverName` to the name on the
certificate and give the proxy's IP as the endpoint's address: leaf then
needs no DNS lookup and still verifies the name.
- The name in SNI is visible to the network unless ECH is used.
### `ws`
The WebSocket transport. `websocket` is accepted as the protocol name too.
| Setting | Meaning | Omitted |
|---|---|---|
| `path` | Request path | `/` |
| `headers` | Request headers, e.g. `{"Host": "proxy.example"}` | `Host` is the next hop's address |
`HTTP_USER_AGENT` sets the `User-Agent` header.
### `quic`
A QUIC transport to a server.
| Setting | Meaning | Omitted |
|---|---|---|
| `address`, `port` | The server | required |
| `serverName` | Name to verify the certificate against | `address` |
| `certificate`, `rawCertificate` | CA to trust instead of the public roots | public roots |
| `certificateKey`, `rawCertificateKey` | Refused, as for `tls` | |
| `alpn` | ALPN protocols | none |
### `amux`
leaf's multiplexing transport: many connections over a few long-lived ones.
| Setting | Meaning | Omitted |
|---|---|---|
| `address`, `port` | The server | required |
| `actors` | Transport tags to run each underlying connection through (e.g. `["tls", "ws"]`) | none |
| `maxAccepts` | Streams per underlying connection before a new one is opened | `8` |
| `concurrency` | Underlying connections to keep | `2` |
| `maxRecvBytes` | Retire a connection after receiving this many bytes; `0` never | `0` |
| `maxLifetime` | Retire a connection after this many seconds; `0` never | `0` |
### `chain`
Runs outbounds one inside the other, first one outermost:
`["tls", "ws", "trojan"]` is Trojan inside WebSocket inside TLS. Each transport
is told to reach the next endpoint in the chain, and the last endpoint the
destination.
| Setting | Meaning |
|---|---|
| `actors` | Outbound tags, outermost first |
### `tryall`
Tries several outbounds at once and keeps the first to connect.
| Setting | Meaning | Omitted |
|---|---|---|
| `actors` | Outbound tags | required |
| `delayBase` | Start actor *n* after *n* × this many milliseconds | `0`, all at once |
**Security.** Each attempt is a real connection. With a `direct` actor among
them, every request is also sent directly.
### `static`
Picks one of several outbounds for each connection.
| Setting | Values | Omitted |
|---|---|---|
| `actors` | Outbound tags | required |
| `method` | `random` or `rr` (round robin) | `random` |
### `failover`
Uses the first healthy outbound in a list and moves to the next when it fails.
| Setting | Meaning | Omitted |
|---|---|---|
| `actors` | Outbound tags, in order of preference | required |
| `lastResort` | An outbound tag to use when the last health check found every actor down; a tag that names no outbound is a configuration error. A `direct` last resort sends traffic straight to its destination whenever the proxy is down. | none: connections fail |
| `failTimeout` | Seconds to wait for a connection before trying the next actor | `4` |
| `failover` | Move to the next actor when one fails. `false` uses the best by health check only. | `true` |
| `healthCheck` | Measure the actors in the background | `true` |
| `checkInterval` | Seconds between health checks | `300` |
| `healthCheckTimeout` | Seconds a check may take | `6` |
| `healthCheckDelay` | Random delay before each check, up to this many milliseconds | `200` |
| `healthCheckActive` | Stop checking after this many seconds without traffic | `900` |
| `healthCheckOnStart` | Check when leaf starts rather than at the first request | `false` |
| `healthCheckWait` | Hold connections until the first check is done | `false` |
| `healthCheckAttempts` | Checks per actor per round; the RTT is their average | `1` |
| `healthCheckSuccessPercentage` | Share of attempts that must succeed for an actor to count as up | `50` |
| `healthCheckPrefers` | Actors to prefer when they are healthy | none |
| `healthCheckTcpDestination` | Where a TCP check connects, as `host:port`, with an IPv6 address in brackets. It must speak TLS there: the check does a TLS handshake and an HTTP `GET /`. | `www.google.com:443` |
| `healthCheckUdpDestination` | The DNS server a UDP check queries, as `ip:port`. It asks for the TCP destination's name, or the root zone when that is an address. | `1.1.1.1:53` |
| `fallbackCache` | Remember which actor worked for a destination | `false` |
| `cacheSize` | Entries in that cache | `256` |
| `cacheTimeout` | Minutes an entry lives | `60` |
**Security.**
- A `direct` actor in the list is a direct fallback: when the proxy is down,
requests go straight to their destination over the local network. Leave it
out where that must not happen; the request then fails instead.
- A health check opens a TLS connection to `healthCheckTcpDestination` and
sends a DNS query to `healthCheckUdpDestination` through every actor, every
`checkInterval` seconds while there is traffic. Through a proxy that is a
regular pattern an observer can see. Through a `direct` actor it is a direct
connection, made in the clear for the DNS query, and with the defaults --
Google and Cloudflare -- a blocked destination marks the direct actor as
down. Pick destinations that are unremarkable on the network in question,
or turn `healthCheck` off.
### `select`
Uses one of several outbounds, chosen at run time through the API or the FFI.
| Setting | Meaning |
|---|---|
| `actors` | Outbound tags. The first is selected until another is chosen. |
The choice is saved in `CACHE_LOCATION` and restored at the next start.
### `mptp`
The multi-path transport client. See [mptp_usage.md](mptp_usage.md).
| Setting | Meaning |
|---|---|
| `actors` | Outbounds to spread traffic over |
| `address`, `port` | The server |
### `plugin`
An outbound implemented by a shared library. See the
[README](../README.md#plugins) for how plugins are loaded and checked.
| Setting | Meaning | Omitted |
|---|---|---|
| `path` | Path to the library. Must have a directory part. | required |
| `sha256` | Lowercase hex SHA-256 the file must match | not checked |
| `args` | A string handed to the plugin untouched; its format is the plugin's | empty |
| `host`, `port` | The server, for a plugin that connects to one. Refused by a transport plugin. | |
Arguments of the reference plugins:
| Plugin | `args` |
|---|---|
| `shadowsocks-cabi-rs` | `method;password` or `method;password;prefix`, with the methods and prefix of the built-in `shadowsocks` outbound |
| `tls-cabi-rs` | A server name, or JSON `{"server_name", "alpn", "certificate", "insecure"}`. Bundled public roots; `certificate` replaces them. `server_name` is required. |
| `tls-cabi-go` | The same. The operating system's roots; `certificate` replaces them. TLS 1.2 or later. |
| `trojan-cabi-go` | The password, or JSON `{"password"}` |
| `socks5-cabi-c`, `socks5-cabi-zig` | See their READMEs |
| `anytls-cabi-go`, `shadowtls-cabi-go` | See their READMEs |
`insecure` in the TLS plugins carries the same warning as in the `tls` outbound.
## Router
```json
"router": {
"domainResolve": false,
"rules": [
{ "domainSuffix": ["internal.example"], "target": "direct" },
{ "type": "FINAL", "target": "proxy" }
]
}
```
| Key | Meaning | Omitted |
|---|---|---|
| `rules` | Rules, in order | none |
| `domainResolve` | When no rule matches a name, resolve it and try the rules again with its address | `false` |
A rule has a `target` -- an outbound tag -- and one or more conditions:
| Condition | Matches |
|---|---|
| `domain` | The name, exactly |
| `domainSuffix` | The name or any name under it: `example.com` matches `www.example.com`, not `badexample.com` |
| `domainKeyword` | Any name containing the text |
| `ip` | An address in one of the CIDRs, e.g. `10.0.0.0/8` |
| `geoip` | An address whose country, in `geo.mmdb` in the asset directory, is this ISO code |
| `external` | `site:TAG` or `site:file:TAG` (names from a V2Ray-style `site.dat`), `mmdb:CODE` or `mmdb:file:CODE`. A relative file is in the asset directory. |
| `portRange` | A destination port: `443` or `1024-5000` |
| `network` | `tcp` or `udp` |
| `inboundTag` | Traffic from an inbound with this tag |
| `processName` | A regular expression matching the process that opened the connection, in builds with process rules |
Each condition takes a list. A rule matches when *each* of its conditions
matches *any* value in its list. The first rule that matches decides; a rule
with no conditions is skipped with a warning.
The names a rule sees are the destination as it arrived. With sniffing turned
on (`TLS_DOMAIN_SNIFFING`, `HTTP_DOMAIN_SNIFFING`, `DNS_DOMAIN_SNIFFING`) a
connection to an address is matched against the name found in its TLS
handshake, HTTP request or DNS cache too.
`{"type": "FINAL", "target": "proxy"}` is not a rule: it makes `proxy` the
first outbound, which is where unmatched traffic goes. Its position in the list
does not matter.
**Security.**
- Unmatched traffic goes to the first outbound. If that is `direct`, everything
nobody wrote a rule for leaves without the proxy.
- `domainResolve` looks the name up *before* choosing an outbound, so the query
for every unmatched name goes to the resolver even when the connection then
goes through the proxy. Leave it off unless IP rules must see names.
- A route that cannot be decided -- a failed lookup for `domainResolve` -- ends
the connection; it is not sent directly.
- Several `geoip` codes in one rule are alternatives, like the values of any
other condition.
- A country whose `geo.mmdb` cannot be opened, or an `external` list that
cannot be loaded or has nothing for its tag, matches nothing. When nothing
else of that kind is left in the rule, leaf drops the whole rule rather than
let its other conditions match on their own, and that traffic falls through
to the rules below, or to the first outbound. leaf says so at startup; check
the log.
- Regex entries in a `site.dat` are skipped.
## Environment variables
Set in leaf's environment or in [`env`](#env). A value that does not parse is
ignored and the default used. Booleans marked *flexible* accept `1`/`0`,
`true`/`false`, `yes`/`no`, `on`/`off`; the rest accept only `true` and
`false`.
### Files and interfaces
| Variable | Meaning | Default |
|---|---|---|
| `ASSET_LOCATION` | Directory for `geo.mmdb`, `site.dat` and relative certificate paths | the directory of the leaf binary |
| `CACHE_LOCATION` | Directory for the `select` cache | empty: not saved |
| `OUTBOUND_INTERFACE` | Comma-separated interfaces or addresses to bind outgoing sockets to (`-b` sets it) | none |
| `UNSPECIFIED_BIND_ADDR` | Address outgoing sockets bind to | `0.0.0.0:0`, or `[::]:0` with `ENABLE_IPV6` |
| `ENABLE_IPV6` | Resolve and connect over IPv6, and route it in TUN `auto` mode | `false` |
| `PREFER_IPV6` | Prefer IPv6 answers | `false` |
| `SOCKET_PROTECT_PATH` | Android: Unix socket of a service that protects outgoing sockets from the VPN | none |
| `SOCKET_PROTECT_SERVER` | The same, as a TCP address | none |
| `GATEWAY_MODE` | TUN `auto`: also forward traffic for other hosts | `false` |
| `API_LISTEN` | Address for the HTTP API, e.g. `127.0.0.1:9991` | off |
**Security.** The API has no authentication. It can reload and shut leaf down,
change the `select` outbounds, and report connection statistics. Keep it on
loopback.
### TUN
| Variable | Default |
|---|---|
| `DEFAULT_TUN_NAME` | `utun233` |
| `DEFAULT_TUN_IPV4_ADDR` | `192.168.233.2` (Windows `10.7.7.2`) |
| `DEFAULT_TUN_IPV4_GW` | `192.168.233.1` (Windows `10.7.7.1`) |
| `DEFAULT_TUN_IPV4_MASK` | `255.255.255.0` |
| `DEFAULT_TUN_IPV6_ADDR` | `2001:2::2` |
| `DEFAULT_TUN_IPV6_GW` | `2001:2::1` |
| `DEFAULT_TUN_IPV6_PREFIXLEN` | `64` |
| `TUN_REJECT_IPV6` | `false`: refuse IPv6 inside the TUN stack |
### DNS
| Variable | Meaning | Default |
|---|---|---|
| `DNS_CACHE_SIZE` | Cached names | `512` (iOS `64`) |
| `DNS_TIMEOUT` | Seconds per query | `4` |
| `MAX_DNS_RETRIES` | Attempts per query and server | `4` |
| `DNS_SERVER_RESELECT_INTERVAL_SECS` | Seconds between reconsidering the primary server | `30` |
| `DNS_SERVER_SLOW_RESPONSE_MS` | A response slower than this counts against the server | `800` |
| `DNS_SERVER_SWITCH_THRESHOLD` | Failures or slow responses before moving to another server | `3` |
| `DNS_SERVER_FALLBACK_CONCURRENCY` | Fallback servers asked at once | `1` |
| `DNS_DUALSTACK_DELAY_MS` | With IPv6, how long to wait for the second family | `250` |
### Sniffing
| Variable | Meaning | Default |
|---|---|---|
| `TLS_DOMAIN_SNIFFING` | Read the SNI of connections to port 443 (`DOMAIN_SNIFFING` is the old name) | `false` |
| `TLS_DOMAIN_SNIFFING_ALL` | On every port | `false` |
| `HTTP_DOMAIN_SNIFFING` | Read the `Host` of connections to port 80 | `false` |
| `HTTP_DOMAIN_SNIFFING_ALL` | On every port | `false` |
| `DNS_DOMAIN_SNIFFING` | Find the name of an address in the DNS cache | `false` |
| `DOMAIN_OVERRIDE` | Send the sniffed name to the outbound instead of the address | `false` |
### Timeouts and buffers
| Variable | Meaning | Default |
|---|---|---|
| `INBOUND_ACCEPT_TIMEOUT` | Seconds a `chain` inbound handshake may take | `60` |
| `OUTBOUND_DIAL_TIMEOUT` | Seconds to connect | `8` |
| `OUTBOUND_HANDSHAKE_TIMEOUT` | Seconds an outbound's protocol handshake may take once connected -- TLS, WebSocket, the proxy request, every stage of a chain. A failover is not bounded as a whole: each actor has its `failTimeout`, and its last resort this limit. `0` for no limit | `30` |
| `OUTBOUND_DIAL_ORDER` | Order to try a name's addresses: `ordered`, `random`, `partial-random` | `ordered` |
| `OUTBOUND_DIAL_CONCURRENCY` | Addresses tried at once | `1` |
| `ENDPOINT_TCP_CONCURRENCY` | Proxy connections at once | `1024` (iOS `45`) |
| `DIRECT_TCP_CONCURRENCY` | Direct connections at once | `1024` (iOS `64`) |
| `INCOMING_ACCEPT_CONCURRENCY` | Handshakes a `chain` inbound runs at once | `256` |
| `TCP_UPLINK_TIMEOUT` | Seconds to keep sending after the remote side closed | `10` |
| `TCP_DOWNLINK_TIMEOUT` | Seconds to keep receiving after the local side closed | `10` |
| `TCP_INBOUND_ABORT_ON_CLOSE` | *Flexible.* Reset rather than close inbound sockets | `false` |
| `WS_HALF_CLOSE` | *Flexible.* Signal half-close over WebSocket with a Close frame; only safe between leaf nodes | `false` |
| `UDP_SESSION_TIMEOUT` | Seconds before an idle UDP session ends | `30` |
| `UDP_SESSION_TIMEOUT_CHECK_INTERVAL` | Seconds between checks | `10` |
| `LINK_BUFFER_SIZE` | Relay buffer, KiB | `2` |
| `DATAGRAM_BUFFER_SIZE` | Datagram buffer, KiB | `2` |
| `UDP_UPLINK_CHANNEL_SIZE`, `UDP_DOWNLINK_CHANNEL_SIZE` | Queued datagrams per direction | `256` |
### Transports
| Variable | Default |
|---|---|
| `QUIC_ACCEPT_CHANNEL_SIZE` | `1024` |
| `QUIC_MAX_CONCURRENT_BIDI_STREAMS` | `1024` |
| `QUIC_MAX_IDLE_TIMEOUT_MS` | `15000` |
| `QUIC_KEEP_ALIVE_INTERVAL_MS` | `3000` |
| `QUIC_ACCEPT_QUEUE_TIMEOUT` | `5` (seconds) |
| `QUIC_SERVER_MAX_IDLE_TIMEOUT_MS` | `120000` |
| `QUIC_SERVER_KEEP_ALIVE_INTERVAL_MS` | `0` |
| `AMUX_ACCEPT_CHANNEL_SIZE` | `1024` |
| `AMUX_STREAM_CHANNEL_SIZE` | `16` |
| `AMUX_FRAME_CHANNEL_SIZE` | `32` |
### HTTP and logging
| Variable | Meaning | Default |
|---|---|---|
| `HTTP_USER_AGENT` | `User-Agent` for WebSocket requests (`USER_AGENT` is the old name) | none |
| `HTTP_FORWARDED_HEADER` | Header a server-side WebSocket inbound takes the client address from | `X-Forwarded-For` |
| `LOG_CONSOLE_OUT` | macOS: console logging goes to the system log | `false` |
### Statistics
| Variable | Meaning | Default |
|---|---|---|
| `MAX_RECENT_CONNECTIONS` | Recent connections kept for the API | `0` |
| `HOST_STATS` | *Flexible.* Keep per-host traffic and recent session events for the FFI | `false` |
**Security.** Both keep a record of destinations in memory, readable through the
API or the FFI. Leave them off unless the application shows that record to the
user it belongs to.
## Command line
| Flag | Meaning |
|---|---|
| `-c, --config <file>` | Configuration file. Default `config.conf`. |
| `-T, --test` | Check the configuration and exit |
| `--auto-reload` | Reload when the file changes |
| `--single-thread` | Run on one thread |
| `--thread-stack-size <bytes>` | Stack size of worker threads |
| `-t, --test-outbound <tag>` | Test one outbound's connectivity and exit |
| `-d, --test-outbound-timeout <secs>` | Timeout for that test. Default `4`. |
| `-b, --boundif <iface>` | Bind outgoing sockets to an interface (sets `OUTBOUND_INTERFACE`) |
| `--verify-plugin <path>` | Check a plugin library and print what it declares |
| `--verify-plugin-sha256 <hex>` | Also require that digest |
| `-V, --version` | Print the version |
## The `.conf` format
A line-based format with `[Section]` headers and `#` comments. Each line
becomes part of the JSON structure above, so the defaults and warnings there
apply. Section names are case-insensitive.
**Quoting.** In `[Proxy]` and `[Proxy Group]` lines a value in double quotes
is taken whole: `password="a,b"`, or a positional `"a,b"`. Without quotes, a
`,` ends the value. A `key=value` is split at its first `=`, so an unquoted
value may hold more of them -- a base64 key, say -- but a positional value
that contains `=` must be quoted, or it is read as a `key=value`. A quote
opens a value only at its start, or right after `key=`; anywhere else, as in
`password=ab"cd`, it is an ordinary character. A quote that is never closed
quotes nothing. There is no way to write a `"` inside a quoted value.
### `[Env]`
`NAME = value` lines, set as environment variables.
### `[General]`
| Key | Becomes |
|---|---|
| `loglevel`, `logoutput`, `logformat` | `log.level`, `log.output`, `log.format` |
| `dns-server = a, b` | `dns.servers` |
| `dns-interface` | Refused: it was never acted on. `OUTBOUND_INTERFACE` in `[Env]` binds every socket leaf opens, DNS included |
| `interface`, `port` (or `http-interface`, `http-port`) | An `http` inbound, tag `http`, when both are set |
| `socks-interface`, `socks-port` | A `socks` inbound, tag `socks`, no authentication, when both are set |
| `tun = auto` | A `tun` inbound with `auto` |
| `tun = name, address, netmask, gateway, mtu` | A `tun` inbound creating that device |
| `tun-fd` | A `tun` inbound with `fd` |
| `tun-dns-server`, `wintun` | `dnsServers`, `wintun` of the `tun` inbound |
| `tun2socks-backend` | Ignored |
| `always-fake-ip = a, b` | `fakeDnsInclude` of the `tun` or `nf` inbound |
| `always-real-ip = a, b` | `fakeDnsExclude` of the `tun` or `nf` inbound |
| `nf = driver, path\to\nfapi.dll` | An `nf` inbound |
| `routing-domain-resolve = true` | `router.domainResolve` |
| `api-interface`, `api-port` | Read and ignored; use `API_LISTEN` |
### `[Proxy]`
`Tag = protocol, address, port, positional..., key=value, ...`
| Protocol | Positional | Becomes |
|---|---|---|
| `direct`, `drop` (`reject`) | none, and no address | `direct`, `drop` |
| `redirect` | | `redirect` |
| `socks` | | `socks`, with `username=`, `password=` |
| `ss`, `shadowsocks` | method, password | `shadowsocks`, with `encrypt-method=`, `password=`, `prefix=`. With `obfs=http` or `obfs=tls` (and `obfs-host=`, `obfs-path=`, default `/`) a chain of `obfs` then `shadowsocks`. |
| `trojan` | password | A chain of `tls`, optionally `ws`, then `trojan` |
| `vmess` | uuid | The same chain with `vmess`; `encrypt-method=` is its `security`, default `chacha20-ietf-poly1305`, and the TLS ALPN is `http/1.1` |
| `vless` | uuid | `vless`, or with `reality=true` a chain of `reality` then `vless` |
`trojan` and `vmess` lines always use TLS; `tls=` is read and ignored. A
`vless` line without `reality=true` has no encryption at all, and should not be
used across a network that is watched. The keys:
| Key | Becomes |
|---|---|
| `sni` | `tls.serverName` (and `quic`/`reality` `serverName`); omitted, the proxy's address |
| `tls-cert` | `tls.certificate`, or the name of a `[Certificate.name]` section whose lines are the PEM |
| `tls-insecure=true` | `tls.insecure` |
| `tls-ech`, `tls-ech-disable-dns-lookup` | `tls.ech`, `tls.echDisableDnsLookup` |
| `tls-ech-config-list` (or `ech-config-list`) | `tls.echConfigList`, or the name of an `[Ech.name]` section holding it |
| `ws=true`, `ws-path`, `ws-host` | A `ws` transport; `path` default `/`, `ws-host` its `Host` header |
| `amux=true`, `amux-max`, `amux-con`, `amux-max-recv`, `amux-max-lifetime` | An `amux` transport carrying the TLS (and WebSocket) connections, with `maxAccepts`, `concurrency`, `maxRecvBytes`, `maxLifetime` |
| `quic=true` | A `quic` transport instead of TLS, ALPN `http/1.1` |
| `uuid`, `username` | The VMess or VLESS id |
| `reality-public-key`, `reality-short-id` | `reality` settings |
| `interface` | Refused, as `dns-interface` |
### `[Proxy Group]`
`Tag = kind, actor, actor, ..., key=value, ...`
| Kind | Becomes |
|---|---|
| `chain`, `tryall`, `static`, `select`, `mptp` | The outbound of that name. Keys: `delay-base`, `method`, `address`, `port`. |
| `failover`, `fallback` | `failover` |
| `url-test` | `failover` with `failover: false` |
The `failover` keys are the JSON settings in kebab-case: `fail-timeout`,
`health-check`, `check-interval`, `health-check-timeout`, `health-check-delay`,
`health-check-active`, `health-check-prefers`, `health-check-on-start`,
`health-check-wait`, `health-check-attempts`,
`health-check-success-percentage`, `health-check-tcp-destination`,
`health-check-udp-destination`, `fallback-cache`, `cache-size`,
`cache-timeout`. `last-resort` is the failover's `lastResort`.
### `[Rule]`
`TYPE, value, target`, one condition per line, in order. `TYPE` is
`DOMAIN`, `DOMAIN-SUFFIX`, `DOMAIN-KEYWORD`, `IP-CIDR`, `GEOIP`, `EXTERNAL`,
`PORT-RANGE`, `NETWORK`, `INBOUND-TAG` or `PROCESS-NAME`, matching the JSON
condition of the same meaning. `FINAL, target` ends the section: lines after
it are not read.
### `[Host]`
`name = ip, ip` lines: `dns.hosts`.