qssh 0.4.3

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
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
//! Session Resumption Support
//!
//! Implements session caching and fast reconnection for mobile and unstable networks

use std::collections::HashMap;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use std::path::PathBuf;
use tokio::sync::RwLock;
use std::sync::Arc;
use serde::{Serialize, Deserialize};
use crate::{Result, QsshError, PqAlgorithm};
use sha2::{Sha256, Digest};
use rand::Rng;

/// Session resumption ticket
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionTicket {
    /// Unique session ID
    pub session_id: String,
    /// Server identifier
    pub server_id: String,
    /// Username
    pub username: String,
    /// Timestamp when ticket was issued
    pub issued_at: u64,
    /// Ticket lifetime in seconds
    pub lifetime: u64,
    /// Encrypted session state
    pub encrypted_state: Vec<u8>,
    /// Post-quantum algorithm used
    pub pq_algorithm: PqAlgorithm,
    /// Session keys (encrypted)
    pub session_keys: EncryptedKeys,
    /// Nonce for encryption
    pub nonce: Vec<u8>,
    /// Signature for authenticity
    pub signature: Vec<u8>,
}

/// Encrypted session keys
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EncryptedKeys {
    /// Encrypted symmetric key
    pub symmetric_key: Vec<u8>,
    /// Encrypted MAC key
    pub mac_key: Vec<u8>,
    /// Key derivation salt
    pub salt: Vec<u8>,
}

/// Session state for resumption
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionState {
    /// Cipher suite in use
    pub cipher_suite: String,
    /// Compression algorithm
    pub compression: String,
    /// Active port forwards
    pub port_forwards: Vec<String>,
    /// Environment variables
    pub environment: HashMap<String, String>,
    /// Terminal settings
    pub terminal: Option<TerminalState>,
    /// X11 forwarding state
    pub x11_forwarding: bool,
    /// Agent forwarding state
    pub agent_forwarding: bool,
}

/// Terminal state for session
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TerminalState {
    /// Terminal type
    pub term_type: String,
    /// Terminal width
    pub cols: u32,
    /// Terminal height
    pub rows: u32,
    /// Terminal modes
    pub modes: HashMap<String, u32>,
}

/// Session cache for managing resumption tickets
pub struct SessionCache {
    /// Active sessions by ID
    sessions: Arc<RwLock<HashMap<String, CachedSession>>>,
    /// Maximum cache size
    max_sessions: usize,
    /// Default ticket lifetime
    default_lifetime: Duration,
    /// Cache directory
    cache_dir: PathBuf,
    /// Server master secret for ticket encryption and HMAC (None = client-only cache)
    server_secret: Option<[u8; 32]>,
}

/// Cached session information
#[derive(Debug, Clone)]
struct CachedSession {
    /// Session ticket
    ticket: SessionTicket,
    /// Last access time
    last_accessed: Instant,
    /// Number of successful resumptions
    resumption_count: u32,
    /// Session state
    state: SessionState,
}

impl SessionCache {
    /// Create new session cache (client-only, no ticket signing)
    pub fn new(cache_dir: PathBuf) -> Result<Self> {
        // Ensure cache directory exists
        std::fs::create_dir_all(&cache_dir)
            .map_err(|e| QsshError::Config(format!("Failed to create session cache dir: {}", e)))?;

        Ok(Self {
            sessions: Arc::new(RwLock::new(HashMap::new())),
            max_sessions: 100,
            default_lifetime: Duration::from_secs(48 * 3600), // 48 hours
            cache_dir,
            server_secret: None,
        })
    }

    /// Create new session cache with server master secret (enables ticket signing/verification)
    pub fn new_server(cache_dir: PathBuf, server_secret: [u8; 32]) -> Result<Self> {
        std::fs::create_dir_all(&cache_dir)
            .map_err(|e| QsshError::Config(format!("Failed to create session cache dir: {}", e)))?;

        Ok(Self {
            sessions: Arc::new(RwLock::new(HashMap::new())),
            max_sessions: 100,
            default_lifetime: Duration::from_secs(48 * 3600),
            cache_dir,
            server_secret: Some(server_secret),
        })
    }

    /// Create new session ticket
    pub async fn create_ticket(
        &self,
        server_id: &str,
        username: &str,
        state: SessionState,
        pq_algorithm: PqAlgorithm,
    ) -> Result<SessionTicket> {
        let session_id = generate_session_id();

        // Serialize session state
        let state_bytes = bincode::serialize(&state)
            .map_err(|e| QsshError::Protocol(format!("Failed to serialize session state: {}", e)))?;

        // Generate encryption key from session ID + server secret
        let encryption_key = derive_ticket_key(&session_id, self.server_secret.as_ref());

        // Encrypt state
        let nonce = generate_nonce();
        let encrypted_state = encrypt_state(&state_bytes, &encryption_key, &nonce)?;

        // Derive session keys from the ticket encryption key
        let salt = generate_salt();
        let session_keys = EncryptedKeys {
            symmetric_key: derive_session_key(&encryption_key, &salt, b"symmetric"),
            mac_key: derive_session_key(&encryption_key, &salt, b"mac"),
            salt,
        };

        // Create ticket (signature placeholder, computed below)
        let mut ticket = SessionTicket {
            session_id: session_id.clone(),
            server_id: server_id.to_string(),
            username: username.to_string(),
            issued_at: current_timestamp(),
            lifetime: self.default_lifetime.as_secs(),
            encrypted_state,
            pq_algorithm,
            session_keys,
            nonce,
            signature: Vec::new(),
        };

        // Compute HMAC-SHA256 over ticket fields for integrity
        ticket.signature = compute_ticket_hmac(&ticket, self.server_secret.as_ref());

        // Cache the session
        let cached = CachedSession {
            ticket: ticket.clone(),
            last_accessed: Instant::now(),
            resumption_count: 0,
            state,
        };

        self.sessions.write().await.insert(session_id, cached);

        // Clean up old sessions if needed
        self.cleanup_old_sessions().await?;

        Ok(ticket)
    }

    /// Validate and retrieve session ticket
    pub async fn validate_ticket(&self, ticket: &SessionTicket) -> Result<SessionState> {
        // Check if ticket is expired
        if is_ticket_expired(ticket) {
            return Err(QsshError::Protocol("Session ticket expired".into()));
        }

        // Verify HMAC integrity
        let expected_hmac = compute_ticket_hmac(ticket, self.server_secret.as_ref());
        if !constant_time_eq(&ticket.signature, &expected_hmac) {
            return Err(QsshError::Protocol("Session ticket signature invalid".into()));
        }

        // Check if session exists in cache
        let mut sessions = self.sessions.write().await;
        if let Some(cached) = sessions.get_mut(&ticket.session_id) {
            // Update access time and count
            cached.last_accessed = Instant::now();
            cached.resumption_count += 1;

            // Return session state
            Ok(cached.state.clone())
        } else {
            // Try to load from disk
            self.load_from_disk(&ticket.session_id).await
        }
    }

    /// Remove session from cache
    pub async fn remove_session(&self, session_id: &str) -> Result<()> {
        self.sessions.write().await.remove(session_id);

        // Remove from disk
        let session_file = self.cache_dir.join(format!("{}.session", session_id));
        if session_file.exists() {
            std::fs::remove_file(session_file)
                .map_err(QsshError::Io)?;
        }

        Ok(())
    }

    /// Save session to disk
    pub async fn save_to_disk(&self, session_id: &str) -> Result<()> {
        let sessions = self.sessions.read().await;
        if let Some(cached) = sessions.get(session_id) {
            let session_file = self.cache_dir.join(format!("{}.session", session_id));

            let data = bincode::serialize(&cached.ticket)
                .map_err(|e| QsshError::Protocol(format!("Failed to serialize ticket: {}", e)))?;

            std::fs::write(session_file, data)
                .map_err(QsshError::Io)?;
        }

        Ok(())
    }

    /// Load session from disk
    async fn load_from_disk(&self, session_id: &str) -> Result<SessionState> {
        let session_file = self.cache_dir.join(format!("{}.session", session_id));

        if !session_file.exists() {
            return Err(QsshError::Protocol("Session not found".into()));
        }

        let data = std::fs::read(session_file)
            .map_err(QsshError::Io)?;

        let ticket: SessionTicket = bincode::deserialize(&data)
            .map_err(|e| QsshError::Protocol(format!("Failed to deserialize ticket: {}", e)))?;

        // Check expiration
        if is_ticket_expired(&ticket) {
            return Err(QsshError::Protocol("Session ticket expired".into()));
        }

        // Decrypt state
        let encryption_key = derive_ticket_key(&ticket.session_id, self.server_secret.as_ref());
        let state_bytes = decrypt_state(&ticket.encrypted_state, &encryption_key, &ticket.nonce)?;

        let state: SessionState = bincode::deserialize(&state_bytes)
            .map_err(|e| QsshError::Protocol(format!("Failed to deserialize state: {}", e)))?;

        Ok(state)
    }

    /// Clean up old sessions
    async fn cleanup_old_sessions(&self) -> Result<()> {
        let mut sessions = self.sessions.write().await;

        // Remove expired sessions
        let now = Instant::now();
        sessions.retain(|_, cached| {
            let age = now.duration_since(cached.last_accessed);
            age < Duration::from_secs(cached.ticket.lifetime)
        });

        // If still over limit, remove least recently used
        if sessions.len() > self.max_sessions {
            let mut entries: Vec<_> = sessions.iter().map(|(id, s)| (id.clone(), s.last_accessed)).collect();
            entries.sort_by_key(|e| e.1);

            let to_remove = sessions.len() - self.max_sessions;
            for (id, _) in entries.iter().take(to_remove) {
                sessions.remove(id);
            }
        }

        Ok(())
    }

    /// Get session statistics
    pub async fn get_stats(&self) -> SessionCacheStats {
        let sessions = self.sessions.read().await;

        SessionCacheStats {
            total_sessions: sessions.len(),
            total_resumptions: sessions.values().map(|s| s.resumption_count).sum(),
            average_lifetime: if sessions.is_empty() {
                Duration::ZERO
            } else {
                let total: Duration = sessions.values()
                    .map(|s| Instant::now().duration_since(s.last_accessed))
                    .sum();
                total / sessions.len() as u32
            },
        }
    }
}

/// Session cache statistics
#[derive(Debug, Clone)]
pub struct SessionCacheStats {
    /// Total cached sessions
    pub total_sessions: usize,
    /// Total successful resumptions
    pub total_resumptions: u32,
    /// Average session lifetime
    pub average_lifetime: Duration,
}

/// Fast reconnection handler
pub struct FastReconnect {
    /// Session cache
    cache: Arc<SessionCache>,
    /// Maximum reconnection attempts
    max_attempts: u32,
    /// Backoff strategy
    backoff: BackoffStrategy,
}

/// Backoff strategy for reconnection
#[derive(Debug, Clone)]
pub enum BackoffStrategy {
    /// Fixed delay between attempts
    Fixed(Duration),
    /// Exponential backoff
    Exponential {
        initial: Duration,
        max: Duration,
        multiplier: f64,
    },
    /// Linear backoff
    Linear {
        initial: Duration,
        increment: Duration,
        max: Duration,
    },
}

impl FastReconnect {
    /// Create new fast reconnect handler
    pub fn new(cache: Arc<SessionCache>) -> Self {
        Self {
            cache,
            max_attempts: 5,
            backoff: BackoffStrategy::Exponential {
                initial: Duration::from_millis(100),
                max: Duration::from_secs(30),
                multiplier: 2.0,
            },
        }
    }

    /// Attempt fast reconnection
    pub async fn reconnect(&self, ticket: &SessionTicket) -> Result<SessionState> {
        let mut attempt = 0;
        let mut delay = self.initial_delay();

        loop {
            attempt += 1;

            // Try to validate ticket
            match self.cache.validate_ticket(ticket).await {
                Ok(state) => return Ok(state),
                Err(e) if attempt >= self.max_attempts => return Err(e),
                Err(_) => {
                    // Wait before retry
                    tokio::time::sleep(delay).await;
                    delay = self.next_delay(delay, attempt);
                }
            }
        }
    }

    /// Get initial delay
    fn initial_delay(&self) -> Duration {
        match &self.backoff {
            BackoffStrategy::Fixed(d) => *d,
            BackoffStrategy::Exponential { initial, .. } => *initial,
            BackoffStrategy::Linear { initial, .. } => *initial,
        }
    }

    /// Calculate next delay
    fn next_delay(&self, current: Duration, attempt: u32) -> Duration {
        match &self.backoff {
            BackoffStrategy::Fixed(d) => *d,
            BackoffStrategy::Exponential { max, multiplier, .. } => {
                let next = current.mul_f64(*multiplier);
                if next > *max { *max } else { next }
            }
            BackoffStrategy::Linear { increment, max, .. } => {
                let next = current + *increment * attempt;
                if next > *max { *max } else { next }
            }
        }
    }
}

// Helper functions

fn generate_session_id() -> String {
    let mut rng = rand::thread_rng();
    let bytes: Vec<u8> = (0..16).map(|_| rng.gen()).collect();
    hex::encode(bytes)
}

fn generate_nonce() -> Vec<u8> {
    let mut rng = rand::thread_rng();
    (0..12).map(|_| rng.gen()).collect()
}

fn generate_salt() -> Vec<u8> {
    let mut rng = rand::thread_rng();
    (0..16).map(|_| rng.gen()).collect()
}

fn current_timestamp() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_else(|_| std::time::Duration::from_secs(0))
        .as_secs()
}

fn is_ticket_expired(ticket: &SessionTicket) -> bool {
    let now = current_timestamp();
    now > ticket.issued_at + ticket.lifetime
}

fn derive_ticket_key(session_id: &str, server_secret: Option<&[u8; 32]>) -> Vec<u8> {
    let mut hasher = Sha256::new();
    if let Some(secret) = server_secret {
        hasher.update(secret);
    }
    hasher.update(session_id.as_bytes());
    hasher.update(b"QSSH_SESSION_TICKET");
    hasher.finalize().to_vec()
}

/// Compute HMAC-SHA256 over ticket fields (excluding the signature field itself)
fn compute_ticket_hmac(ticket: &SessionTicket, server_secret: Option<&[u8; 32]>) -> Vec<u8> {
    use hmac::{Hmac, Mac};
    type HmacSha256 = Hmac<Sha256>;

    // Use server secret as HMAC key, or a zero key for client-only caches
    let key = server_secret.map(|s| s.as_slice()).unwrap_or(&[0u8; 32]);
    let mut mac = HmacSha256::new_from_slice(key).expect("HMAC key length is valid");

    // Feed all ticket fields except signature
    mac.update(ticket.session_id.as_bytes());
    mac.update(ticket.server_id.as_bytes());
    mac.update(ticket.username.as_bytes());
    mac.update(&ticket.issued_at.to_be_bytes());
    mac.update(&ticket.lifetime.to_be_bytes());
    mac.update(&ticket.encrypted_state);
    mac.update(&ticket.nonce);
    mac.update(&ticket.session_keys.symmetric_key);
    mac.update(&ticket.session_keys.mac_key);
    mac.update(&ticket.session_keys.salt);

    mac.finalize().into_bytes().to_vec()
}

/// Constant-time comparison to prevent timing attacks on HMAC verification
fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
    if a.len() != b.len() {
        return false;
    }
    a.iter().zip(b.iter()).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
}

fn derive_session_key(master_key: &[u8], salt: &[u8], context: &[u8]) -> Vec<u8> {
    use hkdf::Hkdf;
    let hk = Hkdf::<Sha256>::new(Some(salt), master_key);
    let mut output = vec![0u8; 32];
    hk.expand(context, &mut output).expect("HKDF expand failed");
    output
}

fn encrypt_state(data: &[u8], key: &[u8], nonce: &[u8]) -> Result<Vec<u8>> {
    use aes_gcm::{Aes256Gcm, KeyInit, aead::Aead};
    use aes_gcm::aead::generic_array::GenericArray;

    let cipher = Aes256Gcm::new(GenericArray::from_slice(key));
    let nonce = GenericArray::from_slice(nonce);

    cipher.encrypt(nonce, data)
        .map_err(|e| QsshError::Crypto(format!("Session state encryption failed: {}", e)))
}

fn decrypt_state(data: &[u8], key: &[u8], nonce: &[u8]) -> Result<Vec<u8>> {
    use aes_gcm::{Aes256Gcm, KeyInit, aead::Aead};
    use aes_gcm::aead::generic_array::GenericArray;

    let cipher = Aes256Gcm::new(GenericArray::from_slice(key));
    let nonce = GenericArray::from_slice(nonce);

    cipher.decrypt(nonce, data)
        .map_err(|e| QsshError::Crypto(format!("Session state decryption failed: {}", e)))
}

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

    #[tokio::test]
    async fn test_session_ticket_creation() {
        let temp_dir = TempDir::new().unwrap();
        let cache = SessionCache::new(temp_dir.path().to_path_buf()).unwrap();

        let state = SessionState {
            cipher_suite: "chacha20-poly1305".to_string(),
            compression: "zlib".to_string(),
            port_forwards: vec![],
            environment: HashMap::new(),
            terminal: None,
            x11_forwarding: false,
            agent_forwarding: true,
        };

        let ticket = cache.create_ticket(
            "server.example.com",
            "user",
            state,
            PqAlgorithm::Falcon512,
        ).await.unwrap();

        assert_eq!(ticket.server_id, "server.example.com");
        assert_eq!(ticket.username, "user");
        assert!(!ticket.session_id.is_empty());
    }

    #[tokio::test]
    async fn test_session_validation() {
        let temp_dir = TempDir::new().unwrap();
        let cache = SessionCache::new(temp_dir.path().to_path_buf()).unwrap();

        let state = SessionState {
            cipher_suite: "aes256-gcm".to_string(),
            compression: "none".to_string(),
            port_forwards: vec!["8080:localhost:80".to_string()],
            environment: HashMap::new(),
            terminal: Some(TerminalState {
                term_type: "xterm-256color".to_string(),
                cols: 80,
                rows: 24,
                modes: HashMap::new(),
            }),
            x11_forwarding: true,
            agent_forwarding: false,
        };

        let ticket = cache.create_ticket(
            "test.server",
            "testuser",
            state.clone(),
            PqAlgorithm::Falcon512,
        ).await.unwrap();

        // Validate ticket
        let retrieved_state = cache.validate_ticket(&ticket).await.unwrap();
        assert_eq!(retrieved_state.cipher_suite, state.cipher_suite);
        assert_eq!(retrieved_state.compression, state.compression);
        assert_eq!(retrieved_state.port_forwards, state.port_forwards);
        assert!(retrieved_state.terminal.is_some());
    }

    #[test]
    fn test_backoff_strategies() {
        let fixed = BackoffStrategy::Fixed(Duration::from_secs(1));
        let exponential = BackoffStrategy::Exponential {
            initial: Duration::from_millis(100),
            max: Duration::from_secs(10),
            multiplier: 2.0,
        };
        let linear = BackoffStrategy::Linear {
            initial: Duration::from_millis(100),
            increment: Duration::from_millis(100),
            max: Duration::from_secs(5),
        };

        // Just verify they can be created
        assert!(matches!(fixed, BackoffStrategy::Fixed(_)));
        assert!(matches!(exponential, BackoffStrategy::Exponential { .. }));
        assert!(matches!(linear, BackoffStrategy::Linear { .. }));
    }

    #[test]
    fn test_ticket_expiration() {
        let ticket = SessionTicket {
            session_id: "test".to_string(),
            server_id: "server".to_string(),
            username: "user".to_string(),
            issued_at: current_timestamp() - 3600, // 1 hour ago
            lifetime: 1800, // 30 minutes
            encrypted_state: vec![],
            pq_algorithm: PqAlgorithm::Falcon512,
            session_keys: EncryptedKeys {
                symmetric_key: vec![],
                mac_key: vec![],
                salt: vec![],
            },
            nonce: vec![],
            signature: vec![],
        };

        assert!(is_ticket_expired(&ticket));
    }
}