forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

auth.rs583 lines, 21.8 KiBHistoryRawDownload
1//! Sessions and the signed-in person: the session cookie, the guards every page calls, the CSRF
2//! checks, the token that protects pre-session forms, the sealed pending-login cookie between the
3//! password and the second factor, and the guard on every `next` redirect.
4//!
5//! The browser holds the session token in `__Host-im_session`. The database holds only its SHA-256,
6//! so a leaked row cannot be replayed as a cookie. Every guard here answers before any side effect,
7//! and a state-changing handler calls [`require_csrf`] or [`check_pre_csrf`] first.
8
9use std::time::{Duration, SystemTime, UNIX_EPOCH};
10
11use im_core::model::{Session, User, amr};
12use im_core::secret;
13use im_core::store::Store;
14use im_core::store::backchannel::EndReason;
15use im_core::store::sessions::{NewSession, SESSION_IDLE, SignInState};
16use im_core::token::{constant_time_eq, generate_token, hash_token};
17use im_core::totp;
18use topcoat::Result;
19use topcoat::context::{Cx, app_context};
20use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time};
21use topcoat::router::error::{forbidden, not_found, see_other};
22use topcoat::router::request::{headers, uri};
23
24use crate::client_ip::client_addr;
25use crate::live::Topic;
26use crate::state::AppState;
27
28/// Logical name of the session cookie. `override_prefix_host()` stores it as `__Host-im_session`.
29pub const SESSION_COOKIE: &str = "im_session";
30
31/// Seconds in a day, for the policy's day counts.
32const DAY: u64 = 24 * 60 * 60;
33
34/// Logical name of the pre-session CSRF cookie, used by the pages that run before a session exists.
35pub const PRE_CSRF_COOKIE: &str = "im_precsrf";
36
37/// How long the pre-session CSRF token stays valid in the browser.
38const PRE_CSRF_TTL: Duration = Duration::from_secs(60 * 60);
39
40/// Logical name of the pending-login cookie, set between the password and the second factor.
41pub const PENDING_COOKIE: &str = "im_pending";
42
43/// How long a password-verified sign-in may wait for its second factor. Five minutes is long enough
44/// to fetch a code from an app, and short enough that a stolen cookie is of little use.
45pub const PENDING_TTL: Duration = Duration::from_secs(5 * 60);
46
47/// The longest `next` value accepted, in bytes.
48const MAX_NEXT_LEN: usize = 2048;
49
50/// The signed-in person and the session they signed in with.
51#[derive(Clone)]
52pub struct Viewer {
53 /// The account. Not disabled.
54 pub user: User,
55 /// The session the request presented. Its `csrf_token` checks forms.
56 pub session: Session,
57}
58
59/// The cookie jar that forces the `__Host-` prefix: `Secure`, `Path=/` and no `Domain`.
60fn jar(cx: &Cx) -> impl Cookies + '_ {
61 cookies(cx).override_prefix_host()
62}
63
64/// The session the request presented, if it is still live.
65async fn presented_session(cx: &Cx) -> Result<Option<Session>> {
66 let Some(cookie) = jar(cx).get(SESSION_COOKIE) else {
67 return Ok(None);
68 };
69 let store = &app_context::<AppState>(cx).store;
70 Ok(store
71 .session_by_token_hash(&hash_token(cookie.value()))
72 .await?)
73}
74
75/// The signed-in person, or `None` when there is no live session. Refreshes `last_seen` (at most
76/// once in five minutes; the store decides).
77pub async fn current_user(cx: &Cx) -> Result<Option<Viewer>> {
78 let Some(session) = presented_session(cx).await? else {
79 return Ok(None);
80 };
81 let store = &app_context::<AppState>(cx).store;
82 let Some(user) = store
83 .user_by_id(&session.user_id)
84 .await?
85 .filter(|user| !user.is_disabled())
86 else {
87 return Ok(None);
88 };
89 store.touch_session(&session.id).await?;
90 Ok(Some(Viewer { user, session }))
91}
92
93/// The signed-in person. Anyone else is sent to `/login`, with the page they asked for as `next`.
94pub async fn require_user(cx: &Cx) -> Result<Viewer> {
95 match current_user(cx).await? {
96 Some(viewer) => Ok(viewer),
97 None => {
98 let path = uri(cx).path_and_query().map_or("/", |p| p.as_str());
99 let target = format!("/login?next={}", percent_encode(path));
100 Err(see_other(target).into())
101 }
102 }
103}
104
105/// The signed-in administrator. A visitor without a session, and a person who is not an administrator,
106/// get 404, the same answer as a page that does not exist. An administrator without two-factor sign-in, while the policy requires
107/// it, is sent to the security page instead.
108pub async fn require_admin(cx: &Cx) -> Result<Viewer> {
109 // Anyone without a live session gets 404 too: an admin page does not redirect to sign-in, so its
110 // existence is not revealed to visitors.
111 let Some(viewer) = current_user(cx).await? else {
112 return Err(not_found().into());
113 };
114 if !viewer.user.is_admin {
115 return Err(not_found().into());
116 }
117 let state = app_context::<AppState>(cx);
118 if state.policy().require_2fa_for_admins && !viewer.user.totp_enabled() {
119 return Err(see_other("/account/security?notice=enrol").into());
120 }
121 Ok(viewer)
122}
123
124/// The signed-in person, when the submitted `csrf` field matches their session. Returns 403 for a
125/// wrong or missing token. Call it first in every state-changing handler.
126pub async fn require_csrf(cx: &Cx, submitted: &str) -> Result<Viewer> {
127 let viewer = require_user(cx).await?;
128 if check_csrf(&viewer.session, submitted) {
129 Ok(viewer)
130 } else {
131 Err(forbidden().into())
132 }
133}
134
135/// The signed-in administrator, when the submitted `csrf` field matches their session. A member gets 404
136/// first, before the token is looked at, so a form of the admin area gives no hint to a member.
137pub async fn require_admin_csrf(cx: &Cx, submitted: &str) -> Result<Viewer> {
138 let viewer = require_admin(cx).await?;
139 if check_csrf(&viewer.session, submitted) {
140 Ok(viewer)
141 } else {
142 Err(forbidden().into())
143 }
144}
145
146/// True only when `submitted` is the session's CSRF token, compared in constant time. An empty
147/// stored token never matches, not even an empty submission.
148pub fn check_csrf(session: &Session, submitted: &str) -> bool {
149 !session.csrf_token.is_empty()
150 && constant_time_eq(session.csrf_token.as_bytes(), submitted.as_bytes())
151}
152
153/// Creates a session for `user`, authenticated by `amr`, and sets the cookie. Returns `false`, with no
154/// session and no cookie, when `decided_on` no longer holds for the user (see
155/// [`im_core::store::Store::create_session`]). The caller then treats the sign-in as failed.
156///
157/// A session the browser already presented is ended first, whoever it belongs to, so a sign-in always
158/// rotates the session id and no row is left live with no cookie holding it. The session lives
159/// [`SESSION_IDLE`] after its last use, up to the policy's `session_max_days` from now; the store keeps
160/// both limits. The per-person cap of the policy is applied inside the store, in the same write.
161pub async fn start_session(
162 cx: &Cx,
163 user: &User,
164 amr: &str,
165 decided_on: SignInState<'_>,
166) -> Result<bool> {
167 let state = app_context::<AppState>(cx);
168 let max_age = Duration::from_secs(u64::from(state.policy().session_max_days) * DAY);
169 if let Some(old) = presented_session(cx).await? {
170 // The owner is the session's own user, so the store's ownership check passes for it.
171 if state
172 .store
173 .end_session(&old.user_id, &old.id, EndReason::Replaced)
174 .await?
175 && old.user_id != user.id
176 {
177 state.live.bump(&Topic::Account(old.user_id.clone()));
178 }
179 }
180 let token = generate_token();
181 let csrf = generate_token();
182 let ip = client_addr(cx).to_string();
183 let user_agent = user_agent(cx);
184 let Some(_) = state
185 .store
186 .create_session(
187 &NewSession {
188 user_id: &user.id,
189 decided_on,
190 token_hash: &hash_token(&token),
191 csrf_token: &csrf,
192 amr,
193 ip: Some(ip.as_str()),
194 user_agent: user_agent.as_deref(),
195 idle: SESSION_IDLE,
196 max_age,
197 },
198 state.policy().max_sessions,
199 )
200 .await?
201 else {
202 return Ok(false);
203 };
204 // Sessions ended by the cap were queued for back-channel logout in the store's transaction.
205 state.live.bump(&Topic::Account(user.id.clone()));
206 // The browser keeps the cookie for the hard cap; the server decides the real expiry.
207 let cookie_age = time::Duration::seconds(i64::try_from(max_age.as_secs()).unwrap_or(i64::MAX));
208 jar(cx).add(
209 Cookie::build((SESSION_COOKIE, token))
210 .path("/")
211 .secure(true)
212 .http_only(true)
213 .same_site(SameSite::Lax)
214 .max_age(cookie_age)
215 .build(),
216 );
217 Ok(true)
218}
219
220/// Ends the session of `viewer` (with its back-channel logouts) and clears its cookie. Other sessions of
221/// the person are untouched.
222pub async fn end_current_session(cx: &Cx, viewer: &Viewer, reason: EndReason) -> Result<()> {
223 let state = app_context::<AppState>(cx);
224 state
225 .store
226 .end_session(&viewer.user.id, &viewer.session.id, reason)
227 .await?;
228 state.live.bump(&Topic::Account(viewer.user.id.clone()));
229 jar(cx).remove(Cookie::build((SESSION_COOKIE, "")).path("/"));
230 Ok(())
231}
232
233/// The pre-session CSRF token. Login, setup and the second-factor page use it, because no session
234/// exists yet. An existing cookie is reused, so two open tabs both keep working.
235pub fn pre_csrf_token(cx: &Cx) -> String {
236 if let Some(cookie) = jar(cx).get(PRE_CSRF_COOKIE) {
237 let value = cookie.value();
238 if !value.is_empty() {
239 return value.to_owned();
240 }
241 }
242 let token = generate_token();
243 jar(cx).add(pre_csrf_cookie(token.clone()));
244 token
245}
246
247/// True only when the submitted `precsrf` equals the pre-session cookie. Call it before any other
248/// work in a pre-session POST.
249pub fn check_pre_csrf(cx: &Cx, submitted: &str) -> bool {
250 let Some(cookie) = jar(cx).get(PRE_CSRF_COOKIE) else {
251 return false;
252 };
253 !cookie.value().is_empty() && constant_time_eq(cookie.value().as_bytes(), submitted.as_bytes())
254}
255
256/// Removes the pre-session CSRF cookie after a successful sign-in or setup.
257pub fn clear_pre_csrf(cx: &Cx) {
258 jar(cx).remove(Cookie::build((PRE_CSRF_COOKIE, "")).path("/"));
259}
260
261fn pre_csrf_cookie(token: String) -> Cookie<'static> {
262 Cookie::build((PRE_CSRF_COOKIE, token))
263 .path("/")
264 .secure(true)
265 .http_only(true)
266 .same_site(SameSite::Strict)
267 .max_age(time::Duration::seconds(
268 i64::try_from(PRE_CSRF_TTL.as_secs()).unwrap_or(i64::MAX),
269 ))
270 .build()
271}
272
273/// A password-verified sign-in that waits for its second factor.
274#[derive(Clone, PartialEq, Eq)]
275pub struct Pending {
276 /// Random id of this pending sign-in. The second factor spends it once (`Store::consume_pending_login`).
277 pub nonce: String,
278 /// The person who passed the password step.
279 pub user_id: String,
280 /// The authentication method so far. Always the password.
281 pub amr: String,
282 /// Where to go after the second factor. Checked again with [`safe_next`] before use.
283 pub next: String,
284}
285
286/// Prints every field, except that the nonce prints as `<redacted>`: spending it signs the person in.
287impl std::fmt::Debug for Pending {
288 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
289 f.debug_struct("Pending")
290 .field("nonce", &format_args!("<redacted>"))
291 .field("user_id", &self.user_id)
292 .field("amr", &self.amr)
293 .field("next", &self.next)
294 .finish()
295 }
296}
297
298/// Parks a password-verified sign-in in the pending cookie. The payload is sealed with the instance
299/// key, so the browser can neither change the person nor extend the expiry. It carries a random nonce,
300/// which a successful second factor spends, so the same cookie cannot sign in twice.
301pub fn set_pending_login(cx: &Cx, key: &[u8; 32], user_id: &str, next: &str) -> Result<()> {
302 let expires = unix_now() + PENDING_TTL.as_secs();
303 let nonce = generate_token();
304 let payload = format!("{user_id}|{expires}|{}|{nonce}|{next}", amr::PASSWORD);
305 let sealed = secret::seal(key, secret::purpose::PENDING_LOGIN, payload.as_bytes())?;
306 let max_age = time::Duration::seconds(i64::try_from(PENDING_TTL.as_secs()).unwrap_or(0));
307 jar(cx).add(
308 Cookie::build((PENDING_COOKIE, sealed))
309 .path("/")
310 .secure(true)
311 .http_only(true)
312 .same_site(SameSite::Strict)
313 .max_age(max_age)
314 .build(),
315 );
316 Ok(())
317}
318
319/// The pending sign-in, or `None` when the cookie is missing, tampered with, malformed or expired.
320/// `next` is the field as it was set; the caller applies [`safe_next`].
321pub fn pending_login(cx: &Cx, key: &[u8; 32]) -> Option<Pending> {
322 let cookie = jar(cx).get(PENDING_COOKIE)?;
323 let plain = secret::open(key, secret::purpose::PENDING_LOGIN, cookie.value()).ok()?;
324 let text = String::from_utf8(plain).ok()?;
325 // `next` comes last, so a `|` inside it cannot shift the other fields.
326 let mut parts = text.splitn(5, '|');
327 let user_id = parts.next()?;
328 let expires: u64 = parts.next()?.parse().ok()?;
329 let amr = parts.next()?;
330 let nonce = parts.next()?;
331 let next = parts.next()?;
332 if unix_now() >= expires {
333 return None;
334 }
335 Some(Pending {
336 nonce: nonce.to_owned(),
337 user_id: user_id.to_owned(),
338 amr: amr.to_owned(),
339 next: next.to_owned(),
340 })
341}
342
343/// Removes the pending-login cookie.
344pub fn clear_pending_login(cx: &Cx) {
345 jar(cx).remove(Cookie::build((PENDING_COOKIE, "")).path("/"));
346}
347
348/// Logical name of the one-time secret cookie. It carries a client secret from the POST that made the secret
349/// to the GET that shows it, so the secret never sits in a response to the POST or in a URL.
350pub const SECRET_FLASH_COOKIE: &str = "im_secret";
351
352/// How long a one-time secret waits in its cookie. Long enough for the redirect to be followed; a secret that
353/// is not shown in that time is not kept.
354pub const SECRET_FLASH_TTL: Duration = Duration::from_secs(2 * 60);
355
356/// Parks a client secret for the page that shows it once. The payload is sealed with the instance key, names
357/// the client it belongs to, and expires after [`SECRET_FLASH_TTL`]. Same cookie attributes as the pending
358/// sign-in: `__Host-`, Secure, HttpOnly, SameSite=Strict, Path=/.
359pub fn set_secret_flash(cx: &Cx, key: &[u8; 32], client_id: &str, secret: &str) -> Result<()> {
360 let expires = unix_now() + SECRET_FLASH_TTL.as_secs();
361 let sealed = secret::seal(
362 key,
363 secret::purpose::SECRET_FLASH,
364 format!("{client_id}|{expires}|{secret}").as_bytes(),
365 )?;
366 let max_age = time::Duration::seconds(i64::try_from(SECRET_FLASH_TTL.as_secs()).unwrap_or(0));
367 jar(cx).add(
368 Cookie::build((SECRET_FLASH_COOKIE, sealed))
369 .path("/")
370 .secure(true)
371 .http_only(true)
372 .same_site(SameSite::Strict)
373 .max_age(max_age)
374 .build(),
375 );
376 Ok(())
377}
378
379/// Takes the secret parked for `client_id`. The cookie is removed whether or not it matches, so a secret is
380/// shown at most once. Returns `None` when the cookie is missing, tampered with, expired or for another client.
381pub fn take_secret_flash(cx: &Cx, key: &[u8; 32], client_id: &str) -> Option<String> {
382 let sealed = jar(cx).get(SECRET_FLASH_COOKIE)?.value().to_owned();
383 clear_secret_flash(cx);
384 let plain = secret::open(key, secret::purpose::SECRET_FLASH, &sealed).ok()?;
385 let text = String::from_utf8(plain).ok()?;
386 let mut parts = text.splitn(3, '|');
387 let id = parts.next()?;
388 let expires: u64 = parts.next()?.parse().ok()?;
389 let secret = parts.next()?;
390 (id == client_id && unix_now() < expires).then(|| secret.to_owned())
391}
392
393/// Removes the one-time secret cookie.
394pub fn clear_secret_flash(cx: &Cx) {
395 jar(cx).remove(Cookie::build((SECRET_FLASH_COOKIE, "")).path("/"));
396}
397
398/// Checks one six-digit TOTP code for `user`, with the replay guard. True only when the code is
399/// valid and its step was not used before. Returns false when two-factor sign-in is off.
400pub async fn verify_totp(store: &Store, key: &[u8; 32], user: &User, code: &str) -> Result<bool> {
401 let Some(sealed) = user.totp_secret_sealed.as_deref() else {
402 return Ok(false);
403 };
404 if !user.totp_enabled() {
405 return Ok(false);
406 }
407 let shared = secret::open(key, secret::purpose::TOTP_SECRET, sealed)?;
408 let last = user
409 .totp_last_step
410 .and_then(|step| u64::try_from(step).ok());
411 match totp::verify(&shared, code, totp::step_for(unix_now()), last) {
412 Some(step) => Ok(store.accept_totp_step(&user.id, step).await?),
413 None => Ok(false),
414 }
415}
416
417/// Checks a second factor: six digits are a TOTP code, anything else is a recovery code, which is
418/// spent on success. Returns the authentication method that was proved, or `None`.
419pub async fn check_second_factor(
420 store: &Store,
421 key: &[u8; 32],
422 user: &User,
423 input: &str,
424) -> Result<Option<&'static str>> {
425 let input = input.trim();
426 if input.len() == totp::DIGITS && input.bytes().all(|b| b.is_ascii_digit()) {
427 let ok = verify_totp(store, key, user, input).await?;
428 return Ok(ok.then_some(amr::PASSWORD_TOTP));
429 }
430 if !user.totp_enabled() {
431 return Ok(None);
432 }
433 let spent = store
434 .consume_recovery_code(&user.id, &totp::recovery_code_hash(key, input))
435 .await?;
436 Ok(spent.then_some(amr::PASSWORD_RECOVERY))
437}
438
439/// Where a person goes after signing in. An administrator without two-factor sign-in goes to the
440/// security page to enrol it, while the policy requires that. Anyone else goes to `next`.
441pub fn after_sign_in(state: &AppState, user: &User, next: &str) -> String {
442 if user.is_admin && state.policy().require_2fa_for_admins && !user.totp_enabled() {
443 "/account/security?notice=enrol".to_owned()
444 } else {
445 safe_next(Some(next)).to_owned()
446 }
447}
448
449/// Returns `next` only when it is a same-site path: one leading `/`, then no `/` or `\` that would
450/// make a browser treat it as another host, no control characters, at most 2048 bytes. Anything else
451/// is `/`.
452pub fn safe_next(next: Option<&str>) -> &str {
453 match next {
454 Some(next) if is_local_path(next) => next,
455 _ => "/",
456 }
457}
458
459fn is_local_path(path: &str) -> bool {
460 path.len() <= MAX_NEXT_LEN
461 && path.starts_with('/')
462 && !path.starts_with("//")
463 && !path.starts_with("/\\")
464 && path.chars().all(|c| !c.is_control())
465}
466
467/// Percent-encodes everything except RFC 3986 unreserved characters and `/`.
468pub fn percent_encode(input: &str) -> String {
469 let mut out = String::with_capacity(input.len());
470 for byte in input.bytes() {
471 match byte {
472 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => {
473 out.push(char::from(byte));
474 }
475 _ => out.push_str(&format!("%{byte:02X}")),
476 }
477 }
478 out
479}
480
481/// The `User-Agent` of the request, truncated to 512 characters.
482pub fn user_agent(cx: &Cx) -> Option<String> {
483 headers(cx)
484 .get(http::header::USER_AGENT)
485 .and_then(|value| value.to_str().ok())
486 .map(|text| text.chars().take(512).collect())
487}
488
489/// Seconds since the Unix epoch. A clock before the epoch reads as 0, which only makes every
490/// pending sign-in expire at once.
491pub fn unix_now() -> u64 {
492 SystemTime::now()
493 .duration_since(UNIX_EPOCH)
494 .map_or(0, |d| d.as_secs())
495}
496
497#[cfg(test)]
498mod tests {
499 use super::*;
500
501 #[test]
502 fn next_accepts_only_local_paths() {
503 assert_eq!(safe_next(Some("/")), "/");
504 assert_eq!(
505 safe_next(Some("/account/security?x=1")),
506 "/account/security?x=1"
507 );
508 assert_eq!(safe_next(None), "/");
509 }
510
511 #[test]
512 fn next_refuses_every_attack_string() {
513 let overlong = format!("/{}", "a".repeat(MAX_NEXT_LEN));
514 for bad in [
515 "",
516 "https://evil.example/",
517 "http://evil.example",
518 "//evil.example/",
519 "/\\evil.example/",
520 "\\\\evil.example",
521 "\\/evil.example",
522 "evil.example",
523 "javascript:alert(1)",
524 "/\n/evil.example",
525 "/\r\nSet-Cookie: x=1",
526 "/\t",
527 "/\u{0}",
528 " //evil.example",
529 overlong.as_str(),
530 ] {
531 assert_eq!(safe_next(Some(bad)), "/", "accepted {bad:?}");
532 }
533 }
534
535 #[test]
536 fn percent_encoding_keeps_slashes_and_encodes_the_rest() {
537 assert_eq!(percent_encode("/a/b-c_d.e~f"), "/a/b-c_d.e~f");
538 assert_eq!(percent_encode("/s?x=1&y=2"), "/s%3Fx%3D1%26y%3D2");
539 }
540
541 #[tokio::test]
542 async fn a_recovery_code_signs_in_once() {
543 use crate::boot::test_state;
544 let (_dir, state) = test_state().await;
545 let user = state
546 .store
547 .create_user("ada@example.com", "Ada", "hash", false)
548 .await
549 .expect("user");
550 let sealed = secret::seal(
551 &state.key,
552 secret::purpose::TOTP_SECRET,
553 &totp::new_secret(),
554 )
555 .expect("seal");
556 let code = totp::new_recovery_code();
557 state
558 .store
559 .enable_totp(
560 &user.id,
561 &sealed,
562 1,
563 &[totp::recovery_code_hash(&state.key, &code)],
564 None,
565 )
566 .await
567 .expect("enable");
568 let user = state
569 .store
570 .user_by_id(&user.id)
571 .await
572 .expect("query")
573 .expect("user");
574 let first = check_second_factor(&state.store, &state.key, &user, &code)
575 .await
576 .expect("check");
577 assert_eq!(first, Some(amr::PASSWORD_RECOVERY));
578 let second = check_second_factor(&state.store, &state.key, &user, &code)
579 .await
580 .expect("check");
581 assert_eq!(second, None);
582 }
583}