//! Signing in to the web browser: a password and an authenticator code, then a session cookie. //! //! Every page except the sign-in page and the static assets it needs sits behind //! [`require_login`]. Sessions live in memory (a restart signs everyone out) and remember the //! account's [fingerprint](gitv_web::auth::Credentials::fingerprint), so changing the password, here //! or with `gitv-web password`, ends every other session. //! //! The command-line account commands (`setup`, `password`) are in `setup.rs`. use std::collections::HashMap; use std::os::unix::fs::MetadataExt; use std::path::PathBuf; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; use axum::Extension; use axum::extract::{Form, FromRequest, RawQuery, Request, State}; use axum::http::{HeaderMap, HeaderValue, StatusCode, header}; use axum::middleware::Next; use axum::response::{IntoResponse, Response}; use data_encoding::BASE64URL_NOPAD; use gitv_core::{percent_decode, unix_now}; use gitv_web::auth::{AuthError, Credentials, MIN_PASSWORD, auth_path, check_new_password, random_bytes}; use serde::Deserialize; use sha2::{Digest, Sha256}; use subtle::ConstantTimeEq; use super::throttle::{Client, Throttle}; use super::{SECURITY, html}; /// The session cookie. The `__Host-` prefix makes browsers insist on `Secure`, `Path=/` and no /// `Domain`, so no other site or subdomain can set or overwrite it. const COOKIE: &str = "__Host-gitv"; /// Marks a browser that has signed in, so the cap on everyone's failures together never locks /// it out (see [`gitv_web::auth::Credentials::device_token`]). Kept across sign-outs. const DEVICE_COOKIE: &str = "__Host-gitv-device"; /// How long a session lasts from sign-in. const SESSION_LIFETIME: Duration = Duration::from_secs(12 * 60 * 60); /// Sign-in state shared by every request. pub struct Login { path: PathBuf, loaded: Mutex>, /// Sessions by the SHA-256 of their token: the token itself is never stored. sessions: Mutex>, /// Failed attempts, by client (see [`Throttle`]). throttle: Mutex, /// Password checks running at once. Argon2 is deliberately costly in memory and time, and /// the sign-in form is open to anyone, so a burst of guesses queues here. hashing: Arc, /// Sign-in attempts admitted at once, waiting or running. Past this, more are turned away /// before their bodies are even read, so a flood can't pile up passwords in memory. admission: Arc, /// Password checks started, for tests to confirm the bound holds. #[cfg(test)] checks_started: std::sync::atomic::AtomicUsize, } /// Sign-in attempts admitted at once (see [`Login::admission`]). const ADMITTED_ATTEMPTS: usize = 32; /// Largest sign-in or account form accepted, in bytes: far more than the fields need. pub const FORM_LIMIT: usize = 8 * 1024; /// Password checks allowed to run at once. const CONCURRENT_CHECKS: usize = 2; /// What checking a password and code found. enum Checked { Right, Wrong, /// This client was locked out by the time this attempt's turn came. Locked(Duration), /// The record of used codes couldn't be read or written, so no code can be trusted. Unavailable, } /// The account file as last read, and how to tell whether it has changed since. struct Loaded { stamp: (u64, i64, i64, u64), credentials: Arc, } #[derive(Clone)] struct Session { expires: Instant, fingerprint: [u8; 32], csrf: String, } /// Who is making a sign-in attempt: their client, and whether their browser has signed in /// before (see [`Login::trusted`]). #[derive(Clone, Copy)] struct Asker { client: Client, trusted: bool, } /// What [`require_login`] hands a signed-in request. #[derive(Clone)] pub struct SignedIn { token_hash: [u8; 32], csrf: String, } impl Login { /// Sign-in backed by the account file at [`auth_path`]. pub fn new() -> Arc { Arc::new(Login::at(auth_path())) } fn at(path: PathBuf) -> Login { Login { path, loaded: Mutex::new(None), sessions: Mutex::new(HashMap::new()), throttle: Mutex::new(Throttle::default()), hashing: Arc::new(tokio::sync::Semaphore::new(CONCURRENT_CHECKS)), admission: Arc::new(tokio::sync::Semaphore::new(ADMITTED_ATTEMPTS)), #[cfg(test)] checks_started: std::sync::atomic::AtomicUsize::new(0), } } /// The account, re-read whenever the file changes (so `gitv-web password` takes effect /// at once). fn credentials(&self) -> Result, AuthError> { let meta = std::fs::metadata(&self.path).map_err(|source| match source.kind() { std::io::ErrorKind::NotFound => AuthError::NotSetUp(self.path.clone()), _ => AuthError::Read { path: self.path.clone(), source }, })?; let stamp = (meta.ino(), meta.mtime(), meta.mtime_nsec(), meta.len()); let mut loaded = self.loaded.lock().unwrap_or_else(|e| e.into_inner()); if let Some(current) = loaded.as_ref().filter(|l| l.stamp == stamp) { return Ok(Arc::clone(¤t.credentials)); } let credentials = Arc::new(Credentials::load(&self.path)?); *loaded = Some(Loaded { stamp, credentials: Arc::clone(&credentials) }); Ok(credentials) } /// The session a request's cookie names, if it's live and the account hasn't changed since. fn session(&self, headers: &HeaderMap, credentials: &Credentials) -> Option { let token_hash = cookie_token(headers)?; let mut sessions = self.sessions.lock().unwrap_or_else(|e| e.into_inner()); let session = sessions.get(&token_hash)?; if session.expires <= Instant::now() || session.fingerprint != credentials.fingerprint() { sessions.remove(&token_hash); return None; } Some(SignedIn { token_hash, csrf: session.csrf.clone() }) } /// Start a session; returns the `Set-Cookie` value. fn start_session(&self, fingerprint: [u8; 32]) -> Result { let token = random_bytes::<32>()?; let csrf = BASE64URL_NOPAD.encode(&random_bytes::<32>()?); let now = Instant::now(); let mut sessions = self.sessions.lock().unwrap_or_else(|e| e.into_inner()); sessions.retain(|_, s| s.expires > now); sessions.insert(Sha256::digest(token).into(), Session { expires: now + SESSION_LIFETIME, fingerprint, csrf }); Ok(format!( "{COOKIE}={}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age={}", BASE64URL_NOPAD.encode(&token), SESSION_LIFETIME.as_secs() )) } fn throttle(&self) -> std::sync::MutexGuard<'_, Throttle> { self.throttle.lock().unwrap_or_else(|e| e.into_inner()) } /// How long `client` must wait to try again, if it must; see [`Throttle::locked_for`]. fn locked_for(&self, Asker { client, trusted }: Asker) -> Option { self.throttle().locked_for(client, Instant::now(), trusted) } /// Whether the request comes from a browser that has signed in to this account before. fn trusted(&self, headers: &HeaderMap) -> bool { let Some(token) = cookie_value(headers, DEVICE_COOKIE) else { return false }; self.credentials().is_ok_and(|c| c.trusts_device(token, unix_now())) } /// Check a password and authenticator code, counting failures and using up the code. /// /// Waits for one of [`CONCURRENT_CHECKS`] slots first, then looks at the lock again, since /// failures may have locked this client out while this attempt waited. The hashing job holds its /// slot until it has recorded its result, so no waiting attempt can start between a failure /// and the lock it causes, and a cancelled request still counts. async fn check( self: &Arc, purpose: &'static str, credentials: &Arc, asker: Asker, user: Option, password: String, code: &str, ) -> Checked { let Ok(permit) = Arc::clone(&self.hashing).acquire_owned().await else { return Checked::Wrong }; if let Some(wait) = self.locked_for(asker) { return Checked::Locked(wait); } #[cfg(test)] self.checks_started.fetch_add(1, std::sync::atomic::Ordering::Relaxed); let (login, creds, code) = (Arc::clone(self), Arc::clone(credentials), code.to_string()); tokio::task::spawn_blocking(move || { let _permit = permit; let user_ok = user.is_none_or(|u| creds.user_matches(&u)); let password_ok = creds.verify_password(&password) && user_ok; login.settle(purpose, &creds, asker, password_ok, &code) }) .await .unwrap_or(Checked::Wrong) } /// Record a check's result. The code is checked and used up in one step, under the account /// file's lock and recorded on disk, so it works once: across simultaneous requests, /// restarts and processes alike. /// /// Every judged attempt goes to the log (the journal, under systemd) with the client, and /// whether the password or the code was wrong. Visitors only ever hear that something was; /// the operator can see a right password with a wrong code, which means the password is known. fn settle( &self, purpose: &'static str, credentials: &Credentials, Asker { client, trusted }: Asker, password_ok: bool, code: &str, ) -> Checked { let code_ok = password_ok && match gitv_web::auth::consume_code(&self.path, credentials, code, unix_now()) { Ok(accepted) => accepted, Err(error) => { eprintln!("gitv-web: checking an authenticator code: {error}"); return Checked::Unavailable; } }; let mut throttle = self.throttle(); if code_ok { throttle.succeed(client); eprintln!("gitv-web: {purpose} succeeded from {client}"); Checked::Right } else { let now = Instant::now(); throttle.fail(client, now); let wrong = if password_ok { "right password, wrong code" } else { "wrong password" }; match throttle.locked_for(client, now, trusted) { Some(wait) => { eprintln!("gitv-web: {purpose} failed from {client} ({wrong}); locked out for {}s", wait.as_secs()); Checked::Locked(wait) } None => { eprintln!("gitv-web: {purpose} failed from {client} ({wrong})"); Checked::Wrong } } } } } /// The value of the cookie called `name`, from any of a request's `Cookie` headers. fn cookie_value<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> { headers .get_all(header::COOKIE) .iter() .filter_map(|v| v.to_str().ok()) .flat_map(|v| v.split(';')) .find_map(|pair| pair.trim().strip_prefix(name)?.strip_prefix('=')) } /// The SHA-256 of the session token in a request's cookie. fn cookie_token(headers: &HeaderMap) -> Option<[u8; 32]> { let token = cookie_value(headers, COOKIE)?; let token = BASE64URL_NOPAD.decode(token.as_bytes()).ok().filter(|t| t.len() == 32)?; Some(Sha256::digest(token).into()) } /// Where to go after signing in: a path on this site, never another site (`//evil.example`). fn safe_next(next: &str) -> &str { let local = next.starts_with('/') && !next.starts_with("//") && !next.starts_with("/\\"); if local && !next.bytes().any(|b| b.is_ascii_control()) { next } else { "/" } } fn redirect(to: &str, cookies: &[String]) -> Response { let mut response = (StatusCode::SEE_OTHER, SECURITY).into_response(); if let Ok(location) = HeaderValue::from_str(to) { response.headers_mut().insert(header::LOCATION, location); } for cookie in cookies.iter().filter_map(|c| HeaderValue::from_str(c).ok()) { response.headers_mut().append(header::SET_COOKIE, cookie); } response } fn not_set_up() -> Response { html( StatusCode::SERVICE_UNAVAILABLE, notice( "Sign-in isn't set up", false, "Sign-in isn’t set up", "Create the account on the server, then reload this page:", Some("gitv-web setup"), ), ) } /// Let signed-in requests through; send everyone else to the sign-in page. This wraps every /// route except the few public ones, which are routed separately by exact path, so no prefix /// rule can ever make a repository page public. pub async fn require_login(State(login): State>, mut request: Request, next: Next) -> Response { let credentials = login.credentials(); if let Ok(creds) = &credentials && let Some(session) = login.session(request.headers(), creds) { request.extensions_mut().insert(session); return next.run(request).await; } challenge(credentials.err(), request.uri()) } pub async fn browse(State(login): State>, mut request: Request, next: Next) -> Response { let credentials = login.credentials(); let signed_in = credentials.as_ref().ok().and_then(|c| login.session(request.headers(), c)).is_some(); request.extensions_mut().insert(signed_in); let uri = request.uri().clone(); let response = next.run(request).await; if response.status() == StatusCode::UNAUTHORIZED { challenge(credentials.err(), &uri) } else { response } } fn challenge(error: Option, uri: &axum::http::Uri) -> Response { match error { Some(AuthError::NotSetUp(_)) => return not_set_up(), Some(error) => { eprintln!("gitv-web: {error}"); return html( StatusCode::SERVICE_UNAVAILABLE, notice("Unavailable", false, "Unavailable", "Sign-in is unavailable.", None), ); } None => {} } let wanted = uri.path_and_query().map_or("/", |p| p.as_str()); redirect(&format!("/login?next={}", super::encode(wanted.as_bytes())), &[]) } // --------------------------------------------------------------------------------------------- // Sign in and out #[derive(Deserialize)] pub struct SignInForm { user: String, password: String, code: String, #[serde(default)] next: String, } fn sign_in_page(status: StatusCode, next: &str, message: &str) -> Response { html( status, super::templates::SignIn { title: "Sign in", signed_in: false, next: safe_next(next), message }.to_string(), ) } /// "Try again in 3 minutes." fn try_again(wait: Duration) -> String { let minutes = wait.as_secs().div_ceil(60).max(1); format!("Try again in {minutes} minute{}.", if minutes == 1 { "" } else { "s" }) } fn locked_page(wait: Duration) -> Response { sign_in_page(StatusCode::TOO_MANY_REQUESTS, "/", &format!("Too many failed sign-ins. {}", try_again(wait))) } pub async fn sign_in_form(State(login): State>, headers: HeaderMap, RawQuery(query): RawQuery) -> Response { let next = query .as_deref() .and_then(|q| q.split('&').find_map(|p| p.strip_prefix("next="))) .map(|n| String::from_utf8_lossy(&percent_decode(n)).into_owned()) .unwrap_or_else(|| "/".into()); // Already signed in: carry on to where they were going. if let Ok(credentials) = login.credentials() && login.session(&headers, &credentials).is_some() { return redirect(safe_next(&next), &[]); } sign_in_page(StatusCode::OK, &next, "") } pub async fn sign_in(State(login): State>, request: Request) -> Response { // Turned away before the body is read when too many attempts are already waiting. let Ok(_admitted) = Arc::clone(&login.admission).try_acquire_owned() else { return sign_in_page(StatusCode::SERVICE_UNAVAILABLE, "/", "Sign-in is busy. Try again in a moment."); }; let client = Client::of(request.headers(), request.extensions()); let asker = Asker { client, trusted: login.trusted(request.headers()) }; if let Some(wait) = login.locked_for(asker) { return locked_page(wait); } // Too large (over FORM_LIMIT) or malformed: refused with the rejection's own status. let form = match Form::::from_request(request, &()).await { Ok(Form(form)) => form, Err(rejection) => { return sign_in_page(rejection.status(), "/", "That sign-in form wasn’t accepted. Try again."); } }; let credentials = match login.credentials() { Ok(credentials) => credentials, Err(AuthError::NotSetUp(_)) => return not_set_up(), Err(error) => { eprintln!("gitv-web: {error}"); return sign_in_page(StatusCode::SERVICE_UNAVAILABLE, &form.next, "Sign-in is unavailable right now."); } }; match login.check("sign-in", &credentials, asker, Some(form.user), form.password, &form.code).await { Checked::Right => {} Checked::Locked(wait) => return locked_page(wait), Checked::Unavailable => { return sign_in_page(StatusCode::SERVICE_UNAVAILABLE, &form.next, "Sign-in is unavailable right now."); } // One message for every mistake, so a guess reveals nothing about which part was wrong. Checked::Wrong => { return sign_in_page(StatusCode::UNAUTHORIZED, &form.next, "That username, password or code isn’t right."); } } match login.start_session(credentials.fingerprint()) { Ok(cookie) => { let device = format!( "{DEVICE_COOKIE}={}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age={}", credentials.device_token(unix_now()), gitv_web::auth::DEVICE_LIFETIME ); redirect(safe_next(&form.next), &[cookie, device]) } Err(error) => { eprintln!("gitv-web: {error}"); sign_in_page(StatusCode::SERVICE_UNAVAILABLE, &form.next, "Sign-in is unavailable right now.") } } } #[derive(Deserialize)] pub struct CsrfForm { csrf: String, } /// Whether a form carries this session's token: forms posted from other sites don't. fn csrf_ok(signed_in: &SignedIn, token: &str) -> bool { signed_in.csrf.as_bytes().ct_eq(token.as_bytes()).into() } pub async fn sign_out( State(login): State>, Extension(signed_in): Extension, Form(form): Form, ) -> Response { if !csrf_ok(&signed_in, &form.csrf) { return html( StatusCode::FORBIDDEN, notice("Not allowed", true, "Not allowed", "That form has expired. Go back and try again.", None), ); } login.sessions.lock().unwrap_or_else(|e| e.into_inner()).remove(&signed_in.token_hash); let clear = format!("{COOKIE}=; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=0"); // The device cookie stays: signing out doesn't make this browser a stranger. redirect("/login", &[clear]) } // --------------------------------------------------------------------------------------------- // Account #[derive(Deserialize)] pub struct ChangePasswordForm { csrf: String, current: String, new: String, repeat: String, code: String, } fn account_page(status: StatusCode, user: &str, signed_in: &SignedIn, message: &str, ok: bool) -> Response { let page = super::templates::Account { title: "Account", signed_in: true, user, message, ok, csrf: &signed_in.csrf, min_password: MIN_PASSWORD, }; html(status, page.to_string()) } /// A page with a heading, a sentence and perhaps a command to copy. fn notice(title: &str, signed_in: bool, heading: &str, message: &str, code: Option<&str>) -> String { super::templates::Notice { title, signed_in, heading, message, code: code.map(str::to_string), link: None } .to_string() } pub async fn account(State(login): State>, Extension(signed_in): Extension) -> Response { match login.credentials() { Ok(credentials) => account_page(StatusCode::OK, credentials.user(), &signed_in, "", false), Err(_) => not_set_up(), } } pub async fn change_password( State(login): State>, Extension(signed_in): Extension, client: Client, headers: HeaderMap, Form(form): Form, ) -> Response { let asker = Asker { client, trusted: login.trusted(&headers) }; let Ok(credentials) = login.credentials() else { return not_set_up() }; let user = credentials.user().to_string(); let refuse = |status, message: &str| account_page(status, &user, &signed_in, message, false); if !csrf_ok(&signed_in, &form.csrf) { return refuse(StatusCode::FORBIDDEN, "That form has expired. Try again."); } if let Some(wait) = login.locked_for(asker) { return refuse(StatusCode::TOO_MANY_REQUESTS, &format!("Too many failed attempts. {}", try_again(wait))); } if form.new != form.repeat { return refuse(StatusCode::BAD_REQUEST, "The new passwords don’t match."); } if let Err(error) = check_new_password(&form.new) { return refuse(StatusCode::BAD_REQUEST, &format!("Choose a different new password: {error}.")); } match login.check("password change", &credentials, asker, None, form.current, &form.code).await { Checked::Right => {} Checked::Locked(wait) => { return refuse(StatusCode::TOO_MANY_REQUESTS, &format!("Too many failed attempts. {}", try_again(wait))); } Checked::Wrong => return refuse(StatusCode::UNAUTHORIZED, "That current password or code isn’t right."), Checked::Unavailable => { return refuse(StatusCode::SERVICE_UNAVAILABLE, "Changing the password is unavailable right now."); } } // Saved only if the account is still the one just checked: an operator's reset in the // meantime wins, rather than being overwritten by a change authorized against the old one. let (path, authorized, new) = (login.path.clone(), credentials.fingerprint(), form.new); let saved = tokio::task::spawn_blocking(move || gitv_web::auth::change_password(&path, authorized, &new, None)).await; let fingerprint = match saved { Ok(Ok(fingerprint)) => fingerprint, Ok(Err(AuthError::Changed)) => { return refuse( StatusCode::CONFLICT, "The account was changed while you were doing this, so nothing was saved. Sign in again.", ); } Ok(Err(error)) => { eprintln!("gitv-web: changing the password: {error}"); return refuse(StatusCode::INTERNAL_SERVER_ERROR, "The password couldn’t be saved. It hasn’t changed."); } Err(error) => { eprintln!("gitv-web: changing the password: {error}"); return refuse(StatusCode::INTERNAL_SERVER_ERROR, "The password couldn’t be saved. It hasn’t changed."); } }; // Every other session ends; this one carries on with the new account fingerprint. { let mut sessions = login.sessions.lock().unwrap_or_else(|e| e.into_inner()); sessions.retain(|token, _| *token == signed_in.token_hash); if let Some(session) = sessions.get_mut(&signed_in.token_hash) { session.fingerprint = fingerprint; } } account_page(StatusCode::OK, &user, &signed_in, "Password changed. Other sessions have been signed out.", true) } #[cfg(test)] mod tests { use super::*; mod safe_next { use super::*; #[test] fn keeps_local_paths() { assert_eq!(safe_next("/ada/site/tree?ref=main"), "/ada/site/tree?ref=main"); } #[test] fn refuses_other_sites() { for next in ["//evil.example/", "/\\evil.example", "https://evil.example/", "evil", "", "/a\r\nb"] { assert_eq!(safe_next(next), "/", "{next:?}"); } } } mod lock { use super::*; fn login() -> Login { Login::at(PathBuf::new()) } /// The client a request without connection details counts as. fn unknown() -> Client { Client::new(std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED)) } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn a_burst_of_guesses_hashes_only_until_the_lock_falls() { let login = Arc::new(login()); let credentials = Arc::new(Credentials::new("Um9i", "the real password").unwrap()); let guesses: Vec<_> = (0..20) .map(|_| { let (login, credentials) = (Arc::clone(&login), Arc::clone(&credentials)); tokio::spawn(async move { let asker = Asker { client: unknown(), trusted: false }; login.check("sign-in", &credentials, asker, None, "a wrong guess".into(), "123456").await }) }) .collect(); for guess in guesses { let _ = guess.await; } // Five free failures lock sign-in on the sixth; at most the other slot's check was // already running then. Everyone still waiting sees the lock and hashes nothing. let started = login.checks_started.load(std::sync::atomic::Ordering::Relaxed); assert!( started <= crate::throttle::FREE_FAILURES as usize + CONCURRENT_CHECKS, "{started} password checks ran" ); } #[tokio::test] async fn a_full_queue_turns_sign_ins_away_unread() { // A real account, so an attempt that got through would be judged (and fail). let dir = std::env::temp_dir().join(format!("gitv-web-admission-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); Credentials::new("Um9i", "the real password").unwrap().save(&dir.join("login"), None).unwrap(); let login = Arc::new(Login::at(dir.join("login"))); let _taken: Vec<_> = (0..ADMITTED_ATTEMPTS).map(|_| Arc::clone(&login.admission).try_acquire_owned().unwrap()).collect(); let request = Request::builder() .method("POST") .uri("/login") .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded") .body(axum::body::Body::from("user=Um9i&password=guess&code=123456")) .unwrap(); let response = sign_in(State(Arc::clone(&login)), request).await; assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); assert_eq!(login.throttle().failures(unknown()), 0, "the attempt was judged anyway"); let _ = std::fs::remove_dir_all(&dir); } } }