Skip to main content

rustfs_iam/mfa/
challenge.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//! Login challenges: the token a client echoes back with its second factor.
16//!
17//! # Why these are stateless
18//!
19//! The obvious design is a TTL cache, the way the OIDC flow stores its PKCE
20//! verifiers. That store is node-local, which is fine for OIDC because the
21//! whole authorization round trip returns to the node that started it. A second
22//! factor does not: a cluster behind a load balancer without session affinity
23//! will issue the challenge on one node and receive the code on another, and a
24//! node-local challenge would fail there for reasons no operator could debug.
25//!
26//! So a challenge carries its own state and a signature over it. Any node
27//! validates one without shared storage, and nothing needs replicating.
28//!
29//! Statelessness costs nothing here because a challenge is not what makes the
30//! exchange single-use — the consumed TOTP time step is
31//! ([`super::totp::TotpSecret::verify`]). A replayed challenge with a replayed
32//! code is refused by the step check; a replayed challenge with a fresh code is
33//! just a normal second attempt inside the window, which the rate limiter
34//! bounds.
35
36use base64_simd::URL_SAFE_NO_PAD;
37use hmac::{Hmac, KeyInit as _, Mac};
38use sha2::Sha256;
39use subtle::ConstantTimeEq as _;
40
41type HmacSha256 = Hmac<Sha256>;
42
43/// How long a challenge stays valid.
44///
45/// Long enough to fetch a phone and type a code, short enough that one
46/// intercepted from a log or a proxy is stale by the time it is useful.
47pub const CHALLENGE_TTL_SECONDS: u64 = 300;
48
49/// Domain separator, so a challenge signature can never be mistaken for — or
50/// produced by — another HMAC over the same key.
51const CHALLENGE_DOMAIN: &[u8] = b"rustfs-mfa-challenge:v1";
52
53/// Wire format version, so a future change to the payload is a decode failure
54/// rather than a misparse.
55const CHALLENGE_VERSION: u8 = 1;
56
57#[derive(Debug, thiserror::Error, PartialEq, Eq)]
58pub enum ChallengeError {
59    #[error("the challenge is malformed")]
60    Malformed,
61    #[error("the challenge signature is invalid")]
62    BadSignature,
63    #[error("the challenge has expired")]
64    Expired,
65    #[error("the challenge was issued for a different identity")]
66    IdentityMismatch,
67}
68
69/// Issue a challenge for `access_key`, valid from `issued_at_unix`.
70///
71/// `signing_key` must be a server secret; the deployment's root secret key is
72/// what the STS token path already uses for the same purpose.
73pub fn issue(access_key: &str, issued_at_unix: u64, signing_key: &[u8]) -> String {
74    let payload = format!("{CHALLENGE_VERSION}:{issued_at_unix}:{access_key}");
75    let signature = sign(&payload, signing_key);
76    format!(
77        "{}.{}",
78        URL_SAFE_NO_PAD.encode_to_string(payload.as_bytes()),
79        URL_SAFE_NO_PAD.encode_to_string(signature)
80    )
81}
82
83/// Validate `challenge` for `access_key` at `now_unix`.
84///
85/// Checks the signature before anything else, so a forged challenge cannot
86/// reach the expiry or identity comparisons and learn from them.
87pub fn validate(challenge: &str, access_key: &str, now_unix: u64, signing_key: &[u8]) -> Result<(), ChallengeError> {
88    let (payload_b64, signature_b64) = challenge.split_once('.').ok_or(ChallengeError::Malformed)?;
89
90    let payload = URL_SAFE_NO_PAD
91        .decode_to_vec(payload_b64.as_bytes())
92        .map_err(|_| ChallengeError::Malformed)?;
93    let payload = String::from_utf8(payload).map_err(|_| ChallengeError::Malformed)?;
94    let signature = URL_SAFE_NO_PAD
95        .decode_to_vec(signature_b64.as_bytes())
96        .map_err(|_| ChallengeError::Malformed)?;
97
98    let expected = sign(&payload, signing_key);
99    if !bool::from(expected.ct_eq(&signature)) {
100        return Err(ChallengeError::BadSignature);
101    }
102
103    let mut parts = payload.splitn(3, ':');
104    let version = parts.next().ok_or(ChallengeError::Malformed)?;
105    let issued_at = parts.next().ok_or(ChallengeError::Malformed)?;
106    let challenge_access_key = parts.next().ok_or(ChallengeError::Malformed)?;
107
108    if version != CHALLENGE_VERSION.to_string() {
109        return Err(ChallengeError::Malformed);
110    }
111
112    let issued_at: u64 = issued_at.parse().map_err(|_| ChallengeError::Malformed)?;
113    // A challenge stamped in the future is treated as expired rather than
114    // accepted: it means the issuing clock is wrong, and honouring it would
115    // extend the window by however far off that clock is.
116    if now_unix < issued_at || now_unix.saturating_sub(issued_at) > CHALLENGE_TTL_SECONDS {
117        return Err(ChallengeError::Expired);
118    }
119
120    if !bool::from(challenge_access_key.as_bytes().ct_eq(access_key.as_bytes())) {
121        return Err(ChallengeError::IdentityMismatch);
122    }
123
124    Ok(())
125}
126
127fn sign(payload: &str, signing_key: &[u8]) -> Vec<u8> {
128    let mut mac = HmacSha256::new_from_slice(signing_key).expect("HMAC accepts keys of any length");
129    mac.update(CHALLENGE_DOMAIN);
130    mac.update(&[0]);
131    mac.update(payload.as_bytes());
132    mac.finalize().into_bytes().to_vec()
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138
139    const KEY: &[u8] = b"root-secret-key-for-tests";
140    const NOW: u64 = 1_700_000_000;
141
142    #[test]
143    fn a_fresh_challenge_validates_for_its_identity() {
144        let challenge = issue("sinan", NOW, KEY);
145        assert_eq!(validate(&challenge, "sinan", NOW, KEY), Ok(()));
146    }
147
148    #[test]
149    fn a_challenge_validates_anywhere_in_its_window() {
150        let challenge = issue("sinan", NOW, KEY);
151
152        assert_eq!(validate(&challenge, "sinan", NOW, KEY), Ok(()));
153        assert_eq!(validate(&challenge, "sinan", NOW + CHALLENGE_TTL_SECONDS, KEY), Ok(()));
154    }
155
156    #[test]
157    fn an_expired_challenge_is_rejected() {
158        let challenge = issue("sinan", NOW, KEY);
159        assert_eq!(
160            validate(&challenge, "sinan", NOW + CHALLENGE_TTL_SECONDS + 1, KEY),
161            Err(ChallengeError::Expired)
162        );
163    }
164
165    #[test]
166    fn a_challenge_from_the_future_is_rejected_rather_than_honoured() {
167        // A skewed issuing clock must not silently widen the window.
168        let challenge = issue("sinan", NOW + 60, KEY);
169        assert_eq!(validate(&challenge, "sinan", NOW, KEY), Err(ChallengeError::Expired));
170    }
171
172    #[test]
173    fn a_challenge_for_another_identity_is_rejected() {
174        // Without this, a caller who can authenticate as one identity could
175        // carry its challenge into another identity's verification.
176        let challenge = issue("sinan", NOW, KEY);
177        assert_eq!(validate(&challenge, "someone-else", NOW, KEY), Err(ChallengeError::IdentityMismatch));
178    }
179
180    #[test]
181    fn a_challenge_signed_with_another_key_is_rejected() {
182        let challenge = issue("sinan", NOW, KEY);
183        assert_eq!(validate(&challenge, "sinan", NOW, b"different-key"), Err(ChallengeError::BadSignature));
184    }
185
186    #[test]
187    fn tampering_with_the_payload_is_rejected() {
188        // The point of signing: an attacker must not be able to extend the
189        // expiry or swap the identity by editing the token.
190        let forged_payload = format!("{CHALLENGE_VERSION}:{}:{}", NOW, "attacker");
191        let genuine = issue("sinan", NOW, KEY);
192        let (_, signature) = genuine.split_once('.').expect("well-formed challenge");
193        let forged = format!("{}.{signature}", URL_SAFE_NO_PAD.encode_to_string(forged_payload.as_bytes()));
194
195        assert_eq!(validate(&forged, "attacker", NOW, KEY), Err(ChallengeError::BadSignature));
196    }
197
198    #[test]
199    fn tampering_with_the_signature_is_rejected() {
200        let challenge = issue("sinan", NOW, KEY);
201        let (payload, signature) = challenge.split_once('.').expect("well-formed challenge");
202        let mut bytes = URL_SAFE_NO_PAD.decode_to_vec(signature.as_bytes()).expect("decode");
203        bytes[0] ^= 0xff;
204        let forged = format!("{payload}.{}", URL_SAFE_NO_PAD.encode_to_string(&bytes));
205
206        assert_eq!(validate(&forged, "sinan", NOW, KEY), Err(ChallengeError::BadSignature));
207    }
208
209    #[test]
210    fn malformed_challenges_are_rejected() {
211        for bad in ["", "no-separator", ".", "a.b", "!!!.!!!"] {
212            let result = validate(bad, "sinan", NOW, KEY);
213            assert!(
214                matches!(result, Err(ChallengeError::Malformed) | Err(ChallengeError::BadSignature)),
215                "input {bad:?} gave {result:?}"
216            );
217        }
218    }
219
220    #[test]
221    fn a_challenge_from_an_unknown_version_is_rejected() {
222        // Forward compatibility: an older node must refuse a payload shape it
223        // cannot interpret rather than guess at its fields.
224        let payload = format!("99:{NOW}:sinan");
225        let signature = sign(&payload, KEY);
226        let challenge = format!(
227            "{}.{}",
228            URL_SAFE_NO_PAD.encode_to_string(payload.as_bytes()),
229            URL_SAFE_NO_PAD.encode_to_string(&signature)
230        );
231
232        assert_eq!(validate(&challenge, "sinan", NOW, KEY), Err(ChallengeError::Malformed));
233    }
234
235    #[test]
236    fn any_node_validates_a_challenge_another_node_issued() {
237        // The reason challenges are stateless: no shared store is consulted, so
238        // a cluster without session affinity still completes the exchange.
239        let issuing_node_challenge = issue("sinan", NOW, KEY);
240        // A second "node" holds only the same signing key.
241        assert_eq!(validate(&issuing_node_challenge, "sinan", NOW + 10, KEY), Ok(()));
242    }
243
244    #[test]
245    fn access_keys_containing_the_separator_still_round_trip() {
246        // The payload splits on the first two colons only, so a colon in the
247        // access key cannot truncate the identity.
248        let challenge = issue("team:sinan", NOW, KEY);
249        assert_eq!(validate(&challenge, "team:sinan", NOW, KEY), Ok(()));
250        assert_eq!(validate(&challenge, "team", NOW, KEY), Err(ChallengeError::IdentityMismatch));
251    }
252}