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