Skip to main content

asterust_junos/system/
services.rs

1//! `system { services { ... } }`.
2
3use super::subscriber::{
4    parse_dhcp_local_server, parse_local_policy_decision_function, parse_static_subscribers,
5    parse_subscriber_management, DhcpLocalServer, LocalPolicyDecisionFunction, StaticSubscribers, SubscriberManagement,
6};
7use crate::{
8    active_children, arg_of, args_of, child_block, has_leaf, list_values, named_children, statement_words, value_after,
9};
10use asterust::config::ConfigLine;
11
12/// The `system services ssh` settings; every field is `None` or empty when only `ssh;` is written.
13#[derive(Clone, Debug, Default, PartialEq, Eq)]
14#[non_exhaustive]
15pub struct SshService {
16    /// `allow`, `deny` or `deny-password`.
17    pub root_login: Option<String>,
18    pub protocol_versions: Vec<String>,
19    pub port: Option<String>,
20    pub connection_limit: Option<String>,
21    pub rate_limit: Option<String>,
22    pub ciphers: Vec<String>,
23    pub sftp_server: bool,
24    /// Methods tried in order: `password`, `radius`, `tacplus`.
25    pub authentication_order: Vec<String>,
26    pub key_exchange: Vec<String>,
27    pub macs: Vec<String>,
28    pub client_alive_count_max: Option<String>,
29    pub client_alive_interval: Option<String>,
30    /// `md5` or `sha2-256`.
31    pub fingerprint_hash: Option<String>,
32    pub max_sessions_per_connection: Option<String>,
33    pub max_pre_authentication_packets: Option<String>,
34    pub no_challenge_response: bool,
35    pub no_password_authentication: bool,
36    pub no_passwords: bool,
37    pub no_public_keys: bool,
38}
39
40/// An `address` of an outbound-ssh client.
41#[derive(Clone, Debug, PartialEq, Eq)]
42#[non_exhaustive]
43pub struct OutboundSshServer {
44    pub address: String,
45    pub port: Option<String>,
46    pub retry: Option<String>,
47    pub timeout: Option<String>,
48}
49
50/// An `outbound-ssh client <id>`. The `secret` is not extracted.
51#[derive(Clone, Debug, PartialEq, Eq)]
52#[non_exhaustive]
53pub struct OutboundSshClient {
54    pub id: String,
55    pub device_id: Option<String>,
56    pub servers: Vec<OutboundSshServer>,
57    /// e.g. `"netconf"`.
58    pub services: Vec<String>,
59    /// `in-order` or `sticky`.
60    pub reconnect_strategy: Option<String>,
61    pub routing_instance: Option<String>,
62}
63
64/// The `web-management http` block.
65#[derive(Clone, Debug, PartialEq, Eq)]
66#[non_exhaustive]
67pub struct WebManagementHttp {
68    pub interfaces: Vec<String>,
69    pub port: Option<String>,
70}
71
72/// The `web-management https` block.
73#[derive(Clone, Debug, PartialEq, Eq)]
74#[non_exhaustive]
75pub struct WebManagementHttps {
76    pub interfaces: Vec<String>,
77    pub port: Option<String>,
78    pub local_certificate: Option<String>,
79    pub pki_local_certificate: Option<String>,
80    pub system_generated_certificate: bool,
81}
82
83/// The `system services web-management` settings.
84#[derive(Clone, Debug, PartialEq, Eq)]
85#[non_exhaustive]
86pub struct WebManagement {
87    /// From `control max-threads`.
88    pub control_max_threads: Option<String>,
89    pub http: Option<WebManagementHttp>,
90    pub https: Option<WebManagementHttps>,
91    pub management_url: Option<String>,
92    /// Minutes, from `session idle-timeout`.
93    pub session_idle_timeout: Option<String>,
94    pub session_limit: Option<String>,
95}
96
97/// The `netconf ssh` block.
98#[derive(Clone, Debug, PartialEq, Eq)]
99#[non_exhaustive]
100pub struct NetconfSsh {
101    pub port: Option<String>,
102    pub connection_limit: Option<String>,
103    pub rate_limit: Option<String>,
104}
105
106/// The `system services netconf` settings.
107#[derive(Clone, Debug, PartialEq, Eq)]
108#[non_exhaustive]
109pub struct Netconf {
110    pub ssh: Option<NetconfSsh>,
111    pub rfc_compliant: bool,
112}
113
114/// The `xnm-clear-text` block.
115#[derive(Clone, Debug, PartialEq, Eq)]
116#[non_exhaustive]
117pub struct XnmClearText {
118    pub connection_limit: Option<String>,
119    pub rate_limit: Option<String>,
120}
121
122/// The `xnm-ssl` block.
123#[derive(Clone, Debug, PartialEq, Eq)]
124#[non_exhaustive]
125pub struct XnmSsl {
126    pub port: Option<String>,
127    pub connection_limit: Option<String>,
128    pub rate_limit: Option<String>,
129    pub local_certificate: Option<String>,
130}
131
132/// The `system services` configuration. Services other than those listed are not extracted.
133#[derive(Clone, Debug, PartialEq, Eq)]
134#[non_exhaustive]
135pub struct Services {
136    pub ssh: Option<SshService>,
137    pub telnet: bool,
138    pub ftp: bool,
139    /// `netconf { ssh; }`.
140    pub netconf_ssh: bool,
141    /// `web-management { http; }`.
142    pub http: bool,
143    /// `web-management { https; }`.
144    pub https: bool,
145    pub outbound_ssh: Vec<OutboundSshClient>,
146    /// The details behind `http` and `https`.
147    pub web_management: Option<WebManagement>,
148    /// The details behind `netconf_ssh`.
149    pub netconf: Option<Netconf>,
150    pub xnm_clear_text: Option<XnmClearText>,
151    pub xnm_ssl: Option<XnmSsl>,
152    pub subscriber_management: Option<SubscriberManagement>,
153    pub static_subscribers: Option<StaticSubscribers>,
154    pub dhcp_local_server: Option<DhcpLocalServer>,
155    pub local_policy_decision_function: Option<LocalPolicyDecisionFunction>,
156}
157
158pub(super) fn parse_services(services: &ConfigLine) -> Services {
159    let web = child_block(services, "web-management");
160    let netconf = child_block(services, "netconf");
161    Services {
162        ssh: child_block(services, "ssh").map(parse_ssh),
163        telnet: child_block(services, "telnet").is_some(),
164        ftp: child_block(services, "ftp").is_some(),
165        netconf_ssh: netconf.is_some_and(|n| child_block(n, "ssh").is_some()),
166        http: web.is_some_and(|w| child_block(w, "http").is_some()),
167        https: web.is_some_and(|w| child_block(w, "https").is_some()),
168        outbound_ssh: child_block(services, "outbound-ssh")
169            .map(|outbound| {
170                named_children(outbound, "client")
171                    .map(|(id, client)| parse_outbound_client(id, client))
172                    .collect()
173            })
174            .unwrap_or_default(),
175        web_management: web.map(parse_web_management),
176        netconf: netconf.map(|netconf| Netconf {
177            ssh: child_block(netconf, "ssh").map(|ssh| NetconfSsh {
178                port: arg_of(ssh, "port").map(str::to_string),
179                connection_limit: arg_of(ssh, "connection-limit").map(str::to_string),
180                rate_limit: arg_of(ssh, "rate-limit").map(str::to_string),
181            }),
182            rfc_compliant: has_leaf(netconf, "rfc-compliant"),
183        }),
184        xnm_clear_text: child_block(services, "xnm-clear-text").map(|xnm| XnmClearText {
185            connection_limit: arg_of(xnm, "connection-limit").map(str::to_string),
186            rate_limit: arg_of(xnm, "rate-limit").map(str::to_string),
187        }),
188        xnm_ssl: child_block(services, "xnm-ssl").map(|xnm| XnmSsl {
189            port: arg_of(xnm, "port").map(str::to_string),
190            connection_limit: arg_of(xnm, "connection-limit").map(str::to_string),
191            rate_limit: arg_of(xnm, "rate-limit").map(str::to_string),
192            local_certificate: arg_of(xnm, "local-certificate").map(str::to_string),
193        }),
194        subscriber_management: child_block(services, "subscriber-management").map(parse_subscriber_management),
195        static_subscribers: child_block(services, "static-subscribers").map(parse_static_subscribers),
196        dhcp_local_server: child_block(services, "dhcp-local-server").map(parse_dhcp_local_server),
197        local_policy_decision_function: child_block(services, "local-policy-decision-function")
198            .map(parse_local_policy_decision_function),
199    }
200}
201
202fn parse_web_management(web: &ConfigLine) -> WebManagement {
203    let interfaces =
204        |block: &ConfigLine| -> Vec<String> { args_of(block, "interface").into_iter().flat_map(list_values).collect() };
205    let session = child_block(web, "session");
206    WebManagement {
207        control_max_threads: statement_words(web, "control").and_then(|words| value_after(&words, "max-threads")),
208        http: child_block(web, "http").map(|http| WebManagementHttp {
209            interfaces: interfaces(http),
210            port: arg_of(http, "port").map(str::to_string),
211        }),
212        https: child_block(web, "https").map(|https| WebManagementHttps {
213            interfaces: interfaces(https),
214            port: arg_of(https, "port").map(str::to_string),
215            local_certificate: arg_of(https, "local-certificate").map(str::to_string),
216            pki_local_certificate: arg_of(https, "pki-local-certificate").map(str::to_string),
217            system_generated_certificate: has_leaf(https, "system-generated-certificate"),
218        }),
219        management_url: arg_of(web, "management-url").map(str::to_string),
220        session_idle_timeout: session.and_then(|s| arg_of(s, "idle-timeout")).map(str::to_string),
221        session_limit: session.and_then(|s| arg_of(s, "session-limit")).map(str::to_string),
222    }
223}
224
225fn parse_outbound_client(id: &str, client: &ConfigLine) -> OutboundSshClient {
226    OutboundSshClient {
227        id: id.to_string(),
228        device_id: arg_of(client, "device-id").map(str::to_string),
229        servers: active_children(client)
230            // Servers are the children written as a bare address; the single-word blocks are other options.
231            .filter(|c| !c.text.contains(' ') && !matches!(c.text.as_str(), "keep-alive" | "proxy-server"))
232            .map(|server| OutboundSshServer {
233                address: server.text.clone(),
234                port: arg_of(server, "port").map(str::to_string),
235                retry: arg_of(server, "retry").map(str::to_string),
236                timeout: arg_of(server, "timeout").map(str::to_string),
237            })
238            .collect(),
239        services: args_of(client, "services").into_iter().flat_map(list_values).collect(),
240        reconnect_strategy: arg_of(client, "reconnect-strategy").map(str::to_string),
241        routing_instance: arg_of(client, "routing-instance").map(str::to_string),
242    }
243}
244
245fn parse_ssh(ssh: &ConfigLine) -> SshService {
246    let list = |keyword: &str| args_of(ssh, keyword).into_iter().flat_map(list_values).collect();
247    let field = |keyword: &str| arg_of(ssh, keyword).map(str::to_string);
248    SshService {
249        root_login: field("root-login"),
250        protocol_versions: list("protocol-version"),
251        port: field("port"),
252        connection_limit: field("connection-limit"),
253        rate_limit: field("rate-limit"),
254        ciphers: list("ciphers"),
255        sftp_server: has_leaf(ssh, "sftp-server"),
256        authentication_order: list("authentication-order"),
257        key_exchange: list("key-exchange"),
258        macs: list("macs"),
259        client_alive_count_max: field("client-alive-count-max"),
260        client_alive_interval: field("client-alive-interval"),
261        fingerprint_hash: field("fingerprint-hash"),
262        max_sessions_per_connection: field("max-sessions-per-connection"),
263        max_pre_authentication_packets: field("max-pre-authentication-packets"),
264        no_challenge_response: has_leaf(ssh, "no-challenge-response"),
265        no_password_authentication: has_leaf(ssh, "no-password-authentication"),
266        no_passwords: has_leaf(ssh, "no-passwords"),
267        no_public_keys: has_leaf(ssh, "no-public-keys"),
268    }
269}
270
271#[cfg(test)]
272mod tests {
273    use super::*;
274    use crate::system::system;
275    use asterust::config::juniper;
276
277    const SERVICES: &str = r#"
278system {
279    services {
280        ssh {
281            root-login deny;
282            protocol-version v2;
283            port 2222;
284            connection-limit 10;
285            rate-limit 5;
286            ciphers [ aes256-ctr aes128-ctr ];
287            sftp-server;
288        }
289        netconf {
290            ssh;
291        }
292        web-management {
293            https {
294                system-generated-certificate;
295            }
296        }
297        telnet;
298    }
299}
300"#;
301
302    #[test]
303    fn extracts_ssh_service_settings() {
304        let services = system(&juniper::parse_braces(SERVICES)).unwrap().services.unwrap();
305        let ssh = services.ssh.unwrap();
306        assert_eq!(ssh.root_login.as_deref(), Some("deny"));
307        assert_eq!(ssh.protocol_versions, ["v2"]);
308        assert_eq!(ssh.port.as_deref(), Some("2222"));
309        assert_eq!(ssh.connection_limit.as_deref(), Some("10"));
310        assert_eq!(ssh.rate_limit.as_deref(), Some("5"));
311        assert_eq!(ssh.ciphers, ["aes256-ctr", "aes128-ctr"]);
312        assert!(ssh.sftp_server);
313    }
314
315    #[test]
316    fn extracts_enabled_services() {
317        let services = system(&juniper::parse_braces(SERVICES)).unwrap().services.unwrap();
318        assert!(services.telnet);
319        assert!(services.netconf_ssh);
320        assert!(services.https);
321        assert!(!services.http);
322        assert!(!services.ftp);
323    }
324
325    #[test]
326    fn bare_service_statements_enable_with_defaults() {
327        let services = system(&juniper::parse_braces(
328            "system {\n    services {\n        ssh;\n        ftp;\n        web-management {\n            http;\n        }\n    }\n}\n",
329        ))
330        .unwrap()
331        .services
332        .unwrap();
333        assert_eq!(services.ssh, Some(SshService::default()));
334        assert!(services.ftp);
335        assert!(services.http);
336        assert!(!services.telnet);
337        assert!(!services.netconf_ssh);
338    }
339
340    #[test]
341    fn disabled_service_is_not_reported() {
342        let services = system(&juniper::parse_braces(
343            "system {\n    services {\n        inactive: telnet;\n        ssh;\n    }\n}\n",
344        ))
345        .unwrap()
346        .services
347        .unwrap();
348        assert!(!services.telnet);
349    }
350
351    #[test]
352    fn extracts_outbound_ssh_clients() {
353        let services = system(&juniper::parse_braces(
354            r#"
355system {
356    services {
357        outbound-ssh {
358            client mgmt {
359                device-id pe1;
360                secret "$9$secret"; ## SECRET-DATA
361                reconnect-strategy sticky;
362                routing-instance mgmt_junos;
363                services netconf;
364                192.0.2.50 {
365                    port 7804;
366                    retry 5;
367                    timeout 20;
368                }
369            }
370            client backup {
371                192.0.2.60;
372                keep-alive {
373                    retry 3;
374                    timeout 15;
375                }
376            }
377        }
378    }
379}
380"#,
381        ))
382        .unwrap()
383        .services
384        .unwrap();
385        assert_eq!(services.outbound_ssh.len(), 2);
386
387        let mgmt = &services.outbound_ssh[0];
388        assert_eq!(mgmt.id, "mgmt");
389        assert_eq!(mgmt.device_id.as_deref(), Some("pe1"));
390        assert_eq!(mgmt.reconnect_strategy.as_deref(), Some("sticky"));
391        assert_eq!(mgmt.routing_instance.as_deref(), Some("mgmt_junos"));
392        assert_eq!(mgmt.services, ["netconf"]);
393        assert_eq!(mgmt.servers.len(), 1);
394        assert_eq!(mgmt.servers[0].address, "192.0.2.50");
395        assert_eq!(mgmt.servers[0].port.as_deref(), Some("7804"));
396        assert_eq!(mgmt.servers[0].retry.as_deref(), Some("5"));
397        assert_eq!(mgmt.servers[0].timeout.as_deref(), Some("20"));
398
399        let backup = &services.outbound_ssh[1];
400        assert_eq!(backup.id, "backup");
401        // `keep-alive` is an option block, not a server.
402        assert_eq!(backup.servers.len(), 1);
403        assert_eq!(backup.servers[0].address, "192.0.2.60");
404        assert_eq!(backup.servers[0].port, None);
405    }
406
407    #[test]
408    fn no_outbound_ssh_is_empty() {
409        let services = system(&juniper::parse_braces(
410            "system {\n    services {\n        ssh;\n    }\n}\n",
411        ))
412        .unwrap()
413        .services
414        .unwrap();
415        assert!(services.outbound_ssh.is_empty());
416    }
417
418    #[test]
419    fn extracts_more_ssh_settings() {
420        let ssh = system(&juniper::parse_braces(
421            r#"
422system {
423    services {
424        ssh {
425            authentication-order [ tacplus password ];
426            key-exchange [ curve25519-sha256 ecdh-sha2-nistp256 ];
427            macs [ hmac-sha2-256 hmac-sha2-512 ];
428            client-alive-count-max 3;
429            client-alive-interval 60;
430            fingerprint-hash sha2-256;
431            max-sessions-per-connection 5;
432            max-pre-authentication-packets 64;
433            no-challenge-response;
434            no-password-authentication;
435            no-public-keys;
436        }
437    }
438}
439"#,
440        ))
441        .unwrap()
442        .services
443        .unwrap()
444        .ssh
445        .unwrap();
446        assert_eq!(ssh.authentication_order, ["tacplus", "password"]);
447        assert_eq!(ssh.key_exchange, ["curve25519-sha256", "ecdh-sha2-nistp256"]);
448        assert_eq!(ssh.macs, ["hmac-sha2-256", "hmac-sha2-512"]);
449        assert_eq!(ssh.client_alive_count_max.as_deref(), Some("3"));
450        assert_eq!(ssh.client_alive_interval.as_deref(), Some("60"));
451        assert_eq!(ssh.fingerprint_hash.as_deref(), Some("sha2-256"));
452        assert_eq!(ssh.max_sessions_per_connection.as_deref(), Some("5"));
453        assert_eq!(ssh.max_pre_authentication_packets.as_deref(), Some("64"));
454        assert!(ssh.no_challenge_response);
455        assert!(ssh.no_password_authentication);
456        assert!(ssh.no_public_keys);
457        assert!(!ssh.no_passwords);
458    }
459
460    #[test]
461    fn extracts_web_management_details() {
462        let web = system(&juniper::parse_braces(
463            r#"
464system {
465    services {
466        web-management {
467            control {
468                max-threads 8;
469            }
470            management-url /manage;
471            http {
472                interface [ fxp0.0 ge-0/0/1.0 ];
473                port 8080;
474            }
475            https {
476                interface fxp0.0;
477                port 8443;
478                pki-local-certificate J-WEB;
479            }
480            session {
481                idle-timeout 20;
482                session-limit 4;
483            }
484        }
485    }
486}
487"#,
488        ))
489        .unwrap()
490        .services
491        .unwrap()
492        .web_management
493        .unwrap();
494        assert_eq!(web.control_max_threads.as_deref(), Some("8"));
495        assert_eq!(web.management_url.as_deref(), Some("/manage"));
496        assert_eq!(web.session_idle_timeout.as_deref(), Some("20"));
497        assert_eq!(web.session_limit.as_deref(), Some("4"));
498
499        let http = web.http.unwrap();
500        assert_eq!(http.interfaces, ["fxp0.0", "ge-0/0/1.0"]);
501        assert_eq!(http.port.as_deref(), Some("8080"));
502
503        let https = web.https.unwrap();
504        assert_eq!(https.interfaces, ["fxp0.0"]);
505        assert_eq!(https.port.as_deref(), Some("8443"));
506        assert_eq!(https.pki_local_certificate.as_deref(), Some("J-WEB"));
507        assert_eq!(https.local_certificate, None);
508        assert!(!https.system_generated_certificate);
509    }
510
511    #[test]
512    fn web_management_with_system_generated_certificate() {
513        let web = system(&juniper::parse_braces(
514            "system {\n    services {\n        web-management {\n            https {\n                system-generated-certificate;\n            }\n        }\n    }\n}\n",
515        ))
516        .unwrap()
517        .services
518        .unwrap()
519        .web_management
520        .unwrap();
521        assert!(web.https.unwrap().system_generated_certificate);
522        assert!(web.http.is_none());
523        assert_eq!(web.control_max_threads, None);
524    }
525
526    #[test]
527    fn extracts_netconf_and_xnm_settings() {
528        let services = system(&juniper::parse_braces(
529            r#"
530system {
531    services {
532        netconf {
533            ssh {
534                port 830;
535                connection-limit 5;
536                rate-limit 10;
537            }
538            rfc-compliant;
539        }
540        xnm-clear-text {
541            connection-limit 3;
542        }
543        xnm-ssl {
544            port 3220;
545            local-certificate XNM;
546            rate-limit 7;
547        }
548    }
549}
550"#,
551        ))
552        .unwrap()
553        .services
554        .unwrap();
555        let netconf = services.netconf.unwrap();
556        assert!(netconf.rfc_compliant);
557        let ssh = netconf.ssh.unwrap();
558        assert_eq!(ssh.port.as_deref(), Some("830"));
559        assert_eq!(ssh.connection_limit.as_deref(), Some("5"));
560        assert_eq!(ssh.rate_limit.as_deref(), Some("10"));
561        assert!(services.netconf_ssh);
562
563        let clear_text = services.xnm_clear_text.unwrap();
564        assert_eq!(clear_text.connection_limit.as_deref(), Some("3"));
565        assert_eq!(clear_text.rate_limit, None);
566
567        let ssl = services.xnm_ssl.unwrap();
568        assert_eq!(ssl.port.as_deref(), Some("3220"));
569        assert_eq!(ssl.local_certificate.as_deref(), Some("XNM"));
570        assert_eq!(ssl.rate_limit.as_deref(), Some("7"));
571    }
572
573    #[test]
574    fn bare_netconf_ssh_has_no_settings() {
575        let netconf = system(&juniper::parse_braces(
576            "system {\n    services {\n        netconf {\n            ssh;\n        }\n    }\n}\n",
577        ))
578        .unwrap()
579        .services
580        .unwrap()
581        .netconf
582        .unwrap();
583        let ssh = netconf.ssh.unwrap();
584        assert_eq!(ssh.port, None);
585        assert!(!netconf.rfc_compliant);
586    }
587
588    #[test]
589    fn no_services_is_none() {
590        assert!(system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n"))
591            .unwrap()
592            .services
593            .is_none());
594    }
595}