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