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 {
57 }57 }
58 }58 }
59 59
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+
60 /// A validated plaintext password. Never stored β€” only hashed or verified.75 /// A validated plaintext password. Never stored β€” only hashed or verified.
61 pub struct Password(String);76 pub struct Password(String);
62 77
@@ -85,6 +100,10 @@ impl Password {
85 /// and they come back as 503. Every request path must use this, not `hash`.100 /// and they come back as 503. Every request path must use this, not `hash`.
86 pub async fn hash_async(&self) -> Result<PasswordHash, AppError> {101 pub async fn hash_async(&self) -> Result<PasswordHash, AppError> {
87 let plain = self.0.clone();102 let plain = self.0.clone();
103+ let _permit = argon2_permits()
104+ .acquire()
105+ .await
106+ .map_err(|e| AppError::Internal(format!("hash permit: {e}")))?;
88 tokio::task::spawn_blocking(move || Password(plain).hash())107 tokio::task::spawn_blocking(move || Password(plain).hash())
89 .await108 .await
90 .map_err(|e| AppError::Internal(format!("hash task: {e}")))?109 .map_err(|e| AppError::Internal(format!("hash task: {e}")))?
@@ -130,6 +149,12 @@ impl PasswordHash {
130 pub async fn verify_async(&self, password: &Password) -> bool {149 pub async fn verify_async(&self, password: &Password) -> bool {
131 let hash = self.0.clone();150 let hash = self.0.clone();
132 let plain = password.0.clone();151 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+ };
133 tokio::task::spawn_blocking(move || PasswordHash(hash).verify(&Password(plain)))158 tokio::task::spawn_blocking(move || PasswordHash(hash).verify(&Password(plain)))
134 .await159 .await
135 .unwrap_or(false)160 .unwrap_or(false)
@@ -142,8 +167,25 @@ impl PasswordHash {
142 /// reply would let an attacker enumerate valid usernames by timing.167 /// reply would let an attacker enumerate valid usernames by timing.
143 pub async fn verify_decoy_async(password: &Password) {168 pub async fn verify_decoy_async(password: &Password) {
144 let plain = password.0.clone();169 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+ };
145 let _ = tokio::task::spawn_blocking(move || decoy_hash().verify(&Password(plain))).await;174 let _ = tokio::task::spawn_blocking(move || decoy_hash().verify(&Password(plain))).await;
146 }175 }
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+ }
147 }189 }
148 190
149 #[derive(Debug, Clone, SurrealValue)]191 #[derive(Debug, Clone, SurrealValue)]
src/main.rsmodified+3 -0
@@ -18,6 +18,9 @@ async fn main() -> anyhow::Result<()> {
18 18
19 let cfg = Config::from_env();19 let cfg = Config::from_env();
20 let db = database::init(&cfg).await?;20 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();
21 seed_admin(&cfg, &db).await?;24 seed_admin(&cfg, &db).await?;
22 let db_up = DbHealth::default();25 let db_up = DbHealth::default();
23 keepalive(db.clone(), db_up.clone());26 keepalive(db.clone(), db_up.clone());
src/web/auth.rsmodified+41 -5
@@ -10,8 +10,9 @@ use utoipa_axum::router::OpenApiRouter;
10 use utoipa_axum::routes;10 use utoipa_axum::routes;
11 11
12 use crate::constant::{RESERVED_USERNAMES, SESSION_DURATION_DAYS};12 use crate::constant::{RESERVED_USERNAMES, SESSION_DURATION_DAYS};
13+use crate::domain::role::Role;
13 use crate::domain::session::Session;14 use crate::domain::session::Session;
14-use crate::domain::user::{Password, PasswordHash, User, Username};15+use crate::domain::user::{Password, PasswordHash, User, UserId, Username};
15 use crate::error::{AppError, ErrorResponse, ValidationError};16 use crate::error::{AppError, ErrorResponse, ValidationError};
16 use crate::rate_limit::{RateLimitConfig, RateLimiter};17 use crate::rate_limit::{RateLimitConfig, RateLimiter};
17 use crate::state::AppState;18 use crate::state::AppState;
@@ -45,15 +46,21 @@ struct Credentials {
45 }46 }
46 47
47 /// Register a new user account.48 /// 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.
48 #[utoipa::path(56 #[utoipa::path(
49 post,57 post,
50 path = "/register",58 path = "/register",
51 tag = "auth",59 tag = "auth",
52 request_body = Credentials,60 request_body = Credentials,
53 responses(61 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),
55 (status = 400, description = "Invalid username or password", body = ErrorResponse),63 (status = 400, description = "Invalid username or password", body = ErrorResponse),
56- (status = 409, description = "Username already taken", body = ErrorResponse),
57 (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse),64 (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse),
58 ),65 ),
59 )]66 )]
@@ -72,9 +79,38 @@ async fn register(
72 }79 }
73 .into());80 .into());
74 }81 }
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.
75 let password_hash = Password::try_new(&req.password)?.hash_async().await?;86 let password_hash = Password::try_new(&req.password)?.hash_async().await?;
76- let user = User::create(username, password_hash, &st.db).await?;87+ match User::create(username.clone(), password_hash, &st.db).await {
77- Ok((StatusCode::CREATED, Json(UserResponse::new(&user))))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+ }
78 }114 }
79 115
80 /// Log in with username + password. Sets a `session` cookie on success.116 /// 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() {
110 assert_eq!(res.body["role"], "student");110 assert_eq!(res.body["role"], "student");
111 assert!(res.body.get("password_hash").is_none());111 assert!(res.body.get("password_hash").is_none());
112 112
113- // Duplicate username -> 409.113+ // A duplicate answers 201 like any other register (the "taken" reply is
114- let res = send(&app, "POST", "/auth/register", None, Some(ok)).await;114+ // deliberately indistinguishable β€” see tests/auth_enumeration.rs), but the
115- assert_eq!(res.status, StatusCode::CONFLICT);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+ );
116 }132 }
117 133
118 #[tokio::test]134 #[tokio::test]
@@ -4773,7 +4789,7 @@ async fn expired_session_is_unauthorized_before_any_purge() {
4773 /// (trimmed) at construction and at login lookup.4789 /// (trimmed) at construction and at login lookup.
4774 #[tokio::test]4790 #[tokio::test]
4775 async fn padded_usernames_are_canonicalized_not_distinct_accounts() {4791 async fn padded_usernames_are_canonicalized_not_distinct_accounts() {
4776- let app = mem_app().await;4792+ let (app, db) = app_and_db().await;
4777 4793
4778 let res = send(4794 let res = send(
4779 &app,4795 &app,
@@ -4785,20 +4801,66 @@ async fn padded_usernames_are_canonicalized_not_distinct_accounts() {
4785 .await;4801 .await;
4786 assert_eq!(res.status, StatusCode::CREATED);4802 assert_eq!(res.status, StatusCode::CREATED);
4787 4803
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.
4789 for spoof in ["ali ", " ali", " ali "] {4808 for spoof in ["ali ", " ali", " ali "] {
4790 let res = send(4809 let res = send(
4791 &app,4810 &app,
4792 "POST",4811 "POST",
4793 "/auth/register",4812 "/auth/register",
4794 None,4813 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" })),
4796 )4858 )
4797 .await;4859 .await;
4798 assert_eq!(4860 assert_eq!(
4799 res.status,4861 res.status,
4800- StatusCode::CONFLICT,4862+ StatusCode::UNAUTHORIZED,
4801- "{spoof:?} must collide with \"ali\""4863+ "a padded register overwrote \"ali\" (as {attempt:?})"
4802 );4864 );
4803 }4865 }
4804 4866
@@ -5099,8 +5161,9 @@ async fn promotion_via_role_endpoint_sweeps_enrollments() {
5099 /// Regression: `User::create` pre-checks the username and then inserts, so two5161 /// Regression: `User::create` pre-checks the username and then inserts, so two
5100 /// concurrent registrations of the same name could both pass the check; the5162 /// concurrent registrations of the same name could both pass the check; the
5101 /// loser then hit the unique index and surfaced as a raw 500. A lost race must5163 /// 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 may5164+/// answer the same uniform 201 as the winner (the "taken" reply is deliberately
5103-/// exist afterwards.5165+/// indistinguishable), exactly one account may exist afterwards, and the
5166+/// winner's password must be the one that works.
5104 #[tokio::test]5167 #[tokio::test]
5105 async fn concurrent_duplicate_registrations_conflict_not_500() {5168 async fn concurrent_duplicate_registrations_conflict_not_500() {
5106 let (app, db) = app_and_db().await;5169 let (app, db) = app_and_db().await;
@@ -5121,15 +5184,14 @@ async fn concurrent_duplicate_registrations_conflict_not_500() {
5121 }));5184 }));
5122 }5185 }
5123 5186
5124- let mut created = 0;
5125 for h in handles {5187 for h in handles {
5126- match h.await.unwrap() {5188+ let status = h.await.unwrap();
5127- StatusCode::CREATED => created += 1,5189+ assert_eq!(
5128- StatusCode::CONFLICT => {}5190+ status,
5129- other => panic!("unexpected status {other} β€” a lost race must be a 409, not a 500"),5191+ StatusCode::CREATED,
5130- }5192+ "a lost race must answer 201 like the winner, not a 500"
5193+ );
5131 }5194 }
5132- assert_eq!(created, 1, "exactly one registration wins");
5133 5195
5134 // Exactly one row exists for the name.5196 // Exactly one row exists for the name.
5135 let users: Vec<hezarfen_backend::domain::user::User> = db5197 let users: Vec<hezarfen_backend::domain::user::User> = db
@@ -5145,6 +5207,40 @@ async fn concurrent_duplicate_registrations_conflict_not_500() {
5145 1,5207 1,
5146 "exactly one user row for the duplicated name"5208 "exactly one user row for the duplicated name"
5147 );5209 );
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+ );
5148 }5244 }
5149 5245
5150 /// Regression: listing a child collection of a missing parent used to return an5246 /// Regression: listing a child collection of a missing parent used to return an