Skip to main content

asterust_junos/system/
ntp.rs

1//! `ntp`
2//! `system { ntp { ... } }`.
3//!
4//! # See also
5//!
6//! - [ntp](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/ntp-edit-system.html)
7//! - [local-certificate (System)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/local-certificate-edit-system.html)
8
9use crate::{
10    active_children, arg_of, args_of, first_word, has_leaf, list_values, named_children, split_name, statement_words,
11    unquote, value_after,
12};
13use asterust::config::ConfigLine;
14
15/// A `nts` statement of an NTP server.
16#[derive(Clone, Debug, PartialEq, Eq)]
17#[non_exhaustive]
18pub struct NtpHostNts {
19    /// From `remote-identity distinguished-name container`.
20    pub remote_identity_container: Option<String>,
21    /// From `remote-identity distinguished-name wildcard`.
22    pub remote_identity_wildcard: Option<String>,
23    pub hostname: Option<String>,
24}
25
26/// A `broadcast` entry under `ntp`.
27#[derive(Clone, Debug, PartialEq, Eq)]
28#[non_exhaustive]
29pub struct NtpBroadcast {
30    pub address: Option<String>,
31    pub key: Option<String>,
32    pub routing_instance_name: Option<String>,
33    pub ttl: Option<String>,
34    pub version: Option<String>,
35}
36
37/// A `restrict <address>` entry under `ntp`.
38#[derive(Clone, Debug, PartialEq, Eq)]
39#[non_exhaustive]
40pub struct NtpRestriction {
41    pub address: String,
42    pub mask: Option<String>,
43    pub noquery: bool,
44}
45
46/// The `nts` block under `ntp`.
47#[derive(Clone, Debug, PartialEq, Eq)]
48#[non_exhaustive]
49pub struct NtpNts {
50    pub local_certificate: Option<String>,
51    pub trusted_ca_group: Option<String>,
52    pub trusted_ca_profile: Option<String>,
53}
54
55/// The `threshold <value> action (accept | reject)` statement under `ntp`.
56#[derive(Clone, Debug, PartialEq, Eq)]
57#[non_exhaustive]
58pub struct NtpThreshold {
59    pub value: String,
60    pub action: Option<String>,
61}
62
63/// A `server` or `peer` entry under `ntp`.
64#[derive(Clone, Debug, PartialEq, Eq)]
65#[non_exhaustive]
66pub struct NtpHost {
67    /// Address or hostname.
68    pub address: String,
69    /// Authentication key number.
70    pub key: Option<String>,
71    pub prefer: bool,
72    pub version: Option<String>,
73    pub routing_instance: Option<String>,
74    pub nts: Option<NtpHostNts>,
75}
76
77/// An `authentication-key`. The key value is read only with the `secrets` feature.
78#[derive(Clone, Debug, PartialEq, Eq)]
79#[non_exhaustive]
80pub struct NtpAuthenticationKey {
81    pub number: String,
82    /// `md5`, `sha1` or `sha256`.
83    pub key_type: Option<String>,
84    /// `None` unless the `secrets` feature is enabled.
85    pub value: Option<crate::Secret>,
86}
87
88/// The `system ntp` configuration.
89#[derive(Clone, Debug, PartialEq, Eq)]
90#[non_exhaustive]
91pub struct Ntp {
92    pub boot_server: Option<String>,
93    pub servers: Vec<NtpHost>,
94    pub peers: Vec<NtpHost>,
95    pub source_address: Option<String>,
96    pub trusted_keys: Vec<String>,
97    pub authentication_keys: Vec<NtpAuthenticationKey>,
98    pub broadcast_client: bool,
99    pub broadcasts: Vec<NtpBroadcast>,
100    pub interval_range: Option<String>,
101    /// `multicast-client`.
102    pub multicast_client: bool,
103    /// The address of `multicast-client <address>`.
104    pub multicast_client_address: Option<String>,
105    pub nts: Option<NtpNts>,
106    pub restrictions: Vec<NtpRestriction>,
107    pub threshold: Option<NtpThreshold>,
108}
109
110pub(super) fn parse_ntp(ntp: &ConfigLine) -> Ntp {
111    let hosts = |keyword: &str| -> Vec<NtpHost> {
112        active_children(ntp)
113            .filter_map(|c| Some(ntp_host(c.arg(keyword)?, c)))
114            .collect()
115    };
116    Ntp {
117        boot_server: arg_of(ntp, "boot-server").map(str::to_string),
118        servers: hosts("server"),
119        peers: hosts("peer"),
120        source_address: arg_of(ntp, "source-address").and_then(first_word).map(str::to_string),
121        trusted_keys: args_of(ntp, "trusted-key").into_iter().flat_map(list_values).collect(),
122        authentication_keys: args_of(ntp, "authentication-key")
123            .into_iter()
124            .filter_map(ntp_authentication_key)
125            .collect(),
126        broadcast_client: has_leaf(ntp, "broadcast-client"),
127        broadcasts: active_children(ntp)
128            .filter(|c| c.text == "broadcast" || c.arg("broadcast").is_some())
129            .map(parse_broadcast)
130            .collect(),
131        interval_range: arg_of(ntp, "interval-range").map(str::to_string),
132        multicast_client: active_children(ntp)
133            .any(|c| c.text == "multicast-client" || c.arg("multicast-client").is_some()),
134        multicast_client_address: arg_of(ntp, "multicast-client").and_then(first_word).map(str::to_string),
135        nts: statement_words(ntp, "nts").map(|words| NtpNts {
136            local_certificate: value_after(&words, "local-certificate"),
137            trusted_ca_group: value_after(&words, "trusted-ca-group"),
138            trusted_ca_profile: value_after(&words, "trusted-ca-profile"),
139        }),
140        restrictions: named_children(ntp, "restrict")
141            .map(|(address, restriction)| NtpRestriction {
142                address: address.to_string(),
143                mask: arg_of(restriction, "mask").map(str::to_string),
144                noquery: has_leaf(restriction, "noquery"),
145            })
146            .collect(),
147        threshold: arg_of(ntp, "threshold").map(|arg| {
148            let words: Vec<&str> = arg.split_whitespace().collect();
149            NtpThreshold {
150                value: words.first().unwrap_or(&"").to_string(),
151                action: value_after(&words, "action"),
152            }
153        }),
154    }
155}
156
157/// A `broadcast [<address>] [key n] [routing-instance-name x] [ttl n] [version n]` entry, with the
158/// options on the line or in a block.
159fn parse_broadcast(line: &ConfigLine) -> NtpBroadcast {
160    let words: Vec<&str> = line
161        .text
162        .split_whitespace()
163        .skip(1)
164        .chain(active_children(line).flat_map(|c| c.text.split_whitespace()))
165        .collect();
166    let address = words
167        .first()
168        .filter(|w| !matches!(**w, "key" | "routing-instance-name" | "ttl" | "version"))
169        .map(|w| w.to_string());
170    NtpBroadcast {
171        address,
172        key: value_after(&words, "key"),
173        routing_instance_name: value_after(&words, "routing-instance-name"),
174        ttl: value_after(&words, "ttl"),
175        version: value_after(&words, "version"),
176    }
177}
178
179/// A host written `<address> [key n] [prefer] [version n] [routing-instance x]`, with the options
180/// on the line or in a block.
181fn ntp_host(arg: &str, line: &ConfigLine) -> NtpHost {
182    let (address, options) = split_name(arg);
183    let mut words = options.split_whitespace();
184    let mut host = NtpHost {
185        address: address.to_string(),
186        key: arg_of(line, "key").map(str::to_string),
187        prefer: has_leaf(line, "prefer"),
188        version: arg_of(line, "version").map(str::to_string),
189        routing_instance: arg_of(line, "routing-instance").map(str::to_string),
190        nts: statement_words(line, "nts").map(|words| NtpHostNts {
191            remote_identity_container: value_after(&words, "container").map(|v| unquote(&v).to_string()),
192            remote_identity_wildcard: value_after(&words, "wildcard").map(|v| unquote(&v).to_string()),
193            hostname: value_after(&words, "hostname"),
194        }),
195    };
196    while let Some(word) = words.next() {
197        match word {
198            "prefer" => host.prefer = true,
199            "key" => host.key = words.next().map(str::to_string),
200            "version" => host.version = words.next().map(str::to_string),
201            "routing-instance" => host.routing_instance = words.next().map(str::to_string),
202            _ => {}
203        }
204    }
205    host
206}
207
208/// `<number> type <type> value <secret>`.
209fn ntp_authentication_key(arg: &str) -> Option<NtpAuthenticationKey> {
210    let mut words = arg.split_whitespace();
211    let number = words.next()?.to_string();
212    let mut rest = words.skip_while(|w| *w != "type").skip(1);
213    let key_type = rest.next().map(str::to_string);
214    let value = rest.skip_while(|w| *w != "value").nth(1);
215    Some(NtpAuthenticationKey {
216        number,
217        key_type,
218        value: crate::secret_value(value),
219    })
220}
221
222#[cfg(test)]
223mod tests {
224    use crate::system::system;
225    use asterust::config::juniper;
226
227    const NTP: &str = r#"
228system {
229    ntp {
230        boot-server 192.0.2.10;
231        source-address 192.0.2.1;
232        authentication-key 1 type md5 value "$9$secret";
233        authentication-key 2 type sha256 value "$9$other";
234        trusted-key [ 1 2 ];
235        server 192.0.2.10 key 1 prefer version 4;
236        server 192.0.2.11;
237        server ntp.example.net {
238            key 2;
239            prefer;
240            version 3;
241            routing-instance mgmt_junos;
242        }
243        inactive: server 192.0.2.12;
244        peer 192.0.2.20 key 1;
245        broadcast-client;
246    }
247}
248"#;
249
250    #[test]
251    fn extracts_ntp_servers_in_line_and_block_form() {
252        let ntp = system(&juniper::parse_braces(NTP)).unwrap().ntp.unwrap();
253        let addresses: Vec<_> = ntp.servers.iter().map(|s| s.address.as_str()).collect();
254        assert_eq!(addresses, ["192.0.2.10", "192.0.2.11", "ntp.example.net"]);
255
256        let line = &ntp.servers[0];
257        assert_eq!(line.key.as_deref(), Some("1"));
258        assert!(line.prefer);
259        assert_eq!(line.version.as_deref(), Some("4"));
260
261        assert_eq!(ntp.servers[1].key, None);
262        assert!(!ntp.servers[1].prefer);
263
264        let block = &ntp.servers[2];
265        assert_eq!(block.key.as_deref(), Some("2"));
266        assert!(block.prefer);
267        assert_eq!(block.version.as_deref(), Some("3"));
268        assert_eq!(block.routing_instance.as_deref(), Some("mgmt_junos"));
269    }
270
271    #[test]
272    fn extracts_ntp_peers_keys_and_global_settings() {
273        let ntp = system(&juniper::parse_braces(NTP)).unwrap().ntp.unwrap();
274        assert_eq!(ntp.peers.len(), 1);
275        assert_eq!(ntp.peers[0].address, "192.0.2.20");
276        assert_eq!(ntp.peers[0].key.as_deref(), Some("1"));
277        assert_eq!(ntp.boot_server.as_deref(), Some("192.0.2.10"));
278        assert_eq!(ntp.source_address.as_deref(), Some("192.0.2.1"));
279        assert_eq!(ntp.trusted_keys, ["1", "2"]);
280        assert!(ntp.broadcast_client);
281    }
282
283    #[test]
284    fn ntp_authentication_keys_omit_the_secret() {
285        let ntp = system(&juniper::parse_braces(NTP)).unwrap().ntp.unwrap();
286        assert_eq!(ntp.authentication_keys.len(), 2);
287        assert_eq!(ntp.authentication_keys[0].number, "1");
288        assert_eq!(ntp.authentication_keys[0].key_type.as_deref(), Some("md5"));
289        assert_eq!(ntp.authentication_keys[1].key_type.as_deref(), Some("sha256"));
290        assert_eq!(
291            ntp.authentication_keys[0].value.as_ref().map(crate::Secret::expose),
292            crate::secret::expected("$9$secret")
293        );
294        assert_eq!(
295            ntp.authentication_keys[1].value.as_ref().map(crate::Secret::expose),
296            crate::secret::expected("$9$other")
297        );
298    }
299
300    // Not from documentation: written from the CLI Reference syntax pages. See the README "Sources".
301    #[test]
302    fn extracts_the_broadcast_restrict_nts_and_threshold_statements() {
303        let ntp = system(&juniper::parse_braces(
304            r#"
305system {
306    ntp {
307        broadcast 192.0.2.255 key 3 routing-instance-name mgmt_junos ttl 4 version 4;
308        broadcast {
309            version 3;
310        }
311        interval-range 2;
312        multicast-client 224.0.1.1;
313        nts {
314            local-certificate ntp-cert;
315            trusted-ca trusted-ca-profile ca-profile;
316        }
317        restrict 192.0.2.0 {
318            mask 255.255.255.0;
319            noquery;
320        }
321        restrict 198.51.100.7;
322        threshold 400 action reject;
323        server pool.example.net {
324            nts {
325                remote-identity distinguished-name wildcard "*.example.net" hostname pool.example.net;
326            }
327        }
328    }
329}
330"#,
331        ))
332        .unwrap()
333        .ntp
334        .unwrap();
335        assert_eq!(ntp.broadcasts.len(), 2);
336        assert_eq!(ntp.broadcasts[0].address.as_deref(), Some("192.0.2.255"));
337        assert_eq!(ntp.broadcasts[0].key.as_deref(), Some("3"));
338        assert_eq!(ntp.broadcasts[0].routing_instance_name.as_deref(), Some("mgmt_junos"));
339        assert_eq!(ntp.broadcasts[0].ttl.as_deref(), Some("4"));
340        assert_eq!(ntp.broadcasts[0].version.as_deref(), Some("4"));
341        assert_eq!(ntp.broadcasts[1].address, None);
342        assert_eq!(ntp.broadcasts[1].version.as_deref(), Some("3"));
343        assert_eq!(ntp.interval_range.as_deref(), Some("2"));
344        assert!(ntp.multicast_client);
345        assert_eq!(ntp.multicast_client_address.as_deref(), Some("224.0.1.1"));
346        let nts = ntp.nts.unwrap();
347        assert_eq!(nts.local_certificate.as_deref(), Some("ntp-cert"));
348        assert_eq!(nts.trusted_ca_profile.as_deref(), Some("ca-profile"));
349        assert_eq!(nts.trusted_ca_group, None);
350        assert_eq!(ntp.restrictions.len(), 2);
351        assert_eq!(ntp.restrictions[0].address, "192.0.2.0");
352        assert_eq!(ntp.restrictions[0].mask.as_deref(), Some("255.255.255.0"));
353        assert!(ntp.restrictions[0].noquery);
354        assert!(!ntp.restrictions[1].noquery);
355        let threshold = ntp.threshold.unwrap();
356        assert_eq!(threshold.value, "400");
357        assert_eq!(threshold.action.as_deref(), Some("reject"));
358        let host_nts = ntp.servers[0].nts.as_ref().unwrap();
359        assert_eq!(host_nts.remote_identity_wildcard.as_deref(), Some("*.example.net"));
360        assert_eq!(host_nts.hostname.as_deref(), Some("pool.example.net"));
361        assert_eq!(host_nts.remote_identity_container, None);
362    }
363
364    #[test]
365    fn ntp_extras_are_optional() {
366        let ntp = system(&juniper::parse_braces(NTP)).unwrap().ntp.unwrap();
367        assert!(ntp.broadcasts.is_empty());
368        assert!(!ntp.multicast_client);
369        assert!(ntp.nts.is_none());
370        assert!(ntp.restrictions.is_empty());
371        assert!(ntp.threshold.is_none());
372        assert!(ntp.servers[0].nts.is_none());
373    }
374
375    #[test]
376    fn no_ntp_is_none() {
377        assert!(system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n"))
378            .unwrap()
379            .ntp
380            .is_none());
381    }
382}