Skip to main content

ntpsec_rs_core/
ntp_auth.rs

1// ──── ntp_auth.rs ───────────────────────────────────────────────────────────
2// Forensic reconstruction of include/ntp_auth.h, libntp/authkeys.c,
3// libntp/authreadkeys.c, libntp/macencrypt.c
4//
5// Full NTP authentication subsystem: key storage, key file parsing with the
6// same format and error messages as ntpsec, MAC computation (MD5, SHA1,
7// AES-128-CMAC), and cryptographic helper functions.
8//
9// ## Oracle
10//   - ntpsec include/ntp_auth.h
11//   - ntpsec libntp/authkeys.c (15K)
12//   - ntpsec libntp/authreadkeys.c (11K)
13//   - ntpsec libntp/macencrypt.c (10K)
14//
15// ## Court
16//   - docs/courts/ntp_auth.md
17// =============================================================================
18
19/// Key identifier type (32-bit unsigned, matching ntpsec's `keyid_t`).
20pub type KeyId = u32;
21
22/// Maximum key ID value (ntpsec uses u32 max).
23pub const KEYID_MAX: KeyId = u32::MAX;
24
25/// Maximum key length in bytes (ntpsec: 64 bytes for SHA1, 16 for MD5).
26pub const KEY_MAX_LEN: usize = 64;
27
28/// Supported digest types for NTP authentication.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub enum DigestType {
31    None,
32    Md5,
33    Sha1,
34    Aes128Cmac,
35}
36
37impl DigestType {
38    /// MAC digest length in bytes.
39    pub fn digest_length(&self) -> usize {
40        match self {
41            DigestType::None => 0,
42            DigestType::Md5 => 16,
43            DigestType::Sha1 => 20,
44            DigestType::Aes128Cmac => 16,
45        }
46    }
47
48    /// NTPsec name string for this digest type.
49    pub fn as_str(&self) -> &'static str {
50        match self {
51            DigestType::None => "none",
52            DigestType::Md5 => "MD5",
53            DigestType::Sha1 => "SHA1",
54            DigestType::Aes128Cmac => "AES-128-CMAC",
55        }
56    }
57
58    /// Parse from ntp.keys format string.
59    pub fn from_name(s: &str) -> Option<Self> {
60        match s.to_lowercase().as_str() {
61            "md5" => Some(DigestType::Md5),
62            "sha" | "sha1" | "sha-1" => Some(DigestType::Sha1),
63            "aes-128-cmac" | "cmac" | "aes" | "aes128cmac" => Some(DigestType::Aes128Cmac),
64            _ => None,
65        }
66    }
67}
68
69/// An NTP authentication key (matching ntpsec's `symkey` struct).
70#[derive(Debug, Clone)]
71pub struct NtpAuthKey {
72    pub id: KeyId,
73    pub digest: DigestType,
74    pub key_data: Vec<u8>,
75}
76
77impl NtpAuthKey {
78    /// Create a new auth key, truncating key data to MAX_KEY_LEN.
79    pub fn new(id: KeyId, digest: DigestType, key_data: Vec<u8>) -> Self {
80        let key_data = key_data.into_iter().take(KEY_MAX_LEN).collect();
81        Self {
82            id,
83            digest,
84            key_data,
85        }
86    }
87
88    /// Compute the MAC for a given packet buffer.
89    /// Real implementation using md-5, sha-1, aes crates.
90    pub fn mac(&self, pkt: &[u8]) -> Option<Vec<u8>> {
91        use digest::{Digest, FixedOutput};
92        let digest_len = self.digest.digest_length();
93        if digest_len == 0 {
94            return None;
95        }
96
97        match self.digest {
98            DigestType::Md5 => {
99                // Keyed MD5 as ntpsec's digest_encrypt: MD5(key || packet)
100                let mut ctx = md5::Md5::default();
101                Digest::update(&mut ctx, &self.key_data);
102                Digest::update(&mut ctx, pkt);
103                let hash = ctx.finalize_fixed();
104                Some(hash[..digest_len].to_vec())
105            }
106            DigestType::Sha1 => {
107                // Keyed SHA1 as ntpsec's digest_encrypt: SHA1(key || packet)
108                let mut ctx = sha1::Sha1::default();
109                Digest::update(&mut ctx, &self.key_data);
110                Digest::update(&mut ctx, pkt);
111                let hash = ctx.finalize_fixed();
112                Some(hash[..digest_len].to_vec())
113            }
114            DigestType::Aes128Cmac => {
115                // AES-128-CMAC (RFC 4493). NTPsec pads short keys with zeroes
116                // and truncates long keys to 16 bytes.
117                use aes::Aes128;
118                use cmac::{Cmac, Mac};
119                let mut aes_key = [0u8; 16];
120                let copy_len = self.key_data.len().min(16);
121                aes_key[..copy_len].copy_from_slice(&self.key_data[..copy_len]);
122                let mut mac = Cmac::<Aes128>::new_from_slice(&aes_key).ok()?;
123                mac.update(pkt);
124                let result = mac.finalize();
125                let bytes = result.into_bytes();
126                Some(bytes.to_vec())
127            }
128            DigestType::None => None,
129        }
130    }
131
132    /// Verify a MAC against a packet (constant-time comparison).
133    pub fn verify_mac(&self, pkt: &[u8], expected_mac: &[u8]) -> bool {
134        self.mac(pkt).is_some_and(|computed| {
135            computed.len() == expected_mac.len()
136                && computed
137                    .iter()
138                    .zip(expected_mac.iter())
139                    .fold(0u8, |acc, (a, b)| acc | (a ^ b))
140                    == 0
141        })
142    }
143}
144
145/// Authentication key store — matches ntpsec's key database.
146#[derive(Debug, Default)]
147pub struct AuthKeyStore {
148    keys: Vec<NtpAuthKey>,
149    trusted_keys: Vec<KeyId>,
150    control_key: Option<KeyId>,
151}
152
153impl AuthKeyStore {
154    pub fn new() -> Self {
155        Self {
156            keys: Vec::new(),
157            trusted_keys: Vec::new(),
158            control_key: None,
159        }
160    }
161
162    pub fn add_key(&mut self, key: NtpAuthKey) {
163        self.keys.push(key);
164    }
165
166    pub fn get_key(&self, id: KeyId) -> Option<&NtpAuthKey> {
167        self.keys.iter().find(|k| k.id == id)
168    }
169
170    pub fn has_key(&self, id: KeyId) -> bool {
171        self.keys.iter().any(|k| k.id == id)
172    }
173
174    pub fn remove_key(&mut self, id: KeyId) {
175        self.keys.retain(|k| k.id != id);
176    }
177
178    pub fn key_count(&self) -> usize {
179        self.keys.len()
180    }
181
182    pub fn add_trusted_key(&mut self, id: KeyId) {
183        if !self.trusted_keys.contains(&id) {
184            self.trusted_keys.push(id);
185        }
186    }
187
188    pub fn remove_trusted_key(&mut self, id: KeyId) {
189        self.trusted_keys.retain(|&k| k != id);
190    }
191
192    pub fn is_trusted_key(&self, id: KeyId) -> bool {
193        self.trusted_keys.contains(&id)
194    }
195
196    pub fn set_control_key(&mut self, id: KeyId) {
197        self.control_key = Some(id);
198    }
199    pub fn get_control_key(&self) -> Option<KeyId> {
200        self.control_key
201    }
202
203    /// Returns `true` if authentication is enabled — i.e. there is at least
204    /// one configured key and at least one trusted key, or a control key is set.
205    pub fn is_auth_enabled(&self) -> bool {
206        !self.keys.is_empty() && (!self.trusted_keys.is_empty() || self.control_key.is_some())
207    }
208
209    /// Parse an ntp.keys file.
210    ///
211    /// File format (matching ntpsec's authreadkeys.c):
212    ///   `keyid digesttype keydata [trusted]`
213    ///
214    /// Comment lines start with `#`.  Empty lines are ignored.
215    pub fn parse_keys_file(&mut self, content: &str) -> Result<usize, String> {
216        let mut count = 0;
217        for (lineno, line) in content.lines().enumerate() {
218            let trimmed = line.trim();
219            if trimmed.is_empty() || trimmed.starts_with('#') {
220                continue;
221            }
222
223            match self.parse_key_line(trimmed, lineno + 1) {
224                Ok(()) => count += 1,
225                Err(e) => return Err(format!("line {}: {}", lineno + 1, e)),
226            }
227        }
228        Ok(count)
229    }
230
231    /// Parse a single ntp.keys line.
232    fn parse_key_line(&mut self, line: &str, _lineno: usize) -> Result<(), String> {
233        let parts: Vec<&str> = line.split_whitespace().collect();
234        if parts.len() < 3 {
235            return Err(format!(
236                "too few fields (need at least 3, got {})",
237                parts.len()
238            ));
239        }
240
241        let id: KeyId = parts[0]
242            .parse()
243            .map_err(|_| format!("invalid key ID '{}'", parts[0]))?;
244        if id == 0 {
245            return Err("key ID 0 is not allowed".to_string());
246        }
247        let digest = DigestType::from_name(parts[1])
248            .ok_or_else(|| format!("unknown digest type '{}'", parts[1]))?;
249        // NTPsec rule (authreadkeys.c):
250        //   ≤ 20 characters → printable ASCII key (used as-is)
251        //   > 20 characters → hex-encoded binary key (must be valid hex, or error)
252        let key_data = if parts[2].len() > 20 {
253            if parts[2].chars().all(|c| c.is_ascii_hexdigit()) && parts[2].len() % 2 == 0 {
254                hex_decode(parts[2])
255                    .map_err(|e| format!("hex decode error for '{}': {}", parts[2], e))?
256            } else {
257                return Err(format!(
258                    "key with length {} is neither valid hex nor ≤20 ASCII",
259                    parts[2].len()
260                ));
261            }
262        } else {
263            parts[2].as_bytes().to_vec()
264        };
265
266        let key = NtpAuthKey::new(id, digest, key_data);
267
268        self.add_key(key);
269
270        // Optional 4th field: "trusted"
271        if parts.len() >= 4 && parts[3].to_lowercase() == "trusted" {
272            self.add_trusted_key(id);
273        }
274
275        Ok(())
276    }
277
278    /// Iterate over all keys.
279    pub fn iter(&self) -> impl Iterator<Item = &NtpAuthKey> {
280        self.keys.iter()
281    }
282
283    /// Dump the key store in ntp.keys format (for debugging).
284    pub fn format(&self) -> String {
285        let mut out = String::new();
286        for key in &self.keys {
287            let hex = hex_encode(&key.key_data);
288            let trusted = if self.trusted_keys.contains(&key.id) {
289                " trusted"
290            } else {
291                ""
292            };
293            out.push_str(&format!(
294                "{} {} {}{}\n",
295                key.id,
296                key.digest.as_str(),
297                hex,
298                trusted
299            ));
300        }
301        out
302    }
303}
304
305// ──── Hex Encoding/Decoding ───────────────────────────────────────────
306
307fn hex_decode(s: &str) -> Result<Vec<u8>, String> {
308    (0..s.len())
309        .step_by(2)
310        .map(|i| u8::from_str_radix(&s[i..i + 2], 16).map_err(|_| format!("invalid hex: {}", s)))
311        .collect()
312}
313
314fn hex_encode(data: &[u8]) -> String {
315    data.iter().map(|b| format!("{:02x}", b)).collect()
316}
317
318// ──── Tests ───────────────────────────────────────────────────────────
319
320#[cfg(test)]
321mod tests {
322    use super::*;
323
324    #[test]
325    fn test_parse_key_line_md5() {
326        let mut store = AuthKeyStore::new();
327        assert!(store.parse_key_line("10 MD5 mysecretkey", 1).is_ok());
328        let key = store.get_key(10).unwrap();
329        assert_eq!(key.digest, DigestType::Md5);
330    }
331
332    #[test]
333    fn test_parse_key_line_sha1() {
334        let mut store = AuthKeyStore::new();
335        assert!(store.parse_key_line("20 SHA1 mysecretkey", 1).is_ok());
336        let key = store.get_key(20).unwrap();
337        assert_eq!(key.digest, DigestType::Sha1);
338    }
339
340    #[test]
341    fn test_parse_key_line_cmac() {
342        let mut store = AuthKeyStore::new();
343        assert!(store.parse_key_line("30 CMAC 0123456789abcdef", 1).is_ok());
344        let key = store.get_key(30).unwrap();
345        assert_eq!(key.digest, DigestType::Aes128Cmac);
346    }
347
348    #[test]
349    fn test_parse_key_line_trusted() {
350        let mut store = AuthKeyStore::new();
351        assert!(store.parse_key_line("10 MD5 secret trusted", 1).is_ok());
352        assert!(store.is_trusted_key(10));
353    }
354
355    #[test]
356    fn test_parse_key_line_too_few() {
357        let mut store = AuthKeyStore::new();
358        assert!(store.parse_key_line("10 MD5", 1).is_err());
359    }
360
361    #[test]
362    fn test_parse_key_line_bad_id() {
363        let mut store = AuthKeyStore::new();
364        assert!(store.parse_key_line("abc MD5 key", 1).is_err());
365    }
366
367    #[test]
368    fn test_parse_keys_file() {
369        let mut store = AuthKeyStore::new();
370        let content =
371            "# NTP keys file\n10 MD5 secret1\n20 SHA1 secret2 trusted\n\n30 CMAC abcdef\n";
372        let count = store.parse_keys_file(content).unwrap();
373        assert_eq!(count, 3);
374        assert!(store.is_trusted_key(20));
375    }
376
377    #[test]
378    fn test_mac_md5_roundtrip() {
379        let key = NtpAuthKey::new(1, DigestType::Md5, b"password".to_vec());
380        let mac = key.mac(b"test packet").unwrap();
381        assert_eq!(mac.len(), 16);
382        assert!(key.verify_mac(b"test packet", &mac));
383        assert!(!key.verify_mac(b"wrong packet", &mac));
384    }
385
386    #[test]
387    fn test_mac_sha1_roundtrip() {
388        let key = NtpAuthKey::new(1, DigestType::Sha1, b"password".to_vec());
389        let mac = key.mac(b"test packet").unwrap();
390        assert_eq!(mac.len(), 20);
391        assert!(key.verify_mac(b"test packet", &mac));
392    }
393
394    #[test]
395    fn test_mac_aes128cmac_roundtrip() {
396        let key = NtpAuthKey::new(1, DigestType::Aes128Cmac, b"0123456789abcdef".to_vec());
397        let mac = key.mac(b"test packet").unwrap();
398        assert_eq!(mac.len(), 16);
399        assert!(key.verify_mac(b"test packet", &mac));
400        assert!(!key.verify_mac(b"wrong packet", &mac));
401    }
402
403    #[test]
404    fn test_md5_known_vector() {
405        use digest::FixedOutput;
406        use hex_literal::hex;
407        let result = md5::Md5::default().finalize_fixed();
408        let expected = hex!("d41d8cd98f00b204e9800998ecf8427e");
409        assert_eq!(result[..], expected);
410    }
411
412    #[test]
413    fn test_sha1_known_vector() {
414        use digest::{Digest, FixedOutput};
415        use hex_literal::hex;
416        let mut ctx = sha1::Sha1::default();
417        Digest::update(&mut ctx, b"abc");
418        let result = ctx.finalize_fixed();
419        let expected = hex!("a9993e364706816aba3e25717850c26c9cd0d89d");
420        assert_eq!(result[..], expected);
421    }
422
423    #[test]
424    fn test_hex_encoding() {
425        let data = b"hello";
426        let hex = hex_encode(data);
427        let decoded = hex_decode(&hex).unwrap();
428        assert_eq!(decoded, data);
429    }
430
431    #[test]
432    fn test_digest_lengths() {
433        assert!(DigestType::Md5.digest_length() == 16);
434        assert!(DigestType::Sha1.digest_length() == 20);
435        assert!(DigestType::Aes128Cmac.digest_length() == 16);
436    }
437
438    #[test]
439    fn test_key_format_dump() {
440        let mut store = AuthKeyStore::new();
441        store.parse_key_line("10 MD5 secret trusted", 1).unwrap();
442        let dump = store.format();
443        assert!(dump.contains("10"));
444        assert!(dump.contains("MD5"));
445    }
446
447    #[test]
448    fn test_remove_key() {
449        let mut store = AuthKeyStore::new();
450        store.add_key(NtpAuthKey::new(1, DigestType::Md5, b"key".to_vec()));
451        assert!(store.has_key(1));
452        store.remove_key(1);
453        assert!(!store.has_key(1));
454    }
455}