diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 44690c1..5663a9c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -13,7 +13,7 @@ env: jobs: build-test: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v4 @@ -27,6 +27,8 @@ jobs: run: cargo build --verbose - name: Run tests + env: + FOCL_REQUIRE_TCP_AO: "1" run: cargo test --verbose create-release: diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 698f7ea..7f09df9 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -15,7 +15,7 @@ env: jobs: check: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v4 @@ -28,5 +28,9 @@ jobs: - name: Build run: cargo build --verbose + # The runner kernel has CONFIG_TCP_AO=y; require it so a runner that + # loses TCP-AO fails here instead of silently skipping those tests. - name: Run tests + env: + FOCL_REQUIRE_TCP_AO: "1" run: cargo test --verbose diff --git a/CHANGELOG.md b/CHANGELOG.md index baccdde..50ccefa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,18 +6,32 @@ All notable changes to this project will be documented in this file. ### Fixes -* **TCP-MD5 on the passive listener** - the per-peer keys are installed on the listening socket (Linux `TCP_MD5SIG`) before the accept loop, because the kernel validates the digest on the SYN and `accept()` never returns for a peer whose key is missing; the key is still applied to the accepted socket as well. +* **One peer per address** - configuration validation rejects two peers that name the same IP in different spellings (`192.0.2.1` and `::ffff:192.0.2.1`); one inbound connection could otherwise be assigned to either peer while only one of their keys was installed. +* **Listener address fallback** - `focld` falls through to the next resolved `listen_addr` when a socket cannot be created for one address, as `TcpListener::bind` does, instead of aborting startup. +* **Listener address family** - on Linux the listener reads `IPV6_V6ONLY` from the bound socket: with `bindv6only=1` an IPv4 passive peer is reported as unreachable in `focl peer show` instead of idling without a reason. Other platforms keep the previous dual-stack assumption, and their kernel authentication options bail out anyway. +* **Listener key failures stay visible** - a key that could not be installed on the listening socket is reported in `focl peer show` under `listener_key_error`, which later session errors or an established session do not clear. +* **TCPAO counters** - the README explains the counters as the kernel counts them: an unsigned segment at a socket that requires TCP-AO lands in `TCPAORequired`, while a segment carrying a TCP-AO option whose KeyID matches no installed key lands in `TCPAOKeyNotFound`. +* **Inbound peer matching** - a peer configured as an IPv4-mapped literal (`::ffff:192.0.2.1`) matches its own inbound connection again: both the configured and the remote address are canonicalized before comparing. +* **Listener key installation failures** - every key of a peer is attempted, and a peer whose listener key the kernel refused now carries that failure in `focl peer show` (`last_error`) instead of only in the startup log. +* **Peer address validation** - a peer address must be a literal IP for every authentication mode, not only for TCP-AO, because the session path and the listener already require one. +* **Interop TCP-AO probe** - `scripts/interop/run_bird_tcpao.sh` probes the socket option through `focld` instead of grepping `/proc/net/netstat`, which lists the TCPAO counters even on a kernel built without `CONFIG_TCP_AO`. +* **TCP-MD5 on active sessions** - the key is installed before `connect()` on every active session; without `local_address` it was set after the connect, so the SYN went out unsigned and a peer enforcing TCP-MD5 dropped it. +* **Dual-stack listener** - an inbound connection on a `[::]` listener is matched against IPv4 peers by its v4-mapped address, and listener keys for IPv4 peers are installed in that form; an IPv6 peer's key is no longer offered to an IPv4-only listener. A peer configured in the v4-mapped form (`::ffff:192.0.2.2`) is keyed as the IPv4 peer it is. A passive peer the listener can never accept (an IPv6 peer on an IPv4 listener, an IPv4 peer on a listener bound to one IPv6 address) gets one warning at startup and says why in `focl peer show` (`last_error`); an active peer in that position, which dials out, is no longer logged as an error. +* **Unknown peer settings are rejected** - a key that `[[peers]]` or `[[peers.tcp_ao_keys]]` does not know is a config error instead of being ignored, so a misspelled `password`, `tcp_ao_keys` or `current` cannot leave a peer without the authentication its config asks for. +* **`BgpService` validates its config** - `BgpService::new` runs `FoclConfig::validate`, so a config built in code is held to the same rules as one read by `FoclConfig::load`; a peer with both a password and TCP-AO keys was silently run with TCP-AO only. +* **TCP-MD5 on the passive listener** - the per-peer keys are installed on the listening socket (Linux `TCP_MD5SIG`) before it starts listening, because the kernel validates the digest on the SYN: without the key a signed SYN is dropped and an unsigned one is accepted. That key is the only check there is, as an accepted socket inherits it and cannot be asked whether the handshake was signed, so inbound connections from a peer whose key the listener refused are dropped instead of running unauthenticated. * **RFC 4271 hold time** - OPEN advertises the configured hold time unchanged (0 disables the timers instead of being raised to 3), the remote OPEN's hold time is taken into account (0 on either side disables the timers, otherwise the smaller value wins), and the keepalive and hold timers are driven by that negotiated value. * **RFC 6793 AS4_PATH fallback** - a session that did not negotiate the four-octet AS capability now carries `AS_TRANS` in AS_PATH and the real local ASN in AS4_PATH instead of a truncated 2-octet AS_PATH. * **RFC 2918 route refresh replay** - a received ROUTE-REFRESH for a negotiated family re-sends that family's Adj-RIB-Out followed by its End-of-RIB (the hold timer reset is unchanged); a refresh for a family the session does not carry is ignored, and the RFC 7313 BoRR/EoRR subtypes are not implemented. * **End-of-RIB for a capability-less peer** - the IPv4 End-of-RIB decision now agrees with the announcement decision, so a plain RFC 4271 peer that negotiated no capabilities gets its IPv4 marker. * **One initial table send** - the establishment table is sent exactly once, inside the registration critical section, with the End-of-RIB markers after it; the previous pre-lock send re-sent every copy after the EoR and archived it twice. -* The TCP-MD5 socket helpers are re-exported as `focl::bgp::{TcpSocketExt, TcpStreamExt}`. +* The TCP-MD5 and TCP-AO socket helpers are re-exported as `focl::bgp::{TcpSocketExt, TcpStreamExt, TcpAoStatus, tcp_ao_supported, tcp_ao_probe}`; `tcp_ao_supported` reports a failed probe as "no TCP-AO", while `tcp_ao_probe` returns the error. ### New features +* **TCP-AO (RFC 5925)** - a peer can authenticate with `[[peers.tcp_ao_keys]]` (send/recv KeyID, `hmac-sha1-96` or `aes-128-cmac-96`, secret, optional `current`) instead of a TCP-MD5 `password`, on Linux 6.7+ with `CONFIG_TCP_AO`. Keys go on active sockets before `connect()` with segments without TCP-AO refused, and on the listening socket for passive peers; an accepted connection from a TCP-AO peer is verified to be TCP-AO protected before it can replace an existing session. `current` picks the signing key on a connection focl opens; on one the peer opens, the peer's SYN picks the keys and focl logs a warning when they are not the `current` ones. Config validation rejects a peer with both a password and TCP-AO keys, duplicate KeyIDs, more than one current key, and secrets or passwords outside 1-80 bytes. `focld` refuses to start when an enabled peer has TCP-AO keys and the kernel has no TCP-AO, naming the peers. `focl peer show` reports `auth_mode` (`none`, `md5` or `tcp_ao`). The socket definitions come from `linux-raw-sys` (Linux only), as `libc` has no TCP-AO yet. Keys change on restart only. * **Real peering collector (Phase 1)** - the established session loop no longer discards UPDATEs: raw frames go to the archive and parsed prefixes fill a per-peer Adj-RIB-In that `focl rib in` reads, cleared on session end. OPEN advertises MP-BGP IPv4 and IPv6 unicast plus four-octet AS (AS_TRANS on the wire for a 4-byte local ASN) and, when configured, route refresh; peer capabilities are parsed from the raw frame with negotiated families, ASN4 and route refresh tracked per session, and the remote ASN validated including AS_TRANS resolution. A peer that negotiates no capabilities still establishes plain IPv4 unicast. IPv4 prefixes are announced with classic NLRI and NEXT_HOP, IPv6 through MP_REACH_NLRI, and an invalid non-IPv6 configured next hop is rejected instead of malformed-encoded. -* **Global passive listener** - one bind of `global.listen_addr` serves every inbound connection; a connection is matched against the configured peers before any state change (unmatched ones are dropped with a log), TCP-MD5 is applied to accepted sockets, an inbound connection wins a collision with a simultaneous outbound attempt, and the active loop resumes once it ends. +* **Global passive listener** - one bind of `global.listen_addr` serves every inbound connection; a connection is matched against the configured peers before any state change (unmatched ones are dropped with a log), TCP-MD5 is enforced through per-peer keys on the listening socket, an inbound connection wins a collision with a simultaneous outbound attempt, and the active loop resumes once it ends. * **Dual-stack archive with raw-frame passthrough (Phase 0)** - archive record types carry `IpAddr`/`IpNet` peers and prefixes, so both families share the update and RIB paths. An UPDATE is written as the original wire frame inside a `BGP4MP_MESSAGE_AS4` envelope instead of being parsed and re-encoded, preserving wire fidelity and unknown attributes. TABLE_DUMP_V2 groups IPv4 and IPv6 entries per (family, prefix) with snapshot-global sequence numbers and ADD-PATH subtypes when a path id is present. Dependencies move to `bgpkit-parser` 0.20 and `bzip2` 0.6, with a new `ipnet-trie` dependency. * **Runtime prefix control** - `focl prefix add|remove|list` announces or withdraws an originated prefix on the running daemon without restarting it or resetting any session. The effective set is (configured `[[prefixes]]` + runtime additions) minus runtime suppressions: `prefix remove` suppresses a configured prefix (a runtime-only one is dropped), `prefix add` announces it again and clears the suppression, and `prefix list` shows each prefix as `announced`/`suppressed` with a `config`/`runtime` source. Runtime overrides are in-memory only and are never written back to the config file. Address family is inferred from the prefix, `--next-hop` defaults to the configured next hop of the same family, `--dry-run` reports what would be sent without changing state, and `--json` prints the control response. * **`focl reload` applies the config's prefix delta** - reload re-reads the config file, announces prefixes added since the last read, withdraws removed ones, and clears runtime overrides; the response reports the delta and how many overrides were reset. Peer and archive settings still require a restart. diff --git a/Cargo.lock b/Cargo.lock index 5bce05f..2cb2341 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1027,6 +1027,7 @@ dependencies = [ "ipnet", "ipnet-trie", "libc", + "linux-raw-sys", "rusqlite", "serde", "serde_json", @@ -1730,9 +1731,9 @@ dependencies = [ [[package]] name = "linux-raw-sys" -version = "0.11.0" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" [[package]] name = "litemap" @@ -2260,9 +2261,9 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.3" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "146c9e247ccc180c1f61615433868c99f3de3ae256a30a43b49f67c2d9171f34" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ "bitflags", "errno", diff --git a/Cargo.toml b/Cargo.toml index 5d190e8..6ff6059 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -49,6 +49,9 @@ tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt", "json"] } zstd = "0.13" +[target.'cfg(target_os = "linux")'.dependencies] +linux-raw-sys = { version = "0.12", default-features = false, features = ["std", "net"] } + [dev-dependencies] tempfile = "3" tokio = { version = "1", features = ["test-util"] } diff --git a/README.md b/README.md index 186d1dd..78d71a5 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,7 @@ The project consists of: - [x] IPv4 and IPv6 unicast support - [x] TCP-MD5 authentication (RFC 2385) for BGP session security +- [x] TCP-AO authentication (RFC 5925) for BGP session security - [x] Static prefix announcements - [x] Runtime prefix announce/withdraw via `focl prefix` (in-memory overrides) - [x] Full BGP FSM with proper timers (hold/keepalive) @@ -170,7 +171,7 @@ See `focl-vultr-example.toml` for a complete production-style example with docum - **bgpkit-parser** - BGP message parsing and MRT encoding - **tokio** - Async runtime - **serde/toml** - Configuration handling -- **libc** - TCP-MD5 socket options (Linux only) +- **libc** / **linux-raw-sys** - TCP-MD5 and TCP-AO socket options (Linux only) ## Platform Support @@ -179,9 +180,68 @@ See `focl-vultr-example.toml` for a complete production-style example with docum | BGP Speaker | ✓ | ✓ | ✓ | ? | | IPv4/IPv6 | ✓ | ✓ | ✓ | ? | | TCP-MD5 Auth | ✓ | ✗ | ✗ | ✗ | +| TCP-AO Auth | ✓ | ✗ | ✗ | ✗ | | MRT Archival | ✓ | ✓ | ✓ | ? | -*Note: TCP-MD5 (RFC 2385) requires Linux kernel support* +*Note: TCP-MD5 (RFC 2385) requires Linux kernel support; TCP-AO (RFC 5925) requires Linux 6.7+ built with `CONFIG_TCP_AO`* + +## TCP Authentication + +A peer authenticates its TCP connection with either TCP-MD5 (`password`) or +TCP-AO (`tcp_ao_keys`), never both. TCP-AO takes one or more master key +tuples: + +```toml +[[peers]] +name = "upstream" +address = "192.0.2.2" +remote_as = 65002 + +[[peers.tcp_ao_keys]] +send_id = 1 # KeyID we sign with = the peer's recv id +recv_id = 2 # KeyID the peer signs with = its send id +algorithm = "hmac-sha1-96" # or "aes-128-cmac-96" (RFC 5926) +secret = "[REDACTED]" # 1-80 bytes +``` + +On a connection focl opens, the key marked `current = true` (else the first) +signs and is the one focl asks the peer to sign with; the others stay +installed for the peer to use. On a connection the peer opens, the peer's SYN +picks both keys (Linux does not let a listener choose), so `current` has no +effect there and focl logs a warning when the session runs on other keys. + +The keys are installed before `connect()` on active sessions and on the +listening socket, before it starts listening, for passive ones, so the kernel +verifies the very first SYN; an accepted connection from a TCP-AO peer is +also checked to really be TCP-AO protected. If the listening socket refuses a +peer's key, focl logs the error and `focl peer show` reports it as the peer's +`last_error`. Inbound connections from a peer the listener holds no key for +are dropped, as nothing would have verified them. Changing keys requires a +restart. +`focl peer show` reports `auth_mode` (`none`, `md5` or `tcp_ao`), and a key the +kernel refused to install on the listening socket appears there as +`listener_key_error`; the peer keeps running without that key and a later +session error does not clear the field. + +`focld` refuses to start when an enabled peer has `tcp_ao_keys` and the +kernel has no TCP-AO: such a peer could never get a session. Remove the keys +or set `enabled = false` on the peer to run the others. + +A peer that never connects usually has mismatched keys: the kernel drops +segments that fail authentication silently. Its counters say why: + +```bash +nstat -az | grep -E 'TCPAO(Good|Bad|KeyNotFound|Required)' +``` + +* `TCPAOBad`: a segment failed its MAC (wrong secret or algorithm). +* `TCPAOKeyNotFound`: a segment carried a TCP-AO option whose KeyID matched no + installed key, which includes a signed SYN from a peer the socket has no key + for. +* `TCPAORequired`: an unsigned segment reached a socket that requires TCP-AO. + That is a listener holding a key for the peer, a session we opened with + `ao_required`, or an accepted session whose keys were copied from such a + listener. ## Development @@ -195,6 +255,7 @@ cargo test cd scripts/interop ./run_gobgp_smoke.sh # Basic test ./run_gobgp_md5.sh # MD5 authentication test (Linux only) +./run_bird_tcpao.sh # TCP-AO test against BIRD 2.17+/3.1+ (Linux only) ``` ### Code Quality @@ -224,7 +285,7 @@ cargo clippy --no-default-features | `asn` | u32 | required | Local AS number | | `router_id` | string | required | Router ID (IPv4) | | `listen` | bool | true | Accept incoming connections | -| `listen_addr` | string | "0.0.0.0:179" | Bind address | +| `listen_addr` | string | "0.0.0.0:179" | Bind address; `[::]:179` accepts IPv4 peers as v4-mapped while the socket's `IPV6_V6ONLY` is 0, which is the Linux default | | `control_socket` | path | "/tmp/focld.sock" | CLI socket path | | `log_level` | string | "info" | Log level | @@ -239,9 +300,13 @@ cargo clippy --no-default-features | `hold_time_secs` | u16 | 90 | BGP hold timer | | `connect_retry_secs` | u16 | 5 | Reconnect interval | | `passive` | bool | false | Wait for peer to connect | -| `password` | string | none | TCP-MD5 password | +| `password` | string | none | TCP-MD5 password (1-80 bytes) | +| `tcp_ao_keys` | array | none | TCP-AO keys: `send_id`, `recv_id`, `algorithm`, `secret`, optional `current` | | `route_refresh` | bool | true | Enable route refresh | +A key that a `[[peers]]` or `[[peers.tcp_ao_keys]]` table does not know is a +config error, so a misspelled `password` cannot leave a peer unauthenticated. + ### Prefix Settings | Option | Type | Default | Description | diff --git a/docs/collector-revision-plan.md b/docs/collector-revision-plan.md index 80b05a1..e8d1a26 100644 --- a/docs/collector-revision-plan.md +++ b/docs/collector-revision-plan.md @@ -160,8 +160,8 @@ MRT; the archive knows nothing about BMP/BGP sessions. ## Phase 2 — BMP station mode 1. **`BmpListener`** on a configurable port per station; per-router - TCP-MD5 (TCP-AO is a documentation-level non-goal for v1; focl - implements TCP-MD5 only); accept many routers concurrently. Parsing via + TCP-MD5 (focl's BGP sessions support TCP-MD5 and TCP-AO; the BMP + listener plans MD5 only); accept many routers concurrently. Parsing via bgpkit-parser 0.20's BMP module. 2. **Feed key (from review blocker 1).** Every route-monitoring feed is keyed by a canonical `BmpFeedKey`: @@ -415,8 +415,8 @@ platform other tools can build on. 3. BMP router identity: one collector_id per router (recommended), resolved from trusted `[[bmp.routers]]` config matched by source identity — never derived from untrusted BMP Init sysName. -4. BMP listener MD5: yes (focl implements Linux TCP-MD5 today; TCP-AO is - not implemented and stays out of v1 docs). +4. BMP listener MD5: yes (focl implements Linux TCP-MD5 and, for BGP + sessions, TCP-AO; TCP-AO on the BMP listener is not planned). 5. Trigger delivery semantics: at-least-once with durable per-trigger delivery records (pending/running/acknowledged/unknown); exec exit 0 = acknowledged; `unknown` retriable. Document clearly, don't pretend diff --git a/docs/examples.md b/docs/examples.md index b32e78a..8ca9c48 100644 --- a/docs/examples.md +++ b/docs/examples.md @@ -43,7 +43,6 @@ collector_id = "edge01" # default when no [[bmp.routers]] match layout_profile = "routeviews" updates_interval_secs = 900 # RV-style 15-minute update files ribs_interval_secs = 7200 # 2-hour RIB dumps, RV convention -ribs_mode = "trie" # trie | initial-only | off (see plan §RIB) compression = "zstd" root = "/data/mrt" retention_days = 30 # local auto-cleanup after replication @@ -102,6 +101,12 @@ address = "203.0.113.6" # neighbor connects to us remote_as = 65002 passive = true password = "[REDACTED]" # optional TCP-MD5 +# or TCP-AO instead of password (Linux 6.7+): +# [[peers.tcp_ao_keys]] +# send_id = 1 +# recv_id = 1 +# algorithm = "hmac-sha1-96" # or "aes-128-cmac-96" +# secret = "[REDACTED]" [archive] enabled = true @@ -109,7 +114,6 @@ collector_id = "focl01" layout_profile = "ris" # rrc-style: updates.* + bview.* updates_interval_secs = 300 # RIS-style 5-minute update files ribs_interval_secs = 86400 # daily bview from adj-rib-in trie -ribs_mode = "trie" compression = "gzip" root = "/data/mrt" ``` @@ -160,7 +164,7 @@ Memory (RSS), per full feed peer held as adj-rib-in trie: |---|---|---| | naive (bytes inline) | 150-250 MB | never ship this | | interned attrs, u32 values | 60-120 MB | default | -| ribs_mode = initial-only | < 10 MB | dump only the post-EoR walk, then updates only | +| planned `ribs_mode = initial-only` | < 10 MB | dump only the post-EoR walk, then updates only; not implemented yet | Plus one process-wide interned attribute store (~50-100 MB total; cross-peer dedup for similar feeds). **All memory figures below are planning estimates @@ -175,7 +179,7 @@ cardinality, churn; see plan §Scale item 8). Fleet sketch, interned mode, | 200 | 12-25 GB | ~200 GB | ~$90 | Knobs that move the needle: `ribs_interval_secs` (biggest storage lever), -`ribs_mode` (biggest memory lever), `retention_days`, compression choice +the planned `ribs_mode` (biggest memory lever), `retention_days`, compression choice (zstd-3 recommended: ~bz2 size at ~10x speed). ## Reading the archive diff --git a/scripts/interop/README.md b/scripts/interop/README.md index 901352f..ea7a453 100644 --- a/scripts/interop/README.md +++ b/scripts/interop/README.md @@ -28,6 +28,34 @@ Interop OK: Established + prefix 203.0.113.0/24 received by GoBGP - `scripts/interop/focl-interop.toml`: focld interop config (non-root ports). - `scripts/interop/run_gobgp_smoke.sh`: end-to-end smoke script. +## TCP-AO against BIRD (Linux) + +`scripts/interop/run_bird_tcpao.sh` checks TCP-AO (RFC 5925) against BIRD +2.17+ or 3.1+, over loopback, in two runs: focld active with HMAC-SHA-1-96, +then BIRD active with AES-128-CMAC-96. Each run waits for an Established +session that `focl peer show` reports as `tcp_ao`, and for a route in each +direction. focld uses 127.0.0.1 and BIRD 127.0.0.2. The configs are +generated into `scripts/interop/.runtime/`. Tested with BIRD 3.4.0. + +Prereqs: Linux 6.7+ with `CONFIG_TCP_AO`, and `bird`/`birdc` on `PATH` (or +`BIRD_BIN`/`BIRDC_BIN`). The ports default to 2179 (focld) and 3179 (BIRD), +overridable with `FOCL_PORT`/`BIRD_PORT`. Both run unprivileged. BIRD does +not need to be installed; an unpacked distro package works: + +```bash +dnf download --destdir /tmp/bird bird +rpm2cpio /tmp/bird/bird-*.rpm | cpio -idm -D /tmp/bird/root +BIRD_BIN=/tmp/bird/root/usr/bin/bird BIRDC_BIN=/tmp/bird/root/usr/bin/birdc \ + ./scripts/interop/run_bird_tcpao.sh +``` + +BIRD lists focld's route as `unreachable`. That is expected: with no device +or kernel protocol, BIRD has no IGP route to resolve the next hop with. + +```text +Interop OK: focld <-> BIRD over TCP-AO in both directions, both RFC 5926 algorithms +``` + ## Useful overrides ```bash diff --git a/scripts/interop/run_bird_tcpao.sh b/scripts/interop/run_bird_tcpao.sh new file mode 100755 index 0000000..b280936 --- /dev/null +++ b/scripts/interop/run_bird_tcpao.sh @@ -0,0 +1,256 @@ +#!/usr/bin/env bash +# TCP-AO (RFC 5925) interop between focld and BIRD (2.17+ / 3.1+) on Linux. +# +# Runs two sessions over loopback, each checked for Established, TCP-AO and a +# route in both directions: +# 1. focld active, BIRD passive, HMAC-SHA-1-96 +# 2. BIRD active, focld passive, AES-128-CMAC-96 +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +RUNTIME_DIR="$ROOT_DIR/scripts/interop/.runtime" +mkdir -p "$RUNTIME_DIR" + +BIRD_BIN="${BIRD_BIN:-$(command -v bird || true)}" +BIRDC_BIN="${BIRDC_BIN:-$(command -v birdc || true)}" +FOCL_PORT="${FOCL_PORT:-2179}" +BIRD_PORT="${BIRD_PORT:-3179}" +SECRET="focl-bird-tcp-ao" +# Separate loopback addresses: BIRD rejects a NEXT_HOP equal to its own +# address, which focld's next hop would be if both used 127.0.0.1. +FOCL_ADDR="127.0.0.1" +BIRD_ADDR="127.0.0.2" + +if [[ "$OSTYPE" != "linux-gnu"* ]]; then + echo "TCP-AO is only supported on Linux; skipping on $OSTYPE" >&2 + exit 0 +fi +if [[ ! -x "$BIRD_BIN" || ! -x "$BIRDC_BIN" ]]; then + echo "bird/birdc not found; set BIRD_BIN and BIRDC_BIN (BIRD 2.17+ or 3.1+)" >&2 + exit 1 +fi + +cargo build --bin focld --bin focl +FOCLD_BIN="$ROOT_DIR/target/debug/focld" +FOCL_BIN="$ROOT_DIR/target/debug/focl" + +# /proc/net/netstat lists the TCPAO counters on a >= 6.7 kernel built without +# CONFIG_TCP_AO too, so probe the socket option through focld: it refuses to +# start with an enabled TCP-AO peer on a kernel without TCP-AO. +probe_tcp_ao_support() { + local dir="$RUNTIME_DIR/ao-support" + mkdir -p "$dir" + cat >"$dir/probe.toml" <"$dir/probe.log" 2>&1 & + local pid=$! + local shown="" + for _ in 1 2 3 4 5; do + sleep 1 + shown=$("$FOCL_BIN" --socket "$dir/probe.sock" peer show 127.0.0.1 2>/dev/null) + if [[ -n $shown ]] || ! kill -0 "$pid" 2>/dev/null; then + break + fi + done + kill "$pid" 2>/dev/null + wait "$pid" 2>/dev/null + if grep -q "this kernel has no TCP-AO" "$dir/probe.log"; then + echo "this kernel has no TCP-AO (needs Linux 6.7+ built with CONFIG_TCP_AO)" >&2 + return 1 + fi + if [[ -z $shown ]]; then + echo "could not probe TCP-AO support: focld did not answer on $dir/probe.sock (see $dir/probe.log)" >&2 + return 1 + fi + return 0 +} + +probe_tcp_ao_support || exit 1 + +FOCL_SOCKET="$RUNTIME_DIR/focld-tcpao.sock" +BIRD_SOCKET="$RUNTIME_DIR/bird-tcpao.ctl" + +stop_daemons() { + set +e + if [[ -n "${FOCLD_PID:-}" ]]; then + kill "$FOCLD_PID" 2>/dev/null + wait "$FOCLD_PID" 2>/dev/null + FOCLD_PID="" + fi + if [[ -n "${BIRD_PID:-}" ]]; then + kill "$BIRD_PID" 2>/dev/null + wait "$BIRD_PID" 2>/dev/null + BIRD_PID="" + fi + rm -f "$FOCL_SOCKET" "$BIRD_SOCKET" + set -e +} +trap stop_daemons EXIT + +# write_bird_config +write_bird_config() { + cat >"$1" < +write_focl_config() { + cat >"$1" </dev/null 2>&1; then + return 0 + fi + sleep 1 + done + echo "timed out waiting for: $description" >&2 + return 1 +} + +focl_session_up() { + local show + show="$("$FOCL_BIN" --socket "$FOCL_SOCKET" peer show "$BIRD_ADDR")" + grep -q '"state": "established"' <<<"$show" && grep -q '"auth_mode": "tcp_ao"' <<<"$show" +} + +# Output is captured before grepping: with pipefail, `cmd | grep -q` fails +# when grep exits early and the writer gets SIGPIPE. +focl_learned_bird_route() { + local rib + rib="$("$FOCL_BIN" --socket "$FOCL_SOCKET" rib in "$BIRD_ADDR")" + grep -q "198.51.100.0/24" <<<"$rib" +} + +bird_learned_focl_route() { + local routes + routes="$("$BIRDC_BIN" -s "$BIRD_SOCKET" show route 203.0.113.0/24)" + grep -q "203.0.113.0/24" <<<"$routes" +} + +dump_logs() { + echo "--- birdc show protocols all focl ---" >&2 + "$BIRDC_BIN" -s "$BIRD_SOCKET" show protocols all focl >&2 || true + echo "--- kernel TCP-AO counters ---" >&2 + nstat -az 2>/dev/null | grep -E 'TCPAO' >&2 || true + echo "--- $1 ---" >&2 + tail -n 100 "$1" >&2 || true + echo "--- $2 ---" >&2 + tail -n 100 "$2" >&2 || true +} + +# run_scenario +run_scenario() { + local name="$1" + local bird_cfg="$RUNTIME_DIR/bird-$name.conf" + local focl_cfg="$RUNTIME_DIR/focl-$name.toml" + local bird_log="$RUNTIME_DIR/bird-$name.log" + local focld_log="$RUNTIME_DIR/focld-$name.log" + write_bird_config "$bird_cfg" "$5" "$6" + write_focl_config "$focl_cfg" "$2" "$3" "$4" + + echo "[$name] starting BIRD and focld..." + "$BIRD_BIN" -f -c "$bird_cfg" -s "$BIRD_SOCKET" >"$bird_log" 2>&1 & + BIRD_PID=$! + "$FOCLD_BIN" --config "$focl_cfg" >"$focld_log" 2>&1 & + FOCLD_PID=$! + + if ! wait_for "focld session Established over TCP-AO" focl_session_up || + ! wait_for "focld learning 198.51.100.0/24 from BIRD" focl_learned_bird_route || + ! wait_for "BIRD learning 203.0.113.0/24 from focld" bird_learned_focl_route; then + dump_logs "$bird_log" "$focld_log" + exit 1 + fi + "$BIRDC_BIN" -s "$BIRD_SOCKET" show protocols all focl | grep -iE 'key|packets' || true + echo "[$name] OK: Established over TCP-AO, routes exchanged both ways" + stop_daemons +} + +run_scenario focl-active-hmac-sha1 false false hmac-sha1-96 on "hmac sha1" +run_scenario bird-active-cmac-aes128 true true aes-128-cmac-96 off "cmac aes128" + +echo "Interop OK: focld <-> BIRD over TCP-AO in both directions, both RFC 5926 algorithms" diff --git a/src/bgp/auth.rs b/src/bgp/auth.rs index ae6bf2a..b7d76dd 100644 --- a/src/bgp/auth.rs +++ b/src/bgp/auth.rs @@ -3,69 +3,73 @@ use std::os::unix::io::AsRawFd; use anyhow::Result; -/// Set TCP-MD5 signature on a socket for BGP authentication (RFC 2385) -/// -/// # Safety -/// This uses libc directly and is marked unsafe due to raw pointer operations. #[cfg(target_os = "linux")] -pub fn set_tcp_md5_signature(socket_fd: i32, peer_addr: &SocketAddr, password: &str) -> Result<()> { - use libc::{setsockopt, socklen_t, AF_INET, AF_INET6, IPPROTO_TCP, TCP_MD5SIG}; - use std::os::raw::c_void; - - // TCP_MD5SIG requires a tcp_md5sig struct - // struct tcp_md5sig { - // struct sockaddr_storage tcpm_addr; - // __u8 tcpm_flags; - // __u8 tcpm_prefixlen; - // __u16 tcpm_keylen; - // __u32 tcpm_ifindex; - // __u8 tcpm_key[TCP_MD5SIG_MAXKEYLEN]; - // }; - - const TCP_MD5SIG_MAXKEYLEN: usize = 80; - - #[repr(C)] - struct TcpMd5Sig { - tcpm_addr: libc::sockaddr_storage, - tcpm_flags: u8, - tcpm_prefixlen: u8, - tcpm_keylen: u16, - tcpm_ifindex: u32, - tcpm_key: [u8; TCP_MD5SIG_MAXKEYLEN], - } - - let mut md5sig = TcpMd5Sig { - tcpm_addr: unsafe { std::mem::zeroed() }, - tcpm_flags: 0, - tcpm_prefixlen: 0, - tcpm_keylen: 0, - tcpm_ifindex: 0, - tcpm_key: [0; TCP_MD5SIG_MAXKEYLEN], - }; +use crate::config::TcpAoAlgorithm; +use crate::config::TcpAoKeyConfig; + +/// The TCP-AO state of a connection, from `getsockopt(TCP_AO_INFO)`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct TcpAoStatus { + /// SendID of the key that signs outgoing segments. + pub current_key: u8, + /// RecvID this side asks the peer to sign with. + pub rnext_key: u8, + /// Segments that verified. + pub pkt_good: u64, + /// Segments that failed verification. + pub pkt_bad: u64, + /// Segments whose KeyID matched no installed key. + pub pkt_key_not_found: u64, + /// Segments dropped for carrying no TCP-AO option. + pub pkt_ao_required: u64, +} + +/// RFC 5926 s3.2: both MAC algorithms are truncated to 96 bits. +#[cfg(target_os = "linux")] +const TCP_AO_MAC_LEN: u8 = 12; + +/// The kernel name of `algorithm`. `cmac(aes128)` is not a crypto API name: +/// the kernel takes it as RFC 5926 AES-128-CMAC-96 and derives the 16-byte +/// traffic key itself (KDF_AES_128_CMAC), so any secret length works. +#[cfg(target_os = "linux")] +fn tcp_ao_alg_name(algorithm: TcpAoAlgorithm) -> &'static str { + match algorithm { + TcpAoAlgorithm::HmacSha1_96 => "hmac(sha1)", + TcpAoAlgorithm::Aes128Cmac96 => "cmac(aes128)", + } +} + +/// Writes `peer_addr` into the address field of a kernel key struct. +#[cfg(target_os = "linux")] +fn write_peer_addr( + storage: &mut linux_raw_sys::net::__kernel_sockaddr_storage, + peer_addr: &SocketAddr, +) { + use libc::{sa_family_t, AF_INET, AF_INET6}; - // Set up address + let storage = storage as *mut _ as *mut u8; match peer_addr { SocketAddr::V4(addr) => { let sin = libc::sockaddr_in { - sin_family: AF_INET as u16, + sin_family: AF_INET as sa_family_t, sin_port: addr.port().to_be(), sin_addr: libc::in_addr { s_addr: u32::from(*addr.ip()).to_be(), }, sin_zero: [0; 8], }; + // SAFETY: a sockaddr_storage is larger than a sockaddr_in. unsafe { std::ptr::copy_nonoverlapping( &sin as *const _ as *const u8, - &mut md5sig.tcpm_addr as *mut _ as *mut u8, + storage, std::mem::size_of::(), ); } - md5sig.tcpm_addr.ss_family = AF_INET as u16; } SocketAddr::V6(addr) => { let sin6 = libc::sockaddr_in6 { - sin6_family: AF_INET6 as u16, + sin6_family: AF_INET6 as sa_family_t, sin6_port: addr.port().to_be(), sin6_flowinfo: 0, sin6_addr: libc::in6_addr { @@ -73,43 +77,67 @@ pub fn set_tcp_md5_signature(socket_fd: i32, peer_addr: &SocketAddr, password: & }, sin6_scope_id: 0, }; + // SAFETY: a sockaddr_storage is larger than a sockaddr_in6. unsafe { std::ptr::copy_nonoverlapping( &sin6 as *const _ as *const u8, - &mut md5sig.tcpm_addr as *mut _ as *mut u8, + storage, std::mem::size_of::(), ); } - md5sig.tcpm_addr.ss_family = AF_INET6 as u16; } } +} - // Set the password - let password_bytes = password.as_bytes(); - if password_bytes.len() > TCP_MD5SIG_MAXKEYLEN { - anyhow::bail!("password too long (max {} bytes)", TCP_MD5SIG_MAXKEYLEN); - } - md5sig.tcpm_keylen = password_bytes.len() as u16; - md5sig.tcpm_key[..password_bytes.len()].copy_from_slice(password_bytes); - +#[cfg(target_os = "linux")] +fn set_tcp_option(socket_fd: i32, option: u32, value: &T) -> std::io::Result<()> { + // SAFETY: `value` is a live `T` and the length passed is its size. let ret = unsafe { - setsockopt( + libc::setsockopt( socket_fd, - IPPROTO_TCP, - TCP_MD5SIG, - &md5sig as *const _ as *const c_void, - std::mem::size_of::() as socklen_t, + libc::IPPROTO_TCP, + option as libc::c_int, + value as *const T as *const libc::c_void, + std::mem::size_of::() as libc::socklen_t, ) }; - if ret < 0 { - let err = std::io::Error::last_os_error(); - anyhow::bail!("failed to set TCP_MD5SIG: {}", err); + return Err(std::io::Error::last_os_error()); } - Ok(()) } +/// Names the kernel requirement when the kernel has no TCP-AO at all. +#[cfg(target_os = "linux")] +fn tcp_ao_error(action: &str, error: std::io::Error) -> anyhow::Error { + if error.raw_os_error() == Some(libc::ENOPROTOOPT) { + anyhow::anyhow!( + "failed to {action}: {error} (TCP-AO needs Linux 6.7+ built with CONFIG_TCP_AO)" + ) + } else { + anyhow::anyhow!("failed to {action}: {error}") + } +} + +/// Set TCP-MD5 signature on a socket for BGP authentication (RFC 2385) +#[cfg(target_os = "linux")] +pub fn set_tcp_md5_signature(socket_fd: i32, peer_addr: &SocketAddr, password: &str) -> Result<()> { + use linux_raw_sys::net::{tcp_md5sig, TCP_MD5SIG, TCP_MD5SIG_MAXKEYLEN}; + + let password = password.as_bytes(); + if password.len() > TCP_MD5SIG_MAXKEYLEN as usize { + anyhow::bail!("password too long (max {} bytes)", TCP_MD5SIG_MAXKEYLEN); + } + // SAFETY: tcp_md5sig is plain old data, for which all zeroes is valid. + let mut md5sig: tcp_md5sig = unsafe { std::mem::zeroed() }; + write_peer_addr(&mut md5sig.tcpm_addr, peer_addr); + md5sig.tcpm_keylen = password.len() as u16; + md5sig.tcpm_key[..password.len()].copy_from_slice(password); + + set_tcp_option(socket_fd, TCP_MD5SIG, &md5sig) + .map_err(|err| anyhow::anyhow!("failed to set TCP_MD5SIG: {}", err)) +} + /// Stub implementation for non-Linux platforms #[cfg(not(target_os = "linux"))] pub fn set_tcp_md5_signature( @@ -120,9 +148,179 @@ pub fn set_tcp_md5_signature( anyhow::bail!("TCP-MD5 authentication is only supported on Linux (RFC 2385)") } -/// Extension trait to set TCP-MD5 on tokio TcpSocket +/// Adds one TCP-AO master key tuple for `peer_addr` (RFC 5925). Only the IP +/// of `peer_addr` is used: Linux matches TCP-AO keys by address only, and +/// rejects a key address that carries a port. `make_current` signs with this +/// key and requests it from the peer; it is only valid before the handshake, +/// and never on a listening socket. +#[cfg(target_os = "linux")] +pub fn add_tcp_ao_key( + socket_fd: i32, + peer_addr: &SocketAddr, + key: &TcpAoKeyConfig, + make_current: bool, +) -> Result<()> { + use linux_raw_sys::net::{tcp_ao_add, TCP_AO_ADD_KEY, TCP_AO_MAXKEYLEN}; + + let secret = key.secret.as_bytes(); + if secret.is_empty() || secret.len() > TCP_AO_MAXKEYLEN as usize { + anyhow::bail!("TCP-AO secret must be 1-{} bytes", TCP_AO_MAXKEYLEN); + } + // SAFETY: tcp_ao_add is plain old data, for which all zeroes is valid. + let mut add: tcp_ao_add = unsafe { std::mem::zeroed() }; + write_peer_addr(&mut add.addr, &SocketAddr::new(peer_addr.ip(), 0)); + for (dst, src) in add + .alg_name + .iter_mut() + .zip(tcp_ao_alg_name(key.algorithm).bytes()) + { + *dst = src as _; + } + // A v4-mapped address on an AF_INET6 socket is keyed as IPv4. + add.prefix = match peer_addr.ip().to_canonical() { + std::net::IpAddr::V4(_) => 32, + std::net::IpAddr::V6(_) => 128, + }; + add.sndid = key.send_id; + add.rcvid = key.recv_id; + add.maclen = TCP_AO_MAC_LEN; + add.keylen = secret.len() as u8; + add.key[..secret.len()].copy_from_slice(secret); + if make_current { + add.set_set_current(1); + add.set_set_rnext(1); + } + + set_tcp_option(socket_fd, TCP_AO_ADD_KEY, &add).map_err(|err| { + tcp_ao_error( + &format!( + "add TCP-AO key (send_id {}, recv_id {})", + key.send_id, key.recv_id + ), + err, + ) + }) +} + +#[cfg(not(target_os = "linux"))] +pub fn add_tcp_ao_key( + _socket_fd: i32, + _peer_addr: &SocketAddr, + _key: &TcpAoKeyConfig, + _make_current: bool, +) -> Result<()> { + anyhow::bail!("TCP-AO authentication is only supported on Linux (RFC 5925)") +} + +/// Makes the socket drop every segment without TCP-AO, also from addresses +/// that match no key. Never set this on a listener shared with peers that do +/// not use TCP-AO. +#[cfg(target_os = "linux")] +pub fn require_tcp_ao(socket_fd: i32) -> Result<()> { + use linux_raw_sys::net::{tcp_ao_info_opt, TCP_AO_INFO}; + + // SAFETY: tcp_ao_info_opt is plain old data, for which all zeroes is valid. + let mut info: tcp_ao_info_opt = unsafe { std::mem::zeroed() }; + info.set_ao_required(1); + set_tcp_option(socket_fd, TCP_AO_INFO, &info).map_err(|err| tcp_ao_error("require TCP-AO", err)) +} + +#[cfg(not(target_os = "linux"))] +pub fn require_tcp_ao(_socket_fd: i32) -> Result<()> { + anyhow::bail!("TCP-AO authentication is only supported on Linux (RFC 5925)") +} + +#[cfg(target_os = "linux")] +fn get_tcp_ao_info(socket_fd: i32) -> std::io::Result { + use linux_raw_sys::net::{tcp_ao_info_opt, TCP_AO_INFO}; + + // SAFETY: tcp_ao_info_opt is plain old data, for which all zeroes is + // valid; the kernel rejects a request whose reserved fields are not zero. + let mut info: tcp_ao_info_opt = unsafe { std::mem::zeroed() }; + let mut len = std::mem::size_of::() as libc::socklen_t; + // SAFETY: `info` and `len` are live and `len` is the size of `info`. + let ret = unsafe { + libc::getsockopt( + socket_fd, + libc::IPPROTO_TCP, + TCP_AO_INFO as libc::c_int, + &mut info as *mut _ as *mut libc::c_void, + &mut len, + ) + }; + if ret < 0 { + return Err(std::io::Error::last_os_error()); + } + Ok(info) +} + +/// The socket's TCP-AO state, or `None` if it carries no TCP-AO keys. +#[cfg(target_os = "linux")] +pub fn tcp_ao_status(socket_fd: i32) -> Result> { + match get_tcp_ao_info(socket_fd) { + Ok(info) => Ok(Some(TcpAoStatus { + current_key: info.current_key, + rnext_key: info.rnext, + pkt_good: info.pkt_good, + pkt_bad: info.pkt_bad, + pkt_key_not_found: info.pkt_key_not_found, + pkt_ao_required: info.pkt_ao_required, + })), + Err(err) if err.raw_os_error() == Some(libc::ENOENT) => Ok(None), + Err(err) => Err(tcp_ao_error("read TCP_AO_INFO", err)), + } +} + +#[cfg(not(target_os = "linux"))] +pub fn tcp_ao_status(_socket_fd: i32) -> Result> { + anyhow::bail!("TCP-AO authentication is only supported on Linux (RFC 5925)") +} + +/// Probes the socket option: `Ok(true)` when the kernel implements TCP-AO +/// (Linux 6.7+ built with `CONFIG_TCP_AO`), `Ok(false)` when it does not, and +/// `Err` when the probe itself failed (no descriptor, `EPERM`, ...), so a +/// failure is never reported as a missing kernel feature. +#[cfg(target_os = "linux")] +pub fn tcp_ao_probe() -> std::io::Result { + use std::os::fd::{FromRawFd, OwnedFd}; + + // SAFETY: plain socket(2); the descriptor is owned and closed below. + let fd = unsafe { libc::socket(libc::AF_INET, libc::SOCK_STREAM | libc::SOCK_CLOEXEC, 0) }; + if fd < 0 { + return Err(std::io::Error::last_os_error()); + } + // SAFETY: `fd` is a fresh descriptor nothing else owns. + let socket = unsafe { OwnedFd::from_raw_fd(fd) }; + // A kernel with TCP-AO reports that this keyless socket has no AO state + // (`ENOENT`); a kernel without the option reports `ENOPROTOOPT`. Anything + // else (no descriptor, `EPERM`) is a failed probe, not a missing feature. + match get_tcp_ao_info(socket.as_raw_fd()) { + Ok(_) => Ok(true), + Err(err) if err.raw_os_error() == Some(libc::ENOENT) => Ok(true), + Err(err) if err.raw_os_error() == Some(libc::ENOPROTOOPT) => Ok(false), + Err(err) => Err(err), + } +} + +#[cfg(not(target_os = "linux"))] +pub fn tcp_ao_probe() -> std::io::Result { + Ok(false) +} + +/// Whether the running kernel implements TCP-AO, treating a failed probe as +/// "no support". Callers that report to an operator use [`tcp_ao_probe`]. +pub fn tcp_ao_supported() -> bool { + tcp_ao_probe().unwrap_or(false) +} + +/// Extension trait to set TCP-MD5 or TCP-AO on tokio TcpSocket pub trait TcpSocketExt { fn set_md5_signature(&self, peer_addr: &SocketAddr, password: &str) -> Result<()>; + + /// Installs `keys` for `peer_addr` and makes the socket refuse segments + /// without TCP-AO (RFC 5925). Has to happen before `connect()`, so the SYN + /// is signed. The key marked `current`, else the first, signs. + fn set_tcp_ao_keys(&self, peer_addr: &SocketAddr, keys: &[TcpAoKeyConfig]) -> Result<()>; } impl TcpSocketExt for tokio::net::TcpSocket { @@ -130,11 +328,26 @@ impl TcpSocketExt for tokio::net::TcpSocket { let fd = self.as_raw_fd(); set_tcp_md5_signature(fd, peer_addr, password) } + + fn set_tcp_ao_keys(&self, peer_addr: &SocketAddr, keys: &[TcpAoKeyConfig]) -> Result<()> { + if keys.is_empty() { + anyhow::bail!("set_tcp_ao_keys needs at least one key"); + } + let fd = self.as_raw_fd(); + let current = keys.iter().position(|key| key.current).unwrap_or(0); + for (index, key) in keys.iter().enumerate() { + add_tcp_ao_key(fd, peer_addr, key, index == current)?; + } + require_tcp_ao(fd) + } } -/// Extension trait to set TCP-MD5 on tokio TcpStream +/// Extension trait for TCP-MD5 and TCP-AO on tokio TcpStream pub trait TcpStreamExt { fn set_md5_signature(&self, peer_addr: &SocketAddr, password: &str) -> Result<()>; + + /// The connection's TCP-AO state, or `None` if it is not TCP-AO protected. + fn tcp_ao_status(&self) -> Result>; } impl TcpStreamExt for tokio::net::TcpStream { @@ -142,4 +355,170 @@ impl TcpStreamExt for tokio::net::TcpStream { let fd = self.as_raw_fd(); set_tcp_md5_signature(fd, peer_addr, password) } + + fn tcp_ao_status(&self) -> Result> { + tcp_ao_status(self.as_raw_fd()) + } +} + +#[cfg(all(test, target_os = "linux"))] +mod tests { + use std::net::{Ipv4Addr, SocketAddr}; + use std::os::unix::io::AsRawFd; + + use super::*; + use crate::config::TcpAoAlgorithm; + + fn key(send_id: u8, recv_id: u8, algorithm: TcpAoAlgorithm) -> TcpAoKeyConfig { + TcpAoKeyConfig { + send_id, + recv_id, + algorithm, + secret: "focl-tcp-ao-unit".to_string(), + current: false, + } + } + + /// Skips an AO-dependent test when the kernel lacks TCP-AO, but refuses to + /// skip when the run declares TCP-AO has to be exercised + /// (`FOCL_REQUIRE_TCP_AO=1`, set by CI): a green suite must not hide an + /// untested path. + fn tcp_ao_or_skip(test: &str) -> bool { + if tcp_ao_supported() { + return true; + } + if std::env::var("FOCL_REQUIRE_TCP_AO").is_ok_and(|value| value == "1") { + panic!("{test} requires TCP-AO (FOCL_REQUIRE_TCP_AO=1) but this kernel does not implement it"); + } + eprintln!("skipping {test}: kernel has no TCP-AO"); + false + } + + /// A dual-stack listener sees IPv4 peers as v4-mapped addresses, so their + /// keys go in that form; the kernel files them as IPv4 keys with a /32. + #[test] + fn dual_stack_listener_accepts_v4_mapped_keys() { + if !tcp_ao_or_skip("dual_stack_listener_accepts_v4_mapped_keys") { + return; + } + let listener = std::net::TcpListener::bind("[::]:0").expect("bind [::]:0"); + let fd = listener.as_raw_fd(); + let mapped = SocketAddr::new(Ipv4Addr::new(192, 0, 2, 1).to_ipv6_mapped().into(), 179); + let native = "[2001:db8::1]:179".parse().unwrap(); + for (peer, algorithm) in [ + (mapped, TcpAoAlgorithm::HmacSha1_96), + (native, TcpAoAlgorithm::Aes128Cmac96), + ] { + add_tcp_ao_key(fd, &peer, &key(1, 1, algorithm), false) + .unwrap_or_else(|error| panic!("key for {peer}: {error}")); + } + let md5_peer = SocketAddr::new(Ipv4Addr::new(192, 0, 2, 2).to_ipv6_mapped().into(), 179); + set_tcp_md5_signature(fd, &md5_peer, "md5").expect("v4-mapped MD5 key"); + } + + #[test] + fn keyless_socket_reports_no_tcp_ao() { + if !tcp_ao_or_skip("keyless_socket_reports_no_tcp_ao") { + return; + } + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind"); + assert_eq!(tcp_ao_status(listener.as_raw_fd()).unwrap(), None); + } + + /// The kernel refuses a second MKT with the same KeyID for one peer, + /// which is why config validation insists on unique ids. + #[test] + fn kernel_rejects_duplicate_key_ids_for_one_peer() { + if !tcp_ao_or_skip("kernel_rejects_duplicate_key_ids_for_one_peer") { + return; + } + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind"); + let peer = "192.0.2.1:179".parse().unwrap(); + let first = key(7, 7, TcpAoAlgorithm::HmacSha1_96); + add_tcp_ao_key(listener.as_raw_fd(), &peer, &first, false).expect("first key"); + assert!(add_tcp_ao_key(listener.as_raw_fd(), &peer, &first, false).is_err()); + } + + /// A listener has no current key: the kernel refuses to set one, and + /// gives an accepted connection the keys its SYN names instead. The + /// peer's RNextKeyID picks the key that signs and its KeyID the one asked + /// of it, so `current` in the config cannot reach a passive session. + #[tokio::test] + async fn accepted_connection_signs_with_the_key_the_syn_names() { + if !tcp_ao_or_skip("accepted_connection_signs_with_the_key_the_syn_names") { + return; + } + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind"); + let local = listener.local_addr().unwrap(); + let fd = listener.as_raw_fd(); + let first = key(1, 2, TcpAoAlgorithm::HmacSha1_96); + let second = key(3, 4, TcpAoAlgorithm::HmacSha1_96); + assert!( + add_tcp_ao_key(fd, &local, &first, true).is_err(), + "a listening socket takes no current key" + ); + add_tcp_ao_key(fd, &local, &first, false).expect("first listener key"); + add_tcp_ao_key(fd, &local, &second, false).expect("second listener key"); + + // The connecting side mirrors both keys and marks the second current. + let mut peer_second = key(4, 3, TcpAoAlgorithm::HmacSha1_96); + peer_second.current = true; + let socket = tokio::net::TcpSocket::new_v4().unwrap(); + socket + .set_tcp_ao_keys( + &local, + &[key(2, 1, TcpAoAlgorithm::HmacSha1_96), peer_second], + ) + .expect("peer keys"); + let client = socket.connect(local).await.expect("signed connect"); + let (accepted, _) = listener.accept().await.expect("accept"); + + let connecting = client.tcp_ao_status().unwrap().expect("TCP-AO on the peer"); + assert_eq!((connecting.current_key, connecting.rnext_key), (4, 3)); + let passive = accepted.tcp_ao_status().unwrap().expect("TCP-AO on accept"); + assert_eq!( + (passive.current_key, passive.rnext_key), + (3, 4), + "the SYN, not the order the listener's keys were added in, picks the key" + ); + } + + /// TCP_MD5SIG installs on any socket, also on an accepted connection whose + /// handshake carried no signature, and the kernel has no option to read + /// back whether a connection is MD5 protected. Setting the key again + /// after `accept()` therefore proves nothing: only the key on the + /// listening socket makes the kernel drop an unsigned SYN. + #[tokio::test] + async fn md5_key_installs_on_a_connection_that_was_never_signed() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind"); + let _client = tokio::net::TcpStream::connect(listener.local_addr().unwrap()) + .await + .expect("unsigned connect"); + let (accepted, remote) = listener.accept().await.expect("accept"); + accepted + .set_md5_signature(&remote, "md5-password") + .expect("the kernel takes the key on an unsigned connection"); + + let mut md5sig = [0u8; std::mem::size_of::()]; + let mut len = md5sig.len() as libc::socklen_t; + // SAFETY: `md5sig` and `len` are live and `len` is the size of `md5sig`. + let ret = unsafe { + libc::getsockopt( + accepted.as_raw_fd(), + libc::IPPROTO_TCP, + linux_raw_sys::net::TCP_MD5SIG as libc::c_int, + md5sig.as_mut_ptr() as *mut libc::c_void, + &mut len, + ) + }; + assert_eq!(ret, -1); + assert_eq!( + std::io::Error::last_os_error().raw_os_error(), + Some(libc::ENOPROTOOPT) + ); + } } diff --git a/src/bgp/mod.rs b/src/bgp/mod.rs index 465d369..9de2011 100644 --- a/src/bgp/mod.rs +++ b/src/bgp/mod.rs @@ -17,7 +17,7 @@ use ipnet::IpNet; use ipnet_trie::IpnetTrie; use serde::{Deserialize, Serialize}; use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; -use tokio::net::{TcpListener, TcpSocket, TcpStream}; +use tokio::net::{TcpSocket, TcpStream}; use tokio::sync::{broadcast, mpsc, Mutex, RwLock}; use tokio::task::JoinHandle; use tokio::time::{sleep, timeout, Instant}; @@ -26,14 +26,14 @@ use crate::archive::types::{ PeerStateRecordInput, RibSnapshotInput, SnapshotPeer, SnapshotRoute, UpdateRecordInput, }; use crate::archive::{ArchiveService, RibSnapshotSource, SnapshotInputFuture}; -use crate::config::{FoclConfig, PeerConfig}; -use crate::types::{Event, EventEnvelope, PeerState}; +use crate::config::{FoclConfig, PeerConfig, TcpAoKeyConfig}; +use crate::types::{Event, EventEnvelope, PeerAuthMode, PeerState}; mod auth; -/// TCP-MD5 socket helpers (RFC 2385). Re-exported so library users and the -/// socket-level tests can authenticate a session against `focld` the same way -/// the daemon does. -pub use auth::{TcpSocketExt, TcpStreamExt}; +/// TCP-MD5 (RFC 2385) and TCP-AO (RFC 5925) socket helpers. Re-exported so +/// library users and the socket-level tests can authenticate a session against +/// `focld` the same way the daemon does. +pub use auth::{tcp_ao_probe, tcp_ao_supported, TcpAoStatus, TcpSocketExt, TcpStreamExt}; const AS_TRANS: u16 = 23_456; @@ -46,8 +46,16 @@ pub struct PeerInfo { pub remote_port: u16, pub passive: bool, pub auth_enabled: bool, + #[serde(default)] + pub auth_mode: PeerAuthMode, pub state: PeerState, pub last_error: Option, + /// Set when a key for this peer could not be installed on the listening + /// socket. Unlike `last_error` it is not a session outcome, so a later + /// connection error or a session that established with the keys that did + /// install never clears it. + #[serde(default)] + pub listener_key_error: Option, pub advertised_prefixes: usize, pub established_at: Option, } @@ -513,6 +521,15 @@ impl BgpService { event_tx: broadcast::Sender, archive: Option>, ) -> Result { + // `FoclConfig::load` validates, but a config built in code arrives + // unchecked, and `peer_auth` relies on a peer naming one mechanism. + cfg.validate().context("invalid configuration")?; + // Only a peer that authenticates with TCP-AO depends on the kernel + // option: a host that cannot answer the probe must not refuse a + // configuration that never asks for it. + if let Some(supported) = probe_kernel_tcp_ao(&cfg.peers, auth::tcp_ao_probe)? { + require_tcp_ao_support(&cfg.peers, supported)?; + } let router_id = cfg .global .router_id @@ -544,22 +561,31 @@ impl BgpService { async fn start_peers(&self, peers: &[PeerConfig]) { for peer in peers.iter().filter(|peer| peer.enabled) { - let runtime = self.make_runtime(peer.clone()); self.inner .rib_in .write() .await .insert(peer.address.clone(), IpnetTrie::new()); - self.inner - .peers - .write() - .await - .insert(peer.address.clone(), runtime); + } + // Register every peer before spawning its loop: an active peer reports + // its first state as soon as the task runs, and a write that arrives + // before the peer is in the map is dropped. The map stays locked across + // the spawn, so that first write waits for the registration. + let mut runtime_peers = self.inner.peers.write().await; + for peer in peers.iter().filter(|peer| peer.enabled) { + runtime_peers.insert(peer.address.clone(), self.make_runtime(peer.clone())); + if !peer.passive { + let task = self.spawn_active_loop(peer.clone()); + if let Some(runtime) = runtime_peers.get_mut(&peer.address) { + runtime.task = Some(task); + } + } } } fn make_runtime(&self, peer_cfg: PeerConfig) -> PeerRuntime { let local_as = peer_cfg.local_as.unwrap_or(self.inner.global_asn); + let auth = peer_auth(&peer_cfg); let info = PeerInfo { address: peer_cfg.address.clone(), name: peer_cfg.name.clone(), @@ -567,17 +593,22 @@ impl BgpService { local_as, remote_port: peer_cfg.remote_port, passive: peer_cfg.passive, - auth_enabled: peer_cfg.password.is_some(), + auth_enabled: auth.is_some(), + auth_mode: match auth { + None => PeerAuthMode::None, + Some(PeerAuth::Md5(_)) => PeerAuthMode::Md5, + Some(PeerAuth::TcpAo(_)) => PeerAuthMode::TcpAo, + }, state: PeerState::Idle, last_error: None, + listener_key_error: None, advertised_prefixes: 0, established_at: None, }; - let task = (!peer_cfg.passive).then(|| self.spawn_active_loop(peer_cfg.clone())); PeerRuntime { info, cfg: peer_cfg, - task, + task: None, remote_bgp_id: None, } } @@ -588,19 +619,48 @@ impl BgpService { } async fn start_listener(&self, listen_addr: &str, peers: &[PeerConfig]) -> Result<()> { - let listener = TcpListener::bind(listen_addr) + let socket = bind_listener_socket(listen_addr) .await .with_context(|| format!("failed binding global BGP listener {listen_addr}"))?; - // RFC 2385: the kernel validates the MD5 digest when the SYN arrives, - // so a passive peer's key has to live on the listening socket before - // `accept()` can ever return for that peer. The accepted-connection - // install in `accept_inbound` stays as the per-connection assertion. - install_listener_md5_keys(listener.as_raw_fd(), &listener_md5_keys(peers)); + // RFC 2385 and RFC 5925: the kernel validates the MD5 digest or the + // TCP-AO MAC when the SYN arrives, so a passive peer's key has to live + // on the listening socket. It goes on before `listen()`: a SYN that + // beat its key would be accepted unsigned, and for TCP-MD5 nothing + // can tell afterwards. A peer whose key did not make it is refused + // in `accept_inbound`. + let local_addr = socket.local_addr()?; + let v6_only = local_addr.is_ipv6() && listener_v6_only(socket.as_raw_fd()); + let (unkeyed, failures) = install_listener_auth_keys( + local_addr, + socket.as_raw_fd(), + &listener_auth_keys(peers), + v6_only, + ); + // Record a key that never reached the socket, and a passive peer that + // can never connect, where `focl peer show` reads it instead of + // leaving it to the startup log. + for (address, error) in failures { + self.set_peer_listener_key_error(&address, error.clone()) + .await; + self.set_peer_state(&address, PeerState::Idle, Some(error), None) + .await; + } + for peer in unreachable_passive_peers(local_addr, peers, v6_only) { + tracing::warn!(peer=%peer.address, listener=%local_addr, "passive peer can never connect: the BGP listener does not take connections of its address family"); + let error = format!( + "listener {local_addr} does not take connections of this peer's address family" + ); + self.set_peer_state(&peer.address, PeerState::Idle, Some(error), None) + .await; + } + let listener = socket + .listen(LISTEN_BACKLOG) + .with_context(|| format!("failed listening on global BGP listener {listen_addr}"))?; let service = self.clone(); tokio::spawn(async move { loop { match listener.accept().await { - Ok((stream, remote)) => service.accept_inbound(stream, remote).await, + Ok((stream, remote)) => service.accept_inbound(stream, remote, &unkeyed).await, Err(error) => tracing::warn!(error=%error, "global BGP listener accept failed"), } } @@ -649,18 +709,22 @@ impl BgpService { } } - async fn accept_inbound(&self, stream: TcpStream, remote: SocketAddr) { + /// Runs a session on an accepted connection. `unkeyed` holds the peers + /// whose authentication key the listener could not take. + async fn accept_inbound( + &self, + stream: TcpStream, + remote: SocketAddr, + unkeyed: &HashSet, + ) { + // A dual-stack listener reports IPv4 peers v4-mapped. + let remote_ip = remote.ip().to_canonical(); let peer = { let peers = self.inner.peers.read().await; peers .values() .find(|runtime| { - runtime.cfg.enabled - && runtime - .cfg - .address - .parse::() - .is_ok_and(|address| address == remote.ip()) + runtime.cfg.enabled && peer_address_matches(&runtime.cfg.address, remote_ip) }) .map(|runtime| runtime.cfg.clone()) }; @@ -668,11 +732,11 @@ impl BgpService { tracing::warn!(remote=%remote, "dropping inbound BGP connection from unconfigured peer"); return; }; - if let Some(password) = &peer.password { - if let Err(error) = stream.set_md5_signature(&remote, password) { - tracing::warn!(peer=%peer.address, error=%error, "failed to set TCP-MD5 on inbound BGP connection"); - return; - } + // Before the collision handling below: a connection that fails here + // must not tear down an authenticated session the peer already has. + if let Err(error) = authenticate_inbound(&stream, &peer, !unkeyed.contains(&remote_ip)) { + tracing::warn!(peer=%peer.address, error=%error, "dropping inbound BGP connection that failed authentication"); + return; } // RFC collision handling deliberately favours the accepted connection. @@ -724,6 +788,7 @@ impl BgpService { } async fn peer_loop(&self, peer: PeerConfig) { + tracing::debug!(peer = %peer.address, "active peer loop started"); loop { self.set_peer_state(&peer.address, PeerState::Connect, None, None) .await; @@ -761,7 +826,7 @@ impl BgpService { } async fn run_session(&self, peer: &PeerConfig, stream: TcpStream) -> Result<()> { - let local_ip = stream.local_addr()?.ip(); + let local_ip = stream.local_addr()?.ip().to_canonical(); self.inner .session_local_ips .write() @@ -1210,6 +1275,12 @@ impl BgpService { Ok(()) } + async fn set_peer_listener_key_error(&self, address: &str, error: String) { + if let Some(runtime) = self.inner.peers.write().await.get_mut(address) { + runtime.info.listener_key_error = Some(error); + } + } + async fn set_peer_state( &self, address: &str, @@ -1220,9 +1291,15 @@ impl BgpService { let old_state = { let mut peers = self.inner.peers.write().await; let Some(runtime) = peers.get_mut(address) else { + tracing::warn!( + address, + ?state, + "state change for a peer that is not running" + ); return; }; let old_state = runtime.info.state; + tracing::debug!(address, ?old_state, ?state, "peer state"); runtime.info.state = state; if let Some(error) = last_error { runtime.info.last_error = Some(error); @@ -1979,35 +2056,22 @@ async fn connect_with_optional_bind(peer: &PeerConfig, remote: SocketAddr) -> Re .map(|raw| normalize_socket_addr(raw, 0)) .transpose() .context("invalid peer local_address")?; - match (remote, local_bind) { - (SocketAddr::V4(remote_v4), Some(SocketAddr::V4(local_v4))) => { - let socket = TcpSocket::new_v4()?; - socket.bind(SocketAddr::V4(local_v4))?; - if let Some(password) = &peer.password { - socket.set_md5_signature(&remote, password)?; - } - Ok(socket.connect(SocketAddr::V4(remote_v4)).await?) - } - (_, Some(local)) => { - let socket = if local.is_ipv4() { - TcpSocket::new_v4()? - } else { - TcpSocket::new_v6()? - }; - socket.bind(local)?; - if let Some(password) = &peer.password { - socket.set_md5_signature(&remote, password)?; - } - Ok(socket.connect(remote).await?) - } - (_, None) => { - let stream = TcpStream::connect(remote).await?; - if let Some(password) = &peer.password { - stream.set_md5_signature(&remote, password)?; - } - Ok(stream) - } + let socket = if local_bind.map_or(remote.is_ipv4(), |local| local.is_ipv4()) { + TcpSocket::new_v4()? + } else { + TcpSocket::new_v6()? + }; + if let Some(local) = local_bind { + socket.bind(local)?; + } + // RFC 2385 and RFC 5925: the SYN is the first segment the peer verifies, + // so the key has to be on the socket before `connect()`. + match peer_auth(peer) { + Some(PeerAuth::Md5(password)) => socket.set_md5_signature(&remote, password)?, + Some(PeerAuth::TcpAo(keys)) => socket.set_tcp_ao_keys(&remote, keys)?, + None => {} } + Ok(socket.connect(remote).await?) } fn normalize_socket_addr(raw: &str, default_port: u16) -> Result { @@ -2020,31 +2084,338 @@ fn normalize_socket_addr(raw: &str, default_port: u16) -> Result { Ok(SocketAddr::new(address, default_port)) } -/// Per-peer TCP-MD5 keys for the listening socket: every enabled peer that -/// has a password. A peer whose configured address is not a literal IP cannot -/// be keyed here; the session path reports such an address. -fn listener_md5_keys(peers: &[PeerConfig]) -> Vec<(IpAddr, String)> { +/// How a peer authenticates its TCP connection: a view of the secrets in its +/// `PeerConfig`, which stays their only copy. The two are mutually exclusive: +/// `BgpService` validates its config before it reads a peer. +#[derive(Clone, Copy, PartialEq, Eq)] +enum PeerAuth<'a> { + /// TCP-MD5 (RFC 2385) password. + Md5(&'a str), + /// TCP-AO (RFC 5925) master key tuples. + TcpAo(&'a [TcpAoKeyConfig]), +} + +impl std::fmt::Debug for PeerAuth<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + PeerAuth::Md5(_) => f.write_str("PeerAuth::Md5()"), + // `TcpAoKeyConfig` leaves its secret out and shows the KeyIDs. + PeerAuth::TcpAo(keys) => f.debug_tuple("PeerAuth::TcpAo").field(keys).finish(), + } + } +} + +fn peer_auth(peer: &PeerConfig) -> Option> { + if !peer.tcp_ao_keys.is_empty() { + return Some(PeerAuth::TcpAo(&peer.tcp_ao_keys)); + } + peer.password.as_deref().map(PeerAuth::Md5) +} + +/// Probes the kernel only when an enabled peer uses TCP-AO, and returns `None` +/// when nothing needs the answer. A probe that fails is an error, never "the +/// kernel has no TCP-AO". +fn probe_kernel_tcp_ao( + peers: &[PeerConfig], + probe: impl FnOnce() -> std::io::Result, +) -> Result> { + if !peers + .iter() + .any(|peer| peer.enabled && !peer.tcp_ao_keys.is_empty()) + { + return Ok(None); + } + Ok(Some(probe().context( + "could not tell whether the kernel implements TCP-AO", + )?)) +} + +/// Fails when an enabled peer has TCP-AO keys and the kernel has no TCP-AO +/// (`supported`). Such a peer can never get a session, which would otherwise +/// only show as a failing connect on every retry or a listener key the kernel +/// refused. A disabled peer may keep its keys. +fn require_tcp_ao_support(peers: &[PeerConfig], supported: bool) -> Result<()> { + let needing: Vec<&str> = peers + .iter() + .filter(|peer| peer.enabled && !peer.tcp_ao_keys.is_empty()) + .map(|peer| peer.address.as_str()) + .collect(); + if supported || needing.is_empty() { + return Ok(()); + } + Err(anyhow!( + "tcp_ao_keys are set for {} but this kernel has no TCP-AO (it takes Linux 6.7+ built with CONFIG_TCP_AO); remove the keys or set enabled = false on those peers", + needing.join(", ") + )) +} + +/// The peer's configured address, with an IPv4 peer spelled v4-mapped +/// (`::ffff:192.0.2.1`) as that IPv4 address: the form an accepted +/// connection's remote address is compared in. `None` if the address is not a +/// literal IP. +fn peer_ip(peer: &PeerConfig) -> Option { + let address = peer.address.parse::().ok()?; + Some(address.to_canonical()) +} + +/// Pending inbound connections the BGP listener queues; the kernel caps it at +/// `net.core.somaxconn`. +const LISTEN_BACKLOG: u32 = 1024; + +/// Binds the socket of the BGP listener the way `TcpListener::bind` does, but +/// leaves it for the caller to `listen()` on: the authentication keys have to +/// be on the socket before it takes its first SYN. +async fn bind_listener_socket(listen_addr: &str) -> std::io::Result { + let addresses: Vec = tokio::net::lookup_host(listen_addr).await?.collect(); + bind_first_listener(addresses, bind_listener_one) +} + +/// Binds the first address that accepts a socket, like `TcpListener::bind`: +/// socket creation, `SO_REUSEADDR` and `bind` all belong to one attempt, so a +/// family this host cannot create a socket for falls through to the next +/// resolved address instead of aborting startup. +fn bind_first_listener( + addresses: Vec, + mut bind: impl FnMut(SocketAddr) -> std::io::Result, +) -> std::io::Result { + let mut last_error = None; + for address in addresses { + match bind(address) { + Ok(socket) => return Ok(socket), + Err(error) => last_error = Some(error), + } + } + Err(last_error.unwrap_or_else(|| { + std::io::Error::new( + std::io::ErrorKind::InvalidInput, + "could not resolve to any address", + ) + })) +} + +fn bind_listener_one(address: SocketAddr) -> std::io::Result { + let socket = if address.is_ipv4() { + TcpSocket::new_v4()? + } else { + TcpSocket::new_v6()? + }; + socket.set_reuseaddr(true)?; + socket.bind(address)?; + Ok(socket) +} + +/// Per-peer keys for the listening socket: every enabled peer that +/// authenticates, with the configured address kept for diagnostics. Config +/// validation has already rejected a peer address that is not a literal IP. +fn listener_auth_keys(peers: &[PeerConfig]) -> Vec<(String, IpAddr, PeerAuth<'_>)> { peers .iter() .filter(|peer| peer.enabled) - .filter_map(|peer| Some((peer.address.parse::().ok()?, peer.password.clone()?))) + .filter_map(|peer| { + let address = peer_ip(peer)?; + let auth = peer_auth(peer)?; + Some((peer.address.clone(), address, auth)) + }) + .collect() +} + +/// The address a listener bound to `listener` keys `peer` under, or `None` +/// if such a listener can never accept that peer. An IPv6 socket takes IPv4 +/// connections on the wildcard address or a v4-mapped one, and sees those +/// peers v4-mapped. The port is not part of the kernel's lookup for either +/// option (the source port of an inbound connection is ephemeral), so the BGP +/// port is used. +fn listener_key_addr(listener: SocketAddr, peer: IpAddr, v6_only: bool) -> Option { + let address = match (listener.ip(), peer) { + (IpAddr::V4(_), IpAddr::V4(_)) => peer, + (IpAddr::V4(_), IpAddr::V6(_)) => return None, + (IpAddr::V6(local), IpAddr::V4(v4)) => { + if v6_only || (!local.is_unspecified() && local.to_ipv4_mapped().is_none()) { + return None; + } + IpAddr::V6(v4.to_ipv6_mapped()) + } + (IpAddr::V6(local), IpAddr::V6(_)) => { + if local.to_ipv4_mapped().is_some() { + return None; + } + peer + } + }; + Some(SocketAddr::new(address, 179)) +} + +/// The enabled passive peers a listener bound to `listener` can never accept, +/// because it does not take connections of their address family. Only they +/// depend on the listener: an active peer dials out. +fn unreachable_passive_peers( + listener: SocketAddr, + peers: &[PeerConfig], + v6_only: bool, +) -> Vec<&PeerConfig> { + peers + .iter() + .filter(|peer| peer.enabled && peer.passive) + .filter(|peer| { + peer_ip(peer) + .is_some_and(|address| listener_key_addr(listener, address, v6_only).is_none()) + }) .collect() } -/// Installs `keys` on a listening socket (RFC 2385). The port of a TCP-MD5 key -/// is not part of the kernel's lookup (the key is per peer address, and the -/// source port of an inbound connection is ephemeral), so the BGP port is used. -/// A key the kernel refuses is logged rather than fatal: that peer cannot -/// complete the handshake, but the listener still serves the others. -fn install_listener_md5_keys(fd: i32, keys: &[(IpAddr, String)]) { - for (address, password) in keys { - let remote = SocketAddr::new(*address, 179); - if let Err(error) = auth::set_tcp_md5_signature(fd, &remote, password) { - tracing::warn!(peer=%address, error=%error, "failed to install TCP-MD5 key on the BGP listener"); +/// Reads `IPV6_V6ONLY` from the bound listening socket. A `[::]` listener takes +/// IPv4 connections as v4-mapped only while this is off (`net.ipv6.bindv6only`). +fn listener_v6_only(fd: i32) -> bool { + #[cfg(target_os = "linux")] + { + let mut value: libc::c_int = 0; + let mut len = std::mem::size_of::() as libc::socklen_t; + // SAFETY: `value` and `len` outlive the call and match the option. + let result = unsafe { + libc::getsockopt( + fd, + libc::IPPROTO_IPV6, + libc::IPV6_V6ONLY, + &mut value as *mut _ as *mut libc::c_void, + &mut len, + ) + }; + if result != 0 { + tracing::warn!( + error = %std::io::Error::last_os_error(), + "could not read IPV6_V6ONLY; assuming the listener takes IPv4 as v4-mapped" + ); + return false; + } + value != 0 + } + #[cfg(not(target_os = "linux"))] + { + // The kernel's authentication options bail out on non-Linux builds, so + // this only affects the unreachable-passive-peer report. + let _ = fd; + false + } +} + +/// Installs `keys` on the socket of the BGP listener. A TCP-AO key goes on +/// without `ao_required`, which would also lock out every other peer, and +/// without current/rnext, which a listener does not have: the kernel already +/// drops an unsigned SYN from an address that has a key. A key the kernel +/// refuses is logged rather than fatal: the listener still serves the other +/// peers. Every key of a peer is attempted, so one refused key does not +/// discard the keys that follow it. +/// +/// Returns the peers the listener holds no key for, which the caller has to +/// refuse because the kernel now accepts their unsigned SYN, and one +/// `(peer, error)` entry per peer with a key the kernel refused. +fn install_listener_auth_keys( + listener: SocketAddr, + fd: i32, + keys: &[(String, IpAddr, PeerAuth<'_>)], + v6_only: bool, +) -> (HashSet, Vec<(String, String)>) { + let mut unkeyed = HashSet::new(); + let mut failures = Vec::new(); + for (configured, address, peer_auth) in keys { + let Some(remote) = listener_key_addr(listener, *address, v6_only) else { + // No connection of this peer's address family reaches the + // listener, so there is nothing to key; `start_listener` reports + // the passive peers this leaves stranded. Should one arrive + // anyway, it is refused like any other unkeyed peer. + unkeyed.insert(*address); + continue; + }; + match *peer_auth { + PeerAuth::Md5(password) => { + if let Err(error) = auth::set_tcp_md5_signature(fd, &remote, password) { + tracing::error!(peer=%address, error=%error, "failed to install authentication key on the BGP listener; refusing inbound connections from this peer"); + unkeyed.insert(*address); + failures.push((configured.clone(), error.to_string())); + } + } + PeerAuth::TcpAo(ao_keys) => { + let mut errors = Vec::new(); + for key in ao_keys { + if let Err(error) = auth::add_tcp_ao_key(fd, &remote, key, false) { + tracing::error!(peer=%address, send_id=key.send_id, error=%error, "failed to install TCP-AO key on the BGP listener"); + errors.push(format!("send_id {}: {error}", key.send_id)); + } + } + // With any key in place the kernel drops an unsigned SYN, and + // `authenticate_inbound` checks the accepted connection. + if errors.len() == ao_keys.len() { + unkeyed.insert(*address); + } + if !errors.is_empty() { + failures.push((configured.clone(), errors.join("; "))); + } + } + } + } + (unkeyed, failures) +} + +/// Whether a configured peer address names `remote`. Both sides are +/// canonicalized: a dual-stack listener reports IPv4 peers v4-mapped, and a +/// peer may be configured as an IPv4-mapped literal. +fn peer_address_matches(configured: &str, remote: IpAddr) -> bool { + configured + .parse::() + .is_ok_and(|address| address.to_canonical() == remote.to_canonical()) +} + +/// Asserts that an accepted connection carries `peer`'s authentication. +/// `listener_keyed` is whether the listening socket took the peer's key. +/// +/// For TCP-MD5 that key is the whole guarantee: it makes the kernel drop an +/// unsigned or wrongly signed SYN and hand the key on to the accepted socket, +/// but nothing can be asked about the connection afterwards. `TCP_MD5SIG` +/// cannot be read back, and setting it again succeeds on a connection that +/// was never signed. For TCP-AO the accepted socket can be asked, and the +/// docs leave verifying its keys to userspace. +fn authenticate_inbound(stream: &TcpStream, peer: &PeerConfig, listener_keyed: bool) -> Result<()> { + let Some(peer_auth) = peer_auth(peer) else { + return Ok(()); + }; + if !listener_keyed { + return Err(anyhow!( + "the listener does not hold the peer's key, so nothing verified the connection" + )); + } + match peer_auth { + PeerAuth::TcpAo(keys) => { + let Some(status) = stream.tcp_ao_status()? else { + return Err(anyhow!("connection is not TCP-AO protected")); + }; + if let Some(key) = overridden_current_key(keys, &status) { + tracing::warn!( + peer=%peer.address, + configured_send_id=key.send_id, + send_id=status.current_key, + recv_id=status.rnext_key, + "TCP-AO `current` is ignored on a connection the peer opens: its SYN picked the keys" + ); + } + Ok(()) } + PeerAuth::Md5(_) => Ok(()), } } +/// The key the config marks `current`, if an accepted connection with +/// `status` uses another one. Linux gives an accepted connection the keys its +/// SYN names (the peer's RNextKeyID is the key that signs, its KeyID the one +/// asked of it), and a listener cannot hold a current key to override that. +fn overridden_current_key<'a>( + keys: &'a [TcpAoKeyConfig], + status: &TcpAoStatus, +) -> Option<&'a TcpAoKeyConfig> { + keys.iter() + .find(|key| key.current) + .filter(|key| key.send_id != status.current_key || key.recv_id != status.rnext_key) +} + async fn write_bgp_message( stream: &mut W, message: &BgpMessage, @@ -2238,25 +2609,538 @@ mod tests { } #[test] - fn listener_md5_keys_cover_exactly_the_enabled_peers_with_passwords() { + fn listener_auth_keys_cover_exactly_the_enabled_peers_that_authenticate() { + let ao_keys = vec![TcpAoKeyConfig { + send_id: 1, + recv_id: 2, + algorithm: crate::config::TcpAoAlgorithm::HmacSha1_96, + secret: "ao-secret".to_string(), + current: false, + }]; + let mut ao_peer = md5_peer("192.0.2.4", true, None); + ao_peer.tcp_ao_keys = ao_keys.clone(); + let mut disabled_ao_peer = md5_peer("192.0.2.5", false, None); + disabled_ao_peer.tcp_ao_keys = ao_keys.clone(); let peers = vec![ md5_peer("192.0.2.1", true, Some("first")), md5_peer("192.0.2.2", false, Some("disabled-peer")), md5_peer("192.0.2.3", true, None), md5_peer("2001:db8::1", true, Some("v6-peer")), md5_peer("not-an-address", true, Some("unusable")), + ao_peer, + disabled_ao_peer, + md5_peer("::ffff:192.0.2.6", true, Some("v4-mapped")), ]; assert_eq!( - listener_md5_keys(&peers), + listener_auth_keys(&peers), vec![ - ("192.0.2.1".parse::().unwrap(), "first".to_string()), ( + "192.0.2.1".to_string(), + "192.0.2.1".parse::().unwrap(), + PeerAuth::Md5("first") + ), + ( + "2001:db8::1".to_string(), "2001:db8::1".parse::().unwrap(), - "v6-peer".to_string() + PeerAuth::Md5("v6-peer") + ), + ( + "192.0.2.4".to_string(), + "192.0.2.4".parse::().unwrap(), + PeerAuth::TcpAo(&ao_keys) + ), + // An IPv4 peer spelled v4-mapped is keyed as the IPv4 peer it is. + ( + "::ffff:192.0.2.6".to_string(), + "192.0.2.6".parse::().unwrap(), + PeerAuth::Md5("v4-mapped") ), ] ); - assert!(listener_md5_keys(&[]).is_empty()); + assert!(listener_auth_keys(&[]).is_empty()); + } + + /// `listener_v6_only` reads the socket, so the test sets the option + /// explicitly: a host with `net.ipv6.bindv6only=1` must not change the + /// expected answer. + #[cfg(target_os = "linux")] + #[test] + fn v6_only_is_read_from_the_bound_socket() { + fn set_v6_only(socket: &TcpSocket, value: libc::c_int) { + // SAFETY: the option value outlives the call and matches IPV6_V6ONLY. + let rc = unsafe { + libc::setsockopt( + socket.as_raw_fd(), + libc::IPPROTO_IPV6, + libc::IPV6_V6ONLY, + &value as *const _ as *const libc::c_void, + std::mem::size_of::() as libc::socklen_t, + ) + }; + assert_eq!( + rc, + 0, + "set IPV6_V6ONLY={value}: {}", + std::io::Error::last_os_error() + ); + } + + let dual = TcpSocket::new_v6().unwrap(); + set_v6_only(&dual, 0); + dual.bind("[::]:0".parse().unwrap()).unwrap(); + assert!(!listener_v6_only(dual.as_raw_fd())); + + let only = TcpSocket::new_v6().unwrap(); + set_v6_only(&only, 1); + only.bind("[::]:0".parse().unwrap()).unwrap(); + assert!(listener_v6_only(only.as_raw_fd())); + } + + /// An active peer reports its first state as soon as its loop runs. If the + /// loop is spawned before the peer is registered, that write is dropped and + /// the peer never reports `Connect`, which is what `start_peers` used to do. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn every_active_peer_reports_its_first_state() { + let mut cfg = test_service_config(); + cfg.peers = (1..=40) + .map(|i| PeerConfig { + address: format!("127.0.1.{i}"), + remote_as: 65_002, + local_as: None, + hold_time_secs: 90, + connect_retry_secs: 30, + remote_port: 1, + local_address: None, + enabled: true, + passive: false, + route_refresh: false, + name: None, + password: None, + tcp_ao_keys: vec![], + }) + .collect(); + let (event_tx, mut event_rx) = broadcast::channel(4096); + let service = BgpService::new(&cfg, event_tx).await.unwrap(); + tokio::time::sleep(Duration::from_millis(300)).await; + + let mut connects: HashSet = HashSet::new(); + while let Ok(envelope) = event_rx.try_recv() { + if let Event::PeerState { + peer, + state: PeerState::Connect, + } = envelope.event + { + connects.insert(peer); + } + } + for i in 1..=40 { + let address = format!("127.0.1.{i}"); + assert!( + connects.contains(&address), + "{address} never reported its first state" + ); + } + drop(service); + } + + #[test] + fn the_tcp_ao_probe_runs_only_for_an_enabled_tcp_ao_peer() { + let ao_peer = |address: &str, enabled: bool| PeerConfig { + tcp_ao_keys: vec![TcpAoKeyConfig { + send_id: 1, + recv_id: 2, + algorithm: crate::config::TcpAoAlgorithm::HmacSha1_96, + secret: "ao-secret".to_string(), + current: false, + }], + ..md5_peer(address, enabled, None) + }; + + let mut called = false; + assert_eq!( + probe_kernel_tcp_ao(&[md5_peer("192.0.2.1", true, Some("md5"))], || { + called = true; + Ok(true) + }) + .unwrap(), + None + ); + assert!(!called, "a config without TCP-AO peers must not probe"); + + let mut called = false; + assert_eq!( + probe_kernel_tcp_ao(&[ao_peer("192.0.2.2", false)], || { + called = true; + Ok(true) + }) + .unwrap(), + None + ); + assert!(!called, "a disabled TCP-AO peer must not probe"); + + let mut called = false; + assert_eq!( + probe_kernel_tcp_ao(&[ao_peer("192.0.2.3", true)], || { + called = true; + Ok(true) + }) + .unwrap(), + Some(true) + ); + assert!(called); + + let error = probe_kernel_tcp_ao(&[ao_peer("192.0.2.4", true)], || { + Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied)) + }) + .unwrap_err(); + assert!( + format!("{error:#}").contains("could not tell whether the kernel implements TCP-AO"), + "{error:#}" + ); + } + + #[test] + fn listener_binding_falls_through_to_the_next_address() { + let addresses = vec![ + "192.0.2.1:179".parse().unwrap(), + "127.0.0.1:0".parse().unwrap(), + ]; + let socket = bind_first_listener(addresses, |address| { + if address.ip().to_string() == "192.0.2.1" { + return Err(std::io::Error::from(std::io::ErrorKind::AddrNotAvailable)); + } + bind_listener_one(address) + }) + .expect("the second address binds"); + assert_eq!(socket.local_addr().unwrap().ip().to_string(), "127.0.0.1"); + } + + #[test] + fn listener_binding_reports_the_last_error() { + let addresses = vec![ + "192.0.2.1:179".parse().unwrap(), + "192.0.2.2:179".parse().unwrap(), + ]; + let error = bind_first_listener(addresses, |address| { + let kind = if address.ip().to_string() == "192.0.2.1" { + std::io::ErrorKind::AddrNotAvailable + } else { + std::io::ErrorKind::PermissionDenied + }; + Err(std::io::Error::from(kind)) + }) + .expect_err("no address binds"); + assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied); + } + + #[test] + fn peer_address_matching_canonicalizes_both_sides() { + // A dual-stack listener reports IPv4 peers v4-mapped. + assert!(peer_address_matches( + "192.0.2.1", + "::ffff:192.0.2.1".parse().unwrap() + )); + // A peer configured as an IPv4-mapped literal matches the plain form. + assert!(peer_address_matches( + "::ffff:192.0.2.1", + "192.0.2.1".parse().unwrap() + )); + assert!(peer_address_matches( + "2001:db8::1", + "2001:db8::1".parse().unwrap() + )); + assert!(!peer_address_matches( + "2001:db8::1", + "192.0.2.1".parse().unwrap() + )); + assert!(!peer_address_matches( + "router.example", + "192.0.2.1".parse().unwrap() + )); + } + + #[test] + fn debug_for_peer_auth_redacts_credentials() { + let rendered = format!( + "{:?} {:?}", + PeerAuth::Md5("md5-secret"), + PeerAuth::TcpAo(&[TcpAoKeyConfig { + send_id: 1, + recv_id: 2, + algorithm: crate::config::TcpAoAlgorithm::HmacSha1_96, + secret: "ao-secret".to_string(), + current: false, + }]) + ); + assert!(!rendered.contains("md5-secret"), "{rendered}"); + assert!(!rendered.contains("ao-secret"), "{rendered}"); + assert!(rendered.contains(""), "{rendered}"); + assert!(rendered.contains("send_id: 1, recv_id: 2"), "{rendered}"); + } + + #[test] + fn listener_key_install_reports_the_peers_it_could_not_key() { + let peers = [ + md5_peer("192.0.2.1", true, Some("first")), + md5_peer("2001:db8::1", true, Some("second")), + ]; + let keys = listener_auth_keys(&peers); + let listener: SocketAddr = "[::]:179".parse().unwrap(); + // No socket behind the descriptor: every install fails. + let (unkeyed, failures) = install_listener_auth_keys(listener, -1, &keys, false); + assert_eq!( + unkeyed, + HashSet::from([ + "192.0.2.1".parse::().unwrap(), + "2001:db8::1".parse::().unwrap(), + ]) + ); + let failed: Vec<&str> = failures.iter().map(|(peer, _)| peer.as_str()).collect(); + assert_eq!(failed, ["192.0.2.1", "2001:db8::1"]); + + #[cfg(target_os = "linux")] + { + let socket = TcpSocket::new_v6().unwrap(); + socket.bind("[::]:0".parse().unwrap()).unwrap(); + let bound = socket.local_addr().unwrap(); + let (unkeyed, failures) = + install_listener_auth_keys(bound, socket.as_raw_fd(), &keys, false); + assert!( + unkeyed.is_empty() && failures.is_empty(), + "a socket that is bound but not listening yet takes the keys" + ); + + // An IPv4 listener has no key for an IPv6 peer, whose connections + // cannot reach it. + let socket = TcpSocket::new_v4().unwrap(); + socket.bind("0.0.0.0:0".parse().unwrap()).unwrap(); + let bound = socket.local_addr().unwrap(); + let (unkeyed, failures) = + install_listener_auth_keys(bound, socket.as_raw_fd(), &keys, false); + assert_eq!( + unkeyed, + HashSet::from(["2001:db8::1".parse::().unwrap()]) + ); + // Not a refused key: `start_listener` reports a stranded passive + // peer, and an active one is not affected. + assert!(failures.is_empty(), "{failures:?}"); + } + } + + /// The kernel accepts an unsigned SYN from a peer whose TCP-MD5 key is + /// not on the listener, and nothing about the accepted connection says so + /// (see `md5_key_installs_on_a_connection_that_was_never_signed`). Such a + /// peer must not get a session. + #[cfg(target_os = "linux")] + #[tokio::test] + async fn inbound_from_a_peer_the_listener_could_not_key_is_refused() { + let port = std::net::TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + .port(); + let mut cfg = test_service_config(); + cfg.peers + .push(md5_peer("127.0.0.1", true, Some("md5-password"))); + let (event_tx, _) = broadcast::channel::(4); + let service = BgpService::new(&cfg, event_tx).await.unwrap(); + // A password over the kernel's 80 bytes cannot be installed, which + // stands in for any key the listener does not take. + let unkeyable = md5_peer("127.0.0.1", true, Some(&"x".repeat(81))); + service + .start_listener(&format!("127.0.0.1:{port}"), &[unkeyable]) + .await + .unwrap(); + + let mut stream = TcpStream::connect(("127.0.0.1", port)) + .await + .expect("the kernel accepts the unsigned SYN"); + let mut buf = [0u8; 19]; + let read = timeout(Duration::from_secs(5), stream.read(&mut buf)) + .await + .expect("focl kept a connection open that nothing verified"); + assert!( + matches!(read, Ok(0) | Err(_)), + "an unverified connection got a session: {read:?}" + ); + let peer = service.peer_show("127.0.0.1").await.unwrap(); + assert!(matches!(peer.state, PeerState::Idle), "{:?}", peer.state); + let recorded = peer + .listener_key_error + .clone() + .expect("the key the listener refused is reported"); + assert!(recorded.contains("password too long"), "{recorded}"); + + // A session that comes up later must not erase the listener's failure: + // the peer still runs without the key that could not be installed. + service + .set_peer_state("127.0.0.1", PeerState::Established, None, Some(0)) + .await; + let peer = service.peer_show("127.0.0.1").await.unwrap(); + assert_eq!(peer.listener_key_error, Some(recorded)); + } + + #[test] + fn current_key_override_is_only_reported_for_an_explicit_current() { + let key = |send_id, recv_id, current| TcpAoKeyConfig { + send_id, + recv_id, + algorithm: crate::config::TcpAoAlgorithm::HmacSha1_96, + secret: "ao-secret".to_string(), + current, + }; + let status = |current_key, rnext_key| TcpAoStatus { + current_key, + rnext_key, + pkt_good: 0, + pkt_bad: 0, + pkt_key_not_found: 0, + pkt_ao_required: 0, + }; + let keys = [key(1, 2, false), key(3, 4, true)]; + // The peer's SYN named the first key, the config asks for the second. + assert_eq!(overridden_current_key(&keys, &status(1, 2)), Some(&keys[1])); + assert_eq!(overridden_current_key(&keys, &status(3, 2)), Some(&keys[1])); + assert_eq!(overridden_current_key(&keys, &status(3, 4)), None); + // Without an explicit `current` no key was asked for. + let unmarked = [key(1, 2, false), key(3, 4, false)]; + assert_eq!(overridden_current_key(&unmarked, &status(3, 4)), None); + } + + #[test] + fn listener_keys_follow_the_listener_address_family() { + let v4_listener: SocketAddr = "0.0.0.0:179".parse().unwrap(); + let v6_listener: SocketAddr = "[::]:179".parse().unwrap(); + let v4_peer: IpAddr = "192.0.2.1".parse().unwrap(); + let v6_peer: IpAddr = "2001:db8::1".parse().unwrap(); + assert_eq!( + listener_key_addr(v4_listener, v4_peer, false), + Some(SocketAddr::new(v4_peer, 179)) + ); + assert_eq!(listener_key_addr(v4_listener, v6_peer, false), None); + assert_eq!( + listener_key_addr(v6_listener, v4_peer, false), + Some("[::ffff:192.0.2.1]:179".parse().unwrap()) + ); + assert_eq!( + listener_key_addr(v6_listener, v6_peer, false), + Some(SocketAddr::new(v6_peer, 179)) + ); + + // `net.ipv6.bindv6only=1`: a `[::]` listener takes no IPv4 connections, + // so an IPv4 peer cannot be keyed and cannot reach it either. + assert_eq!(listener_key_addr(v6_listener, v4_peer, true), None); + assert_eq!( + listener_key_addr(v6_listener, v6_peer, true), + Some(SocketAddr::new(v6_peer, 179)) + ); + + // Bound to one IPv6 address, a listener takes no IPv4 connections. + let v6_only_listener: SocketAddr = "[2001:db8::2]:179".parse().unwrap(); + assert_eq!(listener_key_addr(v6_only_listener, v4_peer, false), None); + assert_eq!( + listener_key_addr(v6_only_listener, v6_peer, false), + Some(SocketAddr::new(v6_peer, 179)) + ); + + // Bound to a v4-mapped address, an IPv6 socket takes only IPv4 ones. + let mapped_listener: SocketAddr = "[::ffff:192.0.2.9]:179".parse().unwrap(); + assert_eq!( + listener_key_addr(mapped_listener, v4_peer, false), + Some("[::ffff:192.0.2.1]:179".parse().unwrap()) + ); + assert_eq!(listener_key_addr(mapped_listener, v6_peer, false), None); + } + + #[test] + fn only_passive_peers_out_of_the_listeners_reach_are_reported() { + let active = |address| PeerConfig { + passive: false, + ..md5_peer(address, true, Some("md5-password")) + }; + let peers = [ + md5_peer("192.0.2.1", true, Some("md5-password")), + md5_peer("2001:db8::1", true, Some("md5-password")), + // Without authentication a passive peer depends on the listener + // just the same. + md5_peer("2001:db8::2", true, None), + md5_peer("2001:db8::3", false, Some("disabled-peer")), + // The README's dual-stack example: an active IPv6 peer next to an + // IPv4 listener dials out and is fine. + active("2001:db8::4"), + active("192.0.2.4"), + ]; + let unreachable = |listener: &str, v6_only: bool| -> Vec<&str> { + unreachable_passive_peers(listener.parse().unwrap(), &peers, v6_only) + .into_iter() + .map(|peer| peer.address.as_str()) + .collect() + }; + + assert_eq!( + unreachable("0.0.0.0:179", false), + ["2001:db8::1", "2001:db8::2"] + ); + assert_eq!(unreachable("[2001:db8::9]:179", false), ["192.0.2.1"]); + assert!(unreachable_passive_peers("[::]:179".parse().unwrap(), &peers, false).is_empty()); + // bindv6only=1: the IPv4 passive peer is stranded, the IPv6 ones are not. + assert_eq!(unreachable("[::]:179", true), ["192.0.2.1"]); + } + + #[test] + fn tcp_ao_peers_need_a_kernel_with_tcp_ao() { + let ao_peer = |address, enabled| PeerConfig { + tcp_ao_keys: vec![TcpAoKeyConfig { + send_id: 1, + recv_id: 2, + algorithm: crate::config::TcpAoAlgorithm::HmacSha1_96, + secret: "ao-secret".to_string(), + current: false, + }], + ..md5_peer(address, enabled, None) + }; + let peers = [ + md5_peer("192.0.2.1", true, Some("md5-password")), + ao_peer("192.0.2.2", true), + ao_peer("192.0.2.3", false), + ao_peer("2001:db8::4", true), + ]; + require_tcp_ao_support(&peers, true).expect("the kernel has TCP-AO"); + + let error = require_tcp_ao_support(&peers, false) + .expect_err("an enabled TCP-AO peer cannot run without TCP-AO") + .to_string(); + assert!(error.contains("192.0.2.2, 2001:db8::4"), "{error}"); + assert!(error.contains("CONFIG_TCP_AO"), "{error}"); + assert!(!error.contains("192.0.2.1"), "{error}"); + assert!(!error.contains("192.0.2.3"), "{error}"); + + // TCP-MD5 peers and disabled TCP-AO peers do not need it. + require_tcp_ao_support(&peers[..1], false).unwrap(); + require_tcp_ao_support(&peers[2..3], false).unwrap(); + } + + /// `FoclConfig::load` is not the only way to a config: one built in code + /// must not get a peer that names two mechanisms past `peer_auth`. + #[tokio::test] + async fn service_refuses_a_config_that_fails_validation() { + let mut cfg = test_service_config(); + cfg.peers.push(PeerConfig { + tcp_ao_keys: vec![TcpAoKeyConfig { + send_id: 1, + recv_id: 2, + algorithm: crate::config::TcpAoAlgorithm::HmacSha1_96, + secret: "ao-secret".to_string(), + current: false, + }], + ..md5_peer("192.0.2.1", true, Some("md5-password")) + }); + let (event_tx, _) = broadcast::channel::(4); + let error = BgpService::new(&cfg, event_tx) + .await + .err() + .expect("a peer with a password and TCP-AO keys must be refused"); + assert!(format!("{error:#}").contains("pick one"), "{error:#}"); } fn md5_peer(address: &str, enabled: bool, password: Option<&str>) -> PeerConfig { @@ -2273,6 +3157,7 @@ mod tests { route_refresh: true, name: None, password: password.map(str::to_string), + tcp_ao_keys: vec![], } } @@ -3084,6 +3969,7 @@ enabled = false route_refresh: true, name: None, password: None, + tcp_ao_keys: vec![], }; let negotiated = NegotiatedCapabilities { families: HashSet::from([(Afi::Ipv4, Safi::Unicast)]), diff --git a/src/config/mod.rs b/src/config/mod.rs index 8117cb2..f780445 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -1,3 +1,4 @@ +use std::fmt; use std::fs; use std::path::{Path, PathBuf}; @@ -36,7 +37,20 @@ impl FoclConfig { bail!("[global].router_id must be a valid IPv4 address"); } + // One peer per address: an inbound connection matches a peer by IP, so + // two spellings of the same address (`192.0.2.1` and `::ffff:192.0.2.1`) + // would leave the choice of peer, its remote AS and its key undefined. + let mut seen: std::collections::HashMap = + std::collections::HashMap::new(); for peer in &self.peers { + if let Ok(address) = peer.address.parse::() { + if let Some(first) = seen.insert(address.to_canonical(), peer.address.as_str()) { + bail!( + "peers {first} and {} are the same address in different spellings", + peer.address + ); + } + } if peer.remote_as == 0 { bail!("peer {} has invalid remote_as 0", peer.address); } @@ -61,6 +75,7 @@ impl FoclConfig { ); } } + validate_peer_auth(peer)?; } for prefix in &self.prefixes { @@ -111,7 +126,11 @@ fn default_log_level() -> String { "info".to_string() } -#[derive(Debug, Clone, Serialize, Deserialize)] +/// One `[[peers]]` table. An unknown key is an error: a misspelled `password` +/// or `tcp_ao_keys` would otherwise leave the peer without the authentication +/// its config asks for. +#[derive(Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] pub struct PeerConfig { pub address: String, pub remote_as: u32, @@ -133,8 +152,168 @@ pub struct PeerConfig { pub route_refresh: bool, #[serde(default)] pub name: Option, + /// TCP-MD5 (RFC 2385) password. Mutually exclusive with `tcp_ao_keys`. #[serde(default)] pub password: Option, + /// TCP-AO (RFC 5925) master key tuples. Mutually exclusive with + /// `password`. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub tcp_ao_keys: Vec, +} + +/// Stands in for a secret in `Debug` output. +struct Redacted; + +impl fmt::Debug for Redacted { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("") + } +} + +/// Leaves the TCP-MD5 password out, so a peer can end up in a log or a panic +/// message. The destructuring makes a new field a compile error here rather +/// than a field that silently goes unprinted. +impl fmt::Debug for PeerConfig { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let Self { + address, + remote_as, + local_as, + hold_time_secs, + connect_retry_secs, + remote_port, + local_address, + enabled, + passive, + route_refresh, + name, + password, + tcp_ao_keys, + } = self; + f.debug_struct("PeerConfig") + .field("address", address) + .field("remote_as", remote_as) + .field("local_as", local_as) + .field("hold_time_secs", hold_time_secs) + .field("connect_retry_secs", connect_retry_secs) + .field("remote_port", remote_port) + .field("local_address", local_address) + .field("enabled", enabled) + .field("passive", passive) + .field("route_refresh", route_refresh) + .field("name", name) + .field("password", &password.as_ref().map(|_| Redacted)) + .field("tcp_ao_keys", tcp_ao_keys) + .finish() + } +} + +/// The longest TCP-MD5 password or TCP-AO secret the Linux kernel accepts. +pub const TCP_AUTH_MAX_KEY_LEN: usize = 80; + +/// One TCP-AO master key tuple (RFC 5925 s3.1). `send_id` goes into the KeyID +/// of outgoing segments and has to equal the peer's `recv_id`, and vice versa. +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct TcpAoKeyConfig { + pub send_id: u8, + pub recv_id: u8, + pub algorithm: TcpAoAlgorithm, + pub secret: String, + /// On a connection focl opens: sign outgoing segments with this key and + /// ask the peer to do the same, the first key when no key sets it. On a + /// connection the peer opens its SYN picks both keys, and this only + /// decides whether focl warns about the ones it picked. + #[serde(default)] + pub current: bool, +} + +/// Leaves the secret out, so a key can end up in a log or a panic message. +impl fmt::Debug for TcpAoKeyConfig { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let Self { + send_id, + recv_id, + algorithm, + secret: _, + current, + } = self; + f.debug_struct("TcpAoKeyConfig") + .field("send_id", send_id) + .field("recv_id", recv_id) + .field("algorithm", algorithm) + .field("secret", &Redacted) + .field("current", current) + .finish() + } +} + +/// The RFC 5926 MAC algorithms, both with a 96-bit MAC. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum TcpAoAlgorithm { + #[serde(rename = "hmac-sha1-96")] + HmacSha1_96, + #[serde(rename = "aes-128-cmac-96")] + Aes128Cmac96, +} + +fn validate_peer_auth(peer: &PeerConfig) -> Result<()> { + if let Some(password) = &peer.password { + if password.is_empty() || password.len() > TCP_AUTH_MAX_KEY_LEN { + bail!( + "peer {} has an invalid password; must be 1-{TCP_AUTH_MAX_KEY_LEN} bytes", + peer.address + ); + } + } + // Sessions are keyed by a literal address: the active path parses the peer + // address, the listener matches inbound connections against it, and both + // kernel authentication options are keyed by address. + if peer.address.parse::().is_err() { + bail!("peer {} needs a literal IP address", peer.address); + } + if peer.tcp_ao_keys.is_empty() { + return Ok(()); + } + if peer.password.is_some() { + bail!( + "peer {} sets both password (TCP-MD5) and tcp_ao_keys (TCP-AO); pick one", + peer.address + ); + } + let mut send_ids = std::collections::HashSet::new(); + let mut recv_ids = std::collections::HashSet::new(); + for key in &peer.tcp_ao_keys { + if key.secret.is_empty() || key.secret.len() > TCP_AUTH_MAX_KEY_LEN { + bail!( + "peer {} has a TCP-AO key (send_id {}) with an invalid secret; must be 1-{TCP_AUTH_MAX_KEY_LEN} bytes", + peer.address, + key.send_id + ); + } + // RFC 5925 s3.1: a KeyID has to identify a single MKT per direction. + if !send_ids.insert(key.send_id) { + bail!( + "peer {} has duplicate TCP-AO send_id {}", + peer.address, + key.send_id + ); + } + if !recv_ids.insert(key.recv_id) { + bail!( + "peer {} has duplicate TCP-AO recv_id {}", + peer.address, + key.recv_id + ); + } + } + if peer.tcp_ao_keys.iter().filter(|key| key.current).count() > 1 { + bail!( + "peer {} marks more than one TCP-AO key as current", + peer.address + ); + } + Ok(()) } fn default_true() -> bool { @@ -405,7 +584,7 @@ pub enum RibSource { LocRib, } -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Clone, Serialize, Deserialize)] pub struct ArchiveDestinationConfig { #[serde(rename = "type")] pub destination_type: DestinationType, @@ -428,6 +607,11 @@ pub struct ArchiveDestinationConfig { pub max_retries: Option, #[serde(default)] pub region: Option, + // TODO: deprecate `access_key_id`, `secret_access_key` and + // `session_token`. Nothing has ever read them: the replicator builds its + // S3 client from the default AWS credential chain (environment, profile, + // instance role), so setting them here has no effect. Warn at load when + // one is set, then drop them. #[serde(default)] pub access_key_id: Option, #[serde(default)] @@ -436,6 +620,50 @@ pub struct ArchiveDestinationConfig { pub session_token: Option, } +/// Leaves the S3 secret access key and session token out, so a destination +/// can end up in a log or a panic message. The access key id stays: it names +/// the credential in use and is no secret, as every signed request carries it +/// in clear. +impl fmt::Debug for ArchiveDestinationConfig { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let Self { + destination_type, + mode, + path, + required, + endpoint, + bucket, + prefix, + upload_concurrency, + retry_backoff_secs, + max_retries, + region, + access_key_id, + secret_access_key, + session_token, + } = self; + f.debug_struct("ArchiveDestinationConfig") + .field("destination_type", destination_type) + .field("mode", mode) + .field("path", path) + .field("required", required) + .field("endpoint", endpoint) + .field("bucket", bucket) + .field("prefix", prefix) + .field("upload_concurrency", upload_concurrency) + .field("retry_backoff_secs", retry_backoff_secs) + .field("max_retries", max_retries) + .field("region", region) + .field("access_key_id", access_key_id) + .field( + "secret_access_key", + &secret_access_key.as_ref().map(|_| Redacted), + ) + .field("session_token", &session_token.as_ref().map(|_| Redacted)) + .finish() + } +} + impl ArchiveDestinationConfig { pub fn validate(&self) -> Result<()> { match self.destination_type { @@ -630,4 +858,230 @@ dev_attr255_interval_secs = 0 }; templates.validate().expect("safe template should validate"); } + + const TCP_AO_PEER: &str = r#" +[global] +asn = 65001 +router_id = "192.0.2.1" + +[[peers]] +address = "192.0.2.2" +remote_as = 65002 + +[[peers.tcp_ao_keys]] +send_id = 1 +recv_id = 2 +algorithm = "hmac-sha1-96" +secret = "first" + +[[peers.tcp_ao_keys]] +send_id = 3 +recv_id = 4 +algorithm = "aes-128-cmac-96" +secret = "second" +current = true +"#; + + fn tcp_ao_config() -> FoclConfig { + toml::from_str(TCP_AO_PEER).expect("toml should parse") + } + + fn validation_error(cfg: &FoclConfig) -> String { + cfg.validate() + .expect_err("config should be rejected") + .to_string() + } + + #[test] + fn parses_and_roundtrips_tcp_ao_keys() { + let cfg = tcp_ao_config(); + cfg.validate().expect("TCP-AO peer should validate"); + let keys = &cfg.peers[0].tcp_ao_keys; + assert_eq!( + keys[0], + TcpAoKeyConfig { + send_id: 1, + recv_id: 2, + algorithm: TcpAoAlgorithm::HmacSha1_96, + secret: "first".to_string(), + current: false, + } + ); + assert_eq!(keys[1].algorithm, TcpAoAlgorithm::Aes128Cmac96); + assert!(keys[1].current); + + let encoded = toml::to_string(&cfg).expect("config should serialize"); + let reparsed: FoclConfig = toml::from_str(&encoded).expect("roundtrip should parse"); + assert_eq!(reparsed.peers[0].tcp_ao_keys, *keys); + } + + #[test] + fn debug_output_leaves_out_the_tcp_ao_secret() { + let cfg = tcp_ao_config(); + let printed = format!("{:?}", cfg.peers[0]); + assert!(printed.contains("send_id: 1"), "{printed}"); + assert!(printed.contains("secret: "), "{printed}"); + assert!(!printed.contains("first"), "{printed}"); + assert!(!printed.contains("second"), "{printed}"); + } + + #[test] + fn debug_output_leaves_out_the_md5_password() { + let mut cfg = tcp_ao_config(); + let peer = &mut cfg.peers[0]; + peer.tcp_ao_keys.clear(); + assert!(format!("{peer:?}").contains("password: None")); + + peer.password = Some("md5-password".to_string()); + let printed = format!("{cfg:?}"); + assert!(printed.contains("address: \"192.0.2.2\""), "{printed}"); + assert!(printed.contains("password: Some()"), "{printed}"); + assert!(!printed.contains("md5-password"), "{printed}"); + } + + #[test] + fn debug_output_leaves_out_the_s3_secrets() { + let mut cfg = tcp_ao_config(); + let destination = &mut cfg.archive.destinations[0]; + assert!(format!("{destination:?}").contains("secret_access_key: None")); + + destination.access_key_id = Some("AKIDEXAMPLE".to_string()); + destination.secret_access_key = Some("s3-secret".to_string()); + destination.session_token = Some("s3-token".to_string()); + let printed = format!("{cfg:?}"); + assert!( + printed.contains("access_key_id: Some(\"AKIDEXAMPLE\")"), + "{printed}" + ); + assert!( + printed.contains("secret_access_key: Some()"), + "{printed}" + ); + assert!( + printed.contains("session_token: Some()"), + "{printed}" + ); + assert!(!printed.contains("s3-secret"), "{printed}"); + assert!(!printed.contains("s3-token"), "{printed}"); + } + + #[test] + fn rejects_unknown_tcp_ao_algorithm() { + let raw = TCP_AO_PEER.replace("aes-128-cmac-96", "hmac-md5"); + assert!(toml::from_str::(&raw).is_err()); + } + + /// A typo must not quietly drop a key's `current` mark, or the keys + /// (and with them the peer's authentication) altogether. + #[test] + fn rejects_unknown_peer_and_tcp_ao_key_fields() { + let parse_error = |raw: &str| { + toml::from_str::(raw) + .expect_err("an unknown field should be rejected") + .to_string() + }; + + let error = parse_error(&TCP_AO_PEER.replace("current = true", "currnet = true")); + assert!(error.contains("unknown field `currnet`"), "{error}"); + + let error = + parse_error(&TCP_AO_PEER.replace("[[peers.tcp_ao_keys]]", "[[peers.tcp_ao_key]]")); + assert!(error.contains("unknown field `tcp_ao_key`"), "{error}"); + + let error = parse_error( + &TCP_AO_PEER.replace("remote_as = 65002", "remote_as = 65002\npasswrod = \"md5\""), + ); + assert!(error.contains("unknown field `passwrod`"), "{error}"); + } + + #[test] + fn shipped_example_configs_still_parse_and_validate() { + for (name, raw) in [ + ("focl.toml", include_str!("../../focl.toml")), + ( + "focl-vultr-example.toml", + include_str!("../../focl-vultr-example.toml"), + ), + ( + "scripts/interop/focl-interop.toml", + include_str!("../../scripts/interop/focl-interop.toml"), + ), + ( + "scripts/interop/focl-interop-md5.toml", + include_str!("../../scripts/interop/focl-interop-md5.toml"), + ), + ] { + let cfg: FoclConfig = + toml::from_str(raw).unwrap_or_else(|error| panic!("{name}: {error}")); + cfg.validate() + .unwrap_or_else(|error| panic!("{name}: {error:#}")); + } + } + + #[test] + fn rejects_password_together_with_tcp_ao_keys() { + let mut cfg = tcp_ao_config(); + cfg.peers[0].password = Some("md5".to_string()); + assert!(validation_error(&cfg).contains("pick one")); + } + + #[test] + fn rejects_a_hostname_peer() { + let mut cfg = tcp_ao_config(); + cfg.peers[0].address = "router.example".to_string(); + assert!(validation_error(&cfg).contains("literal IP address")); + + // The same rule applies to a peer with no authentication at all. + let mut cfg = tcp_ao_config(); + cfg.peers[0].tcp_ao_keys.clear(); + cfg.peers[0].address = "router.example".to_string(); + assert!(validation_error(&cfg).contains("literal IP address")); + } + + #[test] + fn rejects_two_spellings_of_one_peer_address() { + let mut cfg = tcp_ao_config(); + cfg.peers[0].address = "192.0.2.1".to_string(); + let mut alias = cfg.peers[0].clone(); + alias.address = "::ffff:192.0.2.1".to_string(); + cfg.peers.push(alias); + assert!(validation_error(&cfg).contains("same address in different spellings")); + } + + #[test] + fn rejects_duplicate_tcp_ao_key_ids() { + let mut cfg = tcp_ao_config(); + cfg.peers[0].tcp_ao_keys[1].send_id = 1; + assert!(validation_error(&cfg).contains("duplicate TCP-AO send_id 1")); + + let mut cfg = tcp_ao_config(); + cfg.peers[0].tcp_ao_keys[1].recv_id = 2; + assert!(validation_error(&cfg).contains("duplicate TCP-AO recv_id 2")); + } + + #[test] + fn rejects_more_than_one_current_tcp_ao_key() { + let mut cfg = tcp_ao_config(); + cfg.peers[0].tcp_ao_keys[0].current = true; + assert!(validation_error(&cfg).contains("more than one TCP-AO key as current")); + } + + #[test] + fn rejects_empty_or_oversized_secrets_and_passwords() { + for secret in [String::new(), "x".repeat(TCP_AUTH_MAX_KEY_LEN + 1)] { + let mut cfg = tcp_ao_config(); + cfg.peers[0].tcp_ao_keys[0].secret = secret.clone(); + assert!(validation_error(&cfg).contains("invalid secret")); + + let mut cfg = tcp_ao_config(); + cfg.peers[0].tcp_ao_keys.clear(); + cfg.peers[0].password = Some(secret); + assert!(validation_error(&cfg).contains("invalid password")); + } + + let mut cfg = tcp_ao_config(); + cfg.peers[0].tcp_ao_keys[0].secret = "x".repeat(TCP_AUTH_MAX_KEY_LEN); + cfg.validate() + .expect("an 80-byte secret is the kernel maximum"); + } } diff --git a/src/types.rs b/src/types.rs index c284bb5..c866161 100644 --- a/src/types.rs +++ b/src/types.rs @@ -63,6 +63,18 @@ pub enum PeerState { Established, } +/// How a peer's TCP connection is authenticated. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum PeerAuthMode { + #[default] + None, + /// TCP-MD5 (RFC 2385). + Md5, + /// TCP-AO (RFC 5925). + TcpAo, +} + #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(tag = "event", content = "payload")] pub enum Event { @@ -109,3 +121,21 @@ impl EventEnvelope { } } } + +#[cfg(test)] +mod tests { + use super::*; + + /// The control protocol spells its enum values in snake_case. + #[test] + fn peer_auth_mode_serializes_in_snake_case_like_peer_state() { + let encoded = |mode| serde_json::to_value::(mode).unwrap(); + assert_eq!(encoded(PeerAuthMode::None), "none"); + assert_eq!(encoded(PeerAuthMode::Md5), "md5"); + assert_eq!(encoded(PeerAuthMode::TcpAo), "tcp_ao"); + assert_eq!( + serde_json::to_value(PeerState::OpenSent).unwrap(), + "open_sent" + ); + } +} diff --git a/tests/acceptance_peer.rs b/tests/acceptance_peer.rs index c7fb678..49a0244 100644 --- a/tests/acceptance_peer.rs +++ b/tests/acceptance_peer.rs @@ -15,9 +15,14 @@ use bytes::Bytes; use flate2::read::GzDecoder; use focl::archive::types::ArchiveStream; use focl::archive::ArchiveService; -use focl::bgp::{BgpService, PrefixSource, PrefixStatus, TcpSocketExt}; -use focl::config::{ArchiveConfig, FoclConfig, GlobalConfig, PeerConfig, PrefixConfig}; -use focl::types::{Event, PeerState}; +use focl::bgp::{ + tcp_ao_supported, BgpService, PrefixSource, PrefixStatus, TcpSocketExt, TcpStreamExt, +}; +use focl::config::{ + ArchiveConfig, FoclConfig, GlobalConfig, PeerConfig, PrefixConfig, TcpAoAlgorithm, + TcpAoKeyConfig, +}; +use focl::types::{Event, PeerAuthMode, PeerState}; use ipnet::IpNet; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::{TcpSocket, TcpStream}; @@ -26,8 +31,14 @@ use tokio::time::timeout; const PEER_AS: u32 = 65_002; const FOCL_AS: u32 = 65_001; -/// The TCP-MD5 password of the passive peer in the MD5 acceptance test. +/// The TCP-MD5 password of the peer in the MD5 acceptance tests. const MD5_PASSWORD: &str = "focl-md5-acceptance"; +/// The TCP-AO secret of the peer in the TCP-AO acceptance tests. +const AO_SECRET: &str = "focl-tcp-ao-acceptance"; +/// TCP-AO KeyIDs: focld's SendID is the peer's RecvID and vice versa. They +/// differ so a swapped direction cannot pass. +const FOCL_AO_SEND_ID: u8 = 1; +const PEER_AO_SEND_ID: u8 = 2; /// The IPv6 prefix carrying the attribute-255 clock in the clock tests. const CLOCK_PREFIX: &str = "2001:db8:feed::/48"; @@ -59,6 +70,7 @@ async fn configured_prefixes_exchange_bidirectionally_and_archive() -> Result<() route_refresh: true, name: None, password: None, + tcp_ao_keys: vec![], }], prefixes: vec![ PrefixConfig { @@ -227,6 +239,7 @@ async fn rib_snapshot_carries_the_live_adj_rib_in() -> Result<()> { route_refresh: true, name: None, password: None, + tcp_ao_keys: vec![], }], prefixes: vec![], archive: ArchiveConfig { @@ -356,6 +369,7 @@ async fn session_end_archives_the_established_to_active_transition() -> Result<( route_refresh: true, name: None, password: None, + tcp_ao_keys: vec![], }], prefixes: vec![], archive: ArchiveConfig { @@ -447,30 +461,61 @@ async fn service_with_peer( prefixes: Vec, password: Option<&str>, hold_time_secs: u16, +) -> Result { + let mut peer = test_peer(port, hold_time_secs); + peer.password = password.map(str::to_string); + let listen_addr = format!("127.0.0.1:{port}"); + start_service(temp, prefixes, peer, Some(&listen_addr)).await +} + +/// A passive peer at 127.0.0.1, whose remote port (used when it is made +/// active) is `port`. +fn test_peer(port: u16, hold_time_secs: u16) -> PeerConfig { + PeerConfig { + address: "127.0.0.1".to_string(), + remote_as: PEER_AS, + local_as: None, + hold_time_secs, + connect_retry_secs: 1, + remote_port: port, + local_address: None, + enabled: true, + passive: true, + route_refresh: true, + name: None, + password: None, + tcp_ao_keys: vec![], + } +} + +/// Starts focld with `peer`, listening on `listen_addr` if given. +async fn start_service( + temp: &tempfile::TempDir, + prefixes: Vec, + peer: PeerConfig, + listen_addr: Option<&str>, +) -> Result { + start_service_with_peers(temp, prefixes, vec![peer], listen_addr).await +} + +/// Starts focld with several peers on one service, for cases where more than +/// one peer shares the listener. +async fn start_service_with_peers( + temp: &tempfile::TempDir, + prefixes: Vec, + peers: Vec, + listen_addr: Option<&str>, ) -> Result { let cfg = FoclConfig { global: GlobalConfig { asn: FOCL_AS, router_id: "192.0.2.1".to_string(), - listen: true, - listen_addr: format!("127.0.0.1:{port}"), + listen: listen_addr.is_some(), + listen_addr: listen_addr.unwrap_or("127.0.0.1:0").to_string(), control_socket: temp.path().join("focld.sock"), log_level: "warn".to_string(), }, - peers: vec![PeerConfig { - address: "127.0.0.1".to_string(), - remote_as: PEER_AS, - local_as: None, - hold_time_secs, - connect_retry_secs: 1, - remote_port: port, - local_address: None, - enabled: true, - passive: true, - route_refresh: true, - name: None, - password: password.map(str::to_string), - }], + peers, prefixes, archive: ArchiveConfig { enabled: false, @@ -676,6 +721,455 @@ async fn passive_session_with_md5_completes_the_handshake() -> Result<()> { Ok(()) } +/// focld's TCP-AO keys for the peer at 127.0.0.1. +fn focl_ao_keys(algorithm: TcpAoAlgorithm) -> Vec { + vec![TcpAoKeyConfig { + send_id: FOCL_AO_SEND_ID, + recv_id: PEER_AO_SEND_ID, + algorithm, + secret: AO_SECRET.to_string(), + current: false, + }] +} + +/// The peer's side of [`focl_ao_keys`], signing with `secret`. +fn peer_ao_keys(algorithm: TcpAoAlgorithm, secret: &str) -> Vec { + vec![TcpAoKeyConfig { + send_id: PEER_AO_SEND_ID, + recv_id: FOCL_AO_SEND_ID, + algorithm, + secret: secret.to_string(), + current: false, + }] +} + +fn focl_v4_prefix() -> Vec { + vec![PrefixConfig { + network: "198.51.100.0/24".to_string(), + next_hop: Some("192.0.2.1".to_string()), + dev_attr255_interval_secs: None, + }] +} + +/// Plays the peer through OPEN/KEEPALIVE and the initial table on a +/// connection focld already sent its OPEN on, and checks that focld reports +/// the session Established with `auth_mode`. +async fn complete_authenticated_session( + bgp: &BgpService, + stream: &mut TcpStream, + auth_mode: PeerAuthMode, +) -> Result<()> { + assert!(matches!(read_message(stream).await?, BgpMessage::Open(_))); + write_message(stream, &peer_open()).await?; + assert!(matches!(read_message(stream).await?, BgpMessage::KeepAlive)); + write_message(stream, &BgpMessage::KeepAlive).await?; + + let announcement = read_message(stream).await?; + assert!( + has_focl_v4(&announcement), + "expected the configured table over the authenticated session, got {announcement:?}" + ); + assert!(ipv4_eor(&read_message(stream).await?)); + let peer = bgp + .peer_show("127.0.0.1") + .await + .context("peer stays configured")?; + assert!(matches!(peer.state, PeerState::Established)); + assert_eq!(peer.auth_mode, auth_mode); + assert!(peer.auth_enabled); + Ok(()) +} + +/// The peer's view of a TCP-AO session: signed with its own SendID, asking +/// focld for focld's, and every segment so far verified. +fn assert_peer_side_tcp_ao(stream: &TcpStream) -> Result<()> { + let status = stream + .tcp_ao_status()? + .context("the session is not TCP-AO protected")?; + assert_eq!(status.current_key, PEER_AO_SEND_ID); + assert_eq!(status.rnext_key, FOCL_AO_SEND_ID); + assert!(status.pkt_good > 0, "no verified segments: {status:?}"); + assert_eq!( + status.pkt_bad, 0, + "segments failed verification: {status:?}" + ); + Ok(()) +} + +/// Whether focld sends its OPEN on a connection from `socket`: false when +/// the connect or the OPEN does not arrive in time. The kernel silently drops +/// a SYN that fails authentication, so a refused peer just times out. +async fn receives_open(socket: TcpSocket, remote: SocketAddr) -> bool { + let Ok(Ok(mut stream)) = timeout(Duration::from_secs(2), socket.connect(remote)).await else { + return false; + }; + matches!( + timeout(Duration::from_secs(2), read_message(&mut stream)).await, + Ok(Ok(BgpMessage::Open(_))) + ) +} + +/// Round 1 left one case open: a single listener must serve a keyed peer and a +/// peer with no authentication at the same time. The listener holds the keyed +/// peer's key without requiring TCP-AO for everyone, and the unkeyed peer's +/// session is not treated as authenticated. +#[cfg(target_os = "linux")] +#[tokio::test] +async fn one_listener_serves_a_keyed_and_an_unkeyed_peer() -> Result<()> { + let temp = tempfile::tempdir()?; + let port = StdTcpListener::bind("127.0.0.1:0")?.local_addr()?.port(); + + let mut keyed = test_peer(port, 30); + keyed.address = "127.0.0.2".to_string(); + keyed.password = Some(MD5_PASSWORD.to_string()); + let mut plain = test_peer(port, 30); + plain.address = "127.0.0.3".to_string(); + + let bgp = start_service_with_peers( + &temp, + focl_v4_prefix(), + vec![keyed, plain], + Some(&format!("127.0.0.1:{port}")), + ) + .await?; + + let remote = SocketAddr::from(([127, 0, 0, 1], port)); + + // The keyed peer installs its key before the SYN, like a router would. + let keyed_socket = TcpSocket::new_v4()?; + keyed_socket.bind(SocketAddr::from(([127, 0, 0, 2], 0)))?; + keyed_socket + .set_md5_signature(&remote, MD5_PASSWORD) + .context("installing the peer-side TCP-MD5 key (needs CAP_NET_ADMIN)")?; + let mut keyed_stream = timeout(Duration::from_secs(5), keyed_socket.connect(remote)).await??; + + let plain_socket = TcpSocket::new_v4()?; + plain_socket.bind(SocketAddr::from(([127, 0, 0, 3], 0)))?; + let mut plain_stream = timeout(Duration::from_secs(5), plain_socket.connect(remote)).await??; + + complete_session_as(&bgp, "127.0.0.2", &mut keyed_stream, PeerAuthMode::Md5).await?; + complete_session_as(&bgp, "127.0.0.3", &mut plain_stream, PeerAuthMode::None).await +} + +/// The same listener case with TCP-AO: the listener holds the AO peer's key +/// without setting `ao_required`, so an unauthenticated peer on the same socket +/// still gets its session. +#[cfg(target_os = "linux")] +#[tokio::test] +async fn one_listener_serves_an_ao_and_an_unkeyed_peer() -> Result<()> { + if !tcp_ao_or_skip("one_listener_serves_an_ao_and_an_unkeyed_peer") { + return Ok(()); + } + let temp = tempfile::tempdir()?; + let port = StdTcpListener::bind("127.0.0.1:0")?.local_addr()?.port(); + + let algorithm = TcpAoAlgorithm::HmacSha1_96; + let mut keyed = test_peer(port, 30); + keyed.address = "127.0.0.2".to_string(); + keyed.tcp_ao_keys = focl_ao_keys(algorithm); + let mut plain = test_peer(port, 30); + plain.address = "127.0.0.3".to_string(); + + let bgp = start_service_with_peers( + &temp, + focl_v4_prefix(), + vec![keyed, plain], + Some(&format!("127.0.0.1:{port}")), + ) + .await?; + + let remote = SocketAddr::from(([127, 0, 0, 1], port)); + let keyed_socket = TcpSocket::new_v4()?; + keyed_socket.bind(SocketAddr::from(([127, 0, 0, 2], 0)))?; + keyed_socket.set_tcp_ao_keys(&remote, &peer_ao_keys(algorithm, AO_SECRET))?; + let mut keyed_stream = timeout(Duration::from_secs(5), keyed_socket.connect(remote)).await??; + + let plain_socket = TcpSocket::new_v4()?; + plain_socket.bind(SocketAddr::from(([127, 0, 0, 3], 0)))?; + let mut plain_stream = timeout(Duration::from_secs(5), plain_socket.connect(remote)).await??; + + complete_session_as(&bgp, "127.0.0.2", &mut keyed_stream, PeerAuthMode::TcpAo).await?; + complete_session_as(&bgp, "127.0.0.3", &mut plain_stream, PeerAuthMode::None).await +} + +/// Runs one BGP handshake over `stream` and checks what `peer show` reports. +async fn complete_session_as( + bgp: &BgpService, + peer_address: &str, + stream: &mut TcpStream, + mode: PeerAuthMode, +) -> Result<()> { + assert!(matches!(read_message(stream).await?, BgpMessage::Open(_))); + write_message(stream, &peer_open()).await?; + assert!(matches!(read_message(stream).await?, BgpMessage::KeepAlive)); + write_message(stream, &BgpMessage::KeepAlive).await?; + assert!( + matches!(read_message(stream).await?, BgpMessage::Update(_)), + "{peer_address} did not get the establishment table" + ); + assert!(ipv4_eor(&read_message(stream).await?)); + let peer = bgp + .peer_show(peer_address) + .await + .context("the peer stays configured")?; + assert!( + matches!(peer.state, PeerState::Established), + "{peer_address}: {:?}", + peer.state + ); + assert_eq!(peer.auth_mode, mode, "{peer_address}"); + Ok(()) +} + +/// Skips an AO-dependent test when the kernel lacks TCP-AO, but refuses to skip +/// when the run declares TCP-AO has to be exercised (`FOCL_REQUIRE_TCP_AO=1`, +/// which CI sets): a green suite must not hide an untested path. +fn tcp_ao_or_skip(test: &str) -> bool { + if tcp_ao_supported() { + return true; + } + if std::env::var("FOCL_REQUIRE_TCP_AO").is_ok_and(|value| value == "1") { + panic!( + "{test} requires TCP-AO (FOCL_REQUIRE_TCP_AO=1) but this kernel does not implement it" + ); + } + eprintln!("skipping {test}: the kernel has no TCP-AO"); + false +} + +/// TCP-AO (RFC 5925) on a passive session, for both RFC 5926 algorithms: the +/// listener holds the peer's key, so its signed SYN is accepted and the +/// session runs over a TCP-AO protected connection. +#[cfg(target_os = "linux")] +#[tokio::test] +async fn passive_session_with_tcp_ao_completes_the_handshake() -> Result<()> { + if !tcp_ao_or_skip("passive_session_with_tcp_ao_completes_the_handshake") { + return Ok(()); + } + for algorithm in [TcpAoAlgorithm::HmacSha1_96, TcpAoAlgorithm::Aes128Cmac96] { + let temp = tempfile::tempdir()?; + let port = StdTcpListener::bind("127.0.0.1:0")?.local_addr()?.port(); + let mut peer = test_peer(port, 30); + peer.tcp_ao_keys = focl_ao_keys(algorithm); + let listen_addr = format!("127.0.0.1:{port}"); + let bgp = start_service(&temp, focl_v4_prefix(), peer, Some(&listen_addr)).await?; + + let remote = SocketAddr::from(([127, 0, 0, 1], port)); + let socket = TcpSocket::new_v4()?; + socket.set_tcp_ao_keys(&remote, &peer_ao_keys(algorithm, AO_SECRET))?; + let mut stream = timeout(Duration::from_secs(5), socket.connect(remote)) + .await + .with_context(|| format!("{algorithm:?}: the listener refused a TCP-AO peer"))??; + + complete_authenticated_session(&bgp, &mut stream, PeerAuthMode::TcpAo).await?; + assert_peer_side_tcp_ao(&stream)?; + } + Ok(()) +} + +/// A peer configured for TCP-AO gets no session over an unsigned connection +/// or one signed with the wrong secret, and a failed attempt does not stop +/// the right key from working afterwards. +#[cfg(target_os = "linux")] +#[tokio::test] +async fn passive_tcp_ao_peer_refuses_unsigned_and_wrongly_keyed_connections() -> Result<()> { + if !tcp_ao_or_skip("passive_tcp_ao_peer_refuses_unsigned_and_wrongly_keyed_connections") { + return Ok(()); + } + let algorithm = TcpAoAlgorithm::HmacSha1_96; + let temp = tempfile::tempdir()?; + let port = StdTcpListener::bind("127.0.0.1:0")?.local_addr()?.port(); + let mut peer = test_peer(port, 30); + peer.tcp_ao_keys = focl_ao_keys(algorithm); + let listen_addr = format!("127.0.0.1:{port}"); + let bgp = start_service(&temp, focl_v4_prefix(), peer, Some(&listen_addr)).await?; + let remote = SocketAddr::from(([127, 0, 0, 1], port)); + + assert!( + !receives_open(TcpSocket::new_v4()?, remote).await, + "an unsigned connection got a session" + ); + let wrong_secret = TcpSocket::new_v4()?; + wrong_secret.set_tcp_ao_keys(&remote, &peer_ao_keys(algorithm, "not-the-secret"))?; + assert!( + !receives_open(wrong_secret, remote).await, + "a connection with the wrong secret got a session" + ); + let md5_instead = TcpSocket::new_v4()?; + md5_instead.set_md5_signature(&remote, AO_SECRET)?; + assert!( + !receives_open(md5_instead, remote).await, + "a TCP-MD5 connection got a session from a TCP-AO peer" + ); + let peer = bgp.peer_show("127.0.0.1").await.context("peer exists")?; + assert!(!matches!(peer.state, PeerState::Established)); + + let right_key = TcpSocket::new_v4()?; + right_key.set_tcp_ao_keys(&remote, &peer_ao_keys(algorithm, AO_SECRET))?; + assert!( + receives_open(right_key, remote).await, + "the right key no longer works after refused attempts" + ); + Ok(()) +} + +/// TCP-MD5 counterpart of the TCP-AO refusal test. +#[cfg(target_os = "linux")] +#[tokio::test] +async fn passive_md5_peer_refuses_unsigned_and_wrongly_keyed_connections() -> Result<()> { + let temp = tempfile::tempdir()?; + let port = StdTcpListener::bind("127.0.0.1:0")?.local_addr()?.port(); + let bgp = service_with_peer(&temp, port, vec![], Some(MD5_PASSWORD), 30).await?; + let remote = SocketAddr::from(([127, 0, 0, 1], port)); + + assert!( + !receives_open(TcpSocket::new_v4()?, remote).await, + "an unsigned connection got a session" + ); + let wrong_password = TcpSocket::new_v4()?; + wrong_password.set_md5_signature(&remote, "not-the-password")?; + assert!( + !receives_open(wrong_password, remote).await, + "a connection with the wrong password got a session" + ); + let peer = bgp.peer_show("127.0.0.1").await.context("peer exists")?; + assert!(!matches!(peer.state, PeerState::Established)); + + let right_password = TcpSocket::new_v4()?; + right_password.set_md5_signature(&remote, MD5_PASSWORD)?; + assert!( + receives_open(right_password, remote).await, + "the right password no longer works after refused attempts" + ); + Ok(()) +} + +/// A `[::]` listener sees an IPv4 peer v4-mapped: its key goes on in that +/// form and the accepted connection still matches the configured IPv4 peer. +#[cfg(target_os = "linux")] +#[tokio::test] +async fn dual_stack_listener_serves_an_authenticated_ipv4_peer() -> Result<()> { + let mut cases = vec![(PeerAuthMode::Md5, None)]; + if tcp_ao_or_skip("dual_stack_listener_serves_an_authenticated_ipv4_peer (TCP-AO case)") { + cases.push((PeerAuthMode::TcpAo, Some(TcpAoAlgorithm::HmacSha1_96))); + } + for (auth_mode, algorithm) in cases { + let temp = tempfile::tempdir()?; + let port = StdTcpListener::bind("[::]:0")?.local_addr()?.port(); + let remote = SocketAddr::from(([127, 0, 0, 1], port)); + let mut peer = test_peer(port, 30); + let socket = TcpSocket::new_v4()?; + match algorithm { + Some(algorithm) => { + peer.tcp_ao_keys = focl_ao_keys(algorithm); + socket.set_tcp_ao_keys(&remote, &peer_ao_keys(algorithm, AO_SECRET))?; + } + None => { + peer.password = Some(MD5_PASSWORD.to_string()); + socket.set_md5_signature(&remote, MD5_PASSWORD)?; + } + } + let listen_addr = format!("[::]:{port}"); + let bgp = start_service(&temp, focl_v4_prefix(), peer, Some(&listen_addr)).await?; + + let mut stream = timeout(Duration::from_secs(5), socket.connect(remote)) + .await + .with_context(|| { + format!("{auth_mode:?}: the dual-stack listener refused the peer") + })??; + complete_authenticated_session(&bgp, &mut stream, auth_mode).await?; + } + Ok(()) +} + +/// An IPv4 peer may be configured in its v4-mapped spelling. It is the same +/// peer as far as the kernel is concerned, so it is keyed and matched as the +/// IPv4 address it is. +#[cfg(target_os = "linux")] +#[tokio::test] +async fn dual_stack_listener_serves_a_peer_configured_v4_mapped() -> Result<()> { + let temp = tempfile::tempdir()?; + let port = StdTcpListener::bind("[::]:0")?.local_addr()?.port(); + let remote = SocketAddr::from(([127, 0, 0, 1], port)); + let mut peer = test_peer(port, 30); + peer.address = "::ffff:127.0.0.1".to_string(); + peer.password = Some(MD5_PASSWORD.to_string()); + let listen_addr = format!("[::]:{port}"); + let _bgp = start_service(&temp, vec![], peer, Some(&listen_addr)).await?; + + assert!( + !receives_open(TcpSocket::new_v4()?, remote).await, + "an unsigned connection got a session" + ); + let socket = TcpSocket::new_v4()?; + socket.set_md5_signature(&remote, MD5_PASSWORD)?; + assert!( + receives_open(socket, remote).await, + "the peer configured as ::ffff:127.0.0.1 got no session from 127.0.0.1" + ); + Ok(()) +} + +/// A keyed listener at 127.0.0.1 that only accepts focld's signed SYN, and +/// an active focld peer dialing it with no `local_address`. Before the key +/// install moved ahead of `connect()`, that path sent its SYN unsigned. +async fn active_session_against( + listener: TcpSocket, + auth: impl FnOnce(&mut PeerConfig), + auth_mode: PeerAuthMode, +) -> Result { + let listener = listener.listen(8)?; + let port = listener.local_addr()?.port(); + let temp = tempfile::tempdir()?; + let mut peer = test_peer(port, 30); + peer.passive = false; + auth(&mut peer); + let bgp = start_service(&temp, focl_v4_prefix(), peer, None).await?; + + let (mut stream, _) = timeout(Duration::from_secs(10), listener.accept()) + .await + .context("focld never completed an authenticated handshake")??; + complete_authenticated_session(&bgp, &mut stream, auth_mode).await?; + Ok(stream) +} + +#[cfg(target_os = "linux")] +#[tokio::test] +async fn active_session_with_tcp_ao_signs_its_syn() -> Result<()> { + if !tcp_ao_or_skip("active_session_with_tcp_ao_signs_its_syn") { + return Ok(()); + } + let algorithm = TcpAoAlgorithm::Aes128Cmac96; + let listener = TcpSocket::new_v4()?; + listener.bind(SocketAddr::from(([127, 0, 0, 1], 0)))?; + listener.set_tcp_ao_keys( + &SocketAddr::from(([127, 0, 0, 1], 0)), + &peer_ao_keys(algorithm, AO_SECRET), + )?; + let stream = active_session_against( + listener, + |peer| peer.tcp_ao_keys = focl_ao_keys(algorithm), + PeerAuthMode::TcpAo, + ) + .await?; + assert_peer_side_tcp_ao(&stream) +} + +#[cfg(target_os = "linux")] +#[tokio::test] +async fn active_session_with_md5_signs_its_syn() -> Result<()> { + let listener = TcpSocket::new_v4()?; + listener.bind(SocketAddr::from(([127, 0, 0, 1], 0)))?; + listener.set_md5_signature(&SocketAddr::from(([127, 0, 0, 1], 0)), MD5_PASSWORD)?; + active_session_against( + listener, + |peer| peer.password = Some(MD5_PASSWORD.to_string()), + PeerAuthMode::Md5, + ) + .await?; + Ok(()) +} + /// RFC 2918 s4: a ROUTE-REFRESH for a negotiated family replays that family's /// Adj-RIB-Out and then its End-of-RIB. A refresh for the other family stays /// silent (see `route_refresh_for_an_unnegotiated_family_is_ignored`).