Skip to main content

rustfs_iam/mfa/
recovery.rs

1// Copyright 2024 RustFS Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Single-use recovery codes.
16//!
17//! The escape hatch for a lost authenticator. Codes are shown once at
18//! generation and stored only as hashes, so losing the store does not hand an
19//! attacker a working second factor and RustFS cannot show a user their codes
20//! again — only replace them.
21//!
22//! # Why a plain hash and not a password KDF
23//!
24//! A code carries [`RECOVERY_CODE_ENTROPY_BITS`] bits of uniform randomness, so
25//! the attacks a slow KDF defends against do not apply: there is no dictionary
26//! to try and no human-chosen pattern to exploit, and a brute-force search of a
27//! 100-bit space stays infeasible against a fast hash. Meanwhile a memory-hard
28//! KDF would have to run once per stored code on every verification attempt,
29//! which turns each guess into an attacker-controlled multiple of that cost.
30//! This is the standard treatment for high-entropy bearer tokens, and the same
31//! reasoning is why a per-code salt is absent: with no dictionary and no
32//! repeated values, a salt would protect nothing.
33
34use rand::Rng as _;
35use serde::{Deserialize, Serialize};
36use sha2::{Digest as _, Sha256};
37use subtle::ConstantTimeEq as _;
38use time::OffsetDateTime;
39
40/// How many codes a generation produces.
41///
42/// Enough that a user can lose a few without being locked out, few enough that
43/// a verification attempt only ever compares against a short list.
44pub const RECOVERY_CODE_COUNT: usize = 10;
45
46/// Characters per group, and groups per code.
47const GROUP_LEN: usize = 4;
48const GROUP_COUNT: usize = 5;
49
50/// Significant characters in one code.
51const CODE_LEN: usize = GROUP_LEN * GROUP_COUNT;
52
53/// Entropy per code: one alphabet symbol is 5 bits.
54pub const RECOVERY_CODE_ENTROPY_BITS: usize = CODE_LEN * 5;
55
56/// Crockford base32: base32 with `I`, `L`, `O` and `U` removed.
57///
58/// Dropping them means a handwritten code cannot be ambiguous between `1`/`I`/`L`
59/// or `0`/`O`, and `U` is excluded so a random code cannot spell an unfortunate
60/// word. Exactly 32 symbols, so indexing with `byte % 32` is unbiased.
61const ALPHABET: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
62
63/// Domain separator, so a hash from this scheme can never be confused with one
64/// computed over the same bytes for another purpose.
65const HASH_DOMAIN: &[u8] = b"rustfs-recovery-code:v1";
66
67/// A stored recovery code: its hash, and whether it has been spent.
68#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
69pub struct StoredRecoveryCode {
70    /// Lowercase hex of the domain-separated SHA-256 digest.
71    pub hash: String,
72    /// When this code was consumed. `None` while it is still usable.
73    #[serde(with = "time::serde::rfc3339::option", default, skip_serializing_if = "Option::is_none")]
74    pub used_at: Option<OffsetDateTime>,
75}
76
77impl StoredRecoveryCode {
78    pub const fn is_available(&self) -> bool {
79        self.used_at.is_none()
80    }
81}
82
83/// A freshly generated set: the plaintext to show once, and what to persist.
84#[derive(Debug)]
85pub struct GeneratedRecoveryCodes {
86    /// Formatted for display. Never persisted, never logged.
87    pub plaintext: Vec<String>,
88    pub stored: Vec<StoredRecoveryCode>,
89}
90
91/// Generate a fresh set of codes.
92pub fn generate() -> GeneratedRecoveryCodes {
93    let mut rng = rand::rng();
94    let mut plaintext = Vec::with_capacity(RECOVERY_CODE_COUNT);
95    let mut stored = Vec::with_capacity(RECOVERY_CODE_COUNT);
96
97    for _ in 0..RECOVERY_CODE_COUNT {
98        let mut bytes = [0u8; CODE_LEN];
99        rng.fill_bytes(&mut bytes);
100
101        let symbols: Vec<u8> = bytes.iter().map(|byte| ALPHABET[(*byte % 32) as usize]).collect();
102        let formatted = symbols
103            .chunks(GROUP_LEN)
104            .map(|chunk| String::from_utf8_lossy(chunk).to_string())
105            .collect::<Vec<_>>()
106            .join("-");
107
108        stored.push(StoredRecoveryCode {
109            hash: hash_code(&formatted),
110            used_at: None,
111        });
112        plaintext.push(formatted);
113    }
114
115    GeneratedRecoveryCodes { plaintext, stored }
116}
117
118/// Hash a code for storage or comparison.
119///
120/// Normalizes first, so a code retyped in lowercase, without dashes, or with
121/// `O` for `0` still hashes to the stored value.
122pub fn hash_code(code: &str) -> String {
123    let mut hasher = Sha256::new();
124    hasher.update(HASH_DOMAIN);
125    hasher.update([0u8]);
126    hasher.update(normalize(code).as_bytes());
127    hex_lower(&hasher.finalize())
128}
129
130/// Whether `code` could be a recovery code.
131///
132/// Used to route a submitted second factor without asking the user which kind
133/// they typed. Deliberately shape-only: it says nothing about validity.
134pub fn looks_like_recovery_code(code: &str) -> bool {
135    let normalized = normalize(code);
136    normalized.len() == CODE_LEN && normalized.bytes().all(|b| ALPHABET.contains(&b))
137}
138
139/// Outcome of consuming a code against a stored set.
140#[derive(Debug, Clone, Copy, PartialEq, Eq)]
141pub enum ConsumeOutcome {
142    /// The code matched an unused entry, now marked spent at `index`.
143    Consumed { index: usize, remaining: u32 },
144    /// The code matched an entry that had already been spent.
145    AlreadyUsed,
146    /// No entry matched.
147    NoMatch,
148}
149
150/// Spend `code` against `codes`, marking the matching entry used.
151///
152/// Every entry is examined and the comparison is constant-time, so neither the
153/// timing nor the outcome reveals *which* code was close. A code that matches an
154/// already-spent entry is reported distinctly from one that matches nothing:
155/// the caller audits them the same way but an operator investigating a
156/// compromise needs to tell "replayed a used code" from "guessed wrong".
157pub fn consume(codes: &mut [StoredRecoveryCode], code: &str, now: OffsetDateTime) -> ConsumeOutcome {
158    let candidate = hash_code(code);
159
160    let mut matched_unused: Option<usize> = None;
161    let mut matched_used = false;
162
163    for (index, stored) in codes.iter().enumerate() {
164        if !bool::from(stored.hash.as_bytes().ct_eq(candidate.as_bytes())) {
165            continue;
166        }
167        if stored.is_available() {
168            if matched_unused.is_none() {
169                matched_unused = Some(index);
170            }
171        } else {
172            matched_used = true;
173        }
174    }
175
176    if let Some(index) = matched_unused {
177        codes[index].used_at = Some(now);
178        return ConsumeOutcome::Consumed {
179            index,
180            remaining: remaining(codes),
181        };
182    }
183
184    if matched_used {
185        return ConsumeOutcome::AlreadyUsed;
186    }
187
188    ConsumeOutcome::NoMatch
189}
190
191/// How many codes are still usable.
192pub fn remaining(codes: &[StoredRecoveryCode]) -> u32 {
193    codes.iter().filter(|code| code.is_available()).count() as u32
194}
195
196/// Strip formatting and fold the characters Crockford treats as equivalent.
197fn normalize(code: &str) -> String {
198    code.chars()
199        .filter(|c| !c.is_whitespace() && *c != '-')
200        .map(|c| match c.to_ascii_uppercase() {
201            // Crockford's decode aliases: a handwritten code must survive being
202            // read back by a human.
203            'O' => '0',
204            'I' | 'L' => '1',
205            other => other,
206        })
207        .collect()
208}
209
210fn hex_lower(bytes: &[u8]) -> String {
211    let mut out = String::with_capacity(bytes.len() * 2);
212    for byte in bytes {
213        out.push_str(&format!("{byte:02x}"));
214    }
215    out
216}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221    use std::collections::HashSet;
222
223    fn now() -> OffsetDateTime {
224        OffsetDateTime::from_unix_timestamp(1_700_000_000).expect("valid timestamp")
225    }
226
227    #[test]
228    fn generation_produces_the_expected_shape() {
229        let generated = generate();
230
231        assert_eq!(generated.plaintext.len(), RECOVERY_CODE_COUNT);
232        assert_eq!(generated.stored.len(), RECOVERY_CODE_COUNT);
233
234        for code in &generated.plaintext {
235            // Five groups of four, dash-separated, as the UI renders them.
236            let groups: Vec<&str> = code.split('-').collect();
237            assert_eq!(groups.len(), GROUP_COUNT, "code {code} has the wrong group count");
238            for group in groups {
239                assert_eq!(group.len(), GROUP_LEN, "group {group} has the wrong length");
240                assert!(group.bytes().all(|b| ALPHABET.contains(&b)), "group {group} has a stray symbol");
241            }
242        }
243    }
244
245    #[test]
246    fn codes_carry_the_documented_entropy() {
247        assert_eq!(RECOVERY_CODE_ENTROPY_BITS, 100);
248    }
249
250    #[test]
251    fn generated_codes_are_distinct() {
252        let generated = generate();
253        let unique: HashSet<&String> = generated.plaintext.iter().collect();
254        assert_eq!(unique.len(), RECOVERY_CODE_COUNT, "generation produced a duplicate");
255    }
256
257    #[test]
258    fn the_alphabet_excludes_ambiguous_characters() {
259        for excluded in *b"ILOU" {
260            assert!(!ALPHABET.contains(&excluded), "{} must not be in the alphabet", excluded as char);
261        }
262        assert_eq!(ALPHABET.len(), 32, "indexing with `% 32` requires exactly 32 symbols");
263    }
264
265    #[test]
266    fn plaintext_is_never_recoverable_from_what_is_stored() {
267        let generated = generate();
268        for (code, stored) in generated.plaintext.iter().zip(&generated.stored) {
269            let normalized = normalize(code);
270            assert!(!stored.hash.contains(code), "stored hash leaks the formatted code");
271            assert!(!stored.hash.contains(&normalized), "stored hash leaks the normalized code");
272            assert_eq!(stored.hash.len(), 64, "expected a hex SHA-256 digest");
273        }
274    }
275
276    #[test]
277    fn a_generated_code_can_be_consumed_once() {
278        let generated = generate();
279        let mut stored = generated.stored;
280        let code = &generated.plaintext[3];
281
282        assert_eq!(
283            consume(&mut stored, code, now()),
284            ConsumeOutcome::Consumed {
285                index: 3,
286                remaining: (RECOVERY_CODE_COUNT - 1) as u32
287            }
288        );
289        assert_eq!(stored[3].used_at, Some(now()));
290    }
291
292    #[test]
293    fn a_consumed_code_cannot_be_reused() {
294        // The single-use property, which is the whole point of the `used_at`
295        // column: an attacker who saw a code being typed must not be able to
296        // reuse it.
297        let generated = generate();
298        let mut stored = generated.stored;
299        let code = &generated.plaintext[0];
300
301        consume(&mut stored, code, now());
302        assert_eq!(consume(&mut stored, code, now()), ConsumeOutcome::AlreadyUsed);
303        assert_eq!(remaining(&stored), (RECOVERY_CODE_COUNT - 1) as u32);
304    }
305
306    #[test]
307    fn an_unknown_code_does_not_match() {
308        let generated = generate();
309        let mut stored = generated.stored;
310
311        assert_eq!(consume(&mut stored, "ZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZ", now()), ConsumeOutcome::NoMatch);
312        assert_eq!(remaining(&stored), RECOVERY_CODE_COUNT as u32);
313    }
314
315    #[test]
316    fn consuming_does_not_disturb_the_other_codes() {
317        let generated = generate();
318        let mut stored = generated.stored;
319
320        consume(&mut stored, &generated.plaintext[5], now());
321
322        for (index, entry) in stored.iter().enumerate() {
323            assert_eq!(entry.is_available(), index != 5, "entry {index} changed unexpectedly");
324        }
325    }
326
327    #[test]
328    fn codes_verify_after_realistic_transcription() {
329        let generated = generate();
330        let code = &generated.plaintext[1];
331
332        for variant in [
333            code.to_ascii_lowercase(),
334            code.replace('-', ""),
335            code.replace('-', " "),
336            format!("  {code}  "),
337        ] {
338            let mut stored = generated.stored.clone();
339            assert!(
340                matches!(consume(&mut stored, &variant, now()), ConsumeOutcome::Consumed { .. }),
341                "variant {variant:?} should verify"
342            );
343        }
344    }
345
346    #[test]
347    fn crockford_aliases_are_folded() {
348        // A code containing 0 or 1 must still verify when a human writes O or I.
349        assert_eq!(normalize("O1IL-0000-0000-0000-0000"), "0111000000000000 0000".replace(' ', ""));
350        assert_eq!(hash_code("o1il-0000-0000-0000-0000"), hash_code("0111-0000-0000-0000-0000"));
351    }
352
353    #[test]
354    fn shape_detection_separates_recovery_codes_from_totp_codes() {
355        let generated = generate();
356
357        assert!(looks_like_recovery_code(&generated.plaintext[0]));
358        assert!(looks_like_recovery_code(&generated.plaintext[0].to_ascii_lowercase()));
359        assert!(!looks_like_recovery_code("123456"));
360        assert!(!looks_like_recovery_code(""));
361        // Right length, wrong alphabet.
362        assert!(!looks_like_recovery_code("UUUU-UUUU-UUUU-UUUU-UUUU"));
363    }
364
365    #[test]
366    fn hashing_is_domain_separated() {
367        // The same bytes hashed without the domain prefix must not collide with
368        // this scheme's output.
369        let code = "ABCD-EFGH-JKMN-PQRS-TVWX";
370        let mut bare = Sha256::new();
371        bare.update(normalize(code).as_bytes());
372
373        assert_ne!(hash_code(code), hex_lower(&bare.finalize()));
374    }
375
376    #[test]
377    fn remaining_counts_only_unused_codes() {
378        let generated = generate();
379        let mut stored = generated.stored;
380        assert_eq!(remaining(&stored), RECOVERY_CODE_COUNT as u32);
381
382        for index in 0..3 {
383            consume(&mut stored, &generated.plaintext[index], now());
384        }
385        assert_eq!(remaining(&stored), (RECOVERY_CODE_COUNT - 3) as u32);
386    }
387
388    #[test]
389    fn stored_codes_round_trip_through_serde() {
390        let generated = generate();
391        let mut stored = generated.stored;
392        consume(&mut stored, &generated.plaintext[0], now());
393
394        let encoded = serde_json::to_string(&stored).expect("serialize");
395        let decoded: Vec<StoredRecoveryCode> = serde_json::from_str(&encoded).expect("deserialize");
396
397        assert_eq!(decoded, stored);
398        assert!(!encoded.contains(&generated.plaintext[0]), "serialized form must not carry plaintext");
399    }
400}