//! Sessions and the signed-in person: the session cookie, the guards every page calls, the CSRF //! checks, the token that protects pre-session forms, the sealed pending-login cookie between the //! password and the second factor, and the guard on every `next` redirect. //! //! The browser holds the session token in `__Host-im_session`. The database holds only its SHA-256, //! so a leaked row cannot be replayed as a cookie. Every guard here answers before any side effect, //! and a state-changing handler calls [`require_csrf`] or [`check_pre_csrf`] first. use std::time::{Duration, SystemTime, UNIX_EPOCH}; use im_core::model::{Session, User, amr}; use im_core::secret; use im_core::store::Store; use im_core::store::backchannel::EndReason; use im_core::store::sessions::{NewSession, SESSION_IDLE, SignInState}; use im_core::token::{constant_time_eq, generate_token, hash_token}; use im_core::totp; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time}; use topcoat::router::error::{forbidden, not_found, see_other}; use topcoat::router::request::{headers, uri}; use crate::client_ip::client_addr; use crate::live::Topic; use crate::state::AppState; /// Logical name of the session cookie. `override_prefix_host()` stores it as `__Host-im_session`. pub const SESSION_COOKIE: &str = "im_session"; /// Seconds in a day, for the policy's day counts. const DAY: u64 = 24 * 60 * 60; /// Logical name of the pre-session CSRF cookie, used by the pages that run before a session exists. pub const PRE_CSRF_COOKIE: &str = "im_precsrf"; /// How long the pre-session CSRF token stays valid in the browser. const PRE_CSRF_TTL: Duration = Duration::from_secs(60 * 60); /// Logical name of the pending-login cookie, set between the password and the second factor. pub const PENDING_COOKIE: &str = "im_pending"; /// How long a password-verified sign-in may wait for its second factor. Five minutes is long enough /// to fetch a code from an app, and short enough that a stolen cookie is of little use. pub const PENDING_TTL: Duration = Duration::from_secs(5 * 60); /// The longest `next` value accepted, in bytes. const MAX_NEXT_LEN: usize = 2048; /// The signed-in person and the session they signed in with. #[derive(Clone)] pub struct Viewer { /// The account. Not disabled. pub user: User, /// The session the request presented. Its `csrf_token` checks forms. pub session: Session, } /// The cookie jar that forces the `__Host-` prefix: `Secure`, `Path=/` and no `Domain`. fn jar(cx: &Cx) -> impl Cookies + '_ { cookies(cx).override_prefix_host() } /// The session the request presented, if it is still live. async fn presented_session(cx: &Cx) -> Result> { let Some(cookie) = jar(cx).get(SESSION_COOKIE) else { return Ok(None); }; let store = &app_context::(cx).store; Ok(store .session_by_token_hash(&hash_token(cookie.value())) .await?) } /// The signed-in person, or `None` when there is no live session. Refreshes `last_seen` (at most /// once in five minutes; the store decides). pub async fn current_user(cx: &Cx) -> Result> { let Some(session) = presented_session(cx).await? else { return Ok(None); }; let store = &app_context::(cx).store; let Some(user) = store .user_by_id(&session.user_id) .await? .filter(|user| !user.is_disabled()) else { return Ok(None); }; store.touch_session(&session.id).await?; Ok(Some(Viewer { user, session })) } /// The signed-in person. Anyone else is sent to `/login`, with the page they asked for as `next`. pub async fn require_user(cx: &Cx) -> Result { match current_user(cx).await? { Some(viewer) => Ok(viewer), None => { let path = uri(cx).path_and_query().map_or("/", |p| p.as_str()); let target = format!("/login?next={}", percent_encode(path)); Err(see_other(target).into()) } } } /// The signed-in administrator. A visitor without a session, and a person who is not an administrator, /// get 404, the same answer as a page that does not exist. An administrator without two-factor sign-in, while the policy requires /// it, is sent to the security page instead. pub async fn require_admin(cx: &Cx) -> Result { // Anyone without a live session gets 404 too: an admin page does not redirect to sign-in, so its // existence is not revealed to visitors. let Some(viewer) = current_user(cx).await? else { return Err(not_found().into()); }; if !viewer.user.is_admin { return Err(not_found().into()); } let state = app_context::(cx); if state.policy().require_2fa_for_admins && !viewer.user.totp_enabled() { return Err(see_other("/account/security?notice=enrol").into()); } Ok(viewer) } /// The signed-in person, when the submitted `csrf` field matches their session. Returns 403 for a /// wrong or missing token. Call it first in every state-changing handler. pub async fn require_csrf(cx: &Cx, submitted: &str) -> Result { let viewer = require_user(cx).await?; if check_csrf(&viewer.session, submitted) { Ok(viewer) } else { Err(forbidden().into()) } } /// The signed-in administrator, when the submitted `csrf` field matches their session. A member gets 404 /// first, before the token is looked at, so a form of the admin area gives no hint to a member. pub async fn require_admin_csrf(cx: &Cx, submitted: &str) -> Result { let viewer = require_admin(cx).await?; if check_csrf(&viewer.session, submitted) { Ok(viewer) } else { Err(forbidden().into()) } } /// True only when `submitted` is the session's CSRF token, compared in constant time. An empty /// stored token never matches, not even an empty submission. pub fn check_csrf(session: &Session, submitted: &str) -> bool { !session.csrf_token.is_empty() && constant_time_eq(session.csrf_token.as_bytes(), submitted.as_bytes()) } /// Creates a session for `user`, authenticated by `amr`, and sets the cookie. Returns `false`, with no /// session and no cookie, when `decided_on` no longer holds for the user (see /// [`im_core::store::Store::create_session`]). The caller then treats the sign-in as failed. /// /// A session the browser already presented is ended first, whoever it belongs to, so a sign-in always /// rotates the session id and no row is left live with no cookie holding it. The session lives /// [`SESSION_IDLE`] after its last use, up to the policy's `session_max_days` from now; the store keeps /// both limits. The per-person cap of the policy is applied inside the store, in the same write. pub async fn start_session( cx: &Cx, user: &User, amr: &str, decided_on: SignInState<'_>, ) -> Result { let state = app_context::(cx); let max_age = Duration::from_secs(u64::from(state.policy().session_max_days) * DAY); if let Some(old) = presented_session(cx).await? { // The owner is the session's own user, so the store's ownership check passes for it. if state .store .end_session(&old.user_id, &old.id, EndReason::Replaced) .await? && old.user_id != user.id { state.live.bump(&Topic::Account(old.user_id.clone())); } } let token = generate_token(); let csrf = generate_token(); let ip = client_addr(cx).to_string(); let user_agent = user_agent(cx); let Some(_) = state .store .create_session( &NewSession { user_id: &user.id, decided_on, token_hash: &hash_token(&token), csrf_token: &csrf, amr, ip: Some(ip.as_str()), user_agent: user_agent.as_deref(), idle: SESSION_IDLE, max_age, }, state.policy().max_sessions, ) .await? else { return Ok(false); }; // Sessions ended by the cap were queued for back-channel logout in the store's transaction. state.live.bump(&Topic::Account(user.id.clone())); // The browser keeps the cookie for the hard cap; the server decides the real expiry. let cookie_age = time::Duration::seconds(i64::try_from(max_age.as_secs()).unwrap_or(i64::MAX)); jar(cx).add( Cookie::build((SESSION_COOKIE, token)) .path("/") .secure(true) .http_only(true) .same_site(SameSite::Lax) .max_age(cookie_age) .build(), ); Ok(true) } /// Ends the session of `viewer` (with its back-channel logouts) and clears its cookie. Other sessions of /// the person are untouched. pub async fn end_current_session(cx: &Cx, viewer: &Viewer, reason: EndReason) -> Result<()> { let state = app_context::(cx); state .store .end_session(&viewer.user.id, &viewer.session.id, reason) .await?; state.live.bump(&Topic::Account(viewer.user.id.clone())); jar(cx).remove(Cookie::build((SESSION_COOKIE, "")).path("/")); Ok(()) } /// The pre-session CSRF token. Login, setup and the second-factor page use it, because no session /// exists yet. An existing cookie is reused, so two open tabs both keep working. pub fn pre_csrf_token(cx: &Cx) -> String { if let Some(cookie) = jar(cx).get(PRE_CSRF_COOKIE) { let value = cookie.value(); if !value.is_empty() { return value.to_owned(); } } let token = generate_token(); jar(cx).add(pre_csrf_cookie(token.clone())); token } /// True only when the submitted `precsrf` equals the pre-session cookie. Call it before any other /// work in a pre-session POST. pub fn check_pre_csrf(cx: &Cx, submitted: &str) -> bool { let Some(cookie) = jar(cx).get(PRE_CSRF_COOKIE) else { return false; }; !cookie.value().is_empty() && constant_time_eq(cookie.value().as_bytes(), submitted.as_bytes()) } /// Removes the pre-session CSRF cookie after a successful sign-in or setup. pub fn clear_pre_csrf(cx: &Cx) { jar(cx).remove(Cookie::build((PRE_CSRF_COOKIE, "")).path("/")); } fn pre_csrf_cookie(token: String) -> Cookie<'static> { Cookie::build((PRE_CSRF_COOKIE, token)) .path("/") .secure(true) .http_only(true) .same_site(SameSite::Strict) .max_age(time::Duration::seconds( i64::try_from(PRE_CSRF_TTL.as_secs()).unwrap_or(i64::MAX), )) .build() } /// A password-verified sign-in that waits for its second factor. #[derive(Clone, PartialEq, Eq)] pub struct Pending { /// Random id of this pending sign-in. The second factor spends it once (`Store::consume_pending_login`). pub nonce: String, /// The person who passed the password step. pub user_id: String, /// The authentication method so far. Always the password. pub amr: String, /// Where to go after the second factor. Checked again with [`safe_next`] before use. pub next: String, } /// Prints every field, except that the nonce prints as ``: spending it signs the person in. impl std::fmt::Debug for Pending { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Pending") .field("nonce", &format_args!("")) .field("user_id", &self.user_id) .field("amr", &self.amr) .field("next", &self.next) .finish() } } /// Parks a password-verified sign-in in the pending cookie. The payload is sealed with the instance /// key, so the browser can neither change the person nor extend the expiry. It carries a random nonce, /// which a successful second factor spends, so the same cookie cannot sign in twice. pub fn set_pending_login(cx: &Cx, key: &[u8; 32], user_id: &str, next: &str) -> Result<()> { let expires = unix_now() + PENDING_TTL.as_secs(); let nonce = generate_token(); let payload = format!("{user_id}|{expires}|{}|{nonce}|{next}", amr::PASSWORD); let sealed = secret::seal(key, secret::purpose::PENDING_LOGIN, payload.as_bytes())?; let max_age = time::Duration::seconds(i64::try_from(PENDING_TTL.as_secs()).unwrap_or(0)); jar(cx).add( Cookie::build((PENDING_COOKIE, sealed)) .path("/") .secure(true) .http_only(true) .same_site(SameSite::Strict) .max_age(max_age) .build(), ); Ok(()) } /// The pending sign-in, or `None` when the cookie is missing, tampered with, malformed or expired. /// `next` is the field as it was set; the caller applies [`safe_next`]. pub fn pending_login(cx: &Cx, key: &[u8; 32]) -> Option { let cookie = jar(cx).get(PENDING_COOKIE)?; let plain = secret::open(key, secret::purpose::PENDING_LOGIN, cookie.value()).ok()?; let text = String::from_utf8(plain).ok()?; // `next` comes last, so a `|` inside it cannot shift the other fields. let mut parts = text.splitn(5, '|'); let user_id = parts.next()?; let expires: u64 = parts.next()?.parse().ok()?; let amr = parts.next()?; let nonce = parts.next()?; let next = parts.next()?; if unix_now() >= expires { return None; } Some(Pending { nonce: nonce.to_owned(), user_id: user_id.to_owned(), amr: amr.to_owned(), next: next.to_owned(), }) } /// Removes the pending-login cookie. pub fn clear_pending_login(cx: &Cx) { jar(cx).remove(Cookie::build((PENDING_COOKIE, "")).path("/")); } /// Logical name of the one-time secret cookie. It carries a client secret from the POST that made the secret /// to the GET that shows it, so the secret never sits in a response to the POST or in a URL. pub const SECRET_FLASH_COOKIE: &str = "im_secret"; /// How long a one-time secret waits in its cookie. Long enough for the redirect to be followed; a secret that /// is not shown in that time is not kept. pub const SECRET_FLASH_TTL: Duration = Duration::from_secs(2 * 60); /// Parks a client secret for the page that shows it once. The payload is sealed with the instance key, names /// the client it belongs to, and expires after [`SECRET_FLASH_TTL`]. Same cookie attributes as the pending /// sign-in: `__Host-`, Secure, HttpOnly, SameSite=Strict, Path=/. pub fn set_secret_flash(cx: &Cx, key: &[u8; 32], client_id: &str, secret: &str) -> Result<()> { let expires = unix_now() + SECRET_FLASH_TTL.as_secs(); let sealed = secret::seal( key, secret::purpose::SECRET_FLASH, format!("{client_id}|{expires}|{secret}").as_bytes(), )?; let max_age = time::Duration::seconds(i64::try_from(SECRET_FLASH_TTL.as_secs()).unwrap_or(0)); jar(cx).add( Cookie::build((SECRET_FLASH_COOKIE, sealed)) .path("/") .secure(true) .http_only(true) .same_site(SameSite::Strict) .max_age(max_age) .build(), ); Ok(()) } /// Takes the secret parked for `client_id`. The cookie is removed whether or not it matches, so a secret is /// shown at most once. Returns `None` when the cookie is missing, tampered with, expired or for another client. pub fn take_secret_flash(cx: &Cx, key: &[u8; 32], client_id: &str) -> Option { let sealed = jar(cx).get(SECRET_FLASH_COOKIE)?.value().to_owned(); clear_secret_flash(cx); let plain = secret::open(key, secret::purpose::SECRET_FLASH, &sealed).ok()?; let text = String::from_utf8(plain).ok()?; let mut parts = text.splitn(3, '|'); let id = parts.next()?; let expires: u64 = parts.next()?.parse().ok()?; let secret = parts.next()?; (id == client_id && unix_now() < expires).then(|| secret.to_owned()) } /// Removes the one-time secret cookie. pub fn clear_secret_flash(cx: &Cx) { jar(cx).remove(Cookie::build((SECRET_FLASH_COOKIE, "")).path("/")); } /// Checks one six-digit TOTP code for `user`, with the replay guard. True only when the code is /// valid and its step was not used before. Returns false when two-factor sign-in is off. pub async fn verify_totp(store: &Store, key: &[u8; 32], user: &User, code: &str) -> Result { let Some(sealed) = user.totp_secret_sealed.as_deref() else { return Ok(false); }; if !user.totp_enabled() { return Ok(false); } let shared = secret::open(key, secret::purpose::TOTP_SECRET, sealed)?; let last = user .totp_last_step .and_then(|step| u64::try_from(step).ok()); match totp::verify(&shared, code, totp::step_for(unix_now()), last) { Some(step) => Ok(store.accept_totp_step(&user.id, step).await?), None => Ok(false), } } /// Checks a second factor: six digits are a TOTP code, anything else is a recovery code, which is /// spent on success. Returns the authentication method that was proved, or `None`. pub async fn check_second_factor( store: &Store, key: &[u8; 32], user: &User, input: &str, ) -> Result> { let input = input.trim(); if input.len() == totp::DIGITS && input.bytes().all(|b| b.is_ascii_digit()) { let ok = verify_totp(store, key, user, input).await?; return Ok(ok.then_some(amr::PASSWORD_TOTP)); } if !user.totp_enabled() { return Ok(None); } let spent = store .consume_recovery_code(&user.id, &totp::recovery_code_hash(key, input)) .await?; Ok(spent.then_some(amr::PASSWORD_RECOVERY)) } /// Where a person goes after signing in. An administrator without two-factor sign-in goes to the /// security page to enrol it, while the policy requires that. Anyone else goes to `next`. pub fn after_sign_in(state: &AppState, user: &User, next: &str) -> String { if user.is_admin && state.policy().require_2fa_for_admins && !user.totp_enabled() { "/account/security?notice=enrol".to_owned() } else { safe_next(Some(next)).to_owned() } } /// Returns `next` only when it is a same-site path: one leading `/`, then no `/` or `\` that would /// make a browser treat it as another host, no control characters, at most 2048 bytes. Anything else /// is `/`. pub fn safe_next(next: Option<&str>) -> &str { match next { Some(next) if is_local_path(next) => next, _ => "/", } } fn is_local_path(path: &str) -> bool { path.len() <= MAX_NEXT_LEN && path.starts_with('/') && !path.starts_with("//") && !path.starts_with("/\\") && path.chars().all(|c| !c.is_control()) } /// Percent-encodes everything except RFC 3986 unreserved characters and `/`. pub fn percent_encode(input: &str) -> String { let mut out = String::with_capacity(input.len()); for byte in input.bytes() { match byte { b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => { out.push(char::from(byte)); } _ => out.push_str(&format!("%{byte:02X}")), } } out } /// The `User-Agent` of the request, truncated to 512 characters. pub fn user_agent(cx: &Cx) -> Option { headers(cx) .get(http::header::USER_AGENT) .and_then(|value| value.to_str().ok()) .map(|text| text.chars().take(512).collect()) } /// Seconds since the Unix epoch. A clock before the epoch reads as 0, which only makes every /// pending sign-in expire at once. pub fn unix_now() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH) .map_or(0, |d| d.as_secs()) } #[cfg(test)] mod tests { use super::*; #[test] fn next_accepts_only_local_paths() { assert_eq!(safe_next(Some("/")), "/"); assert_eq!( safe_next(Some("/account/security?x=1")), "/account/security?x=1" ); assert_eq!(safe_next(None), "/"); } #[test] fn next_refuses_every_attack_string() { let overlong = format!("/{}", "a".repeat(MAX_NEXT_LEN)); for bad in [ "", "https://evil.example/", "http://evil.example", "//evil.example/", "/\\evil.example/", "\\\\evil.example", "\\/evil.example", "evil.example", "javascript:alert(1)", "/\n/evil.example", "/\r\nSet-Cookie: x=1", "/\t", "/\u{0}", " //evil.example", overlong.as_str(), ] { assert_eq!(safe_next(Some(bad)), "/", "accepted {bad:?}"); } } #[test] fn percent_encoding_keeps_slashes_and_encodes_the_rest() { assert_eq!(percent_encode("/a/b-c_d.e~f"), "/a/b-c_d.e~f"); assert_eq!(percent_encode("/s?x=1&y=2"), "/s%3Fx%3D1%26y%3D2"); } #[tokio::test] async fn a_recovery_code_signs_in_once() { use crate::boot::test_state; let (_dir, state) = test_state().await; let user = state .store .create_user("ada@example.com", "Ada", "hash", false) .await .expect("user"); let sealed = secret::seal( &state.key, secret::purpose::TOTP_SECRET, &totp::new_secret(), ) .expect("seal"); let code = totp::new_recovery_code(); state .store .enable_totp( &user.id, &sealed, 1, &[totp::recovery_code_hash(&state.key, &code)], None, ) .await .expect("enable"); let user = state .store .user_by_id(&user.id) .await .expect("query") .expect("user"); let first = check_second_factor(&state.store, &state.key, &user, &code) .await .expect("check"); assert_eq!(first, Some(amr::PASSWORD_RECOVERY)); let second = check_second_factor(&state.store, &state.key, &user, &code) .await .expect("check"); assert_eq!(second, None); } }