Skip to main content

asterust_junos/system/
mod.rs

1//! `system`
2//! `system { ... }`.
3//!
4//! Each statement with children of its own lives in a submodule named after it.
5//!
6//! # See also
7//!
8//! - [`[edit system]` hierarchy](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/topic-map/hierarchy-edit-system.html)
9//! - [host-name (System)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/host-name-edit-system.html)
10//! - [domain-name (System)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/domain-name-edit-system.html)
11//! - [time-zone](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/time-zone-edit-system.html)
12//! - [domain-search](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/domain-search-edit-system.html)
13//! - [authentication-order (System)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/authentication-order-edit-system.html)
14//! - [max-configurations-on-flash (System)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/max-configurations-on-flash-edit-system.html)
15//! - [no-redirects (IPv4 Traffic)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/no-redirects-edit-system.html)
16//! - [default-address-selection](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/default-address-selection-edit-system.html)
17//! - [diag-port-authentication](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/diag-port-authentication-edit-system.html)
18//! - [pic-console-authentication](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/pic-console-authentication-edit-system.html)
19
20mod accounting;
21mod archival;
22mod authentication_secret;
23mod autoinstallation;
24mod backup_router;
25mod commit;
26mod dynamic_profile_options;
27mod extensions;
28mod internet_options;
29mod license;
30mod location;
31mod login;
32mod master_password;
33mod name_server;
34mod ntp;
35mod pixel_tracing;
36mod ports;
37mod processes;
38mod radius_server;
39mod root_authentication;
40mod schema;
41mod scripts;
42mod services;
43mod static_host_mapping;
44mod syslog;
45mod tacplus_server;
46
47pub use accounting::{Accounting, AccountingDestination};
48pub use archival::{Archival, ArchivalConfiguration};
49pub use authentication_secret::AuthenticationSecret;
50pub use autoinstallation::{Autoinstallation, AutoinstallationInterface};
51pub use backup_router::BackupRouter;
52pub use commit::Commit;
53pub use dynamic_profile_options::DynamicProfileOptions;
54pub use extensions::{ExtensionApplication, ExtensionProvider, Extensions, ProviderLicense};
55pub use internet_options::{IcmpRateLimit, InternetOptions};
56pub use license::{License, LicenseAutoupdate, LicenseRenew};
57pub use location::Location;
58pub use login::{Login, LoginClass, LoginPassword, LoginRetryOptions, LoginUser};
59pub use master_password::MasterPassword;
60pub use name_server::NameServer;
61pub use ntp::{Ntp, NtpAuthenticationKey, NtpHost};
62pub use pixel_tracing::PixelTracing;
63pub use ports::{Auxiliary, Console, Ports};
64pub use processes::Process;
65pub use radius_server::RadiusServer;
66pub use root_authentication::RootAuthentication;
67pub use schema::Schema;
68pub use scripts::Scripts;
69pub use services::{
70    AaclStatisticsProfile, DhcpLocalServer, DhcpLocalServerGroup, FlowTapDtcp, FlowTapDtcpSsh,
71    LocalPolicyDecisionFunction, Netconf, NetconfSsh, OutboundSshClient, OutboundSshServer, RedundancyInterface,
72    ServiceDeployment, ServiceDeploymentServer, Services, SshService, StaticSubscriberGroup, StaticSubscriberProfile,
73    StaticSubscribers, SubscriberManagement, SubscriberRedundancy, WebManagement, WebManagementHttp,
74    WebManagementHttps, XnmClearText, XnmSsl,
75};
76pub use static_host_mapping::StaticHostMapping;
77pub use syslog::{Syslog, SyslogArchive, SyslogHost, SyslogRule, SyslogStructuredData, SyslogTarget};
78pub use tacplus_server::TacplusServer;
79
80use crate::{active_children, arg_of, args_of, child_block, has_leaf, list_values, split_name, top_level, unquote};
81use accounting::parse_accounting;
82use archival::parse_archival;
83use asterust::config::{Config, ConfigLine};
84use authentication_secret::password_secrets;
85use autoinstallation::parse_autoinstallation;
86use backup_router::parse_backup_router;
87use commit::parse_commit;
88use dynamic_profile_options::parse_dynamic_profile_options;
89use extensions::parse_extensions;
90use internet_options::parse_internet_options;
91use license::parse_license;
92use location::parse_location;
93use login::parse_login;
94use master_password::parse_master_password;
95use name_server::name_servers;
96use ntp::parse_ntp;
97use pixel_tracing::parse_pixel_tracing;
98use ports::parse_ports;
99use processes::parse_processes;
100use radius_server::radius_servers;
101use root_authentication::root_authentication;
102use schema::parse_schema;
103use scripts::parse_scripts;
104use services::parse_services;
105use static_host_mapping::static_host_mappings;
106use syslog::parse_syslog;
107use tacplus_server::tacplus_servers;
108
109/// The top-level `system` configuration.
110#[derive(Clone, Debug, PartialEq, Eq)]
111#[non_exhaustive]
112pub struct System {
113    pub host_name: Option<String>,
114    pub domain_name: Option<String>,
115    /// e.g. `"UTC"` or `"America/New_York"`.
116    pub time_zone: Option<String>,
117    pub domain_search: Vec<String>,
118    pub static_host_mappings: Vec<StaticHostMapping>,
119    pub backup_router: Option<BackupRouter>,
120    pub inet6_backup_router: Option<BackupRouter>,
121    /// Methods in the order tried: `password`, `radius`, `tacplus`.
122    pub authentication_order: Vec<String>,
123    pub radius_servers: Vec<RadiusServer>,
124    pub tacplus_servers: Vec<TacplusServer>,
125    pub location: Option<Location>,
126    pub ports: Option<Ports>,
127    pub max_configurations_on_flash: Option<String>,
128    pub max_configuration_rollbacks: Option<String>,
129    pub no_redirects: bool,
130    /// `default-address-selection`: use the loopback as the source of locally generated packets.
131    pub default_address_selection: bool,
132    pub internet_options: Option<InternetOptions>,
133    pub commit: Option<Commit>,
134    pub processes: Vec<Process>,
135    pub dynamic_profile_options: Option<DynamicProfileOptions>,
136    pub extensions: Option<Extensions>,
137    pub autoinstallation: Option<Autoinstallation>,
138    pub schema: Option<Schema>,
139    pub pixel_tracing: Option<PixelTracing>,
140    pub scripts: Option<Scripts>,
141    pub no_multicast_echo: bool,
142    pub no_ping_record_route: bool,
143    pub no_ping_time_stamp: bool,
144    pub auto_snapshot: bool,
145    pub compress_configuration_files: bool,
146    pub mirror_flash_on_disk: bool,
147    pub switchover_on_routing_crash: bool,
148    pub use_imported_time_zones: bool,
149    pub archival: Option<Archival>,
150    pub accounting: Option<Accounting>,
151    pub root_authentication: Option<RootAuthentication>,
152    pub master_password: Option<MasterPassword>,
153    /// Method name of `diag-port-authentication`, e.g. `encrypted-password`.
154    pub diag_port_authentication: Vec<String>,
155    /// The passwords of `diag-port-authentication`; empty unless the `secrets` feature is enabled.
156    pub diag_port_authentication_secrets: Vec<AuthenticationSecret>,
157    /// Method names of `pic-console-authentication`.
158    pub pic_console_authentication: Vec<String>,
159    /// The passwords of `pic-console-authentication`; empty unless the `secrets` feature is enabled.
160    pub pic_console_authentication_secrets: Vec<AuthenticationSecret>,
161    pub license: Option<License>,
162    pub name_servers: Vec<NameServer>,
163    pub ntp: Option<Ntp>,
164    pub syslog: Option<Syslog>,
165    pub login: Option<Login>,
166    pub services: Option<Services>,
167}
168
169/// Returns the top-level `system` block, or `None` if there is none.
170///
171/// # Examples
172///
173/// ```
174/// use asterust::config::juniper;
175/// use asterust_junos::system::system;
176///
177/// let config = juniper::parse_braces("system {\n    host-name pe1;\n}\n");
178/// let system = system(&config).unwrap();
179/// assert_eq!(system.host_name.as_deref(), Some("pe1"));
180/// ```
181pub fn system(config: &Config) -> Option<System> {
182    let system = top_level(config, "system")?;
183    Some(System {
184        host_name: arg_of(system, "host-name").map(str::to_string),
185        domain_name: arg_of(system, "domain-name").map(str::to_string),
186        time_zone: arg_of(system, "time-zone").map(str::to_string),
187        domain_search: args_of(system, "domain-search")
188            .into_iter()
189            .flat_map(list_values)
190            .collect(),
191        static_host_mappings: static_host_mappings(system),
192        backup_router: arg_of(system, "backup-router").map(parse_backup_router),
193        inet6_backup_router: arg_of(system, "inet6-backup-router").map(parse_backup_router),
194        authentication_order: args_of(system, "authentication-order")
195            .into_iter()
196            .flat_map(list_values)
197            .collect(),
198        radius_servers: radius_servers(system, "radius-server"),
199        tacplus_servers: tacplus_servers(system, "tacplus-server"),
200        location: child_block(system, "location").map(parse_location),
201        ports: child_block(system, "ports").map(parse_ports),
202        max_configurations_on_flash: arg_of(system, "max-configurations-on-flash").map(str::to_string),
203        max_configuration_rollbacks: arg_of(system, "max-configuration-rollbacks").map(str::to_string),
204        no_redirects: has_leaf(system, "no-redirects"),
205        default_address_selection: has_leaf(system, "default-address-selection"),
206        internet_options: child_block(system, "internet-options").map(parse_internet_options),
207        commit: child_block(system, "commit").map(parse_commit),
208        processes: child_block(system, "processes")
209            .map(parse_processes)
210            .unwrap_or_default(),
211        dynamic_profile_options: child_block(system, "dynamic-profile-options").map(parse_dynamic_profile_options),
212        extensions: child_block(system, "extensions").map(parse_extensions),
213        autoinstallation: child_block(system, "autoinstallation").map(parse_autoinstallation),
214        schema: child_block(system, "schema").map(parse_schema),
215        pixel_tracing: child_block(system, "pixel-tracing").map(parse_pixel_tracing),
216        scripts: child_block(system, "scripts").map(parse_scripts),
217        no_multicast_echo: has_leaf(system, "no-multicast-echo"),
218        no_ping_record_route: has_leaf(system, "no-ping-record-route"),
219        no_ping_time_stamp: has_leaf(system, "no-ping-time-stamp"),
220        auto_snapshot: has_leaf(system, "auto-snapshot"),
221        compress_configuration_files: has_leaf(system, "compress-configuration-files"),
222        mirror_flash_on_disk: has_leaf(system, "mirror-flash-on-disk"),
223        switchover_on_routing_crash: has_leaf(system, "switchover-on-routing-crash"),
224        use_imported_time_zones: has_leaf(system, "use-imported-time-zones"),
225        archival: child_block(system, "archival").map(parse_archival),
226        accounting: child_block(system, "accounting").map(parse_accounting),
227        root_authentication: root_authentication(system),
228        master_password: child_block(system, "master-password").map(parse_master_password),
229        diag_port_authentication: password_methods(system, "diag-port-authentication"),
230        diag_port_authentication_secrets: password_secrets(system, "diag-port-authentication"),
231        pic_console_authentication: password_methods(system, "pic-console-authentication"),
232        pic_console_authentication_secrets: password_secrets(system, "pic-console-authentication"),
233        license: child_block(system, "license").map(parse_license),
234        name_servers: name_servers(system),
235        ntp: child_block(system, "ntp").map(parse_ntp),
236        syslog: child_block(system, "syslog").map(parse_syslog),
237        login: child_block(system, "login").map(parse_login),
238        services: child_block(system, "services").map(parse_services),
239    })
240}
241
242/// Servers written as `<keyword> <address> { ... }`, or as `<keyword> { <address> { ... } }`, with
243/// their option lines.
244fn servers<'a>(system: &'a ConfigLine, keyword: &str) -> Vec<(&'a str, &'a ConfigLine)> {
245    let mut found = Vec::new();
246    for child in active_children(system) {
247        if child.text == keyword {
248            found.extend(active_children(child).map(|server| (unquote(&server.text), server)));
249        } else if let Some(arg) = child.arg(keyword) {
250            found.push((split_name(arg).0, child));
251        }
252    }
253    found
254}
255
256/// The method names of a password setting such as `diag-port-authentication`, written either as
257/// `<keyword> encrypted-password "...";` or as a block. The passwords are dropped.
258fn password_methods(system: &ConfigLine, keyword: &str) -> Vec<String> {
259    let mut methods = Vec::new();
260    for child in active_children(system) {
261        if child.text == keyword {
262            methods.extend(authentication_methods(child));
263        } else if let Some(method) = child.arg(keyword).and_then(|arg| arg.split_whitespace().next()) {
264            methods.push(method.to_string());
265        }
266    }
267    methods
268}
269
270/// The name of each statement in an `authentication` block. Secrets can carry a trailing `##
271/// SECRET-DATA` marker, so only the first word is kept.
272fn authentication_methods(auth: &ConfigLine) -> Vec<String> {
273    active_children(auth)
274        .filter_map(|c| c.text.split_whitespace().next())
275        .map(str::to_string)
276        .collect()
277}
278
279#[cfg(test)]
280mod tests {
281    use crate::system::system;
282    use asterust::config::juniper;
283
284    // Not from documentation: written from the CLI Reference syntax pages. See the README "Sources".
285    #[test]
286    fn extracts_host_name() {
287        let system = system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n")).unwrap();
288        assert_eq!(system.host_name.as_deref(), Some("pe1"));
289    }
290
291    #[test]
292    fn host_name_is_optional() {
293        let system = system(&juniper::parse_braces("system {\n    domain-name example.net;\n}\n")).unwrap();
294        assert_eq!(system.host_name, None);
295    }
296
297    #[test]
298    fn skips_inactive_host_name() {
299        let system = system(&juniper::parse_braces("system {\n    inactive: host-name pe1;\n}\n")).unwrap();
300        assert_eq!(system.host_name, None);
301    }
302
303    #[test]
304    fn extracts_domain_name() {
305        let system = system(&juniper::parse_braces(
306            "system {\n    host-name pe1;\n    domain-name example.net;\n}\n",
307        ))
308        .unwrap();
309        assert_eq!(system.domain_name.as_deref(), Some("example.net"));
310    }
311
312    #[test]
313    fn domain_name_is_optional() {
314        let system = system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n")).unwrap();
315        assert_eq!(system.domain_name, None);
316    }
317
318    #[test]
319    fn extracts_time_zone() {
320        let system = system(&juniper::parse_braces("system {\n    time-zone America/New_York;\n}\n")).unwrap();
321        assert_eq!(system.time_zone.as_deref(), Some("America/New_York"));
322    }
323
324    #[test]
325    fn time_zone_is_optional() {
326        let system = system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n")).unwrap();
327        assert_eq!(system.time_zone, None);
328    }
329
330    #[test]
331    fn extracts_configuration_limits_and_no_redirects() {
332        let system = system(&juniper::parse_braces(
333            "system {\n    max-configurations-on-flash 5;\n    max-configuration-rollbacks 20;\n    no-redirects;\n}\n",
334        ))
335        .unwrap();
336        assert_eq!(system.max_configurations_on_flash.as_deref(), Some("5"));
337        assert_eq!(system.max_configuration_rollbacks.as_deref(), Some("20"));
338        assert!(system.no_redirects);
339    }
340
341    #[test]
342    fn configuration_limits_are_optional() {
343        let system = system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n")).unwrap();
344        assert_eq!(system.max_configurations_on_flash, None);
345        assert_eq!(system.max_configuration_rollbacks, None);
346        assert!(!system.no_redirects);
347    }
348
349    #[test]
350    fn extracts_system_flags() {
351        let system = system(&juniper::parse_braces(
352            "system {\n    no-multicast-echo;\n    no-ping-record-route;\n    no-ping-time-stamp;\n    auto-snapshot;\n    compress-configuration-files;\n    mirror-flash-on-disk;\n    switchover-on-routing-crash;\n    use-imported-time-zones;\n}\n",
353        ))
354        .unwrap();
355        assert!(system.no_multicast_echo);
356        assert!(system.no_ping_record_route);
357        assert!(system.no_ping_time_stamp);
358        assert!(system.auto_snapshot);
359        assert!(system.compress_configuration_files);
360        assert!(system.mirror_flash_on_disk);
361        assert!(system.switchover_on_routing_crash);
362        assert!(system.use_imported_time_zones);
363    }
364
365    #[test]
366    fn system_flags_default_to_off() {
367        let system = system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n")).unwrap();
368        assert!(!system.no_multicast_echo);
369        assert!(!system.auto_snapshot);
370        assert!(!system.use_imported_time_zones);
371    }
372
373    #[test]
374    fn no_system_is_none() {
375        assert!(system(&juniper::parse_braces("interfaces {\n    lo0;\n}\n")).is_none());
376    }
377
378    #[test]
379    fn diag_port_and_pic_console_report_only_the_method() {
380        let system = system(&juniper::parse_braces(
381            r#"
382system {
383    diag-port-authentication encrypted-password "$6$salt$hash"; ## SECRET-DATA
384    pic-console-authentication {
385        encrypted-password "$6$salt$other"; ## SECRET-DATA
386    }
387}
388"#,
389        ))
390        .unwrap();
391        assert_eq!(system.diag_port_authentication, ["encrypted-password"]);
392        assert_eq!(system.pic_console_authentication, ["encrypted-password"]);
393        let values = |secrets: &[crate::system::AuthenticationSecret]| -> Vec<String> {
394            secrets.iter().map(|s| s.value.expose().to_string()).collect()
395        };
396        let (diag, pic) = if cfg!(feature = "secrets") {
397            (vec!["$6$salt$hash".to_string()], vec!["$6$salt$other".to_string()])
398        } else {
399            (Vec::new(), Vec::new())
400        };
401        assert_eq!(values(&system.diag_port_authentication_secrets), diag);
402        assert_eq!(values(&system.pic_console_authentication_secrets), pic);
403    }
404
405    #[test]
406    fn secret_settings_are_optional() {
407        let system = system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n")).unwrap();
408        assert!(system.master_password.is_none());
409        assert!(system.diag_port_authentication.is_empty());
410        assert!(system.pic_console_authentication.is_empty());
411    }
412
413    #[test]
414    fn extracts_authentication_order() {
415        let system = system(&juniper::parse_braces(
416            "system {\n    authentication-order [ tacplus radius password ];\n}\n",
417        ))
418        .unwrap();
419        assert_eq!(system.authentication_order, ["tacplus", "radius", "password"]);
420    }
421
422    #[test]
423    fn authentication_settings_are_optional() {
424        let system = system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n")).unwrap();
425        assert!(system.authentication_order.is_empty());
426        assert!(system.radius_servers.is_empty());
427        assert!(system.tacplus_servers.is_empty());
428    }
429
430    #[test]
431    fn extracts_domain_search_list() {
432        let system = system(&juniper::parse_braces(
433            "system {\n    domain-search [ example.net lab.example.net ];\n}\n",
434        ))
435        .unwrap();
436        assert_eq!(system.domain_search, ["example.net", "lab.example.net"]);
437    }
438
439    #[test]
440    fn addressing_settings_are_optional() {
441        let system = system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n")).unwrap();
442        assert!(system.domain_search.is_empty());
443        assert!(system.static_host_mappings.is_empty());
444        assert!(system.backup_router.is_none());
445        assert!(system.inet6_backup_router.is_none());
446    }
447}