Skip to main content

auth_framework/security/
secure_mfa.rs

1// Secure MFA implementation with cryptographically strong code generation
2// Fixes critical security vulnerabilities in MFA code generation and validation
3
4use crate::errors::{AuthError, Result};
5use crate::storage::AuthStorage;
6use base64::Engine;
7use dashmap::DashMap;
8use ring::rand::{SecureRandom, SystemRandom};
9use serde::{Deserialize, Serialize};
10use std::sync::Arc;
11use std::time::{Duration, SystemTime};
12use subtle::ConstantTimeEq;
13use zeroize::ZeroizeOnDrop;
14
15/// Secure MFA challenge with proper entropy and expiration
16#[derive(Clone, Serialize, Deserialize)]
17pub struct MfaChallenge {
18    pub challenge_id: String,
19    pub user_id: String,
20    pub challenge_type: MfaChallengeType,
21    pub code_hash: String,
22    pub created_at: SystemTime,
23    pub expires_at: SystemTime,
24    pub attempts: u32,
25    pub max_attempts: u32,
26}
27
28impl std::fmt::Debug for MfaChallenge {
29    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        let mut d = f.debug_struct("MfaChallenge");
31        d.field("challenge_id", &self.challenge_id);
32        d.field("user_id", &self.user_id);
33        d.field("challenge_type", &self.challenge_type);
34        d.field(
35            "code_hash",
36            &crate::utils::redact::redacted(&self.code_hash),
37        );
38        d.field("created_at", &self.created_at);
39        d.field("expires_at", &self.expires_at);
40        d.field("attempts", &self.attempts);
41        d.field("max_attempts", &self.max_attempts);
42        d.finish()
43    }
44}
45
46#[derive(Debug, Clone, Serialize, Deserialize)]
47pub enum MfaChallengeType {
48    Sms,
49    Email,
50    Totp,
51}
52
53/// Secure MFA code that zeros itself when dropped
54#[derive(Clone, ZeroizeOnDrop)]
55pub struct SecureMfaCode {
56    code: String,
57}
58
59impl std::fmt::Debug for SecureMfaCode {
60    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61        let mut d = f.debug_struct("SecureMfaCode");
62        d.field("code", &crate::utils::redact::redacted(&self.code));
63        d.finish()
64    }
65}
66
67impl SecureMfaCode {
68    pub fn as_str(&self) -> &str {
69        &self.code
70    }
71}
72
73/// Secure MFA service with proper cryptographic implementations
74pub struct SecureMfaService {
75    storage: Box<dyn AuthStorage>,
76    rng: SystemRandom,
77    /// Rate limiting: user_id -> (attempts, last_attempt)
78    rate_limits: Arc<DashMap<String, (u32, SystemTime)>>,
79}
80
81impl SecureMfaService {
82    pub fn new(storage: Box<dyn AuthStorage>) -> Self {
83        Self {
84            storage,
85            rng: SystemRandom::new(),
86            rate_limits: Arc::new(DashMap::new()),
87        }
88    }
89
90    /// Generate cryptographically secure MFA code
91    pub fn generate_secure_code(&self, length: usize) -> Result<SecureMfaCode> {
92        if !(4..=12).contains(&length) {
93            return Err(AuthError::validation(
94                "MFA code length must be between 4 and 12",
95            ));
96        }
97
98        let mut code = String::with_capacity(length);
99
100        // Generate each digit individually to avoid modulo bias
101        for _ in 0..length {
102            let mut byte = [0u8; 1];
103            loop {
104                self.rng.fill(&mut byte).map_err(|_| {
105                    AuthError::crypto("Failed to generate secure random bytes".to_string())
106                })?;
107
108                // Use rejection sampling for uniform distribution (0-9)
109                let digit = byte[0] % 250; // Use 250 to avoid bias (250 is divisible by 10)
110                if digit < 250 {
111                    code.push(char::from(b'0' + (digit % 10)));
112                    break;
113                }
114            }
115        }
116
117        Ok(SecureMfaCode { code })
118    }
119
120    /// Hash MFA code for secure storage
121    fn hash_code(&self, code: &str, salt: &[u8]) -> Result<String> {
122        use ring::digest;
123
124        let mut context = digest::Context::new(&digest::SHA256);
125        context.update(salt);
126        context.update(code.as_bytes());
127        let hash = context.finish();
128
129        Ok(base64::engine::general_purpose::STANDARD.encode(hash.as_ref()))
130    }
131
132    /// Generate secure salt
133    fn generate_salt(&self) -> Result<Vec<u8>> {
134        let mut salt = vec![0u8; 32];
135        self.rng
136            .fill(&mut salt)
137            .map_err(|_| AuthError::crypto("Failed to generate salt".to_string()))?;
138        Ok(salt)
139    }
140
141    /// Check rate limiting for user
142    fn check_rate_limit(&self, user_id: &str) -> Result<()> {
143        let now = SystemTime::now();
144        let window = Duration::from_secs(60); // 1 minute window
145        let max_attempts = 5; // Max 5 attempts per minute
146
147        let (attempts, last_attempt) = self
148            .rate_limits
149            .get(user_id)
150            .map(|entry| *entry.value())
151            .unwrap_or((0, now));
152
153        // Reset counter if window has passed
154        if now.duration_since(last_attempt).unwrap_or(Duration::ZERO) > window {
155            self.rate_limits.insert(user_id.to_string(), (1, now));
156            return Ok(());
157        }
158
159        if attempts >= max_attempts {
160            return Err(AuthError::rate_limit(
161                "Too many MFA attempts. Please wait.".to_string(),
162            ));
163        }
164
165        self.rate_limits
166            .insert(user_id.to_string(), (attempts + 1, now));
167        Ok(())
168    }
169
170    /// Create secure MFA challenge
171    pub async fn create_challenge(
172        &self,
173        user_id: &str,
174        challenge_type: MfaChallengeType,
175        code_length: usize,
176    ) -> Result<(String, SecureMfaCode)> {
177        // Check rate limiting
178        self.check_rate_limit(user_id)?;
179
180        // Generate secure challenge ID
181        let challenge_id = self.generate_secure_id("mfa")?;
182
183        // Generate secure code
184        let secure_code = self.generate_secure_code(code_length)?;
185
186        // Generate salt and hash the code
187        let salt = self.generate_salt()?;
188        let code_hash = self.hash_code(secure_code.as_str(), &salt)?;
189
190        // Create challenge
191        let now = SystemTime::now();
192        let challenge = MfaChallenge {
193            challenge_id: challenge_id.clone(),
194            user_id: user_id.to_string(),
195            challenge_type,
196            code_hash,
197            created_at: now,
198            expires_at: now + Duration::from_secs(300), // 5 minutes
199            attempts: 0,
200            max_attempts: 3,
201        };
202
203        // Store challenge and salt
204        let challenge_data = serde_json::to_vec(&challenge)
205            .map_err(|e| AuthError::crypto(format!("Failed to serialize challenge: {}", e)))?;
206
207        self.storage
208            .store_kv(
209                &format!("mfa_challenge:{}", challenge_id),
210                &challenge_data,
211                Some(Duration::from_secs(300)),
212            )
213            .await?;
214
215        self.storage
216            .store_kv(
217                &format!("mfa_salt:{}", challenge_id),
218                &salt,
219                Some(Duration::from_secs(300)),
220            )
221            .await?;
222
223        tracing::info!("Created secure MFA challenge for user: {}", user_id);
224        Ok((challenge_id, secure_code))
225    }
226
227    /// Verify MFA code with constant-time comparison
228    pub async fn verify_challenge(&self, challenge_id: &str, provided_code: &str) -> Result<bool> {
229        // Validate input format
230        if provided_code.is_empty() || provided_code.len() > 12 {
231            return Ok(false);
232        }
233
234        if !provided_code.chars().all(|c| c.is_ascii_digit()) {
235            return Ok(false);
236        }
237
238        // Retrieve challenge
239        let challenge_data = self
240            .storage
241            .get_kv(&format!("mfa_challenge:{}", challenge_id))
242            .await?;
243
244        let mut challenge: MfaChallenge = match challenge_data {
245            Some(data) => serde_json::from_slice(&data)
246                .map_err(|_| AuthError::validation("Invalid challenge data"))?,
247            None => return Ok(false), // Challenge not found or expired
248        };
249
250        // Check if challenge is expired
251        if SystemTime::now() > challenge.expires_at {
252            // Clean up expired challenge
253            self.cleanup_challenge(challenge_id).await?;
254            return Ok(false);
255        }
256
257        // Check attempt limits
258        if challenge.attempts >= challenge.max_attempts {
259            self.cleanup_challenge(challenge_id).await?;
260            return Ok(false);
261        }
262
263        // Increment attempt counter
264        challenge.attempts += 1;
265        let challenge_data = serde_json::to_vec(&challenge)
266            .map_err(|e| AuthError::crypto(format!("Failed to serialize challenge: {}", e)))?;
267        self.storage
268            .store_kv(
269                &format!("mfa_challenge:{}", challenge_id),
270                &challenge_data,
271                Some(Duration::from_secs(300)),
272            )
273            .await?;
274
275        // Retrieve salt
276        let salt = match self
277            .storage
278            .get_kv(&format!("mfa_salt:{}", challenge_id))
279            .await?
280        {
281            Some(salt) => salt,
282            None => return Ok(false),
283        };
284
285        // Hash provided code with same salt
286        let provided_hash = self.hash_code(provided_code, &salt)?;
287
288        // Constant-time comparison
289        let is_valid = challenge
290            .code_hash
291            .as_bytes()
292            .ct_eq(provided_hash.as_bytes())
293            .into();
294
295        if is_valid {
296            // Clean up successful challenge
297            self.cleanup_challenge(challenge_id).await?;
298            tracing::info!(
299                "MFA challenge verified successfully for user: {}",
300                challenge.user_id
301            );
302        }
303
304        Ok(is_valid)
305    }
306
307    /// Clean up challenge data
308    async fn cleanup_challenge(&self, challenge_id: &str) -> Result<()> {
309        let _ = self
310            .storage
311            .delete_kv(&format!("mfa_challenge:{}", challenge_id))
312            .await;
313        let _ = self
314            .storage
315            .delete_kv(&format!("mfa_salt:{}", challenge_id))
316            .await;
317        Ok(())
318    }
319
320    /// Generate secure ID
321    fn generate_secure_id(&self, prefix: &str) -> Result<String> {
322        let mut bytes = vec![0u8; 16];
323        self.rng
324            .fill(&mut bytes)
325            .map_err(|_| AuthError::crypto("Failed to generate secure ID".to_string()))?;
326
327        let id = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(&bytes);
328        Ok(format!("{}_{}", prefix, id))
329    }
330
331    /// Generate cryptographically secure backup codes
332    pub fn generate_backup_codes(
333        &self,
334        count: u8,
335    ) -> Result<Vec<String>, Box<dyn std::error::Error>> {
336        let mut codes = Vec::with_capacity(count as usize);
337
338        for _ in 0..count {
339            // Generate a secure 16-character alphanumeric backup code
340            let mut code_bytes = [0u8; 10]; // 10 bytes = 80 bits of entropy
341            self.rng.fill(&mut code_bytes)?;
342
343            // Convert to base32 for human readability (no ambiguous characters)
344            let code = base32::encode(base32::Alphabet::Rfc4648 { padding: false }, &code_bytes);
345
346            // Format as XXXX-XXXX-XXXX-XXXX for readability
347            let formatted_code = format!(
348                "{}-{}-{}-{}",
349                &code[0..4],
350                &code[4..8],
351                &code[8..12],
352                &code[12..16]
353            );
354
355            codes.push(formatted_code);
356        }
357
358        Ok(codes)
359    }
360
361    /// Securely hash backup codes for storage
362    pub fn hash_backup_codes(
363        &self,
364        codes: &[String],
365    ) -> Result<Vec<String>, Box<dyn std::error::Error>> {
366        let mut hashed_codes = Vec::with_capacity(codes.len());
367
368        for code in codes {
369            // Use ring's PBKDF2 for secure hashing
370            let salt = self.generate_salt()?;
371            let mut hash = [0u8; 32];
372
373            ring::pbkdf2::derive(
374                ring::pbkdf2::PBKDF2_HMAC_SHA256,
375                std::num::NonZeroU32::new(100_000).unwrap(), // 100k iterations
376                &salt,
377                code.as_bytes(),
378                &mut hash,
379            );
380
381            // Store as salt:hash for verification
382            let salt_hex = hex::encode(&salt);
383            let hash_hex = hex::encode(hash);
384            hashed_codes.push(format!("{}:{}", salt_hex, hash_hex));
385        }
386
387        Ok(hashed_codes)
388    }
389
390    /// Verify a backup code against stored hashes
391    pub fn verify_backup_code(
392        &self,
393        hashed_codes: &[String],
394        provided_code: &str,
395    ) -> Result<bool, Box<dyn std::error::Error>> {
396        // Input validation
397        if provided_code.len() != 19 || provided_code.chars().filter(|&c| c == '-').count() != 3 {
398            return Ok(false);
399        }
400
401        // Remove dashes for processing
402        let clean_code = provided_code.replace("-", "");
403        if clean_code.len() != 16 || !clean_code.chars().all(|c| c.is_ascii_alphanumeric()) {
404            return Ok(false);
405        }
406
407        for hashed_code in hashed_codes {
408            let parts: Vec<&str> = hashed_code.split(':').collect();
409            if parts.len() != 2 {
410                continue;
411            }
412
413            let salt = match hex::decode(parts[0]) {
414                Ok(s) => s,
415                Err(_) => continue,
416            };
417
418            let stored_hash = match hex::decode(parts[1]) {
419                Ok(h) => h,
420                Err(_) => continue,
421            };
422
423            // Derive hash from provided code
424            let mut derived_hash = [0u8; 32];
425            ring::pbkdf2::derive(
426                ring::pbkdf2::PBKDF2_HMAC_SHA256,
427                std::num::NonZeroU32::new(100_000).unwrap(),
428                &salt,
429                provided_code.as_bytes(),
430                &mut derived_hash,
431            );
432
433            // Constant-time comparison
434            if subtle::ConstantTimeEq::ct_eq(&stored_hash[..], &derived_hash[..]).into() {
435                return Ok(true);
436            }
437        }
438
439        Ok(false)
440    }
441}
442
443#[cfg(test)]
444mod tests {
445    use super::*;
446    use crate::testing::MockStorage;
447
448    #[tokio::test]
449    async fn test_secure_code_generation() {
450        let storage = Box::new(MockStorage::new());
451        let mfa_service = SecureMfaService::new(storage);
452
453        let code = mfa_service.generate_secure_code(6).unwrap();
454        assert_eq!(code.as_str().len(), 6);
455        assert!(code.as_str().chars().all(|c| c.is_ascii_digit()));
456    }
457
458    #[tokio::test]
459    async fn test_mfa_challenge_flow() {
460        let storage = Box::new(MockStorage::new());
461        let mfa_service = SecureMfaService::new(storage);
462
463        // Create challenge
464        let (challenge_id, code) = mfa_service
465            .create_challenge("user123", MfaChallengeType::Sms, 6)
466            .await
467            .unwrap();
468
469        // Verify with correct code
470        let result = mfa_service
471            .verify_challenge(&challenge_id, code.as_str())
472            .await
473            .unwrap();
474        assert!(result);
475
476        // Challenge should be cleaned up after successful verification
477        let result2 = mfa_service
478            .verify_challenge(&challenge_id, code.as_str())
479            .await
480            .unwrap();
481        assert!(!result2);
482    }
483
484    #[tokio::test]
485    async fn test_invalid_code_rejection() {
486        let storage = Box::new(MockStorage::new());
487        let mfa_service = SecureMfaService::new(storage);
488
489        let (challenge_id, _code) = mfa_service
490            .create_challenge("user123", MfaChallengeType::Sms, 6)
491            .await
492            .unwrap();
493
494        // Test various invalid codes
495        assert!(
496            !mfa_service
497                .verify_challenge(&challenge_id, "000000")
498                .await
499                .unwrap()
500        );
501        assert!(
502            !mfa_service
503                .verify_challenge(&challenge_id, "123abc")
504                .await
505                .unwrap()
506        );
507        assert!(
508            !mfa_service
509                .verify_challenge(&challenge_id, "")
510                .await
511                .unwrap()
512        );
513        assert!(
514            !mfa_service
515                .verify_challenge(&challenge_id, "12345678901234")
516                .await
517                .unwrap()
518        );
519    }
520
521    #[tokio::test]
522    async fn test_rate_limiting() {
523        let storage = Box::new(MockStorage::new());
524        let mfa_service = SecureMfaService::new(storage);
525
526        // Should succeed first few times
527        for _ in 0..5 {
528            let result = mfa_service
529                .create_challenge("user123", MfaChallengeType::Sms, 6)
530                .await;
531            assert!(result.is_ok());
532        }
533
534        // Should fail due to rate limiting
535        let result = mfa_service
536            .create_challenge("user123", MfaChallengeType::Sms, 6)
537            .await;
538        assert!(result.is_err());
539    }
540}