Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_net/src/webauthn/challenge.rs

5.7 KiB, 1 run

created by r1870400018:72157, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! Stateless WebAuthn challenges.
2//!
3//! A challenge kept in a server-side map lets an unauthenticated flood of ceremony starts evict
4//! another browser's challenge. Here nothing is kept at mint: the challenge is a random nonce,
5//! and the browser carries it back in a short-lived pre-auth cookie together with its expiry, its
6//! purpose (`create` or `get`) and an HMAC-SHA256 over all three under a per-process key. The only
7//! server state is the used-set that refuses a second showing inside the window, a
8//! `guard::nonce::NonceTracker`, bounded by its window and its cap. A restart makes a new key and
9//! voids the open challenges, which at 120 s is acceptable.
10//!
11//! The used-set fails closed: once full it refuses every check until pairs lapse, so a site that
12//! lets strangers check challenges should rate-limit that route by address.
13
14use crate::{
15 acme::jose::{
16 base64url_decode,
17 base64url_encode,
18 },
19 guard::nonce::NonceTracker,
20 hmac::{
21 hmac_sha256,
22 verify_hmac_sha256,
23 },
24};
25
26use oxedyne_fe2o3_core::{
27 prelude::*,
28 rand::Rand,
29};
30
31use std::{
32 sync::Mutex,
33 time::Duration,
34};
35
36pub const TTL_SECS: u64 = 120;
37pub const NONCE_LEN: usize = 32;
38
39const DOMAIN: &[u8] = b"fe2o3 webauthn challenge v1";
40const COOKIE_LEN: usize = 1 + 8 + NONCE_LEN + 32; // purpose, expiry, nonce, tag
41
42#[derive(Clone, Copy, Debug, Eq, PartialEq)]
43pub enum Purpose {
44 Create, // navigator.credentials.create()
45 Get, // navigator.credentials.get()
46}
47
48impl Purpose {
49 fn tag(self) -> u8 {
50 match self {
51 Self::Create => b'c',
52 Self::Get => b'g',
53 }
54 }
55}
56
57/// Mints and checks the challenges of one process.
58pub struct Challenges {
59 key: [u8; 32],
60 used: Mutex<NonceTracker>,
61}
62
63impl Challenges {
64 /// A fresh random key, so a restart voids every open challenge.
65 pub fn new() -> Self {
66 let mut key = [0u8; 32];
67 Rand::fill_u8(&mut key);
68 Self::with_key(key)
69 }
70
71 pub fn with_key(key: [u8; 32]) -> Self {
72 Self {
73 key,
74 used: Mutex::new(NonceTracker::new(Duration::from_secs(TTL_SECS))),
75 }
76 }
77
78 /// Caps the used-set, at least one; `NonceTracker::MAX_PAIRS` by default.
79 pub fn with_max_used(self, max: usize) -> Self {
80 let used = match self.used.into_inner() {
81 Ok(t) => t,
82 Err(p) => p.into_inner(),
83 };
84 Self {
85 key: self.key,
86 used: Mutex::new(used.with_max_pairs(max)),
87 }
88 }
89
90 /// A new challenge for `purpose`, valid until `now + TTL_SECS`: the raw challenge bytes for
91 /// the browser's `publicKey.challenge`, and the value of the cookie that carries it back.
92 /// Nothing is recorded.
93 pub fn mint(&self, purpose: Purpose, now: u64) -> ([u8; NONCE_LEN], String) {
94 let mut nonce = [0u8; NONCE_LEN];
95 Rand::fill_u8(&mut nonce);
96 let exp = now.saturating_add(TTL_SECS);
97 let mut b = Vec::with_capacity(COOKIE_LEN);
98 b.push(purpose.tag());
99 b.extend_from_slice(&exp.to_be_bytes());
100 b.extend_from_slice(&nonce);
101 let tag = hmac_sha256(&self.key, &signed(&b));
102 b.extend_from_slice(&tag);
103 (nonce, base64url_encode(&b))
104 }
105
106 /// Accepts `client_challenge` once: the cookie must carry this process's tag, be unexpired at
107 /// `now`, be for `purpose`, and carry exactly this challenge, and its nonce must not have been
108 /// accepted before.
109 pub fn check(
110 &self,
111 cookie: &str,
112 client_challenge: &[u8],
113 purpose: Purpose,
114 now: u64,
115 )
116 -> Outcome<()>
117 {
118 let b = res!(base64url_decode(cookie));
119 if b.len() != COOKIE_LEN {
120 return Err(err!(
121 "A WebAuthn challenge cookie must decode to {} bytes, this one is {}.",
122 COOKIE_LEN, b.len();
123 Invalid, Input, Size));
124 }
125 let (body, tag) = b.split_at(COOKIE_LEN - 32);
126 if !verify_hmac_sha256(&self.key, &signed(body), tag) {
127 return Err(err!(
128 "A WebAuthn challenge cookie's tag does not verify under this process's key: \
129 tampered, or minted before a restart.";
130 Invalid, Security, Mismatch));
131 }
132 if body[0] != purpose.tag() {
133 return Err(err!(
134 "A WebAuthn challenge minted for one ceremony was presented for {:?}.", purpose;
135 Invalid, Security, Mismatch));
136 }
137 let mut eb = [0u8; 8];
138 eb.copy_from_slice(&body[1..9]);
139 let exp = u64::from_be_bytes(eb);
140 if now >= exp {
141 return Err(err!(
142 "A WebAuthn challenge expired at {}, and it is now {}.", exp, now;
143 Invalid, Security, Timeout));
144 }
145 let mut nonce = [0u8; NONCE_LEN];
146 nonce.copy_from_slice(&body[9..]);
147 if client_challenge != &nonce[..] {
148 return Err(err!(
149 "The challenge the browser signed is not the one its cookie carries.";
150 Invalid, Security, Mismatch));
151 }
152 let mut used = lock_mutex!(self.used);
153 // Held until the later of now and the mint time, plus the window: at least to `exp`.
154 res!(used.record(&[body[0]], &nonce, exp.saturating_sub(TTL_SECS), now));
155 Ok(())
156 }
157
158 /// How many accepted nonces the used-set holds.
159 pub fn used_len(&self) -> Outcome<usize> {
160 Ok(lock_mutex!(self.used).len())
161 }
162}
163
164impl Default for Challenges {
165 fn default() -> Self {
166 Self::new()
167 }
168}
169
170fn signed(body: &[u8]) -> Vec<u8> {
171 let mut m = Vec::with_capacity(DOMAIN.len() + body.len());
172 m.extend_from_slice(DOMAIN);
173 m.extend_from_slice(body);
174 m
175}