diff --git a/crates/acaua-core/src/auth/credentials.rs b/crates/acaua-core/src/auth/credentials.rs index 3ba15ba..e27a042 100644 --- a/crates/acaua-core/src/auth/credentials.rs +++ b/crates/acaua-core/src/auth/credentials.rs @@ -59,7 +59,7 @@ fn is_common(password: &str) -> bool { /// NFC form: the same password typed on different keyboards or systems must /// produce the same bytes. Every password path goes through this. -fn normalize(password: &str) -> String { +pub(super) fn normalize(password: &str) -> String { password.nfc().collect() } diff --git a/crates/acaua-core/src/auth/service.rs b/crates/acaua-core/src/auth/service.rs index efeb2b6..3ec0567 100644 --- a/crates/acaua-core/src/auth/service.rs +++ b/crates/acaua-core/src/auth/service.rs @@ -7,8 +7,8 @@ //! failed attempt must return `Ok` from its closure, or its count is discarded. use super::credentials::{ - hash_password, hash_recovery_code, new_recovery_codes, new_totp_secret, totp_uri_and_qr, - validate_password, verify_password, verify_totp, + hash_password, hash_recovery_code, new_recovery_codes, new_totp_secret, normalize, + totp_uri_and_qr, validate_password, verify_password, verify_totp, }; use super::store::{AuthState, AuthStore, Bootstrap, Role, Session, User}; use super::throttle::{lock_until, IpLimiter, UnknownAccounts}; @@ -23,6 +23,7 @@ const BOOTSTRAP_CODE_BYTES: usize = 16; // 128 bits const BOOTSTRAP_TTL_SECS: u64 = 3600; const PENDING_TTL_SECS: u64 = 300; const PENDING_PURPOSE: &str = "pending_mfa"; +const PASSWORD_CHANGE_PURPOSE: &str = "password_change"; const SESSION_TOKEN_BYTES: usize = 32; // 256 bits const SESSION_ABSOLUTE_SECS: u64 = 43_200; const USERNAME_MAX_CHARS: usize = 64; @@ -67,6 +68,9 @@ pub enum LoginStep { Session(NewSession), MfaRequired(PendingMfa), MfaEnrollRequired(PendingMfa), + /// All factors passed, but the token only allows + /// `change_required_password`. It is not a session. + PasswordChangeRequired(PendingMfa), } /// What the user needs to add the account to an authenticator app. @@ -325,7 +329,7 @@ impl AuthService { password_hash: password_hash.clone(), ..Default::default() }); - Ok(Some(self.seal_pending(&id, 0, now)?)) + Ok(Some(self.seal_pending(&id, 0, PENDING_PURPOSE, now)?)) })?; let Some(pending) = done else { self.log("bootstrap.complete", None, None, false, None)?; @@ -335,10 +339,16 @@ impl AuthService { Ok(pending) } - fn seal_pending(&self, user_id: &str, epoch: u64, now: u64) -> Result { + fn seal_pending( + &self, + user_id: &str, + epoch: u64, + purpose: &str, + now: u64, + ) -> Result { let exp = now.saturating_add(PENDING_TTL_SECS); let claims = PendingClaims { - purpose: PENDING_PURPOSE.to_string(), + purpose: purpose.to_string(), user_id: user_id.to_string(), epoch, exp, @@ -350,10 +360,10 @@ impl AuthService { } /// Any defect is the same refusal: forged, expired, or for another purpose. - fn open_pending(&self, token: &str, now: u64) -> Result { + fn open_pending(&self, token: &str, purpose: &str, now: u64) -> Result { let raw = self.secrets.open_sealed(token).map_err(|_| invalid())?; let claims: PendingClaims = serde_json::from_slice(&raw).map_err(|_| invalid())?; - if claims.purpose != PENDING_PURPOSE || now > claims.exp { + if claims.purpose != purpose || now > claims.exp { return Err(invalid()); } Ok(claims) @@ -434,9 +444,16 @@ impl AuthService { refund_attempt(u); let epoch = u.auth_epoch; let step = if u.totp_sealed.is_some() { - LoginStep::MfaRequired(self.seal_pending(&id, epoch, now)?) + LoginStep::MfaRequired(self.seal_pending(&id, epoch, PENDING_PURPOSE, now)?) } else if u.role == Role::Admin { - LoginStep::MfaEnrollRequired(self.seal_pending(&id, epoch, now)?) + LoginStep::MfaEnrollRequired(self.seal_pending(&id, epoch, PENDING_PURPOSE, now)?) + } else if u.must_change_password { + LoginStep::PasswordChangeRequired(self.seal_pending( + &id, + epoch, + PASSWORD_CHANGE_PURPOSE, + now, + )?) } else { LoginStep::Session(complete_login(st, &id, now)?) }; @@ -457,6 +474,7 @@ impl AuthService { LoginStep::Session(_) => "session", LoginStep::MfaRequired(_) => "mfa required", LoginStep::MfaEnrollRequired(_) => "mfa enrollment required", + LoginStep::PasswordChangeRequired(_) => "password change required", }; self.log("login", Some(&name), Some(ip), true, Some(detail))?; Ok(step) @@ -464,16 +482,16 @@ impl AuthService { /// Second factor: a TOTP code or a recovery code. Failures count against /// the account, since 6 digits cannot stand unlimited guesses. - pub fn confirm_mfa(&self, pending: &str, code: &str, now: u64) -> Result { + pub fn confirm_mfa(&self, pending: &str, code: &str, now: u64) -> Result { enum Outcome { Done { - session: NewSession, + step: LoginStep, name: String, method: &'static str, }, Bad(String), } - let claims = self.open_pending(pending, now)?; + let claims = self.open_pending(pending, PENDING_PURPOSE, now)?; let recovery_hash = hash_recovery_code(code); let outcome = self.store.update(|st| { let u = user_mut(st, &claims.user_id) @@ -493,25 +511,31 @@ impl AuthService { count_failure(u, now); return Ok(Outcome::Bad(name)); }; - let session = complete_login(st, &claims.user_id, now)?; - Ok(Outcome::Done { - session, - name, - method, - }) + let step = if u.must_change_password { + // Factors passed, so the throttle clears and this pending + // token dies, but only the password step opens. + u.failed_attempts = 0; + u.locked_until = 0; + u.auth_epoch = u.auth_epoch.wrapping_add(1); + LoginStep::PasswordChangeRequired(self.seal_pending( + &claims.user_id, + u.auth_epoch, + PASSWORD_CHANGE_PURPOSE, + now, + )?) + } else { + LoginStep::Session(complete_login(st, &claims.user_id, now)?) + }; + Ok(Outcome::Done { step, name, method }) })?; match outcome { Outcome::Bad(name) => { self.log("mfa.confirm", Some(&name), None, false, None)?; Err(invalid()) } - Outcome::Done { - session, - name, - method, - } => { + Outcome::Done { step, name, method } => { self.log("mfa.confirm", Some(&name), None, true, Some(method))?; - Ok(session) + Ok(step) } } } @@ -519,7 +543,7 @@ impl AuthService { /// The user a pending token may enroll. Refused once MFA is active, so a /// password alone can never replace an existing second factor. pub fn pending_user(&self, pending: &str, now: u64) -> Result { - let claims = self.open_pending(pending, now)?; + let claims = self.open_pending(pending, PENDING_PURPOSE, now)?; let allowed = self.store.read(|st| { st.users.iter().any(|u| { u.id == claims.user_id && u.auth_epoch == claims.epoch && u.totp_sealed.is_none() @@ -691,6 +715,12 @@ impl AuthService { now: u64, ) -> Result<()> { validate_password(new)?; + // Comparing the two inputs reveals nothing about the stored password. + if normalize(current) == normalize(new) { + return Err(AcauaError::InvalidInput( + "new password must differ from the current one".to_string(), + )); + } let (name, hash) = self.store.update(|st| { let u = user_or_missing(st, user_id)?; reserve_attempt(u, now).map_err(throttled)?; @@ -707,6 +737,7 @@ impl AuthService { }; refund_attempt(u); u.password_hash = new_hash; + u.must_change_password = false; u.auth_epoch = u.auth_epoch.wrapping_add(1); end_sessions(st, user_id, keep_session_token); Ok(true) @@ -718,6 +749,34 @@ impl AuthService { Ok(()) } + /// Spends a `PasswordChangeRequired` ticket: changes the password under + /// the rules of `change_password`, then opens the session. + pub fn change_required_password( + &self, + ticket: &str, + current: &str, + new: &str, + now: u64, + ) -> Result { + let claims = self.open_pending(ticket, PASSWORD_CHANGE_PURPOSE, now)?; + let live = self.store.read(|st| { + st.users.iter().any(|u| { + u.id == claims.user_id && u.auth_epoch == claims.epoch && u.must_change_password + }) + })?; + if !live { + return Err(invalid()); + } + self.change_password(&claims.user_id, current, new, None, now)?; + self.store.update(|st| { + let u = user_mut(st, &claims.user_id).ok_or_else(invalid)?; + if u.must_change_password { + return Err(invalid()); + } + complete_login(st, &claims.user_id, now) + }) + } + /// Refused for administrators. Ends the other sessions. pub fn disable_mfa( &self, @@ -745,7 +804,8 @@ impl AuthService { /// Local recovery for an administrator who lost access: removes MFA and /// sessions, clears the throttle, and returns a temporary password that - /// is shown once. The next login must enroll again. + /// is shown once. The next login must enroll again and change the password + /// before any ordinary session. pub fn reset_admin(&self, username: &str, _now: u64) -> Result { let key = username_key(username); let temp = random_token(TEMP_PASSWORD_BYTES); @@ -759,6 +819,7 @@ impl AuthService { return Ok(None); }; u.password_hash = password_hash; + u.must_change_password = true; u.totp_sealed = None; u.totp_pending_sealed = None; u.totp_last_step = None; diff --git a/crates/acaua-core/src/auth/service_tests.rs b/crates/acaua-core/src/auth/service_tests.rs index e34de32..c44693a 100644 --- a/crates/acaua-core/src/auth/service_tests.rs +++ b/crates/acaua-core/src/auth/service_tests.rs @@ -195,7 +195,7 @@ fn admin_cannot_finish_login_without_mfa() { AuthFailure::InvalidCredentials ); let next = code_at(&s, &id, T0 + 60); - let session = s.confirm_mfa(&p.token, &next, T0 + 60).unwrap(); + let session = session_of(s.confirm_mfa(&p.token, &next, T0 + 60).unwrap()); assert_eq!(session.user_id, id); assert_eq!(sessions(&s, &id), 1); // Once MFA is active a pending token gives no enrollment access. @@ -611,9 +611,10 @@ fn password_or_mfa_change_ends_other_sessions() { // Disabling MFA keeps only the named session. let p = pending_of(s.login("ana", PW2, ip(), T0 + 60).unwrap()); - let a = s - .confirm_mfa(&p.token, &code_at_active(&s, &id, T0 + 60), T0 + 60) - .unwrap(); + let a = session_of( + s.confirm_mfa(&p.token, &code_at_active(&s, &id, T0 + 60), T0 + 60) + .unwrap(), + ); let p = pending_of(s.login("ana", PW2, ip(), T0 + 90).unwrap()); s.confirm_mfa(&p.token, &code_at_active(&s, &id, T0 + 90), T0 + 90) .unwrap(); @@ -793,3 +794,154 @@ fn open_fails_on_missing_key_without_touching_state() { ); assert_eq!(std::fs::read(auth.join("state.json")).unwrap(), before); } + +/// Admin after `reset_admin`, enrolled again. Returns (id, temp password). +fn reset_and_enroll(s: &AuthService) -> (String, String) { + let id = admin(s); + let temp = s.reset_admin("root", T0 + 200).unwrap(); + enroll(s, &id, T0 + 200); + (id, temp) +} + +fn change_ticket(step: LoginStep) -> PendingMfa { + match step { + LoginStep::PasswordChangeRequired(p) => p, + other => panic!("expected PasswordChangeRequired, got {other:?}"), + } +} + +#[test] +fn must_change_password_survives_enrollment_and_reopen() { + let (d, s) = svc(); + let (id, temp) = reset_and_enroll(&s); + drop(s); + let s = AuthService::open(d.path(), None).unwrap(); + let flag = s + .store + .read(|st| { + st.users + .iter() + .find(|u| u.id == id) + .unwrap() + .must_change_password + }) + .unwrap(); + assert!(flag); + let p = pending_of(s.login("root", &temp, ip(), T0 + 300).unwrap()); + let code = code_at_active(&s, &id, T0 + 300); + change_ticket(s.confirm_mfa(&p.token, &code, T0 + 300).unwrap()); +} + +#[test] +fn no_ordinary_session_while_password_change_is_required() { + let (_d, s) = svc(); + let (id, temp) = reset_and_enroll(&s); + let p = pending_of(s.login("root", &temp, ip(), T0 + 300).unwrap()); + let code = code_at_active(&s, &id, T0 + 300); + let ticket = change_ticket(s.confirm_mfa(&p.token, &code, T0 + 300).unwrap()); + assert_eq!(sessions(&s, &id), 0); + // The ticket is good for nothing else, and a pending token is no ticket. + assert_eq!( + failure(s.pending_user(&ticket.token, T0 + 300)), + AuthFailure::InvalidCredentials + ); + let next = code_at_active(&s, &id, T0 + 330); + assert_eq!( + failure(s.confirm_mfa(&ticket.token, &next, T0 + 330)), + AuthFailure::InvalidCredentials + ); + let p2 = pending_of(s.login("root", &temp, ip(), T0 + 330).unwrap()); + assert_eq!( + failure(s.change_required_password(&p2.token, &temp, PW2, T0 + 330)), + AuthFailure::InvalidCredentials + ); + // Expired ticket. + let t2 = change_ticket(s.confirm_mfa(&p2.token, &next, T0 + 330).unwrap()); + assert_eq!( + failure(s.change_required_password(&t2.token, &temp, PW2, T0 + 631)), + AuthFailure::InvalidCredentials + ); + assert_eq!(sessions(&s, &id), 0); + + let n = s + .change_required_password(&t2.token, &temp, PW2, T0 + 330) + .unwrap(); + assert_eq!(n.user_id, id); + assert_eq!(sessions(&s, &id), 1); + // Single use, the flag is gone, the temporary password is dead. + assert_eq!( + failure(s.change_required_password(&t2.token, PW2, PW, T0 + 330)), + AuthFailure::InvalidCredentials + ); + assert_eq!( + failure(s.login("root", &temp, ip(), T0 + 360)), + AuthFailure::InvalidCredentials + ); + let p = pending_of(s.login("root", PW2, ip(), T0 + 360).unwrap()); + let code = code_at_active(&s, &id, T0 + 360); + session_of(s.confirm_mfa(&p.token, &code, T0 + 360).unwrap()); +} + +#[test] +fn flag_also_blocks_password_only_login() { + // A reset admin later demoted, without MFA, reaches the password-only path. + let (_d, s) = svc(); + let root = admin(&s); + s.create_user("root", "second", PW, Role::Admin, T0) + .unwrap(); + let second = uid(&s, "second"); + let temp = s.reset_admin("second", T0).unwrap(); + s.set_role("root", &second, Role::Analyst, T0).unwrap(); + let t = change_ticket(s.login("second", &temp, ip(), T0).unwrap()); + assert_eq!(sessions(&s, &second), 0); + s.change_required_password(&t.token, &temp, PW2, T0) + .unwrap(); + session_of(s.login("second", PW2, ip(), T0).unwrap()); + assert_eq!(sessions(&s, &root), 0); +} + +#[test] +fn change_password_clears_flag_and_refuses_the_same_password() { + let (_d, s) = svc(); + let (id, temp) = reset_and_enroll(&s); + // Same password, also in another Unicode form: refused, nothing counted. + assert!(matches!( + s.change_password(&id, &temp, &temp, None, T0 + 300) + .unwrap_err(), + AcauaError::InvalidInput(_) + )); + assert_eq!( + s.store + .read(|st| st + .users + .iter() + .find(|u| u.id == id) + .unwrap() + .failed_attempts) + .unwrap(), + 0 + ); + assert!(matches!( + s.change_password( + &id, + "maçã açaí pitanga", + "mac\u{0327}a\u{0303} ac\u{0327}ai\u{0301} pitanga", + None, + T0 + ) + .unwrap_err(), + AcauaError::InvalidInput(_) + )); + s.change_password(&id, &temp, PW2, None, T0 + 300).unwrap(); + let flag = s + .store + .read(|st| { + st.users + .iter() + .find(|u| u.id == id) + .unwrap() + .must_change_password + }) + .unwrap(); + assert!(!flag); +} diff --git a/crates/acaua-core/src/auth/store.rs b/crates/acaua-core/src/auth/store.rs index 7e9ffaf..c3393c9 100644 --- a/crates/acaua-core/src/auth/store.rs +++ b/crates/acaua-core/src/auth/store.rs @@ -44,6 +44,8 @@ pub struct User { /// Changes when the password changes and at each completed login, which /// voids the pending MFA tokens issued before it. pub auth_epoch: u64, + /// Set by `reset_admin`: no ordinary session until the password changes. + pub must_change_password: bool, } impl std::fmt::Debug for User {