kaniop-radius 0.24.0

Kanidm RADIUS server management for the Kubernetes operator
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
//! Validated configuration for the upstream Kanidm RADIUS container.
//!
//! The upstream bootstrap converts radius_clients to FreeRADIUS clients.conf
//! using *unquoted* values. Never pass untrusted Kubernetes Secret values
//! through to that bootstrap without checking its syntax first.
//!
//! This module deliberately does not log or derive Debug for credential-bearing
//! objects. The caller must put the resulting TOML in a Kubernetes Secret, not
//! a ConfigMap, status field, event, or pod annotation.

use std::collections::BTreeSet;
use std::net::IpAddr;

use thiserror::Error;

/// Location where the upstream container expects configuration.
pub const CONFIG_PATH: &str = "/data/radius.toml";
pub const SERVER_CERT_PATH: &str = "/data/cert.pem";
pub const SERVER_KEY_PATH: &str = "/data/key.pem";
pub const RADIUS_CA_PATH: &str = "/data/ca.pem";
pub const KANIDM_CA_PATH: &str = "/data/kanidm-ca.pem";

/// No user-supplied content is included in validation errors: clients may hold
/// secrets and should never be accidentally logged by a reconciler.
#[derive(Error, Debug, PartialEq, Eq)]
pub enum RadiusConfigError {
    #[error("Kanidm URL must be a valid HTTPS URI with a host")]
    InvalidKanidmUrl,
    #[error("Kanidm API token is empty")]
    EmptyToken,
    #[error("at least one required Kanidm authorization group must be configured")]
    MissingRequiredGroups,
    #[error("authorization group SPNs must be nonempty and must not contain controls")]
    InvalidGroup,
    #[error("RADIUS NAS client list must not be empty")]
    MissingClients,
    #[error("NAS client names must contain only ASCII letters, numbers, '-' or '_'")]
    InvalidClientName,
    #[error("NAS client names and IP/CIDR ranges must not be duplicated")]
    DuplicateClient,
    #[error("NAS IP address or CIDR range is invalid")]
    InvalidClientAddress,
    #[error("NAS shared secret must be 16-255 safe ASCII characters")]
    InvalidSharedSecret,
    #[error("RADIUS VLAN must be in the 1..=4094 range")]
    InvalidVlan,
    #[error("RADIUS CA material must be mounted when radius_ca_path is configured")]
    InvalidCaPath,
}

/// A NAS definition obtained from a Kubernetes Secret reference.
///
/// Its secret must never appear in a Custom Resource, status, event or log.
#[derive(Clone, PartialEq, Eq)]
pub struct RadiusClient {
    pub name: String,
    pub ipaddr: String,
    pub secret: String,
}

#[derive(Clone, PartialEq, Eq)]
pub struct RadiusGroup {
    pub spn: String,
    pub vlan: u16,
}

/// Validated runtime configuration; contains a bearer token and NAS secrets.
///
/// Upstream consumes this as TOML at startup and then execs FreeRADIUS. Mounted
/// Secret updates require a Deployment rollout; they are not live-reloaded.
#[derive(Clone, PartialEq, Eq)]
pub struct RadiusConfig {
    pub uri: String,
    pub auth_token: String,
    pub ca_path: Option<String>,
    pub radius_required_groups: Vec<String>,
    pub radius_default_vlan: u16,
    pub radius_groups: Vec<RadiusGroup>,
    pub radius_clients: Vec<RadiusClient>,
    pub radius_ca_path: Option<String>,
}

impl RadiusConfig {
    /// Validate against both Kanidm's TOML shape and the FreeRADIUS clients.conf
    /// generated by upstream bootstrap.rs. This method checks the syntax of the
    /// resolved *secret value*, not just the Secret reference in the Kubernetes CR.
    pub fn validate(&self) -> Result<(), RadiusConfigError> {
        let url = url::Url::parse(&self.uri).map_err(|_| RadiusConfigError::InvalidKanidmUrl)?;
        if url.scheme() != "https"
            || url.host_str().is_none()
            || !url.username().is_empty()
            || url.password().is_some()
        {
            return Err(RadiusConfigError::InvalidKanidmUrl);
        }
        if self.auth_token.is_empty() {
            return Err(RadiusConfigError::EmptyToken);
        }
        if self.radius_required_groups.is_empty() {
            return Err(RadiusConfigError::MissingRequiredGroups);
        }

        for group in &self.radius_required_groups {
            if !valid_group(group) {
                return Err(RadiusConfigError::InvalidGroup);
            }
        }
        if !(1..=4094).contains(&self.radius_default_vlan) {
            return Err(RadiusConfigError::InvalidVlan);
        }
        let mut vlan_groups = BTreeSet::new();
        for group in &self.radius_groups {
            if !valid_group(&group.spn) {
                return Err(RadiusConfigError::InvalidGroup);
            }
            if !(1..=4094).contains(&group.vlan) {
                return Err(RadiusConfigError::InvalidVlan);
            }
            if !vlan_groups.insert(group.spn.as_str()) {
                return Err(RadiusConfigError::InvalidGroup);
            }
        }

        if self.radius_clients.is_empty() {
            return Err(RadiusConfigError::MissingClients);
        }
        let mut names = BTreeSet::new();
        let mut addresses = BTreeSet::new();
        for client in &self.radius_clients {
            // Upstream writes "client <name> { ... }" without escaping <name>.
            if client.name.is_empty()
                || client.name.len() > 63
                || !client
                    .name
                    .bytes()
                    .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
            {
                return Err(RadiusConfigError::InvalidClientName);
            }
            if !names.insert(client.name.as_str()) {
                return Err(RadiusConfigError::DuplicateClient);
            }
            let Some(network) = normalize_nas_address(&client.ipaddr) else {
                return Err(RadiusConfigError::InvalidClientAddress);
            };
            if !addresses.insert(network) {
                return Err(RadiusConfigError::DuplicateClient);
            }

            // Upstream writes "secret = <value>" as an unquoted FreeRADIUS
            // directive. Forbid whitespace, comments, quotes, delimiters and
            // control characters. Recommend base64url-generated random secrets.
            if !(16..=255).contains(&client.secret.len())
                || !client
                    .secret
                    .bytes()
                    .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
            {
                return Err(RadiusConfigError::InvalidSharedSecret);
            }
        }
        if self.ca_path.as_deref().is_some_and(|p| p != KANIDM_CA_PATH)
            || self
                .radius_ca_path
                .as_deref()
                .is_some_and(|p| p != RADIUS_CA_PATH)
        {
            return Err(RadiusConfigError::InvalidCaPath);
        }
        Ok(())
    }

    /// Render deterministic TOML using JSON string quoting, which is also valid
    /// TOML basic-string syntax. RADIUS callers MUST store the result in a Secret.
    pub fn render_toml(&self) -> Result<String, RadiusConfigError> {
        self.validate()?;
        let mut out = format!(
            "uri = {}\nauth_token = {}\nverify_hostnames = true\nverify_certificate = true\n",
            quote(&self.uri),
            quote(&self.auth_token)
        );
        if let Some(ca) = &self.ca_path {
            out.push_str(&format!("ca_path = {}\n", quote(ca)));
        }
        out.push_str(&format!(
            "radius_cert_path = {}\nradius_key_path = {}\n",
            quote(SERVER_CERT_PATH),
            quote(SERVER_KEY_PATH)
        ));
        if let Some(ca) = &self.radius_ca_path {
            out.push_str(&format!("radius_ca_path = {}\n", quote(ca)));
        }
        out.push_str(&format!(
            "radius_default_vlan = {}\nradius_required_groups = [{}]\n",
            self.radius_default_vlan,
            self.radius_required_groups
                .iter()
                .map(|group| quote(group))
                .collect::<Vec<_>>()
                .join(", ")
        ));
        out.push_str("radius_groups = [\n");
        for group in &self.radius_groups {
            out.push_str(&format!(
                "  {{ spn = {}, vlan = {} }},\n",
                quote(&group.spn),
                group.vlan
            ));
        }
        out.push_str("]\nradius_clients = [\n");
        for client in &self.radius_clients {
            out.push_str(&format!(
                "  {{ name = {}, ipaddr = {}, secret = {} }},\n",
                quote(&client.name),
                quote(&client.ipaddr),
                quote(&client.secret),
            ));
        }
        out.push_str("]\n");
        Ok(out)
    }
}

fn valid_group(group: &str) -> bool {
    !group.trim().is_empty() && !group.chars().any(char::is_control)
}

/// Canonical network of a NAS address: a bare IP is a host route, and host
/// bits of a CIDR are masked, so `10.0.0.1`, `10.0.0.1/32` and (for a /24)
/// `10.0.0.7/24` and `10.0.0.0/24` compare equal. `None` for anything that is
/// not an IP or an IP/prefix with a non-zero, in-range prefix length.
pub fn normalize_nas_address(address: &str) -> Option<(IpAddr, u8)> {
    let (ip, prefix) = match address.split_once('/') {
        Some((ip, prefix)) => (ip.parse::<IpAddr>().ok()?, prefix.parse::<u8>().ok()?),
        None => {
            let ip = address.parse::<IpAddr>().ok()?;
            (ip, if ip.is_ipv4() { 32 } else { 128 })
        }
    };
    let max_prefix = if ip.is_ipv4() { 32 } else { 128 };
    if prefix == 0 || prefix > max_prefix {
        return None;
    }
    let network = match ip {
        IpAddr::V4(v4) => {
            let mask = u32::MAX << (32 - u32::from(prefix));
            IpAddr::V4((u32::from(v4) & mask).into())
        }
        IpAddr::V6(v6) => {
            let mask = u128::MAX << (128 - u32::from(prefix));
            IpAddr::V6((u128::from(v6) & mask).into())
        }
    };
    Some((network, prefix))
}

fn quote(s: &str) -> String {
    // This is infallible for String (including any Unicode), unlike arbitrary
    // serde_json::Value serialization. JSON and TOML basic-string escapes agree
    // for the values emitted by serde_json here.
    serde_json::to_string(s).expect("serializing a string cannot fail")
}

#[cfg(test)]
mod tests {
    use super::*;

    fn valid_config() -> RadiusConfig {
        RadiusConfig {
            uri: "https://idm.example.com".into(),
            auth_token: "header.payload.signature".into(),
            ca_path: Some(KANIDM_CA_PATH.into()),
            radius_required_groups: vec!["radius_access_allowed@idm.example.com".into()],
            radius_default_vlan: 10,
            radius_groups: vec![RadiusGroup {
                spn: "radius_access_allowed@idm.example.com".into(),
                vlan: 20,
            }],
            radius_clients: vec![RadiusClient {
                name: "mikrotik".into(),
                ipaddr: "192.0.2.10/32".into(),
                secret: "b8_j3Z4yx-3qW1xOAm4c".into(),
            }],
            radius_ca_path: Some(RADIUS_CA_PATH.into()),
        }
    }

    #[test]
    fn renders_upstream_radius_toml() {
        let output = valid_config().render_toml().unwrap();
        assert!(output.contains("verify_certificate = true"));
        assert!(output.contains("radius_cert_path = \"/data/cert.pem\""));
        assert!(output.contains("radius_key_path = \"/data/key.pem\""));
        assert!(output.contains("radius_ca_path = \"/data/ca.pem\""));
        assert!(output.contains("ipaddr = \"192.0.2.10/32\""));
        assert!(output.contains("radius_default_vlan = 10"));
        assert!(
            output.contains("radius_required_groups = [\"radius_access_allowed@idm.example.com\"]")
        );
        assert!(output.contains("secret = \"b8_j3Z4yx-3qW1xOAm4c\""));
    }

    #[test]
    fn rejects_freeradius_config_injection_in_secret_value() {
        for bad_secret in [
            "password\\n}\nclient attacker {",
            "password!another-command",
            "password with spaces",
            "password#comment",
            "password;next",
            "password\"broken",
            "password{block",
            "short",
        ] {
            let mut config = valid_config();
            config.radius_clients[0].secret = bad_secret.into();
            assert_eq!(
                config.validate(),
                Err(RadiusConfigError::InvalidSharedSecret)
            );
        }
    }

    #[test]
    fn rejects_freeradius_config_injection_in_client_name() {
        for bad_name in ["mikrotik\nsecret = attacker", "bad{client", "x y", ""] {
            let mut config = valid_config();
            config.radius_clients[0].name = bad_name.into();
            assert_eq!(config.validate(), Err(RadiusConfigError::InvalidClientName));
        }
    }

    #[test]
    fn rejects_invalid_addresses() {
        for address in [
            "0.0.0.0/0",
            "192.0.2.10/33",
            "::1/129",
            "192.0.2.10\nsecret=x",
            "foo",
        ] {
            let mut config = valid_config();
            config.radius_clients[0].ipaddr = address.into();
            assert_eq!(
                config.validate(),
                Err(RadiusConfigError::InvalidClientAddress)
            );
        }
        for address in ["192.0.2.10", "192.0.2.0/24", "2001:db8::1", "2001:db8::/64"] {
            let mut config = valid_config();
            config.radius_clients[0].ipaddr = address.into();
            assert!(config.validate().is_ok(), "address: {address}");
        }
    }

    #[test]
    fn requires_explicit_authorization_groups_and_safe_vlan() {
        let mut config = valid_config();
        config.radius_required_groups.clear();
        assert_eq!(
            config.validate(),
            Err(RadiusConfigError::MissingRequiredGroups)
        );
        config
            .radius_required_groups
            .push("radius_access_allowed@idm.example.com".into());
        config.radius_default_vlan = 0;
        assert_eq!(config.validate(), Err(RadiusConfigError::InvalidVlan));
        config.radius_default_vlan = 10;
        // VLAN mapping groups are independent of the groups granting access.
        config.radius_groups[0].spn = "staff@idm.example.com".into();
        assert!(config.validate().is_ok());
        config.radius_groups.push(config.radius_groups[0].clone());
        assert_eq!(config.validate(), Err(RadiusConfigError::InvalidGroup));
    }

    #[test]
    fn rejects_duplicates_without_owning_other_clients() {
        let mut config = valid_config();
        config.radius_clients.push(config.radius_clients[0].clone());
        assert_eq!(config.validate(), Err(RadiusConfigError::DuplicateClient));
        config.radius_clients[1].name = "other".into();
        assert_eq!(config.validate(), Err(RadiusConfigError::DuplicateClient));
    }

    #[test]
    fn secrets_not_derived_as_debug_values() {
        // Validation errors are safe to report through status and events; they
        // cannot accidentally include the bearer token or NAS shared secret.
        let mut config = valid_config();
        config.radius_clients[0].secret = "invalid secret".into();
        let message = config.validate().unwrap_err().to_string();
        assert!(!message.contains("invalid secret"));
        assert!(!message.contains(&config.auth_token));
    }

    #[test]
    fn rejects_insecure_kanidm_uri() {
        let mut config = valid_config();
        config.uri = "http://idm.example.com".into();
        assert_eq!(config.validate(), Err(RadiusConfigError::InvalidKanidmUrl));
    }

    #[test]
    fn bare_address_and_host_cidr_are_duplicate_clients() {
        for (a, b) in [
            ("10.0.0.1", "10.0.0.1/32"),
            ("10.0.0.1/32", "10.0.0.1"),
            ("2001:db8::1", "2001:db8::1/128"),
            ("10.0.0.0/24", "10.0.0.7/24"),
        ] {
            let mut config = valid_config();
            config.radius_clients[0].ipaddr = a.into();
            let mut second = config.radius_clients[0].clone();
            second.name = "other".into();
            second.ipaddr = b.into();
            config.radius_clients.push(second);
            assert_eq!(
                config.validate(),
                Err(RadiusConfigError::DuplicateClient),
                "{a} and {b}"
            );
        }
    }

    #[test]
    fn distinct_prefixes_of_one_address_are_not_duplicates() {
        let mut config = valid_config();
        config.radius_clients[0].ipaddr = "10.0.0.1/32".into();
        let mut second = config.radius_clients[0].clone();
        second.name = "other".into();
        second.ipaddr = "10.0.0.0/24".into();
        config.radius_clients.push(second);
        assert_eq!(config.validate(), Ok(()));
    }
}