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 pub fn detect() -> std::io::Result<Self> {
50 let nets = if_addrs::get_if_addrs()?
51 .into_iter()
52 .map(|iface| match iface.addr {
53 if_addrs::IfAddr::V4(v4) => (IpAddr::V4(v4.ip), v4.prefixlen),
54 if_addrs::IfAddr::V6(v6) => (IpAddr::V6(v6.ip), v6.prefixlen),
55 })
56 .collect();
57 Ok(Self { nets })
58 }
59
60 /// A fixed set of subnets, for a host that knows its own topology better than we do.
61 #[must_use]
62 pub fn from_prefixes(nets: impl IntoIterator<Item = (IpAddr, u8)>) -> Self {
63 Self {
64 nets: nets.into_iter().collect(),
65 }
66 }
67
68 /// Whether a peer is on one of them.
69 #[must_use]
70 pub fn contains(&self, peer: IpAddr) -> bool {
71 let peer = unmap(peer);
72 if peer.is_loopback() {
73 return true;
74 }
75 self.nets
76 .iter()
77 .any(|(local, prefix)| same_prefix(unmap(*local), peer, *prefix))
78 }
79}
80
81/// `::ffff:a.b.c.d` is an IPv4 peer seen through a dual-stack socket.
82fn unmap(ip: IpAddr) -> IpAddr {
83 match ip {
84 IpAddr::V6(v6) => v6.to_ipv4_mapped().map_or(IpAddr::V6(v6), IpAddr::V4),
85 other @ IpAddr::V4(_) => other,
86 }
87}
88
89/// Whether two addresses of the same family share the first `prefix` bits.
90fn same_prefix(a: IpAddr, b: IpAddr, prefix: u8) -> bool {
91 match (a, b) {
92 (IpAddr::V4(a), IpAddr::V4(b)) => matches_prefix(&a.octets(), &b.octets(), prefix.min(32)),
93 (IpAddr::V6(a), IpAddr::V6(b)) => matches_prefix(&a.octets(), &b.octets(), prefix.min(128)),
94 // Different families are never the same subnet.
95 _ => false,
96 }
97}
98
99fn matches_prefix(a: &[u8], b: &[u8], prefix: u8) -> bool {
100 let whole = usize::from(prefix / 8);
101 let bits = prefix % 8;
102 if a.get(..whole) != b.get(..whole) {
103 return false;
104 }
105 if bits == 0 {
106 return true;
107 }
108 // A prefix that does not land on a byte boundary: compare the leading bits of the
109 // next byte. `1u8 << (8 - bits)` cannot overflow because `bits` is 1..=7 here.
110 let mask = !0u8 << (8 - bits);
111 match (a.get(whole), b.get(whole)) {
112 (Some(a), Some(b)) => a & mask == b & mask,
113 _ => false,
114 }
115}
116
117/// Refuse a request that did not come from this host's subnet.
118///
119/// Wrap the LAN-only routes in this, as `axum::middleware::from_fn_with_state`. The
120/// router does not do it for you because it cannot know whether the host is a LAN endpoint
121/// at all — a WAN endpoint "**cannot** implement these operations" and should return `404`
122/// instead.
123///
124/// Requires the server to have been started with
125/// `into_make_service_with_connect_info::<SocketAddr>()`, or there is no peer address to
126/// check and every request is refused.
127///
128/// ```no_run
129/// use s2_kit::connect::server::{LocalSubnets, same_subnet};
130///
131/// # fn build(lan_only: axum::Router) -> Result<axum::Router, Box<dyn std::error::Error>> {
132/// let subnets = LocalSubnets::detect()?;
133/// let guarded = lan_only.layer(axum::middleware::from_fn_with_state(
134/// subnets,
135/// same_subnet,
136/// ));
137/// # Ok(guarded)
138/// # }
139/// ```
140pub async fn same_subnet(
141 axum::extract::State(subnets): axum::extract::State<LocalSubnets>,
142 request: Request,
143 next: axum::middleware::Next,
144) -> Response {
145 let peer = request
146 .extensions()
147 .get::<ConnectInfo<std::net::SocketAddr>>()
148 .map(|ConnectInfo(addr)| addr.ip());
149 // No peer address means the server was not started with connect info. Failing closed
150 // is the only safe reading: the alternative is serving the unauthenticated routes to
151 // the internet because of a missing builder call.
152 match peer {
153 Some(peer) if subnets.contains(peer) => next.run(request).await,
154 _ => StatusCode::UNAUTHORIZED.into_response(),
155 }
156}
157
158#[cfg(test)]
159mod tests {
160 use super::*;
161
162 fn v4(s: &str) -> IpAddr {
163 IpAddr::V4(s.parse::<core::net::Ipv4Addr>().expect("an IPv4 address"))
164 }
165
166 fn v6(s: &str) -> IpAddr {
167 IpAddr::V6(s.parse::<core::net::Ipv6Addr>().expect("an IPv6 address"))
168 }
169
170 #[test]
171 fn a_peer_on_the_same_ipv4_subnet_is_local() {
172 let nets = LocalSubnets::from_prefixes([(v4("192.168.1.10"), 24)]);
173 assert!(nets.contains(v4("192.168.1.1")));
174 assert!(nets.contains(v4("192.168.1.254")));
175 // One subnet over is not the same subnet, however private it looks.
176 assert!(!nets.contains(v4("192.168.2.1")));
177 assert!(!nets.contains(v4("10.0.0.1")));
178 }
179
180 #[test]
181 fn a_prefix_that_does_not_land_on_a_byte_boundary_still_works() {
182 // /20: the first sixteen bits plus the top four of the third byte.
183 let nets = LocalSubnets::from_prefixes([(v4("10.1.16.5"), 20)]);
184 assert!(nets.contains(v4("10.1.16.1")));
185 assert!(nets.contains(v4("10.1.31.255")));
186 assert!(!nets.contains(v4("10.1.32.1")));
187 // /25 splits the last byte in half.
188 let nets = LocalSubnets::from_prefixes([(v4("10.0.0.5"), 25)]);
189 assert!(nets.contains(v4("10.0.0.127")));
190 assert!(!nets.contains(v4("10.0.0.128")));
191 }
192
193 #[test]
194 fn ipv6_is_checked_the_same_way() {
195 let nets = LocalSubnets::from_prefixes([(v6("fd00:1234::1"), 64)]);
196 assert!(nets.contains(v6("fd00:1234::abcd")));
197 assert!(!nets.contains(v6("fd00:5678::1")));
198 // Link-local is its own /64 and is not implicitly local.
199 assert!(!nets.contains(v6("fe80::1")));
200 }
201
202 #[test]
203 fn a_dual_stack_listener_does_not_reject_every_ipv4_client() {
204 // A dual-stack socket reports IPv4 peers as `::ffff:a.b.c.d`. Comparing that
205 // against an IPv4 interface without unmapping refuses everyone, which is the
206 // usual way this check is got wrong.
207 let nets = LocalSubnets::from_prefixes([(v4("192.168.1.10"), 24)]);
208 assert!(nets.contains(v6("::ffff:192.168.1.50")));
209 assert!(!nets.contains(v6("::ffff:8.8.8.8")));
210 }
211
212 #[test]
213 fn the_machine_itself_is_always_local() {
214 let nets = LocalSubnets::from_prefixes([]);
215 assert!(nets.contains(v4("127.0.0.1")));
216 assert!(nets.contains(v6("::1")));
217 assert!(nets.contains(v6("::ffff:127.0.0.1")));
218 // And with no interfaces at all, nothing else is.
219 assert!(!nets.contains(v4("192.168.1.1")));
220 }
221
222 #[test]
223 fn the_families_do_not_cross() {
224 let nets = LocalSubnets::from_prefixes([(v4("192.168.1.10"), 24)]);
225 assert!(!nets.contains(v6("fd00::1")));
226 let nets = LocalSubnets::from_prefixes([(v6("fd00::1"), 64)]);
227 assert!(!nets.contains(v4("192.168.1.1")));
228 }
229
230 #[test]
231 fn this_hosts_own_interfaces_can_be_read() {
232 let Ok(nets) = LocalSubnets::detect() else {
233 return; // A sandbox with no interfaces; nothing to assert.
234 };
235 assert!(nets.contains(v4("127.0.0.1")));
236 }
237}