Skip to main content

s2_kit/connect/server/
subnet.rs

1//! The same-subnet check the LAN-only operations require.
2//!
3//! `S2C §LAN-LAN only interactions`: "the pairing server **must** check if the request
4//! originated from the same subnet. This functionality **must** be implemented in such a
5//! way that it works with both IPv4 and IPv6. When a request does not originate from the
6//! same subnet the server **must** respond with status code 401."
7//!
8//! This matters because those operations have no other protection. `GET /v1/nodes` will
9//! tell anyone who asks the brand, model and role of every flexible device in a building,
10//! and `POST /v1/preparePairing` will make a device display its pairing code. Neither
11//! carries a bearer, a challenge or a signature; the subnet is the whole of the access
12//! control.
13//!
14//! # What "same subnet" is taken to mean
15//!
16//! For each address this host holds, the prefix length that address was configured with
17//! defines a subnet; a peer is local if it falls inside any of them. Loopback is always
18//! accepted — a request from the machine itself is as local as it gets, and refusing it
19//! would make every integration test unrunnable for no gain.
20//!
21//! A peer arriving as an IPv4-mapped IPv6 address (`::ffff:192.0.2.1`, which is what a
22//! dual-stack listener reports) is unmapped first. Skipping that step is the standard way
23//! this check ends up rejecting every IPv4 client on a dual-stack server.
24
25use core::net::IpAddr;
26
27use axum::extract::{ConnectInfo, Request};
28use axum::http::StatusCode;
29use axum::response::{IntoResponse, Response};
30
31/// The subnets this host is on.
32///
33/// Enumerated once, at construction: interfaces do change, but re-reading them on every
34/// request turns a `GET` into a syscall storm, and a device whose address changes is going
35/// to be restarted or re-paired anyway.
36#[derive(Debug, Clone)]
37pub struct LocalSubnets {
38    nets: alloc::vec::Vec<(IpAddr, u8)>,
39}
40
41impl LocalSubnets {
42    /// Read this host's interfaces.
43    ///
44    /// # Errors
45    ///
46    /// When the interfaces cannot be enumerated at all. A host in that state cannot make
47    /// the check the specification requires, and the caller must decide whether to serve
48    /// the LAN-only routes without it — this crate will not decide that quietly.
49    ///
50    /// Loopback interfaces are left out: behind a local reverse proxy that terminates TLS,
51    /// *every* request arrives from `127.0.0.1`, and counting that as the same subnet would
52    /// serve the unauthenticated LAN routes to the internet. A host that really serves
53    /// clients on loopback says so with [`allowing_loopback`](Self::allowing_loopback).
54    pub fn detect() -> std::io::Result<Self> {
55        let nets = if_addrs::get_if_addrs()?
56            .into_iter()
57            .filter(|iface| !iface.is_loopback())
58            .map(|iface| match iface.addr {
59                if_addrs::IfAddr::V4(v4) => (IpAddr::V4(v4.ip), v4.prefixlen),
60                if_addrs::IfAddr::V6(v6) => (IpAddr::V6(v6.ip), v6.prefixlen),
61            })
62            .collect();
63        Ok(Self { nets })
64    }
65
66    /// A fixed set of subnets, for a host that knows its own topology better than we do.
67    #[must_use]
68    pub fn from_prefixes(nets: impl IntoIterator<Item = (IpAddr, u8)>) -> Self {
69        Self {
70            nets: nets.into_iter().collect(),
71        }
72    }
73
74    /// Also admit peers on loopback — a test, or a host whose clients really are local
75    /// processes. Not for a host behind a reverse proxy on the same machine.
76    #[must_use]
77    pub fn allowing_loopback(mut self) -> Self {
78        self.nets
79            .push((IpAddr::V4(core::net::Ipv4Addr::LOCALHOST), 8));
80        self.nets
81            .push((IpAddr::V6(core::net::Ipv6Addr::LOCALHOST), 128));
82        self
83    }
84
85    /// Whether a peer is on one of them.
86    #[must_use]
87    pub fn contains(&self, peer: IpAddr) -> bool {
88        let peer = unmap(peer);
89        self.nets
90            .iter()
91            .any(|(local, prefix)| same_prefix(unmap(*local), peer, *prefix))
92    }
93}
94
95/// `::ffff:a.b.c.d` is an IPv4 peer seen through a dual-stack socket.
96fn unmap(ip: IpAddr) -> IpAddr {
97    match ip {
98        IpAddr::V6(v6) => v6.to_ipv4_mapped().map_or(IpAddr::V6(v6), IpAddr::V4),
99        other @ IpAddr::V4(_) => other,
100    }
101}
102
103/// Whether two addresses of the same family share the first `prefix` bits.
104fn same_prefix(a: IpAddr, b: IpAddr, prefix: u8) -> bool {
105    match (a, b) {
106        (IpAddr::V4(a), IpAddr::V4(b)) => matches_prefix(&a.octets(), &b.octets(), prefix.min(32)),
107        (IpAddr::V6(a), IpAddr::V6(b)) => matches_prefix(&a.octets(), &b.octets(), prefix.min(128)),
108        // Different families are never the same subnet.
109        _ => false,
110    }
111}
112
113fn matches_prefix(a: &[u8], b: &[u8], prefix: u8) -> bool {
114    let whole = usize::from(prefix / 8);
115    let bits = prefix % 8;
116    if a.get(..whole) != b.get(..whole) {
117        return false;
118    }
119    if bits == 0 {
120        return true;
121    }
122    // A prefix that does not land on a byte boundary: compare the leading bits of the
123    // next byte. `1u8 << (8 - bits)` cannot overflow because `bits` is 1..=7 here.
124    let mask = !0u8 << (8 - bits);
125    match (a.get(whole), b.get(whole)) {
126        (Some(a), Some(b)) => a & mask == b & mask,
127        _ => false,
128    }
129}
130
131/// Refuse a request that did not come from this host's subnet.
132///
133/// Wrap the LAN-only routes in this, as `axum::middleware::from_fn_with_state`. The
134/// router does not do it for you because it cannot know whether the host is a LAN endpoint
135/// at all — a WAN endpoint "**cannot** implement these operations" and should return `404`
136/// instead.
137///
138/// Requires the server to have been started with
139/// `into_make_service_with_connect_info::<SocketAddr>()`, or there is no peer address to
140/// check and every request is refused.
141///
142/// ```no_run
143/// use s2_kit::connect::server::{LocalSubnets, same_subnet};
144///
145/// # fn build(lan_only: axum::Router) -> Result<axum::Router, Box<dyn std::error::Error>> {
146/// let subnets = LocalSubnets::detect()?;
147/// let guarded = lan_only.layer(axum::middleware::from_fn_with_state(
148///     subnets,
149///     same_subnet,
150/// ));
151/// # Ok(guarded)
152/// # }
153/// ```
154pub async fn same_subnet(
155    axum::extract::State(subnets): axum::extract::State<LocalSubnets>,
156    request: Request,
157    next: axum::middleware::Next,
158) -> Response {
159    let peer = request
160        .extensions()
161        .get::<ConnectInfo<std::net::SocketAddr>>()
162        .map(|ConnectInfo(addr)| addr.ip());
163    // No peer address means the server was not started with connect info. Failing closed
164    // is the only safe reading: the alternative is serving the unauthenticated routes to
165    // the internet because of a missing builder call.
166    match peer {
167        Some(peer) if subnets.contains(peer) => next.run(request).await,
168        _ => StatusCode::UNAUTHORIZED.into_response(),
169    }
170}
171
172#[cfg(test)]
173mod tests {
174    use super::*;
175
176    fn v4(s: &str) -> IpAddr {
177        IpAddr::V4(s.parse::<core::net::Ipv4Addr>().expect("an IPv4 address"))
178    }
179
180    fn v6(s: &str) -> IpAddr {
181        IpAddr::V6(s.parse::<core::net::Ipv6Addr>().expect("an IPv6 address"))
182    }
183
184    #[test]
185    fn a_peer_on_the_same_ipv4_subnet_is_local() {
186        let nets = LocalSubnets::from_prefixes([(v4("192.168.1.10"), 24)]);
187        assert!(nets.contains(v4("192.168.1.1")));
188        assert!(nets.contains(v4("192.168.1.254")));
189        // One subnet over is not the same subnet, however private it looks.
190        assert!(!nets.contains(v4("192.168.2.1")));
191        assert!(!nets.contains(v4("10.0.0.1")));
192    }
193
194    #[test]
195    fn a_prefix_that_does_not_land_on_a_byte_boundary_still_works() {
196        // /20: the first sixteen bits plus the top four of the third byte.
197        let nets = LocalSubnets::from_prefixes([(v4("10.1.16.5"), 20)]);
198        assert!(nets.contains(v4("10.1.16.1")));
199        assert!(nets.contains(v4("10.1.31.255")));
200        assert!(!nets.contains(v4("10.1.32.1")));
201        // /25 splits the last byte in half.
202        let nets = LocalSubnets::from_prefixes([(v4("10.0.0.5"), 25)]);
203        assert!(nets.contains(v4("10.0.0.127")));
204        assert!(!nets.contains(v4("10.0.0.128")));
205    }
206
207    #[test]
208    fn ipv6_is_checked_the_same_way() {
209        let nets = LocalSubnets::from_prefixes([(v6("fd00:1234::1"), 64)]);
210        assert!(nets.contains(v6("fd00:1234::abcd")));
211        assert!(!nets.contains(v6("fd00:5678::1")));
212        // Link-local is its own /64 and is not implicitly local.
213        assert!(!nets.contains(v6("fe80::1")));
214    }
215
216    #[test]
217    fn a_dual_stack_listener_does_not_reject_every_ipv4_client() {
218        // A dual-stack socket reports IPv4 peers as `::ffff:a.b.c.d`. Comparing that
219        // against an IPv4 interface without unmapping refuses everyone, which is the
220        // usual way this check is got wrong.
221        let nets = LocalSubnets::from_prefixes([(v4("192.168.1.10"), 24)]);
222        assert!(nets.contains(v6("::ffff:192.168.1.50")));
223        assert!(!nets.contains(v6("::ffff:8.8.8.8")));
224    }
225
226    #[test]
227    fn loopback_is_local_only_when_the_host_says_so() {
228        // Behind a reverse proxy on the same machine every request arrives from
229        // 127.0.0.1, so "loopback is always local" opened the unauthenticated LAN routes
230        // to whatever the proxy forwards — the internet, typically.
231        let nets = LocalSubnets::from_prefixes([]);
232        assert!(!nets.contains(v4("127.0.0.1")));
233        assert!(!nets.contains(v6("::1")));
234
235        let nets = nets.allowing_loopback();
236        assert!(nets.contains(v4("127.0.0.1")));
237        assert!(nets.contains(v6("::1")));
238        assert!(nets.contains(v6("::ffff:127.0.0.1")));
239        // And nothing else comes with it.
240        assert!(!nets.contains(v4("192.168.1.1")));
241    }
242
243    #[test]
244    fn the_families_do_not_cross() {
245        let nets = LocalSubnets::from_prefixes([(v4("192.168.1.10"), 24)]);
246        assert!(!nets.contains(v6("fd00::1")));
247        let nets = LocalSubnets::from_prefixes([(v6("fd00::1"), 64)]);
248        assert!(!nets.contains(v4("192.168.1.1")));
249    }
250
251    #[test]
252    fn this_hosts_own_interfaces_can_be_read() {
253        let Ok(nets) = LocalSubnets::detect() else {
254            return; // A sandbox with no interfaces; nothing to assert.
255        };
256        // The loopback interface is left out of what was detected.
257        assert!(!nets.contains(v4("127.0.0.1")));
258    }
259}