Skip to main content

asterust_junos/system/
services.rs

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