qssh 0.0.2-alpha

Experimental quantum-safe SSH using post-quantum crypto. Research project - NOT for production. See LIMITATIONS.md
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
//! Security monitoring and audit logging
//!
//! Provides comprehensive security monitoring, threat detection,
//! and audit logging for QSSH operations.

use crate::{Result, QsshError};
use serde::{Serialize, Deserialize};
use std::sync::Arc;
use tokio::sync::{RwLock, mpsc};
use std::collections::HashMap;
use std::net::IpAddr;
use std::time::{SystemTime, UNIX_EPOCH, Duration};
use tokio::fs::OpenOptions;
use tokio::io::AsyncWriteExt;

/// Security event severity levels
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum Severity {
    Debug,
    Info,
    Warning,
    Error,
    Critical,
}

/// Security event types
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum EventType {
    /// Authentication events
    AuthSuccess { username: String, method: String },
    AuthFailure { username: String, method: String, reason: String },
    AuthRateLimited { ip: IpAddr },

    /// Connection events
    ConnectionEstablished { ip: IpAddr, version: String },
    ConnectionClosed { ip: IpAddr, reason: String },
    ConnectionRejected { ip: IpAddr, reason: String },

    /// Key management events
    KeyExchange { algorithm: String, success: bool },
    KeyRotation { generation: u64, method: String },
    QkdKeyUsed { size: usize },

    /// Channel events
    ChannelOpened { channel_id: u32, channel_type: String },
    ChannelClosed { channel_id: u32 },
    PortForward { local: u16, remote: String },

    /// Security violations
    InvalidProtocol { description: String },
    ReplayAttack { sequence: u64 },
    CryptoError { description: String },

    /// Administrative events
    ConfigChange { setting: String, old_value: String, new_value: String },
    AuditLogRotated { old_file: String, new_file: String },

    /// Anomaly detection
    AnomalyDetected { anomaly_type: String, details: String },
    BruteForceAttempt { ip: IpAddr, attempts: u32 },
    SuspiciousPattern { pattern: String, confidence: f32 },
}

/// Security event
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityEvent {
    pub timestamp: u64,
    pub severity: Severity,
    pub event_type: EventType,
    pub session_id: Option<String>,
    pub source_ip: Option<IpAddr>,
    pub additional_data: HashMap<String, String>,
}

impl SecurityEvent {
    pub fn new(severity: Severity, event_type: EventType) -> Self {
        Self {
            timestamp: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs(),
            severity,
            event_type,
            session_id: None,
            source_ip: None,
            additional_data: HashMap::new(),
        }
    }

    pub fn with_session(mut self, session_id: String) -> Self {
        self.session_id = Some(session_id);
        self
    }

    pub fn with_ip(mut self, ip: IpAddr) -> Self {
        self.source_ip = Some(ip);
        self
    }

    pub fn with_data(mut self, key: String, value: String) -> Self {
        self.additional_data.insert(key, value);
        self
    }
}

/// Security monitor configuration
#[derive(Clone)]
pub struct SecurityConfig {
    pub log_file: String,
    pub max_log_size: u64,
    pub rotation_count: u32,
    pub enable_anomaly_detection: bool,
    pub alert_threshold: Severity,
    pub retention_days: u32,
}

impl Default for SecurityConfig {
    fn default() -> Self {
        Self {
            log_file: "/var/log/qssh/security.log".to_string(),
            max_log_size: 100 * 1024 * 1024, // 100MB
            rotation_count: 10,
            enable_anomaly_detection: true,
            alert_threshold: Severity::Warning,
            retention_days: 90,
        }
    }
}

/// Security monitor
pub struct SecurityMonitor {
    config: SecurityConfig,
    events: Arc<RwLock<Vec<SecurityEvent>>>,
    alert_handlers: Arc<RwLock<Vec<Box<dyn AlertHandler>>>>,
    anomaly_detector: Arc<AnomalyDetector>,
    event_sender: mpsc::Sender<SecurityEvent>,
    stats: Arc<RwLock<SecurityStats>>,
}

impl SecurityMonitor {
    /// Create new security monitor
    pub fn new(config: SecurityConfig) -> Self {
        let (event_sender, event_receiver) = mpsc::channel(1000);

        let monitor = Self {
            config: config.clone(),
            events: Arc::new(RwLock::new(Vec::new())),
            alert_handlers: Arc::new(RwLock::new(Vec::new())),
            anomaly_detector: Arc::new(AnomalyDetector::new()),
            event_sender,
            stats: Arc::new(RwLock::new(SecurityStats::default())),
        };

        // Start background tasks
        let monitor_clone = monitor.clone();
        tokio::spawn(async move {
            monitor_clone.event_processor(event_receiver).await;
        });

        if config.enable_anomaly_detection {
            let monitor_clone = monitor.clone();
            tokio::spawn(async move {
                monitor_clone.anomaly_detection_task().await;
            });
        }

        monitor
    }

    /// Log a security event
    pub async fn log_event(&self, event: SecurityEvent) -> Result<()> {
        // Update statistics
        {
            let mut stats = self.stats.write().await;
            stats.total_events += 1;
            match event.severity {
                Severity::Debug => stats.debug_count += 1,
                Severity::Info => stats.info_count += 1,
                Severity::Warning => stats.warning_count += 1,
                Severity::Error => stats.error_count += 1,
                Severity::Critical => stats.critical_count += 1,
            }
        }

        // Send to processor
        self.event_sender.send(event.clone()).await
            .map_err(|_| QsshError::Protocol("Failed to send event".into()))?;

        // Check for alerts
        if event.severity >= self.config.alert_threshold {
            self.trigger_alerts(&event).await;
        }

        Ok(())
    }

    /// Process events in background
    async fn event_processor(&self, mut receiver: mpsc::Receiver<SecurityEvent>) {
        while let Some(event) = receiver.recv().await {
            // Store in memory
            {
                let mut events = self.events.write().await;
                events.push(event.clone());

                // Limit memory usage
                if events.len() > 10000 {
                    events.drain(0..5000);
                }
            }

            // Write to log file
            if let Err(e) = self.write_to_log(&event).await {
                log::error!("Failed to write security event to log: {}", e);
            }

            // Check for anomalies
            if self.config.enable_anomaly_detection {
                self.anomaly_detector.analyze(&event).await;
            }
        }
    }

    /// Write event to log file
    async fn write_to_log(&self, event: &SecurityEvent) -> Result<()> {
        let json = serde_json::to_string(event)
            .map_err(|e| QsshError::Protocol(format!("Failed to serialize event: {}", e)))?;

        let mut file = OpenOptions::new()
            .create(true)
            .append(true)
            .open(&self.config.log_file)
            .await
            .map_err(|e| QsshError::Io(e))?;

        file.write_all(format!("{}\n", json).as_bytes()).await
            .map_err(|e| QsshError::Io(e))?;

        file.flush().await
            .map_err(|e| QsshError::Io(e))?;

        // Check for rotation
        let metadata = file.metadata().await
            .map_err(|e| QsshError::Io(e))?;

        if metadata.len() > self.config.max_log_size {
            self.rotate_log().await?;
        }

        Ok(())
    }

    /// Rotate log files
    async fn rotate_log(&self) -> Result<()> {
        for i in (1..self.config.rotation_count).rev() {
            let old_name = format!("{}.{}", self.config.log_file, i);
            let new_name = format!("{}.{}", self.config.log_file, i + 1);

            if tokio::fs::metadata(&old_name).await.is_ok() {
                tokio::fs::rename(&old_name, &new_name).await
                    .map_err(|e| QsshError::Io(e))?;
            }
        }

        // Rename current to .1
        tokio::fs::rename(&self.config.log_file, format!("{}.1", self.config.log_file)).await
            .map_err(|e| QsshError::Io(e))?;

        // Log rotation event
        let event = SecurityEvent::new(
            Severity::Info,
            EventType::AuditLogRotated {
                old_file: self.config.log_file.clone(),
                new_file: format!("{}.1", self.config.log_file),
            },
        );

        self.log_event(event).await?;
        Ok(())
    }

    /// Trigger alerts for high-severity events
    async fn trigger_alerts(&self, event: &SecurityEvent) {
        let handlers = self.alert_handlers.read().await;
        for handler in handlers.iter() {
            handler.handle_alert(event).await;
        }
    }

    /// Register an alert handler
    pub async fn register_alert_handler(&self, handler: Box<dyn AlertHandler>) {
        let mut handlers = self.alert_handlers.write().await;
        handlers.push(handler);
    }

    /// Anomaly detection task
    async fn anomaly_detection_task(&self) {
        let mut interval = tokio::time::interval(Duration::from_secs(60));

        loop {
            interval.tick().await;

            let events = self.events.read().await;
            let recent_events: Vec<_> = events.iter()
                .rev()
                .take(1000)
                .cloned()
                .collect();

            drop(events); // Release lock

            // Analyze patterns
            for anomaly in self.anomaly_detector.detect_patterns(&recent_events).await {
                let event = SecurityEvent::new(
                    Severity::Warning,
                    EventType::AnomalyDetected {
                        anomaly_type: anomaly.anomaly_type,
                        details: anomaly.details,
                    },
                );

                if let Err(e) = self.log_event(event).await {
                    log::error!("Failed to log anomaly: {}", e);
                }
            }
        }
    }

    /// Get security statistics
    pub async fn get_stats(&self) -> SecurityStats {
        self.stats.read().await.clone()
    }

    /// Query events
    pub async fn query_events(&self, filter: EventFilter) -> Vec<SecurityEvent> {
        let events = self.events.read().await;
        events.iter()
            .filter(|e| filter.matches(e))
            .cloned()
            .collect()
    }
}

impl Clone for SecurityMonitor {
    fn clone(&self) -> Self {
        Self {
            config: self.config.clone(),
            events: self.events.clone(),
            alert_handlers: self.alert_handlers.clone(),
            anomaly_detector: self.anomaly_detector.clone(),
            event_sender: self.event_sender.clone(),
            stats: self.stats.clone(),
        }
    }
}

/// Alert handler trait
#[async_trait::async_trait]
pub trait AlertHandler: Send + Sync {
    async fn handle_alert(&self, event: &SecurityEvent);
}

/// Email alert handler
pub struct EmailAlertHandler {
    recipient: String,
}

#[async_trait::async_trait]
impl AlertHandler for EmailAlertHandler {
    async fn handle_alert(&self, event: &SecurityEvent) {
        // In production, send actual email
        log::error!("SECURITY ALERT to {}: {:?}", self.recipient, event);
    }
}

/// Anomaly detector
struct AnomalyDetector {
    patterns: Arc<RwLock<HashMap<String, PatternTracker>>>,
}

impl AnomalyDetector {
    fn new() -> Self {
        Self {
            patterns: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    async fn analyze(&self, event: &SecurityEvent) {
        // Track patterns
        let mut patterns = self.patterns.write().await;

        // Track auth failures per IP
        if let EventType::AuthFailure { .. } = &event.event_type {
            if let Some(ip) = event.source_ip {
                let key = format!("auth_fail_{}", ip);
                let tracker = patterns.entry(key).or_insert(PatternTracker::new());
                tracker.increment();
            }
        }
    }

    async fn detect_patterns(&self, events: &[SecurityEvent]) -> Vec<Anomaly> {
        let mut anomalies = Vec::new();
        let patterns = self.patterns.read().await;

        // Check for brute force
        for (key, tracker) in patterns.iter() {
            if key.starts_with("auth_fail_") && tracker.count > 5 {
                let ip_str = key.strip_prefix("auth_fail_").unwrap_or("");
                if let Ok(ip) = ip_str.parse::<IpAddr>() {
                    anomalies.push(Anomaly {
                        anomaly_type: "BruteForce".to_string(),
                        details: format!("Multiple auth failures from {}", ip),
                        confidence: 0.9,
                    });
                }
            }
        }

        anomalies
    }
}

/// Pattern tracker
struct PatternTracker {
    count: u32,
    first_seen: u64,
    last_seen: u64,
}

impl PatternTracker {
    fn new() -> Self {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();

        Self {
            count: 0,
            first_seen: now,
            last_seen: now,
        }
    }

    fn increment(&mut self) {
        self.count += 1;
        self.last_seen = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
    }
}

/// Detected anomaly
struct Anomaly {
    anomaly_type: String,
    details: String,
    confidence: f32,
}

/// Event filter for queries
pub struct EventFilter {
    pub severity_min: Option<Severity>,
    pub time_range: Option<(u64, u64)>,
    pub event_types: Option<Vec<String>>,
    pub session_id: Option<String>,
    pub source_ip: Option<IpAddr>,
}

impl EventFilter {
    pub fn new() -> Self {
        Self {
            severity_min: None,
            time_range: None,
            event_types: None,
            session_id: None,
            source_ip: None,
        }
    }

    fn matches(&self, event: &SecurityEvent) -> bool {
        if let Some(min_severity) = self.severity_min {
            if event.severity < min_severity {
                return false;
            }
        }

        if let Some((start, end)) = self.time_range {
            if event.timestamp < start || event.timestamp > end {
                return false;
            }
        }

        if let Some(session_id) = &self.session_id {
            if event.session_id.as_ref() != Some(session_id) {
                return false;
            }
        }

        if let Some(ip) = self.source_ip {
            if event.source_ip != Some(ip) {
                return false;
            }
        }

        true
    }
}

/// Security statistics
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SecurityStats {
    pub total_events: u64,
    pub debug_count: u64,
    pub info_count: u64,
    pub warning_count: u64,
    pub error_count: u64,
    pub critical_count: u64,
    pub anomalies_detected: u64,
    pub alerts_triggered: u64,
}

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

    #[tokio::test]
    async fn test_security_event_creation() {
        let event = SecurityEvent::new(
            Severity::Warning,
            EventType::AuthFailure {
                username: "alice".to_string(),
                method: "password".to_string(),
                reason: "Invalid password".to_string(),
            },
        );

        assert_eq!(event.severity, Severity::Warning);
        assert!(event.timestamp > 0);
    }

    #[tokio::test]
    async fn test_event_filter() {
        let filter = EventFilter {
            severity_min: Some(Severity::Warning),
            time_range: None,
            event_types: None,
            session_id: None,
            source_ip: None,
        };

        let event1 = SecurityEvent::new(Severity::Info, EventType::AuthSuccess {
            username: "alice".to_string(),
            method: "key".to_string(),
        });

        let event2 = SecurityEvent::new(Severity::Error, EventType::CryptoError {
            description: "Invalid signature".to_string(),
        });

        assert!(!filter.matches(&event1)); // Info < Warning
        assert!(filter.matches(&event2));  // Error >= Warning
    }
}