qssh 0.4.4

Post-quantum secure shell with NIST PQC algorithms (Falcon, SPHINCS+, ML-KEM), configurable security tiers, and quantum-resistant protocol design
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
//! Configuration file parsing for QSSH
//! Compatible with OpenSSH config format

use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use crate::{Result, QsshError, QsshConfig, PortForward, PqAlgorithm, KexAlgorithm, security_tiers::SecurityTier};

/// Host configuration from config file
#[derive(Debug, Clone)]
#[derive(Default)]
pub struct HostConfig {
    pub hostname: Option<String>,
    pub port: Option<u16>,
    pub user: Option<String>,
    pub identity_file: Option<PathBuf>,
    pub local_forward: Vec<String>,
    pub remote_forward: Vec<String>,
    pub dynamic_forward: Vec<String>,
    pub pq_algorithm: Option<PqAlgorithm>,
    /// Key exchange algorithm (default: ML-KEM-1024, FIPS 203 — confidential PQ KEX)
    pub kex_algorithm: Option<KexAlgorithm>,
    pub use_qkd: bool,
    pub qkd_endpoint: Option<String>,
    pub qkd_cert_path: Option<String>,
    pub qkd_key_path: Option<String>,
    pub qkd_ca_path: Option<String>,
    pub key_rotation_interval: Option<u64>,
    pub compression: bool,
    pub server_alive_interval: Option<u64>,
    pub server_alive_count_max: Option<u32>,
}


/// SSH config file parser
pub struct ConfigParser {
    hosts: HashMap<String, HostConfig>,
    default_config: HostConfig,
}

impl ConfigParser {
    /// Load config from default location (~/.qssh/config or ~/.ssh/config)
    pub fn load_default() -> Result<Self> {
        let home = std::env::var("HOME")
            .map_err(|_| QsshError::Config("HOME environment variable not set".into()))?;

        let qssh_config = PathBuf::from(&home).join(".qssh").join("config");
        let ssh_config = PathBuf::from(&home).join(".ssh").join("config");

        if qssh_config.exists() {
            Self::load_from_file(&qssh_config)
        } else if ssh_config.exists() {
            Self::load_from_file(&ssh_config)
        } else {
            Ok(Self {
                hosts: HashMap::new(),
                default_config: HostConfig::default(),
            })
        }
    }

    /// Load config from specific file
    pub fn load_from_file(path: &Path) -> Result<Self> {
        let content = fs::read_to_string(path)
            .map_err(|e| QsshError::Config(format!("Failed to read config file: {}", e)))?;

        Self::parse(&content)
    }

    /// Parse config content
    pub fn parse(content: &str) -> Result<Self> {
        let mut parser = Self {
            hosts: HashMap::new(),
            default_config: HostConfig::default(),
        };

        let mut current_host: Option<String> = None;
        let mut current_config = HostConfig::default();

        for line in content.lines() {
            let line = line.trim();

            // Skip comments and empty lines
            if line.is_empty() || line.starts_with('#') {
                continue;
            }

            // Parse key-value pairs
            let parts: Vec<&str> = line.splitn(2, char::is_whitespace).collect();
            if parts.len() != 2 {
                continue;
            }

            let key = parts[0].to_lowercase();
            let value = parts[1].trim();

            match key.as_str() {
                "host" => {
                    // Save previous host config
                    if let Some(host) = current_host.take() {
                        parser.hosts.insert(host, current_config.clone());
                    }

                    // Start new host section
                    if value != "*" {
                        current_host = Some(value.to_string());
                        current_config = HostConfig::default();
                    } else {
                        // Global defaults
                        current_host = None;
                        current_config = HostConfig::default();
                    }
                }
                "hostname" => {
                    current_config.hostname = Some(value.to_string());
                }
                "port" => {
                    current_config.port = value.parse().ok();
                }
                "user" => {
                    current_config.user = Some(value.to_string());
                }
                "identityfile" => {
                    let path = expand_tilde(value);
                    current_config.identity_file = Some(PathBuf::from(path));
                }
                "localforward" => {
                    current_config.local_forward.push(value.to_string());
                }
                "remoteforward" => {
                    current_config.remote_forward.push(value.to_string());
                }
                "dynamicforward" => {
                    current_config.dynamic_forward.push(value.to_string());
                }
                "pqalgorithm" => {
                    current_config.pq_algorithm = match value.to_lowercase().as_str() {
                        "sphincs" | "sphincsplus" => Some(PqAlgorithm::SphincsPlus),
                        "falcon" | "falcon512" => Some(PqAlgorithm::Falcon512),
                        "falcon1024" => Some(PqAlgorithm::Falcon1024),
                        // Deprecated/vulnerable algorithms - warn and use safe alternative
                        "kyber512" | "kyber768" | "kyber1024" => {
                            log::warn!("Kyber algorithm '{}' is vulnerable (KyberSlash). Using Falcon512 instead.", value);
                            Some(PqAlgorithm::Falcon512)
                        },
                        _ => None,
                    };
                }
                "kexalgorithm" => {
                    current_config.kex_algorithm = match value.to_lowercase().as_str() {
                        "falcon-signed" | "falcon-signed-shares" | "falconsignedshares" => {
                            Some(KexAlgorithm::FalconSignedShares)
                        }
                        "mlkem768" | "ml-kem-768" | "mlkem-768" => {
                            Some(KexAlgorithm::MlKem768)
                        }
                        "mlkem1024" | "ml-kem-1024" | "mlkem-1024" => {
                            Some(KexAlgorithm::MlKem1024)
                        }
                        #[cfg(feature = "hybrid-kex")]
                        "hybrid" | "hybrid-x25519-mlkem768" | "x25519-mlkem768" => {
                            Some(KexAlgorithm::HybridX25519MlKem768)
                        }
                        #[cfg(not(feature = "hybrid-kex"))]
                        "hybrid" | "hybrid-x25519-mlkem768" | "x25519-mlkem768" => {
                            log::warn!("Hybrid KEX requested but 'hybrid-kex' feature not enabled. Using MlKem768 instead.");
                            Some(KexAlgorithm::MlKem768)
                        }
                        // Deprecated Kyber aliases - map to ML-KEM with warning
                        "kyber512" | "kyber768" => {
                            log::warn!("Kyber KEX '{}' is deprecated and vulnerable. Using ML-KEM-768 instead.", value);
                            Some(KexAlgorithm::MlKem768)
                        }
                        "kyber1024" => {
                            log::warn!("Kyber KEX '{}' is deprecated and vulnerable. Using ML-KEM-1024 instead.", value);
                            Some(KexAlgorithm::MlKem1024)
                        }
                        _ => {
                            log::warn!("Unknown KEX algorithm '{}'. Using default.", value);
                            None
                        }
                    };
                }
                "useqkd" => {
                    current_config.use_qkd = value.to_lowercase() == "yes" || value == "1";
                }
                "qkdendpoint" => {
                    current_config.qkd_endpoint = Some(value.to_string());
                }
                "qkdcertpath" => {
                    current_config.qkd_cert_path = Some(expand_tilde(value));
                }
                "qkdkeypath" => {
                    current_config.qkd_key_path = Some(expand_tilde(value));
                }
                "qkdcapath" => {
                    current_config.qkd_ca_path = Some(expand_tilde(value));
                }
                "keyrotationinterval" => {
                    current_config.key_rotation_interval = value.parse().ok();
                }
                "compression" => {
                    current_config.compression = value.to_lowercase() == "yes" || value == "1";
                }
                "serveraliveinterval" => {
                    current_config.server_alive_interval = value.parse().ok();
                }
                "serveralivecountmax" => {
                    current_config.server_alive_count_max = value.parse().ok();
                }
                _ => {
                    // Ignore unknown options (for OpenSSH compatibility)
                }
            }
        }

        // Save last host config
        if let Some(host) = current_host {
            parser.hosts.insert(host, current_config);
        } else {
            // If no host was being parsed, these were global defaults
            parser.default_config = current_config;
        }

        Ok(parser)
    }

    /// List all configured host names
    pub fn list_hosts(&self) -> Vec<String> {
        self.hosts.keys().cloned().collect()
    }

    /// Get configuration for a specific host
    pub fn get_host_config(&self, hostname: &str) -> HostConfig {
        // Check for exact match
        if let Some(config) = self.hosts.get(hostname) {
            return self.merge_with_defaults(config.clone());
        }

        // Check for wildcard matches
        for (pattern, config) in &self.hosts {
            if pattern_matches(pattern, hostname) {
                return self.merge_with_defaults(config.clone());
            }
        }

        // Return defaults (also apply merge_with_defaults to ensure all defaults are set)
        self.merge_with_defaults(self.default_config.clone())
    }

    /// Merge host config with defaults
    fn merge_with_defaults(&self, mut config: HostConfig) -> HostConfig {
        if config.port.is_none() {
            config.port = self.default_config.port.or(Some(22222));
        }
        if config.user.is_none() {
            config.user = self.default_config.user.clone();
        }
        if config.identity_file.is_none() {
            config.identity_file = self.default_config.identity_file.clone();
        }
        if config.pq_algorithm.is_none() {
            config.pq_algorithm = self.default_config.pq_algorithm.or(Some(PqAlgorithm::Falcon512));
        }
        if config.kex_algorithm.is_none() {
            config.kex_algorithm = self.default_config.kex_algorithm.or(Some(KexAlgorithm::MlKem1024));
        }
        if config.key_rotation_interval.is_none() {
            config.key_rotation_interval = self.default_config.key_rotation_interval.or(Some(3600));
        }
        
        // Merge QKD settings
        if !config.use_qkd && self.default_config.use_qkd {
            config.use_qkd = self.default_config.use_qkd;
        }
        if config.qkd_endpoint.is_none() {
            config.qkd_endpoint = self.default_config.qkd_endpoint.clone();
        }
        if config.qkd_cert_path.is_none() {
            config.qkd_cert_path = self.default_config.qkd_cert_path.clone();
        }
        if config.qkd_key_path.is_none() {
            config.qkd_key_path = self.default_config.qkd_key_path.clone();
        }
        if config.qkd_ca_path.is_none() {
            config.qkd_ca_path = self.default_config.qkd_ca_path.clone();
        }

        // Merge forward lists
        config.local_forward.extend(self.default_config.local_forward.clone());
        config.remote_forward.extend(self.default_config.remote_forward.clone());
        config.dynamic_forward.extend(self.default_config.dynamic_forward.clone());

        config
    }

    /// Convert host config to QsshConfig
    pub fn to_qssh_config(&self, hostname: &str, username: Option<String>) -> Result<QsshConfig> {
        let host_config = self.get_host_config(hostname);

        let server = if let Some(h) = host_config.hostname {
            format!("{}:{}", h, host_config.port.unwrap_or(22222))
        } else {
            format!("{}:{}", hostname, host_config.port.unwrap_or(22222))
        };

        let username = username.or(host_config.user)
            .ok_or_else(|| QsshError::Config("Username not specified".into()))?;

        let mut port_forwards = Vec::new();
        for forward_spec in &host_config.local_forward {
            if let Some(pf) = parse_port_forward(forward_spec) {
                port_forwards.push(pf);
            }
        }

        Ok(QsshConfig {
            server,
            username,
            password: None,  // Password should be provided via command line for security
            port_forwards,
            use_qkd: host_config.use_qkd,
            qkd_endpoint: host_config.qkd_endpoint,
            qkd_cert_path: host_config.qkd_cert_path,
            qkd_key_path: host_config.qkd_key_path,
            qkd_ca_path: host_config.qkd_ca_path,
            pq_algorithm: host_config.pq_algorithm.unwrap_or(PqAlgorithm::Falcon512),
            kex_algorithm: host_config.kex_algorithm.unwrap_or(KexAlgorithm::MlKem1024),
            key_rotation_interval: host_config.key_rotation_interval.unwrap_or(3600),
            security_tier: SecurityTier::default(),
            quantum_native: true,  // Default to quantum-native transport
        })
    }
}

/// Expand ~ in paths
fn expand_tilde(path: &str) -> String {
    if path.starts_with("~/") {
        if let Ok(home) = std::env::var("HOME") {
            return path.replacen("~", &home, 1);
        }
    }
    path.to_string()
}

/// Check if pattern matches hostname (supports * wildcard)
fn pattern_matches(pattern: &str, hostname: &str) -> bool {
    if pattern == "*" {
        return true;
    }

    if pattern.contains('*') {
        let parts: Vec<&str> = pattern.split('*').collect();
        if parts.len() == 2 {
            return hostname.starts_with(parts[0]) && hostname.ends_with(parts[1]);
        }
    }

    pattern == hostname
}

/// Parse port forward specification
fn parse_port_forward(spec: &str) -> Option<PortForward> {
    let parts: Vec<&str> = spec.split(':').collect();
    if parts.len() != 3 {
        // Try space-separated format
        let parts: Vec<&str> = spec.split_whitespace().collect();
        if parts.len() != 3 {
            return None;
        }

        let local_port = parts[0].parse().ok()?;
        let remote_host = parts[1].to_string();
        let remote_port = parts[2].parse().ok()?;

        return Some(PortForward {
            local_port,
            remote_host,
            remote_port,
        });
    }

    let local_port = parts[0].parse().ok()?;
    let remote_host = parts[1].to_string();
    let remote_port = parts[2].parse().ok()?;

    Some(PortForward {
        local_port,
        remote_host,
        remote_port,
    })
}

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

    #[test]
    fn test_parse_config() {
        let config = r#"
# Global defaults
User alice
Port 2222

Host github
    Hostname github.com
    User git
    IdentityFile ~/.ssh/id_rsa

Host *.internal
    Port 22
    User admin

Host quantum-server
    Hostname quantum.example.com
    Port 22222
    PqAlgorithm falcon
    UseQkd yes
    LocalForward 8080:localhost:80
        "#;

        let parser = ConfigParser::parse(config).unwrap();

        // Test github config
        let github = parser.get_host_config("github");
        assert_eq!(github.hostname, Some("github.com".to_string()));
        assert_eq!(github.user, Some("git".to_string()));

        // Test wildcard match
        let internal = parser.get_host_config("server.internal");
        assert_eq!(internal.port, Some(22));
        assert_eq!(internal.user, Some("admin".to_string()));

        // Test quantum server
        let quantum = parser.get_host_config("quantum-server");
        assert_eq!(quantum.pq_algorithm, Some(PqAlgorithm::Falcon512));
        assert!(quantum.use_qkd);
        assert_eq!(quantum.local_forward.len(), 1);
    }

    #[test]
    fn test_kex_algorithm_parsing() {
        let config = r#"
Host fips-server
    Hostname fips.example.com
    KexAlgorithm mlkem768

Host high-security
    Hostname secure.example.com
    KexAlgorithm mlkem1024

Host legacy-server
    Hostname legacy.example.com
    KexAlgorithm falcon-signed
        "#;

        let parser = ConfigParser::parse(config).unwrap();

        // Test ML-KEM-768
        let fips = parser.get_host_config("fips-server");
        assert_eq!(fips.kex_algorithm, Some(KexAlgorithm::MlKem768));

        // Test ML-KEM-1024
        let secure = parser.get_host_config("high-security");
        assert_eq!(secure.kex_algorithm, Some(KexAlgorithm::MlKem1024));

        // Test Falcon-signed (legacy)
        let legacy = parser.get_host_config("legacy-server");
        assert_eq!(legacy.kex_algorithm, Some(KexAlgorithm::FalconSignedShares));

        // Test default (unset/unknown -> secure ML-KEM-1024, not auth-only Falcon)
        let unknown = parser.get_host_config("unknown-server");
        assert_eq!(unknown.kex_algorithm, Some(KexAlgorithm::MlKem1024));
    }

    #[test]
    fn test_deprecated_kyber_mapping() {
        let config = r#"
Host kyber-server
    KexAlgorithm kyber768
        "#;

        let parser = ConfigParser::parse(config).unwrap();

        // Kyber768 should be mapped to ML-KEM-768 with warning
        let kyber = parser.get_host_config("kyber-server");
        assert_eq!(kyber.kex_algorithm, Some(KexAlgorithm::MlKem768));
    }
}