bssh 2.1.2

Parallel SSH command execution tool for cluster management
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
// Copyright 2025 Lablup Inc. and Jeongkyu Shin
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! SSH configuration parsing and management
//!
//! This module provides functionality to parse SSH configuration files, resolve host-specific
//! configurations, and provide a clean API for SSH connection setup.

use anyhow::{Context, Result};
use std::path::{Path, PathBuf};

// Internal modules
mod env_cache;
mod include;
#[cfg(test)]
mod integration_tests;
mod match_directive;
mod parser;
mod path;
mod pattern;
mod resolver;
#[cfg(test)]
mod resolver_tests;
mod security;
#[cfg(test)]
mod security_fix_tests;
mod types;

// Re-export public types
pub use types::SshHostConfig;

/// SSH configuration parser and resolver
#[derive(Debug, Clone, Default)]
pub struct SshConfig {
    pub hosts: Vec<SshHostConfig>,
}

impl SshConfig {
    /// Create a new empty SSH configuration
    pub fn new() -> Self {
        Self::default()
    }

    /// Load SSH configuration from a file with Include support
    pub async fn load_from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
        let path = path.as_ref();
        let content = tokio::fs::read_to_string(path)
            .await
            .with_context(|| format!("Failed to read SSH config file: {}", path.display()))?;

        Self::parse_from_file_with_content(path, &content)
            .await
            .with_context(|| format!("Failed to parse SSH config file: {}", path.display()))
    }

    /// Load SSH configuration from a file with caching
    /// Uses the global cache to improve performance for repeated access
    pub async fn load_from_file_cached<P: AsRef<Path>>(path: P) -> Result<Self> {
        crate::ssh::GLOBAL_CACHE.get_or_load(path).await
    }

    /// Load SSH configuration from the default locations
    pub async fn load_default() -> Result<Self> {
        // Try user-specific SSH config first
        if let Some(home_dir) = dirs::home_dir() {
            let user_config = home_dir.join(".ssh").join("config");
            if tokio::fs::try_exists(&user_config).await.unwrap_or(false) {
                return Self::load_from_file(&user_config).await;
            }
        }

        // Try system-wide SSH config
        let system_config = Path::new("/etc/ssh/ssh_config");
        if tokio::fs::try_exists(system_config).await.unwrap_or(false) {
            return Self::load_from_file(system_config).await;
        }

        // Return empty config if no files found
        Ok(Self::new())
    }

    /// Load SSH configuration from the default locations with caching
    /// Uses the global cache to improve performance for repeated access
    pub async fn load_default_cached() -> Result<Self> {
        crate::ssh::GLOBAL_CACHE.load_default().await
    }

    /// Parse SSH configuration from a string (without Include support)
    pub fn parse(content: &str) -> Result<Self> {
        let hosts = parser::parse(content)?;
        Ok(Self { hosts })
    }

    /// Parse SSH configuration from a file with Include support
    pub async fn parse_from_file_with_content(path: &Path, content: &str) -> Result<Self> {
        let hosts = parser::parse_from_file(path, content).await?;
        Ok(Self { hosts })
    }

    /// Find configuration for a specific hostname
    pub fn find_host_config(&self, hostname: &str) -> SshHostConfig {
        resolver::find_host_config(&self.hosts, hostname)
    }

    /// Get the effective hostname (resolves HostName directive)
    pub fn get_effective_hostname(&self, hostname: &str) -> String {
        resolver::get_effective_hostname(&self.hosts, hostname)
    }

    /// Get the effective username
    pub fn get_effective_user(&self, hostname: &str, cli_user: Option<&str>) -> Option<String> {
        resolver::get_effective_user(&self.hosts, hostname, cli_user)
    }

    /// Get the effective port
    pub fn get_effective_port(&self, hostname: &str, cli_port: Option<u16>) -> u16 {
        resolver::get_effective_port(&self.hosts, hostname, cli_port)
    }

    /// Get identity files for a hostname
    pub fn get_identity_files(&self, hostname: &str) -> Vec<PathBuf> {
        resolver::get_identity_files(&self.hosts, hostname)
    }

    /// Get the effective StrictHostKeyChecking value
    pub fn get_strict_host_key_checking(&self, hostname: &str) -> Option<String> {
        resolver::get_strict_host_key_checking(&self.hosts, hostname)
    }

    /// Get ProxyJump configuration
    pub fn get_proxy_jump(&self, hostname: &str) -> Option<String> {
        resolver::get_proxy_jump(&self.hosts, hostname)
    }

    /// Get an integer option value for a hostname.
    ///
    /// Currently supports:
    /// - `serveraliveinterval` - Keepalive interval in seconds
    /// - `serveralivecountmax` - Maximum keepalive messages before disconnect
    ///
    /// Option names are case-insensitive.
    pub fn get_int_option(&self, hostname: Option<&str>, option: &str) -> Option<i64> {
        let hostname = hostname.unwrap_or("*");
        let config = self.find_host_config(hostname);

        match option.to_lowercase().as_str() {
            "serveraliveinterval" => config.server_alive_interval.map(|v| v as i64),
            "serveralivecountmax" => config.server_alive_count_max.map(|v| v as i64),
            _ => None,
        }
    }

    /// Get all host configurations (for debugging)
    pub fn get_all_configs(&self) -> &[SshHostConfig] {
        &self.hosts
    }

    /// Resolve jump host parameters from an SSH config Host alias.
    ///
    /// This method looks up a Host alias in the SSH config and extracts
    /// the connection parameters needed for a jump host connection.
    ///
    /// # Arguments
    /// * `host_alias` - The Host alias to look up (e.g., "bastion" from `Host bastion`)
    ///
    /// # Returns
    /// A tuple of (hostname, user, port, identity_file) if the alias is found,
    /// or None if the alias doesn't exist or has no configuration.
    ///
    /// # Example
    /// For SSH config:
    /// ```text
    /// Host bastion
    ///     HostName bastion.example.com
    ///     User jumpuser
    ///     Port 2222
    ///     IdentityFile ~/.ssh/bastion_key
    /// ```
    ///
    /// `resolve_jump_host("bastion")` returns:
    /// `Some(("bastion.example.com", Some("jumpuser"), Some(2222), Some("~/.ssh/bastion_key")))`
    #[allow(clippy::type_complexity)]
    pub fn resolve_jump_host(
        &self,
        host_alias: &str,
    ) -> Option<(String, Option<String>, Option<u16>, Option<String>)> {
        let config = self.find_host_config(host_alias);

        // Get the effective hostname (HostName directive or the alias itself)
        let hostname = config
            .hostname
            .clone()
            .unwrap_or_else(|| host_alias.to_string());

        // If no configuration was found (empty config), return None
        // This happens when the alias doesn't match any Host pattern
        if config.hostname.is_none()
            && config.user.is_none()
            && config.port.is_none()
            && config.identity_files.is_empty()
        {
            // Check if there's at least a matching host pattern
            // If not, this alias doesn't exist in SSH config
            let has_matching_pattern = self
                .hosts
                .iter()
                .any(|h| h.host_patterns.iter().any(|p| p == host_alias || p == "*"));

            if !has_matching_pattern {
                return None;
            }
        }

        // Get the first identity file if available
        let identity_file = config
            .identity_files
            .first()
            .map(|p| p.to_string_lossy().to_string());

        Some((hostname, config.user, config.port, identity_file))
    }

    /// Resolve jump host to a connection string with SSH key.
    ///
    /// This is a convenience method that resolves an SSH config Host alias
    /// and returns the information in a format suitable for jump host connection.
    ///
    /// # Arguments
    /// * `host_alias` - The Host alias to look up
    ///
    /// # Returns
    /// A tuple of (connection_string, optional_ssh_key_path) where:
    /// - `connection_string` is in format `[user@]hostname[:port]`
    /// - `optional_ssh_key_path` is the first IdentityFile if specified
    pub fn resolve_jump_host_connection(
        &self,
        host_alias: &str,
    ) -> Option<(String, Option<String>)> {
        let (hostname, user, port, identity_file) = self.resolve_jump_host(host_alias)?;

        let mut conn_str = String::new();
        if let Some(u) = user {
            conn_str.push_str(&u);
            conn_str.push('@');
        }
        conn_str.push_str(&hostname);
        if let Some(p) = port {
            conn_str.push(':');
            conn_str.push_str(&p.to_string());
        }

        Some((conn_str, identity_file))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[test]
    fn test_parse_basic_host_config() {
        let config_content = r#"
Host example.com
    User testuser
    Port 2222
    IdentityFile ~/.ssh/test_key
"#;

        let config = SshConfig::parse(config_content).unwrap();
        assert_eq!(config.hosts.len(), 1);

        let host = &config.hosts[0];
        assert_eq!(host.host_patterns, vec!["example.com"]);
        assert_eq!(host.user, Some("testuser".to_string()));
        assert_eq!(host.port, Some(2222));
        assert_eq!(host.identity_files.len(), 1);
    }

    #[test]
    fn test_parse_multiple_hosts() {
        let config_content = r#"
Host web*.example.com
    User webuser
    Port 22

Host db*.example.com
    User dbuser
    Port 5432
"#;

        let config = SshConfig::parse(config_content).unwrap();
        assert_eq!(config.hosts.len(), 2);

        let web_host = &config.hosts[0];
        assert_eq!(web_host.host_patterns, vec!["web*.example.com"]);
        assert_eq!(web_host.user, Some("webuser".to_string()));
        assert_eq!(web_host.port, Some(22));

        let db_host = &config.hosts[1];
        assert_eq!(db_host.host_patterns, vec!["db*.example.com"]);
        assert_eq!(db_host.user, Some("dbuser".to_string()));
        assert_eq!(db_host.port, Some(5432));
    }

    #[test]
    fn test_find_host_config() {
        let config_content = r#"
Host *.example.com
    User defaultuser
    Port 22

Host web*.example.com
    User webuser
    Port 8080

Host web1.example.com
    Port 9090
"#;

        let config = SshConfig::parse(config_content).unwrap();

        // Test that most specific match wins
        let host_config = config.find_host_config("web1.example.com");
        assert_eq!(host_config.user, Some("webuser".to_string())); // From web*.example.com
        assert_eq!(host_config.port, Some(9090)); // From web1.example.com (most specific)

        // Test that patterns are applied in order
        let host_config = config.find_host_config("web2.example.com");
        assert_eq!(host_config.user, Some("webuser".to_string())); // From web*.example.com
        assert_eq!(host_config.port, Some(8080)); // From web*.example.com

        let host_config = config.find_host_config("db1.example.com");
        assert_eq!(host_config.user, Some("defaultuser".to_string())); // From *.example.com
        assert_eq!(host_config.port, Some(22)); // From *.example.com
    }

    #[test]
    fn test_load_from_file() {
        let temp_dir = TempDir::new().unwrap();
        let config_file = temp_dir.path().join("ssh_config");

        let config_content = r#"
Host test.example.com
    User testuser
    Port 2222
"#;

        std::fs::write(&config_file, config_content).unwrap();

        let config = tokio_test::block_on(SshConfig::load_from_file(&config_file)).unwrap();
        assert_eq!(config.hosts.len(), 1);
        assert_eq!(config.hosts[0].host_patterns, vec!["test.example.com"]);
        assert_eq!(config.hosts[0].user, Some("testuser".to_string()));
        assert_eq!(config.hosts[0].port, Some(2222));
    }

    #[test]
    fn test_parse_certificate_and_forwarding_options() {
        // Test parsing of certificate authentication and advanced port forwarding options
        let config_content = r#"
Host *.secure.example.com
    CertificateFile ~/.ssh/id_rsa-cert.pub
    CASignatureAlgorithms ssh-ed25519,rsa-sha2-512
    GatewayPorts yes
    ExitOnForwardFailure yes
    HostbasedAuthentication yes
    HostbasedAcceptedAlgorithms ssh-ed25519,rsa-sha2-512

Host web1.secure.example.com
    CertificateFile /etc/ssh/host-cert.pub
    PermitRemoteOpen localhost:8080 db.internal:5432
    GatewayPorts clientspecified
"#;

        let config = SshConfig::parse(config_content).unwrap();
        assert_eq!(config.hosts.len(), 2);

        // Verify first host (*.secure.example.com)
        let host1 = &config.hosts[0];
        assert_eq!(host1.certificate_files.len(), 1);
        assert!(
            host1.certificate_files[0]
                .to_string_lossy()
                .contains("id_rsa-cert.pub")
        );
        assert_eq!(host1.ca_signature_algorithms.len(), 2);
        assert_eq!(host1.ca_signature_algorithms[0], "ssh-ed25519");
        assert_eq!(host1.ca_signature_algorithms[1], "rsa-sha2-512");
        assert_eq!(host1.gateway_ports, Some("yes".to_string()));
        assert_eq!(host1.exit_on_forward_failure, Some(true));
        assert_eq!(host1.hostbased_authentication, Some(true));
        assert_eq!(host1.hostbased_accepted_algorithms.len(), 2);

        // Verify second host (web1.secure.example.com)
        let host2 = &config.hosts[1];
        assert_eq!(host2.certificate_files.len(), 1);
        assert!(
            host2.certificate_files[0]
                .to_string_lossy()
                .contains("host-cert.pub")
        );
        assert_eq!(host2.permit_remote_open.len(), 2);
        assert_eq!(host2.permit_remote_open[0], "localhost:8080");
        assert_eq!(host2.permit_remote_open[1], "db.internal:5432");
        assert_eq!(host2.gateway_ports, Some("clientspecified".to_string()));
    }

    #[test]
    fn test_merge_certificate_and_forwarding_options() {
        // Test that certificate and forwarding options are properly merged according to SSH config precedence
        let config_content = r#"
Host *.example.com
    CertificateFile ~/.ssh/default-cert.pub
    CASignatureAlgorithms ssh-ed25519
    GatewayPorts no
    HostbasedAuthentication no

Host web*.example.com
    CertificateFile ~/.ssh/web-cert.pub
    GatewayPorts yes
    PermitRemoteOpen localhost:8080

Host web1.example.com
    CASignatureAlgorithms rsa-sha2-512,rsa-sha2-256
    ExitOnForwardFailure yes
"#;

        let config = SshConfig::parse(config_content).unwrap();

        // Test merging for web1.example.com (should get configs from all three blocks)
        let host_config = config.find_host_config("web1.example.com");

        // Should have certificate files from both *.example.com and web*.example.com (appended)
        assert_eq!(host_config.certificate_files.len(), 2);

        // CASignatureAlgorithms should be from web1.example.com (most specific)
        assert_eq!(host_config.ca_signature_algorithms.len(), 2);
        assert_eq!(host_config.ca_signature_algorithms[0], "rsa-sha2-512");
        assert_eq!(host_config.ca_signature_algorithms[1], "rsa-sha2-256");

        // GatewayPorts should be from web*.example.com
        assert_eq!(host_config.gateway_ports, Some("yes".to_string()));

        // ExitOnForwardFailure should be from web1.example.com
        assert_eq!(host_config.exit_on_forward_failure, Some(true));

        // PermitRemoteOpen should be from web*.example.com
        assert_eq!(host_config.permit_remote_open.len(), 1);
        assert_eq!(host_config.permit_remote_open[0], "localhost:8080");

        // HostbasedAuthentication should be from *.example.com
        assert_eq!(host_config.hostbased_authentication, Some(false));
    }

    #[test]
    fn test_parse_host_key_verification_options() {
        // Test parsing of host key verification options
        let config_content = r#"
Host localhost 127.0.0.1
    NoHostAuthenticationForLocalhost yes
    HashKnownHosts yes

Host *.example.com
    CheckHostIP no
    VisualHostKey yes
    HostKeyAlias shared-key.example.com
    VerifyHostKeyDNS ask
    UpdateHostKeys yes
"#;

        let config = SshConfig::parse(config_content).unwrap();
        assert_eq!(config.hosts.len(), 2);

        // Verify localhost config
        let host1 = &config.hosts[0];
        assert_eq!(host1.no_host_authentication_for_localhost, Some(true));
        assert_eq!(host1.hash_known_hosts, Some(true));

        // Verify *.example.com config
        let host2 = &config.hosts[1];
        assert_eq!(host2.check_host_ip, Some(false));
        assert_eq!(host2.visual_host_key, Some(true));
        assert_eq!(
            host2.host_key_alias,
            Some("shared-key.example.com".to_string())
        );
        assert_eq!(host2.verify_host_key_dns, Some("ask".to_string()));
        assert_eq!(host2.update_host_keys, Some("yes".to_string()));
    }

    #[test]
    fn test_parse_authentication_options() {
        // Test parsing of authentication options
        let config_content = r#"
Host automated-server
    NumberOfPasswordPrompts 1
    EnableSSHKeysign yes

Host secure-server
    NumberOfPasswordPrompts 5
    EnableSSHKeysign no
"#;

        let config = SshConfig::parse(config_content).unwrap();
        assert_eq!(config.hosts.len(), 2);

        // Verify automated-server config
        let host1 = &config.hosts[0];
        assert_eq!(host1.number_of_password_prompts, Some(1));
        assert_eq!(host1.enable_ssh_keysign, Some(true));

        // Verify secure-server config
        let host2 = &config.hosts[1];
        assert_eq!(host2.number_of_password_prompts, Some(5));
        assert_eq!(host2.enable_ssh_keysign, Some(false));
    }

    #[test]
    fn test_parse_network_options() {
        // Test parsing of network options
        let config_content = r#"
Host vpn-server
    BindInterface tun0
    IPQoS lowdelay throughput
    RekeyLimit 1G 1h

Host backup-server
    BindInterface eth1
    IPQoS af21
    RekeyLimit default none
"#;

        let config = SshConfig::parse(config_content).unwrap();
        assert_eq!(config.hosts.len(), 2);

        // Verify vpn-server config
        let host1 = &config.hosts[0];
        assert_eq!(host1.bind_interface, Some("tun0".to_string()));
        assert_eq!(host1.ipqos, Some("lowdelay throughput".to_string()));
        assert_eq!(host1.rekey_limit, Some("1G 1h".to_string()));

        // Verify backup-server config
        let host2 = &config.hosts[1];
        assert_eq!(host2.bind_interface, Some("eth1".to_string()));
        assert_eq!(host2.ipqos, Some("af21".to_string()));
        assert_eq!(host2.rekey_limit, Some("default none".to_string()));
    }

    #[test]
    fn test_parse_x11_forwarding_options() {
        // Test parsing of X11 forwarding options
        let config_content = r#"
Host gui-server
    ForwardX11 yes
    ForwardX11Timeout 1h
    ForwardX11Trusted yes

Host desktop-server
    ForwardX11 yes
    ForwardX11Timeout 0
    ForwardX11Trusted no
"#;

        let config = SshConfig::parse(config_content).unwrap();
        assert_eq!(config.hosts.len(), 2);

        // Verify gui-server config
        let host1 = &config.hosts[0];
        assert_eq!(host1.forward_x11, Some(true));
        assert_eq!(host1.forward_x11_timeout, Some("1h".to_string()));
        assert_eq!(host1.forward_x11_trusted, Some(true));

        // Verify desktop-server config
        let host2 = &config.hosts[1];
        assert_eq!(host2.forward_x11, Some(true));
        assert_eq!(host2.forward_x11_timeout, Some("0".to_string()));
        assert_eq!(host2.forward_x11_trusted, Some(false));
    }

    #[test]
    fn test_merge_host_key_and_network_options() {
        // Test that host key verification and network options are properly merged according to SSH config precedence
        let config_content = r#"
Host *
    HashKnownHosts yes
    NumberOfPasswordPrompts 3
    BindInterface eth0
    ForwardX11Trusted no

Host *.example.com
    VisualHostKey yes
    EnableSSHKeysign yes
    IPQoS lowdelay
    ForwardX11Timeout 30m

Host web1.example.com
    HostKeyAlias shared.example.com
    NumberOfPasswordPrompts 1
    RekeyLimit 1G 2h
    ForwardX11Trusted yes
"#;

        let config = SshConfig::parse(config_content).unwrap();

        // Test merging for web1.example.com (should get configs from all three blocks)
        let host_config = config.find_host_config("web1.example.com");

        // HashKnownHosts should be from * (least specific)
        assert_eq!(host_config.hash_known_hosts, Some(true));

        // VisualHostKey should be from *.example.com
        assert_eq!(host_config.visual_host_key, Some(true));

        // HostKeyAlias should be from web1.example.com (most specific)
        assert_eq!(
            host_config.host_key_alias,
            Some("shared.example.com".to_string())
        );

        // NumberOfPasswordPrompts should be from web1.example.com (most specific)
        assert_eq!(host_config.number_of_password_prompts, Some(1));

        // EnableSSHKeysign should be from *.example.com
        assert_eq!(host_config.enable_ssh_keysign, Some(true));

        // BindInterface should be from * (least specific)
        assert_eq!(host_config.bind_interface, Some("eth0".to_string()));

        // IPQoS should be from *.example.com
        assert_eq!(host_config.ipqos, Some("lowdelay".to_string()));

        // RekeyLimit should be from web1.example.com (most specific)
        assert_eq!(host_config.rekey_limit, Some("1G 2h".to_string()));

        // ForwardX11Timeout should be from *.example.com
        assert_eq!(host_config.forward_x11_timeout, Some("30m".to_string()));

        // ForwardX11Trusted should be from web1.example.com (most specific)
        assert_eq!(host_config.forward_x11_trusted, Some(true));
    }

    #[test]
    fn test_host_key_and_network_validation_errors() {
        // Test validation of host key verification and network options

        // Invalid VerifyHostKeyDNS value
        let config_content = r#"
Host test
    VerifyHostKeyDNS invalid
"#;
        assert!(SshConfig::parse(config_content).is_err());

        // Invalid UpdateHostKeys value
        let config_content = r#"
Host test
    UpdateHostKeys invalid
"#;
        assert!(SshConfig::parse(config_content).is_err());

        // Invalid NumberOfPasswordPrompts (not a number)
        let config_content = r#"
Host test
    NumberOfPasswordPrompts abc
"#;
        assert!(SshConfig::parse(config_content).is_err());
    }

    #[test]
    fn test_host_key_and_network_option_value_syntax() {
        // Test Option=Value syntax for host key verification and network options
        let config_content = r#"
Host test
    NoHostAuthenticationForLocalhost=yes
    HashKnownHosts=yes
    NumberOfPasswordPrompts=2
    BindInterface=eth0
    ForwardX11Trusted=yes
"#;

        let config = SshConfig::parse(config_content).unwrap();
        assert_eq!(config.hosts.len(), 1);

        let host = &config.hosts[0];
        assert_eq!(host.no_host_authentication_for_localhost, Some(true));
        assert_eq!(host.hash_known_hosts, Some(true));
        assert_eq!(host.number_of_password_prompts, Some(2));
        assert_eq!(host.bind_interface, Some("eth0".to_string()));
        assert_eq!(host.forward_x11_trusted, Some(true));
    }

    #[test]
    fn test_host_key_and_network_security_validations() {
        // Test HostKeyAlias - should reject shell metacharacters
        let config_content = r#"
Host test
    HostKeyAlias "bad;command"
"#;
        assert!(
            SshConfig::parse(config_content).is_err(),
            "Should reject shell metacharacters in HostKeyAlias"
        );

        // Test HostKeyAlias - should reject path traversal
        let config_content = r#"
Host test
    HostKeyAlias "../etc/passwd"
"#;
        assert!(
            SshConfig::parse(config_content).is_err(),
            "Should reject path traversal in HostKeyAlias"
        );

        // Test HostKeyAlias - should accept valid hostnames
        let config_content = r#"
Host test
    HostKeyAlias lb-1.example.com
"#;
        let config = SshConfig::parse(config_content).unwrap();
        assert_eq!(
            config.hosts[0].host_key_alias,
            Some("lb-1.example.com".to_string())
        );

        // Test BindInterface - should reject shell metacharacters
        let config_content = r#"
Host test
    BindInterface "eth0;rm -rf /"
"#;
        assert!(
            SshConfig::parse(config_content).is_err(),
            "Should reject shell metacharacters in BindInterface"
        );

        // Test BindInterface - should reject too long names
        let config_content = r#"
Host test
    BindInterface "verylonginterfacename123456789"
"#;
        assert!(
            SshConfig::parse(config_content).is_err(),
            "Should reject too long interface names"
        );

        // Test BindInterface - should accept valid interface names
        let config_content = r#"
Host test
    BindInterface eth0
"#;
        let config = SshConfig::parse(config_content).unwrap();
        assert_eq!(config.hosts[0].bind_interface, Some("eth0".to_string()));

        // Test BindInterface - should accept tun0
        let config_content = r#"
Host test
    BindInterface tun0
"#;
        let config = SshConfig::parse(config_content).unwrap();
        assert_eq!(config.hosts[0].bind_interface, Some("tun0".to_string()));

        // Test IPQoS - should reject invalid values
        let config_content = r#"
Host test
    IPQoS invalid-value
"#;
        assert!(
            SshConfig::parse(config_content).is_err(),
            "Should reject invalid IPQoS values"
        );

        // Test IPQoS - should reject too many values
        let config_content = r#"
Host test
    IPQoS af11 af12 af13
"#;
        assert!(
            SshConfig::parse(config_content).is_err(),
            "Should reject more than 2 IPQoS values"
        );

        // Test IPQoS - should accept valid values
        let config_content = r#"
Host test
    IPQoS lowdelay throughput
"#;
        let config = SshConfig::parse(config_content).unwrap();
        assert_eq!(
            config.hosts[0].ipqos,
            Some("lowdelay throughput".to_string())
        );

        // Test RekeyLimit - should reject invalid format
        let config_content = r#"
Host test
    RekeyLimit invalid
"#;
        assert!(
            SshConfig::parse(config_content).is_err(),
            "Should reject invalid RekeyLimit format"
        );

        // Test RekeyLimit - should accept valid format
        let config_content = r#"
Host test
    RekeyLimit 1G 1h
"#;
        let config = SshConfig::parse(config_content).unwrap();
        assert_eq!(config.hosts[0].rekey_limit, Some("1G 1h".to_string()));

        // Test ForwardX11Timeout - should reject invalid format
        let config_content = r#"
Host test
    ForwardX11Timeout "../../etc/passwd"
"#;
        assert!(
            SshConfig::parse(config_content).is_err(),
            "Should reject path traversal in ForwardX11Timeout"
        );

        // Test ForwardX11Timeout - should accept valid format
        let config_content = r#"
Host test
    ForwardX11Timeout 1h
"#;
        let config = SshConfig::parse(config_content).unwrap();
        assert_eq!(config.hosts[0].forward_x11_timeout, Some("1h".to_string()));

        // Test NumberOfPasswordPrompts - should reject 0
        let config_content = r#"
Host test
    NumberOfPasswordPrompts 0
"#;
        assert!(
            SshConfig::parse(config_content).is_err(),
            "Should reject 0 for NumberOfPasswordPrompts"
        );

        // Test NumberOfPasswordPrompts - should reject values > 100
        let config_content = r#"
Host test
    NumberOfPasswordPrompts 101
"#;
        assert!(
            SshConfig::parse(config_content).is_err(),
            "Should reject values > 100 for NumberOfPasswordPrompts"
        );

        // Test NumberOfPasswordPrompts - should accept valid range
        let config_content = r#"
Host test
    NumberOfPasswordPrompts 3
"#;
        let config = SshConfig::parse(config_content).unwrap();
        assert_eq!(config.hosts[0].number_of_password_prompts, Some(3));
    }
}