1use crate::{
4 active_children, arg_of, args_of, child_block, first_word, has_leaf, list_values, named_children, split_name,
5 top_level, unquote,
6};
7use asterust::config::{Config, ConfigLine};
8
9#[derive(Clone, Debug, PartialEq, Eq)]
11#[non_exhaustive]
12pub struct NameServer {
13 pub address: String,
14 pub routing_instance: Option<String>,
16}
17
18#[derive(Clone, Debug, PartialEq, Eq)]
20#[non_exhaustive]
21pub struct NtpHost {
22 pub address: String,
24 pub key: Option<String>,
26 pub prefer: bool,
27 pub version: Option<String>,
28 pub routing_instance: Option<String>,
29}
30
31#[derive(Clone, Debug, PartialEq, Eq)]
33#[non_exhaustive]
34pub struct NtpAuthenticationKey {
35 pub number: String,
36 pub key_type: Option<String>,
38}
39
40#[derive(Clone, Debug, PartialEq, Eq)]
42#[non_exhaustive]
43pub struct Ntp {
44 pub boot_server: Option<String>,
45 pub servers: Vec<NtpHost>,
46 pub peers: Vec<NtpHost>,
47 pub source_address: Option<String>,
48 pub trusted_keys: Vec<String>,
49 pub authentication_keys: Vec<NtpAuthenticationKey>,
50 pub broadcast_client: bool,
51}
52
53#[derive(Clone, Debug, PartialEq, Eq)]
55#[non_exhaustive]
56pub struct SyslogRule {
57 pub facility: String,
59 pub severity: String,
61}
62
63#[derive(Clone, Debug, PartialEq, Eq)]
65#[non_exhaustive]
66pub struct SyslogHost {
67 pub address: String,
69 pub rules: Vec<SyslogRule>,
70 pub port: Option<String>,
71 pub source_address: Option<String>,
72 pub routing_instance: Option<String>,
73 pub facility_override: Option<String>,
74 pub log_prefix: Option<String>,
75}
76
77#[derive(Clone, Debug, Default, PartialEq, Eq)]
79#[non_exhaustive]
80pub struct SyslogArchive {
81 pub files: Option<String>,
83 pub size: Option<String>,
85 pub world_readable: Option<bool>,
87}
88
89#[derive(Clone, Debug, PartialEq, Eq)]
91#[non_exhaustive]
92pub struct SyslogTarget {
93 pub name: String,
95 pub rules: Vec<SyslogRule>,
96 pub archive: Option<SyslogArchive>,
98}
99
100#[derive(Clone, Debug, PartialEq, Eq)]
102#[non_exhaustive]
103pub struct Syslog {
104 pub hosts: Vec<SyslogHost>,
105 pub files: Vec<SyslogTarget>,
106 pub users: Vec<SyslogTarget>,
107 pub console: Vec<SyslogRule>,
108 pub source_address: Option<String>,
109 pub time_format: Option<String>,
111 pub archive: Option<SyslogArchive>,
113}
114
115#[derive(Clone, Debug, PartialEq, Eq)]
117#[non_exhaustive]
118pub struct LoginClass {
119 pub name: String,
120 pub permissions: Vec<String>,
121 pub idle_timeout: Option<String>,
123 pub allow_commands: Option<String>,
125 pub deny_commands: Option<String>,
126 pub allow_configuration: Option<String>,
127 pub deny_configuration: Option<String>,
128}
129
130#[derive(Clone, Debug, PartialEq, Eq)]
132#[non_exhaustive]
133pub struct LoginUser {
134 pub name: String,
135 pub class: Option<String>,
136 pub uid: Option<String>,
137 pub full_name: Option<String>,
138 pub authentication_methods: Vec<String>,
140}
141
142#[derive(Clone, Debug, PartialEq, Eq)]
144#[non_exhaustive]
145pub struct Login {
146 pub message: Option<String>,
148 pub announcement: Option<String>,
150 pub classes: Vec<LoginClass>,
151 pub users: Vec<LoginUser>,
152}
153
154#[derive(Clone, Debug, Default, PartialEq, Eq)]
156#[non_exhaustive]
157pub struct SshService {
158 pub root_login: Option<String>,
160 pub protocol_versions: Vec<String>,
161 pub port: Option<String>,
162 pub connection_limit: Option<String>,
163 pub rate_limit: Option<String>,
164 pub ciphers: Vec<String>,
165 pub sftp_server: bool,
166}
167
168#[derive(Clone, Debug, PartialEq, Eq)]
170#[non_exhaustive]
171pub struct OutboundSshServer {
172 pub address: String,
173 pub port: Option<String>,
174 pub retry: Option<String>,
175 pub timeout: Option<String>,
176}
177
178#[derive(Clone, Debug, PartialEq, Eq)]
180#[non_exhaustive]
181pub struct OutboundSshClient {
182 pub id: String,
183 pub device_id: Option<String>,
184 pub servers: Vec<OutboundSshServer>,
185 pub services: Vec<String>,
187 pub reconnect_strategy: Option<String>,
189 pub routing_instance: Option<String>,
190}
191
192#[derive(Clone, Debug, PartialEq, Eq)]
194#[non_exhaustive]
195pub struct Services {
196 pub ssh: Option<SshService>,
197 pub telnet: bool,
198 pub ftp: bool,
199 pub netconf_ssh: bool,
201 pub http: bool,
203 pub https: bool,
205 pub outbound_ssh: Vec<OutboundSshClient>,
206}
207
208#[derive(Clone, Debug, PartialEq, Eq)]
210#[non_exhaustive]
211pub struct RootAuthentication {
212 pub methods: Vec<String>,
214}
215
216#[derive(Clone, Debug, PartialEq, Eq)]
218#[non_exhaustive]
219pub struct System {
220 pub host_name: Option<String>,
221 pub domain_name: Option<String>,
222 pub time_zone: Option<String>,
224 pub root_authentication: Option<RootAuthentication>,
225 pub name_servers: Vec<NameServer>,
226 pub ntp: Option<Ntp>,
227 pub syslog: Option<Syslog>,
228 pub login: Option<Login>,
229 pub services: Option<Services>,
230}
231
232pub fn system(config: &Config) -> Option<System> {
234 let system = top_level(config, "system")?;
235 Some(System {
236 host_name: arg_of(system, "host-name").map(str::to_string),
237 domain_name: arg_of(system, "domain-name").map(str::to_string),
238 time_zone: arg_of(system, "time-zone").map(str::to_string),
239 root_authentication: child_block(system, "root-authentication").map(|auth| RootAuthentication {
240 methods: authentication_methods(auth),
241 }),
242 name_servers: name_servers(system),
243 ntp: child_block(system, "ntp").map(parse_ntp),
244 syslog: child_block(system, "syslog").map(parse_syslog),
245 login: child_block(system, "login").map(parse_login),
246 services: child_block(system, "services").map(parse_services),
247 })
248}
249
250fn parse_services(services: &ConfigLine) -> Services {
251 let web = child_block(services, "web-management");
252 let netconf = child_block(services, "netconf");
253 Services {
254 ssh: child_block(services, "ssh").map(parse_ssh),
255 telnet: child_block(services, "telnet").is_some(),
256 ftp: child_block(services, "ftp").is_some(),
257 netconf_ssh: netconf.is_some_and(|n| child_block(n, "ssh").is_some()),
258 http: web.is_some_and(|w| child_block(w, "http").is_some()),
259 https: web.is_some_and(|w| child_block(w, "https").is_some()),
260 outbound_ssh: child_block(services, "outbound-ssh")
261 .map(|outbound| {
262 named_children(outbound, "client")
263 .map(|(id, client)| parse_outbound_client(id, client))
264 .collect()
265 })
266 .unwrap_or_default(),
267 }
268}
269
270fn parse_outbound_client(id: &str, client: &ConfigLine) -> OutboundSshClient {
271 OutboundSshClient {
272 id: id.to_string(),
273 device_id: arg_of(client, "device-id").map(str::to_string),
274 servers: active_children(client)
275 .filter(|c| !c.text.contains(' ') && !matches!(c.text.as_str(), "keep-alive" | "proxy-server"))
277 .map(|server| OutboundSshServer {
278 address: server.text.clone(),
279 port: arg_of(server, "port").map(str::to_string),
280 retry: arg_of(server, "retry").map(str::to_string),
281 timeout: arg_of(server, "timeout").map(str::to_string),
282 })
283 .collect(),
284 services: args_of(client, "services").into_iter().flat_map(list_values).collect(),
285 reconnect_strategy: arg_of(client, "reconnect-strategy").map(str::to_string),
286 routing_instance: arg_of(client, "routing-instance").map(str::to_string),
287 }
288}
289
290fn parse_ssh(ssh: &ConfigLine) -> SshService {
291 let list = |keyword: &str| args_of(ssh, keyword).into_iter().flat_map(list_values).collect();
292 SshService {
293 root_login: arg_of(ssh, "root-login").map(str::to_string),
294 protocol_versions: list("protocol-version"),
295 port: arg_of(ssh, "port").map(str::to_string),
296 connection_limit: arg_of(ssh, "connection-limit").map(str::to_string),
297 rate_limit: arg_of(ssh, "rate-limit").map(str::to_string),
298 ciphers: list("ciphers"),
299 sftp_server: has_leaf(ssh, "sftp-server"),
300 }
301}
302
303fn authentication_methods(auth: &ConfigLine) -> Vec<String> {
306 active_children(auth)
307 .filter_map(|c| c.text.split_whitespace().next())
308 .map(str::to_string)
309 .collect()
310}
311
312fn parse_login(login: &ConfigLine) -> Login {
313 Login {
314 message: arg_of(login, "message").map(str::to_string),
315 announcement: arg_of(login, "announcement").map(str::to_string),
316 classes: named_children(login, "class")
317 .map(|(name, class)| LoginClass {
318 name: name.to_string(),
319 permissions: args_of(class, "permissions")
320 .into_iter()
321 .flat_map(list_values)
322 .collect(),
323 idle_timeout: arg_of(class, "idle-timeout").map(str::to_string),
324 allow_commands: arg_of(class, "allow-commands").map(str::to_string),
325 deny_commands: arg_of(class, "deny-commands").map(str::to_string),
326 allow_configuration: arg_of(class, "allow-configuration").map(str::to_string),
327 deny_configuration: arg_of(class, "deny-configuration").map(str::to_string),
328 })
329 .collect(),
330 users: named_children(login, "user")
331 .map(|(name, user)| LoginUser {
332 name: name.to_string(),
333 class: arg_of(user, "class").map(str::to_string),
334 uid: arg_of(user, "uid").map(str::to_string),
335 full_name: arg_of(user, "full-name").map(str::to_string),
336 authentication_methods: child_block(user, "authentication")
337 .map(authentication_methods)
338 .unwrap_or_default(),
339 })
340 .collect(),
341 }
342}
343
344fn parse_syslog(syslog: &ConfigLine) -> Syslog {
345 Syslog {
346 hosts: named_children(syslog, "host")
347 .map(|(address, host)| SyslogHost {
348 address: address.to_string(),
349 rules: syslog_rules(host),
350 port: arg_of(host, "port").map(str::to_string),
351 source_address: arg_of(host, "source-address").map(str::to_string),
352 routing_instance: arg_of(host, "routing-instance").map(str::to_string),
353 facility_override: arg_of(host, "facility-override").map(str::to_string),
354 log_prefix: arg_of(host, "log-prefix").map(str::to_string),
355 })
356 .collect(),
357 files: syslog_targets(syslog, "file"),
358 users: syslog_targets(syslog, "user"),
359 console: child_block(syslog, "console").map(syslog_rules).unwrap_or_default(),
360 source_address: arg_of(syslog, "source-address").map(str::to_string),
361 time_format: arg_of(syslog, "time-format").map(str::to_string),
362 archive: syslog_archive(syslog),
363 }
364}
365
366fn syslog_targets(syslog: &ConfigLine, keyword: &str) -> Vec<SyslogTarget> {
367 named_children(syslog, keyword)
368 .map(|(name, target)| SyslogTarget {
369 name: name.to_string(),
370 rules: syslog_rules(target),
371 archive: syslog_archive(target),
372 })
373 .collect()
374}
375
376fn syslog_archive(parent: &ConfigLine) -> Option<SyslogArchive> {
378 let archive = active_children(parent).find(|c| c.text == "archive" || c.arg("archive").is_some())?;
379 let mut words = archive
381 .text
382 .split_whitespace()
383 .skip(1)
384 .chain(active_children(archive).flat_map(|c| c.text.split_whitespace()));
385 let mut settings = SyslogArchive::default();
386 while let Some(word) = words.next() {
387 match word {
388 "files" => settings.files = words.next().map(str::to_string),
389 "size" => settings.size = words.next().map(str::to_string),
390 "world-readable" => settings.world_readable = Some(true),
391 "no-world-readable" => settings.world_readable = Some(false),
392 _ => {}
393 }
394 }
395 Some(settings)
396}
397
398fn syslog_rules(destination: &ConfigLine) -> Vec<SyslogRule> {
400 const SEVERITIES: [&str; 10] = [
401 "any",
402 "none",
403 "emergency",
404 "alert",
405 "critical",
406 "error",
407 "warning",
408 "notice",
409 "info",
410 "debug",
411 ];
412 active_children(destination)
413 .filter_map(|c| {
414 let (facility, severity) = c.text.split_once(' ')?;
415 SEVERITIES.contains(&severity).then(|| SyslogRule {
416 facility: facility.to_string(),
417 severity: severity.to_string(),
418 })
419 })
420 .collect()
421}
422
423fn parse_ntp(ntp: &ConfigLine) -> Ntp {
424 let hosts = |keyword: &str| -> Vec<NtpHost> {
425 active_children(ntp)
426 .filter_map(|c| Some(ntp_host(c.arg(keyword)?, c)))
427 .collect()
428 };
429 Ntp {
430 boot_server: arg_of(ntp, "boot-server").map(str::to_string),
431 servers: hosts("server"),
432 peers: hosts("peer"),
433 source_address: arg_of(ntp, "source-address").and_then(first_word).map(str::to_string),
434 trusted_keys: args_of(ntp, "trusted-key").into_iter().flat_map(list_values).collect(),
435 authentication_keys: args_of(ntp, "authentication-key")
436 .into_iter()
437 .filter_map(ntp_authentication_key)
438 .collect(),
439 broadcast_client: has_leaf(ntp, "broadcast-client"),
440 }
441}
442
443fn ntp_host(arg: &str, line: &ConfigLine) -> NtpHost {
446 let (address, options) = split_name(arg);
447 let mut words = options.split_whitespace();
448 let mut host = NtpHost {
449 address: address.to_string(),
450 key: arg_of(line, "key").map(str::to_string),
451 prefer: has_leaf(line, "prefer"),
452 version: arg_of(line, "version").map(str::to_string),
453 routing_instance: arg_of(line, "routing-instance").map(str::to_string),
454 };
455 while let Some(word) = words.next() {
456 match word {
457 "prefer" => host.prefer = true,
458 "key" => host.key = words.next().map(str::to_string),
459 "version" => host.version = words.next().map(str::to_string),
460 "routing-instance" => host.routing_instance = words.next().map(str::to_string),
461 _ => {}
462 }
463 }
464 host
465}
466
467fn ntp_authentication_key(arg: &str) -> Option<NtpAuthenticationKey> {
469 let mut words = arg.split_whitespace();
470 let number = words.next()?.to_string();
471 let key_type = words.skip_while(|w| *w != "type").nth(1).map(str::to_string);
472 Some(NtpAuthenticationKey { number, key_type })
473}
474
475fn name_servers(system: &ConfigLine) -> Vec<NameServer> {
477 let mut found = Vec::new();
478 for child in active_children(system) {
479 if child.text == "name-server" {
480 found.extend(active_children(child).map(|server| name_server(&server.text, server)));
481 } else if let Some(address) = child.arg("name-server") {
482 found.push(name_server(address, child));
483 }
484 }
485 found
486}
487
488fn name_server(address: &str, line: &ConfigLine) -> NameServer {
489 NameServer {
490 address: unquote(address).to_string(),
491 routing_instance: arg_of(line, "routing-instance").map(str::to_string),
492 }
493}
494
495#[cfg(test)]
496mod tests {
497 use super::*;
498 use asterust::config::juniper;
499
500 #[test]
502 fn extracts_host_name() {
503 let system = system(&juniper::parse_braces("system {\n host-name pe1;\n}\n")).unwrap();
504 assert_eq!(system.host_name.as_deref(), Some("pe1"));
505 }
506
507 #[test]
508 fn host_name_is_optional() {
509 let system = system(&juniper::parse_braces("system {\n domain-name example.net;\n}\n")).unwrap();
510 assert_eq!(system.host_name, None);
511 }
512
513 #[test]
514 fn skips_inactive_host_name() {
515 let system = system(&juniper::parse_braces("system {\n inactive: host-name pe1;\n}\n")).unwrap();
516 assert_eq!(system.host_name, None);
517 }
518
519 #[test]
520 fn extracts_name_server_block() {
521 let system = system(&juniper::parse_braces(
522 "system {\n name-server {\n 192.0.2.53;\n 2001:db8::53;\n }\n}\n",
523 ))
524 .unwrap();
525 let addresses: Vec<_> = system.name_servers.iter().map(|s| s.address.as_str()).collect();
526 assert_eq!(addresses, ["192.0.2.53", "2001:db8::53"]);
527 assert_eq!(system.name_servers[0].routing_instance, None);
528 }
529
530 #[test]
531 fn name_server_in_management_instance() {
532 let system = system(&juniper::parse_braces(
533 "system {\n name-server {\n 192.0.2.53 {\n routing-instance mgmt_junos;\n }\n }\n}\n",
534 ))
535 .unwrap();
536 assert_eq!(system.name_servers[0].address, "192.0.2.53");
537 assert_eq!(system.name_servers[0].routing_instance.as_deref(), Some("mgmt_junos"));
538 }
539
540 #[test]
541 fn extracts_one_line_name_servers_and_skips_inactive() {
542 let system = system(&juniper::parse_braces(
543 "system {\n name-server 192.0.2.53;\n name-server 192.0.2.54;\n inactive: name-server 192.0.2.55;\n}\n",
544 ))
545 .unwrap();
546 let addresses: Vec<_> = system.name_servers.iter().map(|s| s.address.as_str()).collect();
547 assert_eq!(addresses, ["192.0.2.53", "192.0.2.54"]);
548 }
549
550 const NTP: &str = r#"
551system {
552 ntp {
553 boot-server 192.0.2.10;
554 source-address 192.0.2.1;
555 authentication-key 1 type md5 value "$9$secret";
556 authentication-key 2 type sha256 value "$9$other";
557 trusted-key [ 1 2 ];
558 server 192.0.2.10 key 1 prefer version 4;
559 server 192.0.2.11;
560 server ntp.example.net {
561 key 2;
562 prefer;
563 version 3;
564 routing-instance mgmt_junos;
565 }
566 inactive: server 192.0.2.12;
567 peer 192.0.2.20 key 1;
568 broadcast-client;
569 }
570}
571"#;
572
573 #[test]
574 fn extracts_ntp_servers_in_line_and_block_form() {
575 let ntp = system(&juniper::parse_braces(NTP)).unwrap().ntp.unwrap();
576 let addresses: Vec<_> = ntp.servers.iter().map(|s| s.address.as_str()).collect();
577 assert_eq!(addresses, ["192.0.2.10", "192.0.2.11", "ntp.example.net"]);
578
579 let line = &ntp.servers[0];
580 assert_eq!(line.key.as_deref(), Some("1"));
581 assert!(line.prefer);
582 assert_eq!(line.version.as_deref(), Some("4"));
583
584 assert_eq!(ntp.servers[1].key, None);
585 assert!(!ntp.servers[1].prefer);
586
587 let block = &ntp.servers[2];
588 assert_eq!(block.key.as_deref(), Some("2"));
589 assert!(block.prefer);
590 assert_eq!(block.version.as_deref(), Some("3"));
591 assert_eq!(block.routing_instance.as_deref(), Some("mgmt_junos"));
592 }
593
594 #[test]
595 fn extracts_ntp_peers_keys_and_global_settings() {
596 let ntp = system(&juniper::parse_braces(NTP)).unwrap().ntp.unwrap();
597 assert_eq!(ntp.peers.len(), 1);
598 assert_eq!(ntp.peers[0].address, "192.0.2.20");
599 assert_eq!(ntp.peers[0].key.as_deref(), Some("1"));
600 assert_eq!(ntp.boot_server.as_deref(), Some("192.0.2.10"));
601 assert_eq!(ntp.source_address.as_deref(), Some("192.0.2.1"));
602 assert_eq!(ntp.trusted_keys, ["1", "2"]);
603 assert!(ntp.broadcast_client);
604 }
605
606 #[test]
607 fn ntp_authentication_keys_omit_the_secret() {
608 let ntp = system(&juniper::parse_braces(NTP)).unwrap().ntp.unwrap();
609 assert_eq!(ntp.authentication_keys.len(), 2);
610 assert_eq!(ntp.authentication_keys[0].number, "1");
611 assert_eq!(ntp.authentication_keys[0].key_type.as_deref(), Some("md5"));
612 assert_eq!(ntp.authentication_keys[1].key_type.as_deref(), Some("sha256"));
613 }
614
615 #[test]
616 fn no_ntp_is_none() {
617 assert!(system(&juniper::parse_braces("system {\n host-name pe1;\n}\n"))
618 .unwrap()
619 .ntp
620 .is_none());
621 }
622
623 const SYSLOG: &str = r#"
624system {
625 syslog {
626 user * {
627 any emergency;
628 }
629 host 192.0.2.5 {
630 any notice;
631 authorization info;
632 port 514;
633 source-address 192.0.2.1;
634 routing-instance mgmt_junos;
635 facility-override local3;
636 log-prefix pe1;
637 }
638 host other-routing-engine {
639 any critical;
640 }
641 file messages {
642 any notice;
643 authorization info;
644 explicit-priority;
645 }
646 file interactive-commands {
647 interactive-commands any;
648 }
649 inactive: file debug {
650 any debug;
651 }
652 console {
653 any critical;
654 }
655 source-address 192.0.2.1;
656 time-format year millisecond;
657 }
658}
659"#;
660
661 #[test]
662 fn extracts_syslog_hosts() {
663 let syslog = system(&juniper::parse_braces(SYSLOG)).unwrap().syslog.unwrap();
664 let addresses: Vec<_> = syslog.hosts.iter().map(|h| h.address.as_str()).collect();
665 assert_eq!(addresses, ["192.0.2.5", "other-routing-engine"]);
666
667 let host = &syslog.hosts[0];
668 assert_eq!(host.rules.len(), 2);
669 assert_eq!(host.rules[1].facility, "authorization");
670 assert_eq!(host.rules[1].severity, "info");
671 assert_eq!(host.port.as_deref(), Some("514"));
672 assert_eq!(host.source_address.as_deref(), Some("192.0.2.1"));
673 assert_eq!(host.routing_instance.as_deref(), Some("mgmt_junos"));
674 assert_eq!(host.facility_override.as_deref(), Some("local3"));
675 assert_eq!(host.log_prefix.as_deref(), Some("pe1"));
676 }
677
678 #[test]
679 fn extracts_syslog_files_users_and_console() {
680 let syslog = system(&juniper::parse_braces(SYSLOG)).unwrap().syslog.unwrap();
681
682 let files: Vec<_> = syslog.files.iter().map(|f| f.name.as_str()).collect();
683 assert_eq!(files, ["messages", "interactive-commands"]);
684 assert_eq!(syslog.files[0].rules.len(), 2);
686 assert_eq!(syslog.files[1].rules[0].facility, "interactive-commands");
687 assert_eq!(syslog.files[1].rules[0].severity, "any");
688
689 assert_eq!(syslog.users[0].name, "*");
690 assert_eq!(syslog.users[0].rules[0].severity, "emergency");
691 assert_eq!(syslog.console[0].facility, "any");
692 assert_eq!(syslog.console[0].severity, "critical");
693 }
694
695 #[test]
696 fn extracts_syslog_global_settings() {
697 let syslog = system(&juniper::parse_braces(SYSLOG)).unwrap().syslog.unwrap();
698 assert_eq!(syslog.source_address.as_deref(), Some("192.0.2.1"));
699 assert_eq!(syslog.time_format.as_deref(), Some("year millisecond"));
700 }
701
702 #[test]
703 fn extracts_syslog_archive_in_line_and_block_form() {
704 let syslog = system(&juniper::parse_braces(
705 r#"
706system {
707 syslog {
708 archive {
709 files 20;
710 size 5m;
711 world-readable;
712 }
713 file messages {
714 any notice;
715 archive size 100k files 10 no-world-readable;
716 }
717 file plain {
718 any info;
719 }
720 }
721}
722"#,
723 ))
724 .unwrap()
725 .syslog
726 .unwrap();
727
728 let default = syslog.archive.unwrap();
729 assert_eq!(default.files.as_deref(), Some("20"));
730 assert_eq!(default.size.as_deref(), Some("5m"));
731 assert_eq!(default.world_readable, Some(true));
732
733 let messages = syslog.files[0].archive.as_ref().unwrap();
734 assert_eq!(messages.files.as_deref(), Some("10"));
735 assert_eq!(messages.size.as_deref(), Some("100k"));
736 assert_eq!(messages.world_readable, Some(false));
737
738 assert_eq!(syslog.files[1].archive, None);
739 }
740
741 #[test]
742 fn no_syslog_is_none() {
743 assert!(system(&juniper::parse_braces("system {\n host-name pe1;\n}\n"))
744 .unwrap()
745 .syslog
746 .is_none());
747 }
748
749 const LOGIN: &str = r#"
750system {
751 login {
752 message "Authorized access only";
753 announcement "Maintenance window Sunday";
754 class NOC {
755 permissions [ view view-configuration ];
756 idle-timeout 15;
757 allow-commands "(ping)|(traceroute)";
758 deny-configuration ".*";
759 }
760 class OPS {
761 permissions all;
762 deny-commands "(request system)";
763 allow-configuration "(interfaces)|(protocols)";
764 }
765 user admin {
766 uid 2000;
767 class super-user;
768 full-name "Network Admin";
769 authentication {
770 encrypted-password "$6$salt$hash"; ## SECRET-DATA
771 ssh-ed25519 "ssh-ed25519 AAAAC3Nza admin@host"; ## SECRET-DATA
772 }
773 }
774 user monitor {
775 class NOC;
776 }
777 }
778}
779"#;
780
781 #[test]
782 fn extracts_login_banner_and_classes() {
783 let login = system(&juniper::parse_braces(LOGIN)).unwrap().login.unwrap();
784 assert_eq!(login.message.as_deref(), Some("Authorized access only"));
785 assert_eq!(login.announcement.as_deref(), Some("Maintenance window Sunday"));
786
787 assert_eq!(login.classes.len(), 2);
788 let noc = &login.classes[0];
789 assert_eq!(noc.name, "NOC");
790 assert_eq!(noc.permissions, ["view", "view-configuration"]);
791 assert_eq!(noc.idle_timeout.as_deref(), Some("15"));
792 assert_eq!(noc.allow_commands.as_deref(), Some("(ping)|(traceroute)"));
793 assert_eq!(noc.deny_configuration.as_deref(), Some(".*"));
794 assert_eq!(noc.deny_commands, None);
795
796 let ops = &login.classes[1];
797 assert_eq!(ops.permissions, ["all"]);
798 assert_eq!(ops.deny_commands.as_deref(), Some("(request system)"));
799 assert_eq!(ops.allow_configuration.as_deref(), Some("(interfaces)|(protocols)"));
800 }
801
802 #[test]
803 fn extracts_login_users_without_secrets() {
804 let login = system(&juniper::parse_braces(LOGIN)).unwrap().login.unwrap();
805 assert_eq!(login.users.len(), 2);
806
807 let admin = &login.users[0];
808 assert_eq!(admin.name, "admin");
809 assert_eq!(admin.class.as_deref(), Some("super-user"));
810 assert_eq!(admin.uid.as_deref(), Some("2000"));
811 assert_eq!(admin.full_name.as_deref(), Some("Network Admin"));
812 assert_eq!(admin.authentication_methods, ["encrypted-password", "ssh-ed25519"]);
813
814 let monitor = &login.users[1];
815 assert_eq!(monitor.class.as_deref(), Some("NOC"));
816 assert!(monitor.authentication_methods.is_empty());
817 }
818
819 #[test]
820 fn no_login_is_none() {
821 assert!(system(&juniper::parse_braces("system {\n host-name pe1;\n}\n"))
822 .unwrap()
823 .login
824 .is_none());
825 }
826
827 const SERVICES: &str = r#"
828system {
829 services {
830 ssh {
831 root-login deny;
832 protocol-version v2;
833 port 2222;
834 connection-limit 10;
835 rate-limit 5;
836 ciphers [ aes256-ctr aes128-ctr ];
837 sftp-server;
838 }
839 netconf {
840 ssh;
841 }
842 web-management {
843 https {
844 system-generated-certificate;
845 }
846 }
847 telnet;
848 }
849}
850"#;
851
852 #[test]
853 fn extracts_ssh_service_settings() {
854 let services = system(&juniper::parse_braces(SERVICES)).unwrap().services.unwrap();
855 let ssh = services.ssh.unwrap();
856 assert_eq!(ssh.root_login.as_deref(), Some("deny"));
857 assert_eq!(ssh.protocol_versions, ["v2"]);
858 assert_eq!(ssh.port.as_deref(), Some("2222"));
859 assert_eq!(ssh.connection_limit.as_deref(), Some("10"));
860 assert_eq!(ssh.rate_limit.as_deref(), Some("5"));
861 assert_eq!(ssh.ciphers, ["aes256-ctr", "aes128-ctr"]);
862 assert!(ssh.sftp_server);
863 }
864
865 #[test]
866 fn extracts_enabled_services() {
867 let services = system(&juniper::parse_braces(SERVICES)).unwrap().services.unwrap();
868 assert!(services.telnet);
869 assert!(services.netconf_ssh);
870 assert!(services.https);
871 assert!(!services.http);
872 assert!(!services.ftp);
873 }
874
875 #[test]
876 fn bare_service_statements_enable_with_defaults() {
877 let services = system(&juniper::parse_braces(
878 "system {\n services {\n ssh;\n ftp;\n web-management {\n http;\n }\n }\n}\n",
879 ))
880 .unwrap()
881 .services
882 .unwrap();
883 assert_eq!(services.ssh, Some(SshService::default()));
884 assert!(services.ftp);
885 assert!(services.http);
886 assert!(!services.telnet);
887 assert!(!services.netconf_ssh);
888 }
889
890 #[test]
891 fn disabled_service_is_not_reported() {
892 let services = system(&juniper::parse_braces(
893 "system {\n services {\n inactive: telnet;\n ssh;\n }\n}\n",
894 ))
895 .unwrap()
896 .services
897 .unwrap();
898 assert!(!services.telnet);
899 }
900
901 #[test]
902 fn extracts_outbound_ssh_clients() {
903 let services = system(&juniper::parse_braces(
904 r#"
905system {
906 services {
907 outbound-ssh {
908 client mgmt {
909 device-id pe1;
910 secret "$9$secret"; ## SECRET-DATA
911 reconnect-strategy sticky;
912 routing-instance mgmt_junos;
913 services netconf;
914 192.0.2.50 {
915 port 7804;
916 retry 5;
917 timeout 20;
918 }
919 }
920 client backup {
921 192.0.2.60;
922 keep-alive {
923 retry 3;
924 timeout 15;
925 }
926 }
927 }
928 }
929}
930"#,
931 ))
932 .unwrap()
933 .services
934 .unwrap();
935 assert_eq!(services.outbound_ssh.len(), 2);
936
937 let mgmt = &services.outbound_ssh[0];
938 assert_eq!(mgmt.id, "mgmt");
939 assert_eq!(mgmt.device_id.as_deref(), Some("pe1"));
940 assert_eq!(mgmt.reconnect_strategy.as_deref(), Some("sticky"));
941 assert_eq!(mgmt.routing_instance.as_deref(), Some("mgmt_junos"));
942 assert_eq!(mgmt.services, ["netconf"]);
943 assert_eq!(mgmt.servers.len(), 1);
944 assert_eq!(mgmt.servers[0].address, "192.0.2.50");
945 assert_eq!(mgmt.servers[0].port.as_deref(), Some("7804"));
946 assert_eq!(mgmt.servers[0].retry.as_deref(), Some("5"));
947 assert_eq!(mgmt.servers[0].timeout.as_deref(), Some("20"));
948
949 let backup = &services.outbound_ssh[1];
950 assert_eq!(backup.id, "backup");
951 assert_eq!(backup.servers.len(), 1);
953 assert_eq!(backup.servers[0].address, "192.0.2.60");
954 assert_eq!(backup.servers[0].port, None);
955 }
956
957 #[test]
958 fn no_outbound_ssh_is_empty() {
959 let services = system(&juniper::parse_braces(
960 "system {\n services {\n ssh;\n }\n}\n",
961 ))
962 .unwrap()
963 .services
964 .unwrap();
965 assert!(services.outbound_ssh.is_empty());
966 }
967
968 #[test]
969 fn no_services_is_none() {
970 assert!(system(&juniper::parse_braces("system {\n host-name pe1;\n}\n"))
971 .unwrap()
972 .services
973 .is_none());
974 }
975
976 #[test]
977 fn extracts_domain_name() {
978 let system = system(&juniper::parse_braces(
979 "system {\n host-name pe1;\n domain-name example.net;\n}\n",
980 ))
981 .unwrap();
982 assert_eq!(system.domain_name.as_deref(), Some("example.net"));
983 }
984
985 #[test]
986 fn domain_name_is_optional() {
987 let system = system(&juniper::parse_braces("system {\n host-name pe1;\n}\n")).unwrap();
988 assert_eq!(system.domain_name, None);
989 }
990
991 #[test]
992 fn extracts_time_zone() {
993 let system = system(&juniper::parse_braces("system {\n time-zone America/New_York;\n}\n")).unwrap();
994 assert_eq!(system.time_zone.as_deref(), Some("America/New_York"));
995 }
996
997 #[test]
998 fn time_zone_is_optional() {
999 let system = system(&juniper::parse_braces("system {\n host-name pe1;\n}\n")).unwrap();
1000 assert_eq!(system.time_zone, None);
1001 }
1002
1003 #[test]
1004 fn extracts_root_authentication_methods_without_secrets() {
1005 let system = system(&juniper::parse_braces(
1006 r#"
1007system {
1008 root-authentication {
1009 encrypted-password "$6$salt$hash"; ## SECRET-DATA
1010 ssh-rsa "ssh-rsa AAAAB3Nza root@host"; ## SECRET-DATA
1011 ssh-rsa "ssh-rsa AAAAB3Nzb ops@host" {
1012 from 192.0.2.0/24;
1013 }
1014 }
1015}
1016"#,
1017 ))
1018 .unwrap();
1019 let root = system.root_authentication.unwrap();
1020 assert_eq!(root.methods, ["encrypted-password", "ssh-rsa", "ssh-rsa"]);
1021 }
1022
1023 #[test]
1024 fn root_authentication_can_disable_public_keys() {
1025 let system = system(&juniper::parse_braces(
1026 "system {\n root-authentication {\n no-public-keys;\n }\n}\n",
1027 ))
1028 .unwrap();
1029 assert_eq!(system.root_authentication.unwrap().methods, ["no-public-keys"]);
1030 }
1031
1032 #[test]
1033 fn no_root_authentication_is_none() {
1034 let system = system(&juniper::parse_braces("system {\n host-name pe1;\n}\n")).unwrap();
1035 assert!(system.root_authentication.is_none());
1036 }
1037
1038 #[test]
1039 fn no_system_is_none() {
1040 assert!(system(&juniper::parse_braces("interfaces {\n lo0;\n}\n")).is_none());
1041 }
1042}