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