Skip to main content

rtflow_security/
lib.rs

1//! Network admission controls independent of a particular management plane.
2pub mod guard;
3pub use guard::{Guard, GuardConfig, GuardSnapshot, MediaKind};
4#[cfg(feature = "tls")]
5mod tls;
6
7use rtflow_core::error::{Error, Result};
8use std::{collections::HashMap, sync::Mutex, time::Instant};
9use std::{
10    net::{IpAddr, Ipv4Addr, Ipv6Addr},
11    str::FromStr,
12    time::Duration,
13};
14#[cfg(feature = "tls")]
15pub use tls::{TlsClientConfig, TlsServerConfig};
16
17#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
18pub enum IpCidr {
19    V4 { network: u32, prefix: u8 },
20    V6 { network: u128, prefix: u8 },
21}
22
23impl IpCidr {
24    pub fn contains(self, address: IpAddr) -> bool {
25        match (self, address) {
26            (Self::V4 { network, prefix }, IpAddr::V4(address)) => {
27                masked_v4(u32::from(address), prefix) == network
28            }
29            (Self::V6 { network, prefix }, IpAddr::V6(address)) => {
30                masked_v6(u128::from(address), prefix) == network
31            }
32            _ => false,
33        }
34    }
35}
36
37impl FromStr for IpCidr {
38    type Err = Error;
39
40    fn from_str(value: &str) -> Result<Self> {
41        let (address, prefix) = value
42            .split_once('/')
43            .ok_or_else(|| Error::InvalidConfig("CIDR prefix is missing".into()))?;
44        let address = IpAddr::from_str(address)
45            .map_err(|_| Error::InvalidConfig("invalid CIDR address".into()))?;
46        let prefix = prefix
47            .parse::<u8>()
48            .map_err(|_| Error::InvalidConfig("invalid CIDR prefix".into()))?;
49        match address {
50            IpAddr::V4(address) if prefix <= 32 => Ok(Self::V4 {
51                network: masked_v4(u32::from(address), prefix),
52                prefix,
53            }),
54            IpAddr::V6(address) if prefix <= 128 => Ok(Self::V6 {
55                network: masked_v6(u128::from(address), prefix),
56                prefix,
57            }),
58            _ => Err(Error::InvalidConfig("CIDR prefix is out of range".into())),
59        }
60    }
61}
62
63impl From<Ipv4Addr> for IpCidr {
64    fn from(address: Ipv4Addr) -> Self {
65        Self::V4 {
66            network: u32::from(address),
67            prefix: 32,
68        }
69    }
70}
71
72impl From<Ipv6Addr> for IpCidr {
73    fn from(address: Ipv6Addr) -> Self {
74        Self::V6 {
75            network: u128::from(address),
76            prefix: 128,
77        }
78    }
79}
80
81#[derive(Clone, Debug, Default)]
82pub struct IpAcl {
83    pub allow: Vec<IpCidr>,
84    pub deny: Vec<IpCidr>,
85}
86
87impl IpAcl {
88    pub fn permits(&self, address: IpAddr) -> bool {
89        if self.deny.iter().any(|network| network.contains(address)) {
90            return false;
91        }
92        self.allow.is_empty() || self.allow.iter().any(|network| network.contains(address))
93    }
94}
95
96#[derive(Clone, Copy, Debug)]
97pub struct RateLimitConfig {
98    pub burst: u32,
99    pub refill_per_second: f64,
100    pub idle_retention: Duration,
101    pub max_tracked_peers: usize,
102}
103
104impl Default for RateLimitConfig {
105    fn default() -> Self {
106        Self {
107            burst: 32,
108            refill_per_second: 8.0,
109            idle_retention: Duration::from_secs(300),
110            max_tracked_peers: 65_536,
111        }
112    }
113}
114
115impl RateLimitConfig {
116    pub fn validate(self) -> Result<()> {
117        if self.burst == 0
118            || !self.refill_per_second.is_finite()
119            || self.refill_per_second <= 0.0
120            || self.idle_retention == Duration::ZERO
121            || self.max_tracked_peers == 0
122        {
123            return Err(Error::Limit("connection rate limit"));
124        }
125        Ok(())
126    }
127}
128
129#[derive(Clone, Debug)]
130pub struct SecurityConfig {
131    pub ip_acl: IpAcl,
132    pub connection_rate_limit: Option<RateLimitConfig>,
133    pub authentication_failure_delay: Duration,
134}
135
136impl Default for SecurityConfig {
137    fn default() -> Self {
138        Self {
139            ip_acl: IpAcl::default(),
140            connection_rate_limit: None,
141            authentication_failure_delay: Duration::from_millis(25),
142        }
143    }
144}
145
146struct Bucket {
147    tokens: f64,
148    updated_at: Instant,
149}
150
151#[doc(hidden)]
152pub struct ConnectionRateLimiter {
153    config: Option<RateLimitConfig>,
154    state: Mutex<LimiterState>,
155}
156
157struct LimiterState {
158    buckets: HashMap<IpAddr, Bucket>,
159    last_cleanup: Instant,
160}
161
162impl ConnectionRateLimiter {
163    pub fn new(config: Option<RateLimitConfig>) -> Result<Self> {
164        if let Some(config) = config {
165            config.validate()?;
166        }
167        Ok(Self {
168            config,
169            state: Mutex::new(LimiterState {
170                buckets: HashMap::new(),
171                last_cleanup: Instant::now(),
172            }),
173        })
174    }
175
176    pub fn admit(&self, address: IpAddr, now: Instant) -> bool {
177        let Some(config) = self.config else {
178            return true;
179        };
180        let mut state = self
181            .state
182            .lock()
183            .unwrap_or_else(std::sync::PoisonError::into_inner);
184        if now.saturating_duration_since(state.last_cleanup) >= config.idle_retention / 2 {
185            state.buckets.retain(|_, bucket| {
186                now.saturating_duration_since(bucket.updated_at) <= config.idle_retention
187            });
188            state.last_cleanup = now;
189        }
190        if !state.buckets.contains_key(&address) && state.buckets.len() >= config.max_tracked_peers
191        {
192            return false;
193        }
194        let bucket = state.buckets.entry(address).or_insert(Bucket {
195            tokens: f64::from(config.burst),
196            updated_at: now,
197        });
198        let elapsed = now
199            .saturating_duration_since(bucket.updated_at)
200            .as_secs_f64();
201        bucket.tokens =
202            (bucket.tokens + elapsed * config.refill_per_second).min(f64::from(config.burst));
203        bucket.updated_at = now;
204        if bucket.tokens < 1.0 {
205            return false;
206        }
207        bucket.tokens -= 1.0;
208        true
209    }
210}
211
212fn masked_v4(address: u32, prefix: u8) -> u32 {
213    if prefix == 0 {
214        0
215    } else {
216        address & (u32::MAX << (32 - prefix))
217    }
218}
219
220fn masked_v6(address: u128, prefix: u8) -> u128 {
221    if prefix == 0 {
222        0
223    } else {
224        address & (u128::MAX << (128 - prefix))
225    }
226}
227
228#[cfg(test)]
229mod tests {
230    use super::*;
231
232    #[test]
233    fn cidr_acl_handles_v4_v6_and_deny_precedence() {
234        let acl = IpAcl {
235            allow: vec![
236                "10.0.0.0/8".parse().unwrap(),
237                "2001:db8::/32".parse().unwrap(),
238            ],
239            deny: vec!["10.1.0.0/16".parse().unwrap()],
240        };
241        assert!(acl.permits("10.2.3.4".parse().unwrap()));
242        assert!(!acl.permits("10.1.3.4".parse().unwrap()));
243        assert!(acl.permits("2001:db8::1".parse().unwrap()));
244        assert!(!acl.permits("192.168.1.1".parse().unwrap()));
245    }
246
247    #[test]
248    fn token_bucket_refills_deterministically() {
249        use std::time::Instant;
250        let limiter = ConnectionRateLimiter::new(Some(RateLimitConfig {
251            burst: 2,
252            refill_per_second: 10.0,
253            idle_retention: Duration::from_secs(1),
254            max_tracked_peers: 16,
255        }))
256        .unwrap();
257        let address = "127.0.0.1".parse().unwrap();
258        let start = Instant::now();
259        assert!(limiter.admit(address, start));
260        assert!(limiter.admit(address, start));
261        assert!(!limiter.admit(address, start));
262        assert!(limiter.admit(address, start + Duration::from_millis(100)));
263    }
264}