"""Rust: an IPv4 allowlist (CIDR blocks, dash ranges, single hosts) merged into half-open spans. range.rs documents spans as [start, end); Cidr::to_range in cidr.rs returns base | !mask, the block's last address, as `end`, so every CIDR entry loses its last address and a /32 becomes empty. The symptom is IpSet::contains failing for a /32 bastion host (set.rs, via the test); the tempting patches (inclusive contains in range.rs or set.rs, a /32 special case in set.rs) either break the dash-range/host tests or still miss the last address of the /31 uplink.""" import re ITEM_ID = "rust-allowlist" LANG = "rust" TOOL = "cargo" PROJECT = { "Cargo.toml": r'''[package] name = "allowlist" version = "0.1.0" edition = "2021" [dependencies] ''', "src/lib.rs": r'''//! IPv4 allowlists for firewall and reverse-proxy configs. //! //! An allowlist file holds one entry per line: //! //! ```text //! 10.40.0.0/22 # CIDR block //! 10.8.0.10-10.8.0.250 # dash range, both ends included //! 198.51.100.10 # single host //! ``` //! //! Every entry becomes an [`IpRange`] span (see [`range`] for the span //! convention) and an [`IpSet`] keeps the spans sorted and merged, so a lookup //! is one binary search. pub mod addr; pub mod cidr; pub mod range; pub mod set; pub use addr::{format_ipv4, parse_ipv4, AddrError}; pub use cidr::Cidr; pub use range::IpRange; pub use set::{EntryError, IpSet}; ''', "src/addr.rs": r'''//! Dotted-quad IPv4 addresses as `u32`, plus prefix masks. use std::fmt; #[derive(Debug, Clone, PartialEq, Eq)] pub enum AddrError { /// Not four decimal octets in 0..=255. Malformed(String), /// A prefix length outside 0..=32, or not a number. BadPrefix(String), /// A CIDR whose base address has bits set below the prefix. HostBits(String), /// A dash range whose end comes before its start. Reversed(String), } impl fmt::Display for AddrError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { AddrError::Malformed(s) => write!(f, "malformed address {:?}", s), AddrError::BadPrefix(s) => write!(f, "bad prefix length in {:?}", s), AddrError::HostBits(s) => write!(f, "host bits set in {:?}", s), AddrError::Reversed(s) => write!(f, "range ends before it starts: {:?}", s), } } } impl std::error::Error for AddrError {} /// Parses `a.b.c.d`. Octets with leading zeros are rejected, so `010.0.0.1` /// is never silently read as decimal. pub fn parse_ipv4(text: &str) -> Result { let bad = || AddrError::Malformed(text.to_string()); let mut value: u32 = 0; let mut octets = 0; for part in text.trim().split('.') { let digits = !part.is_empty() && part.len() <= 3 && part.bytes().all(|b| b.is_ascii_digit()); if !digits || (part.len() > 1 && part.starts_with('0')) || octets == 4 { return Err(bad()); } let octet: u32 = part.parse().map_err(|_| bad())?; if octet > 255 { return Err(bad()); } value = (value << 8) | octet; octets += 1; } if octets != 4 { return Err(bad()); } Ok(value) } pub fn format_ipv4(ip: u32) -> String { let [a, b, c, d] = ip.to_be_bytes(); format!("{}.{}.{}.{}", a, b, c, d) } /// The network mask for a prefix length: `/0` is 0.0.0.0, `/24` is /// 255.255.255.0, `/32` is 255.255.255.255. `len` must be at most 32. pub fn prefix_mask(len: u8) -> u32 { if len == 0 { 0 } else { u32::MAX << (32 - u32::from(len)) } } ''', "src/range.rs": r'''//! `IpRange`: a span of IPv4 addresses. //! //! Spans are half-open, `[start, end)`: `start` is the first address in the //! span and `end` is one past the last, so `len()` is `end - start`. They are //! held as u64 so that a span reaching 255.255.255.255 still has a //! representable `end` (2^32). Every producer of spans (dash ranges, single //! hosts, CIDR blocks) and every consumer (`merge`, `IpSet`) uses this //! convention. //! //! The text form `a-b` is inclusive on both ends, the way people write it in //! firewall configs: `10.0.0.1-10.0.0.9` is nine addresses. use crate::addr::{format_ipv4, parse_ipv4, AddrError}; use std::fmt; #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct IpRange { pub start: u64, pub end: u64, } impl IpRange { pub fn new(start: u64, end: u64) -> IpRange { debug_assert!(start <= end && end <= 1 << 32, "bad span {}..{}", start, end); IpRange { start, end } } pub fn single(ip: u32) -> IpRange { IpRange::new(u64::from(ip), u64::from(ip) + 1) } /// Parses the inclusive text form `first-last`. pub fn parse(text: &str) -> Result { let (first, last) = text .split_once('-') .ok_or_else(|| AddrError::Malformed(text.to_string()))?; let (first, last) = (parse_ipv4(first)?, parse_ipv4(last)?); if last < first { return Err(AddrError::Reversed(text.to_string())); } Ok(IpRange::new(u64::from(first), u64::from(last) + 1)) } pub fn len(&self) -> u64 { self.end - self.start } pub fn is_empty(&self) -> bool { self.start == self.end } pub fn contains(&self, ip: u32) -> bool { let ip = u64::from(ip); self.start <= ip && ip < self.end } } impl fmt::Display for IpRange { /// The inclusive text form, the inverse of `parse`. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self.is_empty() { return write!(f, "(empty at {})", format_ipv4(self.start as u32)); } write!(f, "{}-{}", format_ipv4(self.start as u32), format_ipv4((self.end - 1) as u32)) } } /// Sorts spans and joins any that overlap or touch: `[1,5)` and `[5,9)` become /// `[1,9)`, while `[1,5)` and `[6,9)` stay apart. pub fn merge(mut spans: Vec) -> Vec { spans.sort(); let mut out: Vec = Vec::with_capacity(spans.len()); for span in spans { match out.last_mut() { Some(prev) if span.start <= prev.end => prev.end = prev.end.max(span.end), _ => out.push(span), } } out } ''', "src/cidr.rs": r'''//! CIDR blocks: an aligned base address and a prefix length. use crate::addr::{format_ipv4, parse_ipv4, prefix_mask, AddrError}; use crate::range::IpRange; use std::fmt; use std::str::FromStr; #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Cidr { base: u32, len: u8, } impl Cidr { /// A block from its parts. The base must be aligned to the prefix: /// `10.0.0.0/8` is fine, `10.0.0.1/8` is `HostBits`. pub fn new(base: u32, len: u8) -> Result { let text = || format!("{}/{}", format_ipv4(base), len); if len > 32 { return Err(AddrError::BadPrefix(text())); } if base & !prefix_mask(len) != 0 { return Err(AddrError::HostBits(text())); } Ok(Cidr { base, len }) } pub fn parse(text: &str) -> Result { let (addr, len) = text .trim() .split_once('/') .ok_or_else(|| AddrError::Malformed(text.to_string()))?; let len: u8 = len.parse().map_err(|_| AddrError::BadPrefix(text.to_string()))?; Cidr::new(parse_ipv4(addr)?, len) } pub fn base(&self) -> u32 { self.base } pub fn prefix_len(&self) -> u8 { self.len } /// Number of addresses in the block. pub fn size(&self) -> u64 { 1u64 << (32 - u32::from(self.len)) } pub fn contains(&self, ip: u32) -> bool { ip & prefix_mask(self.len) == self.base } /// The block as a span, for merging with the other entries of an `IpSet`. pub fn to_range(&self) -> IpRange { let mask = prefix_mask(self.len); IpRange::new(u64::from(self.base), u64::from(self.base | !mask)) } } impl FromStr for Cidr { type Err = AddrError; fn from_str(text: &str) -> Result { Cidr::parse(text) } } impl fmt::Display for Cidr { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}/{}", format_ipv4(self.base), self.len) } } ''', "src/set.rs": r'''//! `IpSet`: the union of allowlist entries, kept as sorted, merged spans. use crate::addr::{parse_ipv4, AddrError}; use crate::cidr::Cidr; use crate::range::{merge, IpRange}; use std::fmt; #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct IpSet { spans: Vec, } /// A line of allowlist text that could not be read (`line` counts from 1). #[derive(Debug, Clone, PartialEq, Eq)] pub struct EntryError { pub line: usize, pub reason: AddrError, } impl fmt::Display for EntryError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "line {}: {}", self.line, self.reason) } } impl std::error::Error for EntryError {} impl IpSet { /// Reads allowlist text: one entry per line; `#` starts a comment and /// blank lines are skipped. pub fn parse(text: &str) -> Result { let mut spans = Vec::new(); for (index, raw) in text.lines().enumerate() { let entry = raw.split('#').next().unwrap_or("").trim(); if entry.is_empty() { continue; } let span = entry_span(entry).map_err(|reason| EntryError { line: index + 1, reason })?; spans.push(span); } Ok(IpSet::from_spans(spans)) } pub fn from_spans(spans: Vec) -> IpSet { IpSet { spans: merge(spans) } } pub fn spans(&self) -> &[IpRange] { &self.spans } pub fn contains(&self, ip: u32) -> bool { let after = self.spans.partition_point(|s| s.start <= u64::from(ip)); after > 0 && self.spans[after - 1].contains(ip) } /// Total number of addresses in the set. pub fn size(&self) -> u64 { self.spans.iter().map(IpRange::len).sum() } /// The fewest CIDR blocks that cover exactly this set, in address order. pub fn to_cidrs(&self) -> Vec { let mut out = Vec::new(); for span in &self.spans { let mut start = span.start; while start < span.end { // the largest block aligned at `start` that stays inside the span let mut bits = start.trailing_zeros().min(32); while (1u64 << bits) > span.end - start { bits -= 1; } out.push(Cidr::new(start as u32, (32 - bits) as u8).expect("aligned block")); start += 1u64 << bits; } } out } } /// One entry as a span: `a.b.c.d/len`, `a.b.c.d-e.f.g.h` or `a.b.c.d`. fn entry_span(entry: &str) -> Result { if entry.contains('/') { Ok(Cidr::parse(entry)?.to_range()) } else if entry.contains('-') { IpRange::parse(entry) } else { Ok(IpRange::single(parse_ipv4(entry)?)) } } ''', "tests/allowlist.rs": r'''use allowlist::range::merge; use allowlist::{format_ipv4, parse_ipv4, Cidr, IpRange, IpSet}; fn ip(text: &str) -> u32 { parse_ipv4(text).unwrap() } fn cidrs(set: &IpSet) -> Vec { set.to_cidrs().iter().map(|c| c.to_string()).collect() } #[test] fn dotted_quads() { assert_eq!(ip("10.0.0.1"), 0x0a00_0001); assert_eq!(format_ipv4(0xc0a8_0101), "192.168.1.1"); for bad in ["10.0.0", "10.0.0.256", "010.0.0.1", "10.0.0.1.5", "a.b.c.d", ""] { assert!(parse_ipv4(bad).is_err(), "{:?} accepted", bad); } } #[test] fn dash_ranges_are_inclusive() { let r = IpRange::parse("10.0.0.1-10.0.0.9").unwrap(); assert_eq!(r.len(), 9); assert!(r.contains(ip("10.0.0.1"))); assert!(r.contains(ip("10.0.0.9"))); assert!(!r.contains(ip("10.0.0.10"))); assert_eq!(r.to_string(), "10.0.0.1-10.0.0.9"); assert!(IpRange::parse("10.0.0.9-10.0.0.1").is_err()); assert_eq!(IpRange::parse("0.0.0.0-255.255.255.255").unwrap().len(), 1 << 32); } #[test] fn merge_joins_touching_spans_only() { let a = IpRange::parse("10.0.0.1-10.0.0.4").unwrap(); let b = IpRange::parse("10.0.0.5-10.0.0.9").unwrap(); let c = IpRange::parse("10.0.0.11-10.0.0.20").unwrap(); let merged: Vec = merge(vec![c, b, a]).iter().map(|s| s.to_string()).collect(); assert_eq!(merged, ["10.0.0.1-10.0.0.9", "10.0.0.11-10.0.0.20"]); } #[test] fn cidr_parse_and_display() { for text in ["10.0.0.0/8", "192.168.4.0/22", "0.0.0.0/0", "203.0.113.7/32"] { assert_eq!(text.parse::().unwrap().to_string(), text); } assert_eq!(Cidr::parse("192.168.4.0/22").unwrap().size(), 1024); assert!(Cidr::parse("10.0.0.1/24").is_err()); assert!(Cidr::parse("10.0.0.0/33").is_err()); assert!(Cidr::parse("10.0.0.0").is_err()); } #[test] fn cidr_contains_by_prefix() { let c = Cidr::parse("192.168.4.0/22").unwrap(); assert!(c.contains(ip("192.168.4.0"))); assert!(c.contains(ip("192.168.7.255"))); assert!(!c.contains(ip("192.168.8.0"))); assert!(!c.contains(ip("192.168.3.255"))); } #[test] fn hosts_and_ranges() { let set = IpSet::parse("10.0.0.1\n10.0.0.2-10.0.0.3 # pair\n\n10.0.0.4\n").unwrap(); assert_eq!(set.size(), 4); assert!(set.contains(ip("10.0.0.4"))); assert!(!set.contains(ip("10.0.0.5"))); assert!(!set.contains(ip("10.0.0.0"))); assert_eq!(cidrs(&set), ["10.0.0.1/32", "10.0.0.2/31", "10.0.0.4/32"]); } #[test] fn ranges_summarize_to_blocks() { let set = IpSet::parse("192.168.0.0-192.168.1.255\n192.168.2.0-192.168.2.9\n").unwrap(); assert_eq!(set.size(), 522); assert_eq!(cidrs(&set), ["192.168.0.0/23", "192.168.2.0/29", "192.168.2.8/31"]); } #[test] fn bad_lines_are_reported() { let err = IpSet::parse("10.0.0.0/8\n# fine\n10.0.0.300\n").unwrap_err(); assert_eq!(err.line, 3); assert!(IpSet::parse("10.0.0.1/16").is_err()); } const SITE: &str = " # office LAN 10.40.0.0/22 # bastion 198.51.100.10/32 # uplink to the ISP router 10.255.0.0/31 # VPN pool 10.8.0.10-10.8.0.250 "; #[test] fn site_allowlist() { let set = IpSet::parse(SITE).unwrap(); let expected = [ "10.40.0.1", "10.40.2.17", "198.51.100.10", "10.255.0.0", "10.255.0.1", "10.8.0.10", "10.8.0.250", ]; for addr in expected { assert!(set.contains(ip(addr)), "{} not matched", addr); } } ''', } def _patched(path, old, new): """{path: PROJECT[path] with `old` replaced once}; fails loudly if `old` is not there.""" src = PROJECT[path] assert src.count(old) == 1, (path, old) return {path: src.replace(old, new)} HIDDEN = ("tests/allowlist.rs",) FIX = _patched("src/cidr.rs", "u64::from(self.base | !mask))\n", "u64::from(self.base | !mask) + 1)\n") TEST_CMD = ["cargo", "test", "--offline"] PASS_RE = r"^test (\S+) \.\.\. ok$" TESTS = tuple(re.findall(r"^#\[test\]\nfn (\w+)\(", PROJECT["tests/allowlist.rs"], re.M)) WRONG = [ # inclusive end in the span type _patched("src/range.rs", "self.start <= ip && ip < self.end\n", "self.start <= ip && ip <= self.end\n"), # inclusive end at the lookup site _patched("src/set.rs", "after > 0 && self.spans[after - 1].contains(ip)\n", "after > 0 && u64::from(ip) <= self.spans[after - 1].end\n"), # a /32 entry read as a single host _patched("src/set.rs", " Ok(Cidr::parse(entry)?.to_range())\n", " let block = Cidr::parse(entry)?;\n" " if block.prefix_len() == 32 {\n" " Ok(IpRange::single(block.base()))\n" " } else {\n" " Ok(block.to_range())\n" " }\n"), ]