use core::net::IpAddr;
use axum::extract::{ConnectInfo, Request};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
#[derive(Debug, Clone)]
pub struct LocalSubnets {
nets: alloc::vec::Vec<(IpAddr, u8)>,
}
impl LocalSubnets {
pub fn detect() -> std::io::Result<Self> {
let nets = if_addrs::get_if_addrs()?
.into_iter()
.filter(|iface| !iface.is_loopback())
.map(|iface| match iface.addr {
if_addrs::IfAddr::V4(v4) => (IpAddr::V4(v4.ip), v4.prefixlen),
if_addrs::IfAddr::V6(v6) => (IpAddr::V6(v6.ip), v6.prefixlen),
})
.collect();
Ok(Self { nets })
}
#[must_use]
pub fn from_prefixes(nets: impl IntoIterator<Item = (IpAddr, u8)>) -> Self {
Self {
nets: nets.into_iter().collect(),
}
}
#[must_use]
pub fn allowing_loopback(mut self) -> Self {
self.nets
.push((IpAddr::V4(core::net::Ipv4Addr::LOCALHOST), 8));
self.nets
.push((IpAddr::V6(core::net::Ipv6Addr::LOCALHOST), 128));
self
}
#[must_use]
pub fn contains(&self, peer: IpAddr) -> bool {
let peer = unmap(peer);
self.nets
.iter()
.any(|(local, prefix)| same_prefix(unmap(*local), peer, *prefix))
}
}
fn unmap(ip: IpAddr) -> IpAddr {
match ip {
IpAddr::V6(v6) => v6.to_ipv4_mapped().map_or(IpAddr::V6(v6), IpAddr::V4),
other @ IpAddr::V4(_) => other,
}
}
fn same_prefix(a: IpAddr, b: IpAddr, prefix: u8) -> bool {
match (a, b) {
(IpAddr::V4(a), IpAddr::V4(b)) => matches_prefix(&a.octets(), &b.octets(), prefix.min(32)),
(IpAddr::V6(a), IpAddr::V6(b)) => matches_prefix(&a.octets(), &b.octets(), prefix.min(128)),
_ => false,
}
}
fn matches_prefix(a: &[u8], b: &[u8], prefix: u8) -> bool {
let whole = usize::from(prefix / 8);
let bits = prefix % 8;
if a.get(..whole) != b.get(..whole) {
return false;
}
if bits == 0 {
return true;
}
let mask = !0u8 << (8 - bits);
match (a.get(whole), b.get(whole)) {
(Some(a), Some(b)) => a & mask == b & mask,
_ => false,
}
}
pub async fn same_subnet(
axum::extract::State(subnets): axum::extract::State<LocalSubnets>,
request: Request,
next: axum::middleware::Next,
) -> Response {
let peer = request
.extensions()
.get::<ConnectInfo<std::net::SocketAddr>>()
.map(|ConnectInfo(addr)| addr.ip());
match peer {
Some(peer) if subnets.contains(peer) => next.run(request).await,
_ => StatusCode::UNAUTHORIZED.into_response(),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn v4(s: &str) -> IpAddr {
IpAddr::V4(s.parse::<core::net::Ipv4Addr>().expect("an IPv4 address"))
}
fn v6(s: &str) -> IpAddr {
IpAddr::V6(s.parse::<core::net::Ipv6Addr>().expect("an IPv6 address"))
}
#[test]
fn a_peer_on_the_same_ipv4_subnet_is_local() {
let nets = LocalSubnets::from_prefixes([(v4("192.168.1.10"), 24)]);
assert!(nets.contains(v4("192.168.1.1")));
assert!(nets.contains(v4("192.168.1.254")));
assert!(!nets.contains(v4("192.168.2.1")));
assert!(!nets.contains(v4("10.0.0.1")));
}
#[test]
fn a_prefix_that_does_not_land_on_a_byte_boundary_still_works() {
let nets = LocalSubnets::from_prefixes([(v4("10.1.16.5"), 20)]);
assert!(nets.contains(v4("10.1.16.1")));
assert!(nets.contains(v4("10.1.31.255")));
assert!(!nets.contains(v4("10.1.32.1")));
let nets = LocalSubnets::from_prefixes([(v4("10.0.0.5"), 25)]);
assert!(nets.contains(v4("10.0.0.127")));
assert!(!nets.contains(v4("10.0.0.128")));
}
#[test]
fn ipv6_is_checked_the_same_way() {
let nets = LocalSubnets::from_prefixes([(v6("fd00:1234::1"), 64)]);
assert!(nets.contains(v6("fd00:1234::abcd")));
assert!(!nets.contains(v6("fd00:5678::1")));
assert!(!nets.contains(v6("fe80::1")));
}
#[test]
fn a_dual_stack_listener_does_not_reject_every_ipv4_client() {
let nets = LocalSubnets::from_prefixes([(v4("192.168.1.10"), 24)]);
assert!(nets.contains(v6("::ffff:192.168.1.50")));
assert!(!nets.contains(v6("::ffff:8.8.8.8")));
}
#[test]
fn loopback_is_local_only_when_the_host_says_so() {
let nets = LocalSubnets::from_prefixes([]);
assert!(!nets.contains(v4("127.0.0.1")));
assert!(!nets.contains(v6("::1")));
let nets = nets.allowing_loopback();
assert!(nets.contains(v4("127.0.0.1")));
assert!(nets.contains(v6("::1")));
assert!(nets.contains(v6("::ffff:127.0.0.1")));
assert!(!nets.contains(v4("192.168.1.1")));
}
#[test]
fn the_families_do_not_cross() {
let nets = LocalSubnets::from_prefixes([(v4("192.168.1.10"), 24)]);
assert!(!nets.contains(v6("fd00::1")));
let nets = LocalSubnets::from_prefixes([(v6("fd00::1"), 64)]);
assert!(!nets.contains(v4("192.168.1.1")));
}
#[test]
fn this_hosts_own_interfaces_can_be_read() {
let Ok(nets) = LocalSubnets::detect() else {
return; };
assert!(!nets.contains(v4("127.0.0.1")));
}
}