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
//! Rate limiting for authentication attempts
//!
//! Prevents brute force attacks by limiting authentication attempts
//! per IP address with exponential backoff

use crate::{Result, QsshError};
use std::collections::HashMap;
use std::net::IpAddr;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::RwLock;
use serde::{Serialize, Deserialize};

/// Configuration for rate limiting
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RateLimitConfig {
    /// Maximum attempts before temporary ban
    pub max_attempts: u32,
    /// Time window for counting attempts (seconds)
    pub window_seconds: u64,
    /// Base ban duration (seconds) - doubles with each violation
    pub base_ban_seconds: u64,
    /// Maximum ban duration (seconds)
    pub max_ban_seconds: u64,
    /// Whether to use exponential backoff
    pub exponential_backoff: bool,
}

impl Default for RateLimitConfig {
    fn default() -> Self {
        Self {
            max_attempts: 5,           // 5 attempts
            window_seconds: 60,         // per minute
            base_ban_seconds: 60,       // 1 minute base ban
            max_ban_seconds: 3600,      // 1 hour max ban
            exponential_backoff: true,  // Use exponential backoff
        }
    }
}

/// Track authentication attempts for an IP
#[derive(Debug, Clone)]
struct AttemptRecord {
    /// Number of failed attempts
    failed_attempts: u32,
    /// Time of first attempt in current window
    window_start: Instant,
    /// Time when ban expires (if banned)
    ban_until: Option<Instant>,
    /// Number of times this IP has been banned
    ban_count: u32,
    /// Last successful authentication time
    last_success: Option<Instant>,
}

impl AttemptRecord {
    fn new() -> Self {
        Self {
            failed_attempts: 0,
            window_start: Instant::now(),
            ban_until: None,
            ban_count: 0,
            last_success: None,
        }
    }

    /// Check if currently banned
    fn is_banned(&self) -> bool {
        if let Some(ban_until) = self.ban_until {
            ban_until > Instant::now()
        } else {
            false
        }
    }

    /// Get remaining ban time
    fn ban_remaining(&self) -> Option<Duration> {
        if let Some(ban_until) = self.ban_until {
            let now = Instant::now();
            if ban_until > now {
                Some(ban_until - now)
            } else {
                None
            }
        } else {
            None
        }
    }

    /// Reset the window if expired
    fn reset_if_expired(&mut self, window: Duration) {
        let now = Instant::now();
        if now.duration_since(self.window_start) > window {
            self.failed_attempts = 0;
            self.window_start = now;
        }
    }
}

/// Rate limiter for authentication attempts
pub struct RateLimiter {
    config: RateLimitConfig,
    attempts: Arc<RwLock<HashMap<IpAddr, AttemptRecord>>>,
}

impl RateLimiter {
    /// Create new rate limiter with default config
    pub fn new() -> Self {
        Self::with_config(RateLimitConfig::default())
    }

    /// Create rate limiter with custom config
    pub fn with_config(config: RateLimitConfig) -> Self {
        Self {
            config,
            attempts: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// Check if an IP is allowed to attempt authentication
    pub async fn check_allowed(&self, ip: IpAddr) -> Result<()> {
        let mut attempts = self.attempts.write().await;
        let record = attempts.entry(ip).or_insert_with(AttemptRecord::new);

        // Check if currently banned
        if record.is_banned() {
            let remaining = record.ban_remaining()
                .map(|d| d.as_secs())
                .unwrap_or(0);

            return Err(QsshError::RateLimited(format!(
                "Too many failed attempts. Try again in {} seconds",
                remaining
            )));
        }

        // Reset window if expired
        let window = Duration::from_secs(self.config.window_seconds);
        record.reset_if_expired(window);

        // Check if over limit
        if record.failed_attempts >= self.config.max_attempts {
            // Apply ban
            let ban_duration = if self.config.exponential_backoff {
                // Exponential backoff: base * 2^ban_count
                let multiplier = 2_u64.saturating_pow(record.ban_count);
                let duration = self.config.base_ban_seconds.saturating_mul(multiplier);
                duration.min(self.config.max_ban_seconds)
            } else {
                self.config.base_ban_seconds
            };

            record.ban_until = Some(Instant::now() + Duration::from_secs(ban_duration));
            record.ban_count = record.ban_count.saturating_add(1);

            return Err(QsshError::RateLimited(format!(
                "Too many failed attempts. Banned for {} seconds",
                ban_duration
            )));
        }

        Ok(())
    }

    /// Record a failed authentication attempt
    pub async fn record_failure(&self, ip: IpAddr) {
        let mut attempts = self.attempts.write().await;
        let record = attempts.entry(ip).or_insert_with(AttemptRecord::new);

        // Reset window if expired
        let window = Duration::from_secs(self.config.window_seconds);
        record.reset_if_expired(window);

        // Increment failure count
        record.failed_attempts = record.failed_attempts.saturating_add(1);

        log::warn!(
            "Failed auth attempt from {} ({}/{} in window)",
            ip,
            record.failed_attempts,
            self.config.max_attempts
        );
    }

    /// Record a successful authentication
    pub async fn record_success(&self, ip: IpAddr) {
        let mut attempts = self.attempts.write().await;
        let record = attempts.entry(ip).or_insert_with(AttemptRecord::new);

        // Reset on success
        record.failed_attempts = 0;
        record.last_success = Some(Instant::now());

        // Don't reset ban_count immediately - decay it over time
        // This prevents attackers from resetting their penalty with stolen creds

        log::info!("Successful auth from {}", ip);
    }

    /// Clean up old records (housekeeping)
    pub async fn cleanup(&self) {
        let mut attempts = self.attempts.write().await;
        let now = Instant::now();
        let window = Duration::from_secs(self.config.window_seconds * 10); // Keep 10x window

        // Remove old records that haven't been used recently
        attempts.retain(|ip, record| {
            // Keep if:
            // - Currently banned
            // - Had activity in last 10 windows
            // - Has recent success

            if record.is_banned() {
                return true;
            }

            if now.duration_since(record.window_start) < window {
                return true;
            }

            if let Some(last_success) = record.last_success {
                if now.duration_since(last_success) < Duration::from_secs(86400) {
                    return true; // Keep successful logins for 24 hours
                }
            }

            log::debug!("Cleaning up rate limit record for {}", ip);
            false
        });
    }

    /// Get current statistics
    pub async fn get_stats(&self) -> RateLimitStats {
        let attempts = self.attempts.read().await;

        let total_tracked = attempts.len();
        let currently_banned = attempts.values()
            .filter(|r| r.is_banned())
            .count();

        let high_risk = attempts.iter()
            .filter(|(_, r)| r.ban_count > 2)
            .map(|(ip, _)| *ip)
            .collect();

        RateLimitStats {
            total_tracked,
            currently_banned,
            high_risk_ips: high_risk,
        }
    }

    /// Manually unban an IP (admin function)
    pub async fn unban(&self, ip: IpAddr) -> Result<()> {
        let mut attempts = self.attempts.write().await;

        if let Some(record) = attempts.get_mut(&ip) {
            record.ban_until = None;
            record.failed_attempts = 0;
            log::info!("Manually unbanned {}", ip);
            Ok(())
        } else {
            Err(QsshError::NotFound(format!("No record for IP {}", ip)))
        }
    }

    /// Check if IP is suspicious (for monitoring)
    pub async fn is_suspicious(&self, ip: IpAddr) -> bool {
        let attempts = self.attempts.read().await;

        if let Some(record) = attempts.get(&ip) {
            // Suspicious if:
            // - Has been banned multiple times
            // - Currently has high failure rate
            // - Is currently banned

            record.ban_count > 1 ||
            record.failed_attempts > self.config.max_attempts / 2 ||
            record.is_banned()
        } else {
            false
        }
    }
}

/// Statistics from the rate limiter
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RateLimitStats {
    /// Total IPs being tracked
    pub total_tracked: usize,
    /// IPs currently banned
    pub currently_banned: usize,
    /// High risk IPs (banned multiple times)
    pub high_risk_ips: Vec<IpAddr>,
}

/// Background task to periodically clean up old records
pub async fn cleanup_task(limiter: Arc<RateLimiter>) {
    let mut interval = tokio::time::interval(Duration::from_secs(300)); // Every 5 minutes

    loop {
        interval.tick().await;
        limiter.cleanup().await;
    }
}

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

    #[tokio::test]
    async fn test_rate_limiting() {
        let config = RateLimitConfig {
            max_attempts: 3,
            window_seconds: 60,
            base_ban_seconds: 10,
            max_ban_seconds: 100,
            exponential_backoff: true,
        };

        let limiter = RateLimiter::with_config(config);
        let ip = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 100));

        // First attempts should succeed
        assert!(limiter.check_allowed(ip).await.is_ok());
        limiter.record_failure(ip).await;

        assert!(limiter.check_allowed(ip).await.is_ok());
        limiter.record_failure(ip).await;

        assert!(limiter.check_allowed(ip).await.is_ok());
        limiter.record_failure(ip).await;

        // Fourth attempt should be rate limited
        assert!(limiter.check_allowed(ip).await.is_err());
    }

    #[tokio::test]
    async fn test_exponential_backoff() {
        let config = RateLimitConfig {
            max_attempts: 2,
            window_seconds: 60,
            base_ban_seconds: 1,
            max_ban_seconds: 100,
            exponential_backoff: true,
        };

        let limiter = RateLimiter::with_config(config);
        let ip = IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1));

        // Get banned once
        limiter.record_failure(ip).await;
        limiter.record_failure(ip).await;
        assert!(limiter.check_allowed(ip).await.is_err());

        // Wait for ban to expire
        tokio::time::sleep(Duration::from_secs(2)).await;

        // Get banned again - should be longer
        assert!(limiter.check_allowed(ip).await.is_ok());
        limiter.record_failure(ip).await;
        limiter.record_failure(ip).await;

        let err = limiter.check_allowed(ip).await.unwrap_err();
        assert!(err.to_string().contains("Banned for 2 seconds"));
    }

    #[tokio::test]
    async fn test_success_resets() {
        let limiter = RateLimiter::new();
        let ip = IpAddr::V4(Ipv4Addr::new(172, 16, 0, 1));

        // Some failures
        limiter.record_failure(ip).await;
        limiter.record_failure(ip).await;

        // Success should reset
        limiter.record_success(ip).await;

        // Should be able to try again
        assert!(limiter.check_allowed(ip).await.is_ok());
    }

    #[tokio::test]
    async fn test_cleanup() {
        let mut config = RateLimitConfig::default();
        config.window_seconds = 1; // Short window for testing

        let limiter = RateLimiter::with_config(config);
        let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));

        // Add a record
        limiter.record_failure(ip).await;

        // Should have one record
        let stats = limiter.get_stats().await;
        assert_eq!(stats.total_tracked, 1);

        // Wait for window to expire significantly
        tokio::time::sleep(Duration::from_secs(15)).await;

        // Cleanup should remove it
        limiter.cleanup().await;
        let stats = limiter.get_stats().await;
        assert_eq!(stats.total_tracked, 0);
    }
}