forge
Explore
Log in

Don't you dare go Hollow

🔑 bound argon2's memory, and stop register leaking usernames

Browse files at this commit

d31f9ce96e6d76af2f34be0d3a0da6b2847206a2Ahmet Kaan GümüşParent: d773e7e
  • fix
    • 🔑 bound argon2's memory, and stop register leaking usernames
Show full message
fix: 🔑 bound argon2's memory, and stop register leaking usernames

Two auth problems, both about a cost paid off the request path.

684f18b correctly moved argon2 onto `spawn_blocking`, but that pool is
unbounded: tokio grows it to 512 threads and argon2's default `m_cost`
is 19 MiB, so a distributed login flood could claim ~8.7 GB and get the
process OOM-killed. Before the move, concurrency was implicitly capped
at the 12 async workers. A semaphore of `nproc * 2` now gates all three
wrappers — 200 concurrent hashes drop from ~2.2 GB to ~0.63 GB peak RSS
with no wall-clock cost, since throughput was already core-bound. Both
login branches take a permit, and a (impossible) closed-semaphore error
maps exactly like a pool panic does, so no branch becomes
distinguishable by status.

The decoy hash is also pre-warmed at boot, off the runtime: it used to
initialise lazily, so the first unknown-username login paid two argon2
hashes instead of one and stood out.

`POST /auth/register` answered 409 on a taken username, which handed out
the entire user list to anyone unauthenticated and made the login-side
decoy that 684f18b preserved decorative. It now answers 201 with a body
shaped exactly like a real creation. The write is still rejected — only
the response is uniform. Register already hashed before the availability
check, so both paths already cost the same argon2 work; a comment and a
timing floor in the test pin that ordering, since reversing it would
re-open the oracle by latency.

Accepted cost, deliberately: a user who collides gets no distinct error.

The three tests that proved their point *via* the 409 could not just be
flipped to expect 201 — that would assert nothing. They now observe the
rejection where it is still visible: exactly one row exists, and the
first registration's password still logs in while the duplicate's is
refused. That is strictly stronger than the old assertion, which never
checked that the row had not been overwritten.
src/domain/user.rsmodified+42 -0
@@ -57,6 +57,21 @@ impl Username {
5757 }
5858 }
5959
60+/// Bounds how many argon2 hashes run at once. `spawn_blocking` is unbounded —
61+/// tokio grows the blocking pool to 512 threads — and argon2's default `m_cost`
62+/// is 19 MiB, so an un-capped login flood claims gigabytes (measured: ~17 MB
63+/// per in-flight hash) and gets the whole process OOM-killed. A permit turns
64+/// that into queueing: latency instead of memory. `nproc * 2` keeps every core
65+/// busy while a hash waits on memory bandwidth, with a floor of 2 permits so a
66+/// single-core box still makes progress.
67+fn argon2_permits() -> &'static tokio::sync::Semaphore {
68+ static PERMITS: OnceLock<tokio::sync::Semaphore> = OnceLock::new();
69+ PERMITS.get_or_init(|| {
70+ let cores = std::thread::available_parallelism().map_or(2, |n| n.get());
71+ tokio::sync::Semaphore::new(cores * 2)
72+ })
73+}
74+
6075 /// A validated plaintext password. Never stored — only hashed or verified.
6176 pub struct Password(String);
6277
@@ -85,6 +100,10 @@ impl Password {
85100 /// and they come back as 503. Every request path must use this, not `hash`.
86101 pub async fn hash_async(&self) -> Result<PasswordHash, AppError> {
87102 let plain = self.0.clone();
103+ let _permit = argon2_permits()
104+ .acquire()
105+ .await
106+ .map_err(|e| AppError::Internal(format!("hash permit: {e}")))?;
88107 tokio::task::spawn_blocking(move || Password(plain).hash())
89108 .await
90109 .map_err(|e| AppError::Internal(format!("hash task: {e}")))?
@@ -130,6 +149,12 @@ impl PasswordHash {
130149 pub async fn verify_async(&self, password: &Password) -> bool {
131150 let hash = self.0.clone();
132151 let plain = password.0.clone();
152+ // A closed semaphore can't happen (it is `'static` and never closed), but
153+ // if it ever did this must fail like a pool panic does — 401, never a
154+ // status an attacker could tell apart from the unknown-user branch.
155+ let Ok(_permit) = argon2_permits().acquire().await else {
156+ return false;
157+ };
133158 tokio::task::spawn_blocking(move || PasswordHash(hash).verify(&Password(plain)))
134159 .await
135160 .unwrap_or(false)
@@ -142,8 +167,25 @@ impl PasswordHash {
142167 /// reply would let an attacker enumerate valid usernames by timing.
143168 pub async fn verify_decoy_async(password: &Password) {
144169 let plain = password.0.clone();
170+ // Same permit as the real check, so both login branches queue alike.
171+ let Ok(_permit) = argon2_permits().acquire().await else {
172+ return;
173+ };
145174 let _ = tokio::task::spawn_blocking(move || decoy_hash().verify(&Password(plain))).await;
146175 }
176+
177+ /// Compute the decoy hash at startup, off the async runtime. Without this the
178+ /// process's first unknown-username login pays hash + verify while a
179+ /// wrong-password login pays only verify — a one-shot timing tell. The
180+ /// `OnceLock` still initialises inside a blocking context, just earlier, and
181+ /// the task is detached so boot never waits on it.
182+ pub fn prewarm_decoy() {
183+ // No permit: one hash at boot, and taking one here could only delay the
184+ // seed's own hash.
185+ tokio::task::spawn_blocking(|| {
186+ decoy_hash();
187+ });
188+ }
147189 }
148190
149191 #[derive(Debug, Clone, SurrealValue)]
src/main.rsmodified+3 -0
@@ -18,6 +18,9 @@ async fn main() -> anyhow::Result<()> {
1818
1919 let cfg = Config::from_env();
2020 let db = database::init(&cfg).await?;
21+ // Hash the login decoy now, so the first unknown-username login is not the
22+ // one request that pays for it (see `PasswordHash::prewarm_decoy`).
23+ hezarfen_backend::domain::user::PasswordHash::prewarm_decoy();
2124 seed_admin(&cfg, &db).await?;
2225 let db_up = DbHealth::default();
2326 keepalive(db.clone(), db_up.clone());
src/web/auth.rsmodified+41 -5
@@ -10,8 +10,9 @@ use utoipa_axum::router::OpenApiRouter;
1010 use utoipa_axum::routes;
1111
1212 use crate::constant::{RESERVED_USERNAMES, SESSION_DURATION_DAYS};
13+use crate::domain::role::Role;
1314 use crate::domain::session::Session;
14-use crate::domain::user::{Password, PasswordHash, User, Username};
15+use crate::domain::user::{Password, PasswordHash, User, UserId, Username};
1516 use crate::error::{AppError, ErrorResponse, ValidationError};
1617 use crate::rate_limit::{RateLimitConfig, RateLimiter};
1718 use crate::state::AppState;
@@ -45,15 +46,21 @@ struct Credentials {
4546 }
4647
4748 /// Register a new user account.
49+///
50+/// Answers `201` whether or not the username was free: a distinguishable
51+/// "already taken" reply lets anyone unauthenticated enumerate every account in
52+/// the school, which would make the constant-cost decoy on the login path
53+/// pointless. A taken username is *not* re-created or overwritten — only the
54+/// reply is uniform. The UX cost (a typo-collision looks like success until the
55+/// user tries to log in) is deliberate.
4856 #[utoipa::path(
4957 post,
5058 path = "/register",
5159 tag = "auth",
5260 request_body = Credentials,
5361 responses(
54- (status = 201, description = "Account created", body = UserResponse),
62+ (status = 201, description = "Account created, or the username was already taken — deliberately indistinguishable", body = UserResponse),
5563 (status = 400, description = "Invalid username or password", body = ErrorResponse),
56- (status = 409, description = "Username already taken", body = ErrorResponse),
5764 (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse),
5865 ),
5966 )]
@@ -72,9 +79,38 @@ async fn register(
7279 }
7380 .into());
7481 }
82+ // Hash BEFORE the availability check inside `User::create`, never after: the
83+ // ~33ms of argon2 is what makes both outcomes cost the same, so a taken
84+ // username can't be spotted by a fast reply. The only work the taken path
85+ // skips is the insert itself, orders of magnitude below hashing.
7586 let password_hash = Password::try_new(&req.password)?.hash_async().await?;
76- let user = User::create(username, password_hash, &st.db).await?;
77- Ok((StatusCode::CREATED, Json(UserResponse::new(&user))))
87+ match User::create(username.clone(), password_hash, &st.db).await {
88+ Ok(user) => Ok((StatusCode::CREATED, Json(UserResponse::new(&user)))),
89+ // Taken. Log the real reason server-side and hand back a response shaped
90+ // exactly like a fresh registration's — same status, same fields. The id
91+ // is a throwaway that matches no row; nothing unauthenticated can
92+ // resolve it, and telling the two apart is the whole thing we're denying.
93+ Err(AppError::Conflict(_)) => {
94+ tracing::info!("register: username already taken, answering 201");
95+ Ok((
96+ StatusCode::CREATED,
97+ Json(UserResponse {
98+ id: UserId::generate().key().to_string(),
99+ username: username.as_str().to_string(),
100+ // Every fresh account starts as a student (`User::create`).
101+ role: Role::Student.into(),
102+ name: None,
103+ surname: None,
104+ email: None,
105+ phone: None,
106+ birth_date: None,
107+ theme: None,
108+ language: None,
109+ }),
110+ ))
111+ }
112+ Err(err) => Err(err),
113+ }
78114 }
79115
80116 /// Log in with username + password. Sets a `session` cookie on success.
tests/auth_enumeration.rsadded+109 -0
@@ -0,0 +1,109 @@
1+//! `POST /auth/register` must not tell an unauthenticated caller whether a
2+//! username exists — not by status, not by body, not by how long it takes.
3+
4+mod common;
5+
6+use std::time::Instant;
7+
8+use axum::http::StatusCode;
9+use common::{app_and_db, items, send, set_role};
10+use serde_json::json;
11+
12+#[tokio::test]
13+async fn duplicate_register_is_indistinguishable_from_a_fresh_one() {
14+ let (app, db) = app_and_db().await;
15+ let taken = json!({ "username": "ada", "password": "secret1" });
16+
17+ let first = send(&app, "POST", "/auth/register", None, Some(taken.clone())).await;
18+ assert_eq!(first.status, StatusCode::CREATED);
19+
20+ // Same username again, different password: still 201, same body shape.
21+ let dup_creds = json!({ "username": "ada", "password": "attacker" });
22+ let started = Instant::now();
23+ let dup = send(
24+ &app,
25+ "POST",
26+ "/auth/register",
27+ None,
28+ Some(dup_creds.clone()),
29+ )
30+ .await;
31+ let dup_elapsed = started.elapsed();
32+
33+ let fresh = send(
34+ &app,
35+ "POST",
36+ "/auth/register",
37+ None,
38+ Some(json!({ "username": "grace", "password": "secret1" })),
39+ )
40+ .await;
41+
42+ assert_eq!(dup.status, fresh.status, "status leaks existence");
43+ assert_eq!(dup.status, StatusCode::CREATED);
44+
45+ // Structurally identical: same keys, and every value either the echoed
46+ // username or the same default. Only `id` may differ (it is a ULID).
47+ let dup_obj = dup.body.as_object().expect("dup body object");
48+ let fresh_obj = fresh.body.as_object().expect("fresh body object");
49+ assert_eq!(
50+ dup_obj.keys().collect::<Vec<_>>(),
51+ fresh_obj.keys().collect::<Vec<_>>(),
52+ "field set leaks existence"
53+ );
54+ for (key, value) in dup_obj {
55+ if key == "id" || key == "username" {
56+ continue;
57+ }
58+ assert_eq!(value, &fresh_obj[key], "field {key} leaks existence");
59+ }
60+ assert_eq!(dup_obj["username"], "ada");
61+ assert_eq!(dup_obj["role"], "student");
62+ assert_eq!(
63+ dup_obj["id"].as_str().map(str::len),
64+ fresh_obj["id"].as_str().map(str::len),
65+ "id shape leaks existence"
66+ );
67+ assert!(dup.cookie.is_none() && fresh.cookie.is_none());
68+
69+ // The argon2 work is what equalises timing, so pin that the taken path pays
70+ // it. A floor, not a comparison between the two paths — a gap assertion
71+ // would be flaky, whereas this can only fail if hashing got skipped
72+ // (argon2's default cost is ~33ms; 8ms leaves room for a loaded CI box).
73+ assert!(
74+ dup_elapsed.as_millis() >= 8,
75+ "taken-username register returned in {dup_elapsed:?} — it skipped argon2, \
76+ which re-opens the timing oracle"
77+ );
78+
79+ // The original account is untouched: its password still works and the
80+ // attacker's does not.
81+ let login = send(&app, "POST", "/auth/login", None, Some(taken)).await;
82+ assert_eq!(
83+ login.status,
84+ StatusCode::OK,
85+ "original password stopped working"
86+ );
87+ let hijack = send(&app, "POST", "/auth/login", None, Some(dup_creds)).await;
88+ assert_eq!(
89+ hijack.status,
90+ StatusCode::UNAUTHORIZED,
91+ "the duplicate register overwrote the password"
92+ );
93+
94+ // And no second row was written: exactly two users exist (ada, grace).
95+ set_role(&db, "ada", "admin").await;
96+ let cookie = login.cookie.expect("session cookie");
97+ let list = send(&app, "GET", "/users", Some(&cookie), None).await;
98+ assert_eq!(list.status, StatusCode::OK);
99+ let names: Vec<&str> = items(&list.body)
100+ .iter()
101+ .map(|u| u["username"].as_str().expect("username"))
102+ .collect();
103+ assert_eq!(
104+ names.iter().filter(|n| **n == "ada").count(),
105+ 1,
106+ "duplicate register created a second row: {names:?}"
107+ );
108+ assert_eq!(names.len(), 2, "unexpected user rows: {names:?}");
109+}
tests/integration.rsmodified+113 -17
@@ -110,9 +110,25 @@ async fn register_validates_input() {
110110 assert_eq!(res.body["role"], "student");
111111 assert!(res.body.get("password_hash").is_none());
112112
113- // Duplicate username -> 409.
114- let res = send(&app, "POST", "/auth/register", None, Some(ok)).await;
115- assert_eq!(res.status, StatusCode::CONFLICT);
113+ // A duplicate answers 201 like any other register (the "taken" reply is
114+ // deliberately indistinguishable — see tests/auth_enumeration.rs), but the
115+ // write is still rejected: the original password keeps working and the
116+ // second one never becomes valid.
117+ let dup = json!({ "username": "bob", "password": "hijack1" });
118+ let res = send(&app, "POST", "/auth/register", None, Some(dup.clone())).await;
119+ assert_eq!(res.status, StatusCode::CREATED);
120+ let res = send(&app, "POST", "/auth/login", None, Some(ok)).await;
121+ assert_eq!(
122+ res.status,
123+ StatusCode::OK,
124+ "original password stopped working"
125+ );
126+ let res = send(&app, "POST", "/auth/login", None, Some(dup)).await;
127+ assert_eq!(
128+ res.status,
129+ StatusCode::UNAUTHORIZED,
130+ "the duplicate register overwrote the account"
131+ );
116132 }
117133
118134 #[tokio::test]
@@ -4773,7 +4789,7 @@ async fn expired_session_is_unauthorized_before_any_purge() {
47734789 /// (trimmed) at construction and at login lookup.
47744790 #[tokio::test]
47754791 async fn padded_usernames_are_canonicalized_not_distinct_accounts() {
4776- let app = mem_app().await;
4792+ let (app, db) = app_and_db().await;
47774793
47784794 let res = send(
47794795 &app,
@@ -4785,20 +4801,66 @@ async fn padded_usernames_are_canonicalized_not_distinct_accounts() {
47854801 .await;
47864802 assert_eq!(res.status, StatusCode::CREATED);
47874803
4788- // Padding must not mint a lookalike account.
4804+ // Padding must not mint a lookalike account. Register answers 201 either way
4805+ // (username enumeration is denied, see tests/auth_enumeration.rs), so the
4806+ // collision is observed through the account itself: each spoof asks for a
4807+ // different password, and none of them may take effect.
47894808 for spoof in ["ali ", " ali", " ali "] {
47904809 let res = send(
47914810 &app,
47924811 "POST",
47934812 "/auth/register",
47944813 None,
4795- Some(json!({ "username": spoof, "password": "secret1" })),
4814+ Some(json!({ "username": spoof, "password": "spoof1" })),
4815+ )
4816+ .await;
4817+ assert_eq!(res.status, StatusCode::CREATED, "{spoof:?}");
4818+ }
4819+
4820+ // One row, not four — the padded forms collided with the canonical name.
4821+ let rows: Vec<User> = db
4822+ .query("SELECT * FROM user WHERE username = 'ali'")
4823+ .await
4824+ .unwrap()
4825+ .check()
4826+ .unwrap()
4827+ .take(0)
4828+ .unwrap();
4829+ assert_eq!(rows.len(), 1, "padding minted a lookalike account");
4830+ let all: Vec<User> = db
4831+ .query("SELECT * FROM user")
4832+ .await
4833+ .unwrap()
4834+ .check()
4835+ .unwrap()
4836+ .take(0)
4837+ .unwrap();
4838+ assert_eq!(all.len(), 1, "unexpected extra user rows");
4839+
4840+ // That one account still belongs to the first registration, and every
4841+ // spelling of the name resolves to it.
4842+ for attempt in ["ali", "ali ", " ali", " ali "] {
4843+ let res = send(
4844+ &app,
4845+ "POST",
4846+ "/auth/login",
4847+ None,
4848+ Some(json!({ "username": attempt, "password": "secret1" })),
4849+ )
4850+ .await;
4851+ assert_eq!(res.status, StatusCode::OK, "login as {attempt:?}");
4852+ let res = send(
4853+ &app,
4854+ "POST",
4855+ "/auth/login",
4856+ None,
4857+ Some(json!({ "username": attempt, "password": "spoof1" })),
47964858 )
47974859 .await;
47984860 assert_eq!(
47994861 res.status,
4800- StatusCode::CONFLICT,
4801- "{spoof:?} must collide with \"ali\""
4862+ StatusCode::UNAUTHORIZED,
4863+ "a padded register overwrote \"ali\" (as {attempt:?})"
48024864 );
48034865 }
48044866
@@ -5099,8 +5161,9 @@ async fn promotion_via_role_endpoint_sweeps_enrollments() {
50995161 /// Regression: `User::create` pre-checks the username and then inserts, so two
51005162 /// concurrent registrations of the same name could both pass the check; the
51015163 /// loser then hit the unique index and surfaced as a raw 500. A lost race must
5102-/// report the same 409 as the sequential duplicate, and exactly one account may
5103-/// exist afterwards.
5164+/// answer the same uniform 201 as the winner (the "taken" reply is deliberately
5165+/// indistinguishable), exactly one account may exist afterwards, and the
5166+/// winner's password must be the one that works.
51045167 #[tokio::test]
51055168 async fn concurrent_duplicate_registrations_conflict_not_500() {
51065169 let (app, db) = app_and_db().await;
@@ -5121,15 +5184,14 @@ async fn concurrent_duplicate_registrations_conflict_not_500() {
51215184 }));
51225185 }
51235186
5124- let mut created = 0;
51255187 for h in handles {
5126- match h.await.unwrap() {
5127- StatusCode::CREATED => created += 1,
5128- StatusCode::CONFLICT => {}
5129- other => panic!("unexpected status {other} — a lost race must be a 409, not a 500"),
5130- }
5188+ let status = h.await.unwrap();
5189+ assert_eq!(
5190+ status,
5191+ StatusCode::CREATED,
5192+ "a lost race must answer 201 like the winner, not a 500"
5193+ );
51315194 }
5132- assert_eq!(created, 1, "exactly one registration wins");
51335195
51345196 // Exactly one row exists for the name.
51355197 let users: Vec<hezarfen_backend::domain::user::User> = db
@@ -5145,6 +5207,40 @@ async fn concurrent_duplicate_registrations_conflict_not_500() {
51455207 1,
51465208 "exactly one user row for the duplicated name"
51475209 );
5210+
5211+ // And the winner's credentials survived the pile-up: a further duplicate
5212+ // asking for a different password does not replace them.
5213+ let res = send(
5214+ &app,
5215+ "POST",
5216+ "/auth/register",
5217+ None,
5218+ Some(json!({ "username": "dup", "password": "hijack1" })),
5219+ )
5220+ .await;
5221+ assert_eq!(res.status, StatusCode::CREATED);
5222+ let res = send(
5223+ &app,
5224+ "POST",
5225+ "/auth/login",
5226+ None,
5227+ Some(json!({ "username": "dup", "password": "secret1" })),
5228+ )
5229+ .await;
5230+ assert_eq!(res.status, StatusCode::OK, "the winning password broke");
5231+ let res = send(
5232+ &app,
5233+ "POST",
5234+ "/auth/login",
5235+ None,
5236+ Some(json!({ "username": "dup", "password": "hijack1" })),
5237+ )
5238+ .await;
5239+ assert_eq!(
5240+ res.status,
5241+ StatusCode::UNAUTHORIZED,
5242+ "a duplicate register overwrote the account"
5243+ );
51485244 }
51495245
51505246 /// Regression: listing a child collection of a missing parent used to return an