Skip to main content

asterust_junos/system/
services.rs

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