forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

security.rs649 lines, 22.9 KiBHistoryRawDownload
1//! The security page: the password, two-factor sign-in and the recovery codes of the signed-in
2//! person. Each change is a POST that checks the CSRF token first and then redirects (PRG), except
3//! where the codes are shown: those render on the POST response, once.
4
5use std::time::Instant;
6
7use base64::Engine as _;
8use base64::engine::general_purpose::STANDARD as BASE64;
9use im_core::model::AuditAction;
10use im_core::password::{check_policy, hash_password_async, verify_password_async};
11use im_core::secret;
12use im_core::totp;
13use serde::Deserialize;
14use serde_json::json;
15use topcoat::Result;
16use topcoat::context::{Cx, app_context};
17use topcoat::router::content::Form;
18use topcoat::router::error::see_other;
19use topcoat::router::page;
20use topcoat::view::{View, component, view};
21
22use crate::audit::{Actor, record};
23use crate::auth::{Viewer, check_second_factor, require_csrf, require_user, unix_now};
24use crate::i18n::Lang;
25use crate::i18n::account::{Txt, policy_problem, recovery_left, text};
26use crate::live::Topic;
27use crate::mail::{self, Notice};
28use crate::state::AppState;
29use crate::throttle::{LOGIN_USER_LIMIT, user_key};
30use crate::views::{ViewerInfo, alert, field, notice, page_lang, shell};
31
32/// How many recovery codes one issue gives.
33const RECOVERY_CODES: usize = 10;
34
35/// The query of `GET /account/security`.
36#[derive(Deserialize, Default)]
37struct NoticeQuery {
38 #[serde(default)]
39 notice: String,
40}
41
42/// The password change form.
43#[derive(Deserialize, Default)]
44struct PasswordForm {
45 #[serde(default)]
46 csrf: String,
47 #[serde(default)]
48 current_password: String,
49 #[serde(default)]
50 new_password: String,
51 #[serde(default)]
52 new_password_again: String,
53}
54
55/// A form with a CSRF token and one six-digit code (or recovery code).
56#[derive(Deserialize, Default)]
57struct CodeForm {
58 #[serde(default)]
59 csrf: String,
60 #[serde(default)]
61 code: String,
62}
63
64/// The enrolment form: the current password when two-factor sign-in is off, a code when it is on.
65#[derive(Deserialize, Default)]
66struct StartForm {
67 #[serde(default)]
68 csrf: String,
69 #[serde(default)]
70 current_password: String,
71 #[serde(default)]
72 code: String,
73}
74
75/// The turn-off form: the password and a second factor.
76#[derive(Deserialize, Default)]
77struct DisableForm {
78 #[serde(default)]
79 csrf: String,
80 #[serde(default)]
81 current_password: String,
82 #[serde(default)]
83 code: String,
84}
85
86/// The recovery-code form: the password only.
87#[derive(Deserialize, Default)]
88struct RecoveryForm {
89 #[serde(default)]
90 csrf: String,
91 #[serde(default)]
92 current_password: String,
93}
94
95/// What the page shows above its sections: a notice, an error, or freshly issued codes.
96#[derive(Default)]
97struct Flash {
98 notice: Option<String>,
99 alert: Option<String>,
100 codes: Vec<String>,
101}
102
103impl Flash {
104 fn alert(message: impl Into<String>) -> Self {
105 Self {
106 alert: Some(message.into()),
107 ..Self::default()
108 }
109 }
110}
111
112/// A pending enrolment, ready to show: the base32 secret, the otpauth link and the QR code.
113struct Enrolment {
114 secret: String,
115 link: String,
116 qr: String,
117}
118
119/// `GET /account/security`.
120#[page("/account/security")]
121async fn security_page(cx: &Cx, Form(query): Form<NoticeQuery>) -> Result<impl View> {
122 let viewer = require_user(cx).await?;
123 let lang = page_lang(cx, Some(&viewer));
124 let flash_notice = match query.notice.as_str() {
125 "enrol" => Some(text(lang, Txt::EnrolSecurityNotice)),
126 "saved-password" => Some(text(lang, Txt::SavedPassword)),
127 "saved-2fa-on" => Some(text(lang, Txt::Saved2faOn)),
128 "saved-2fa-off" => Some(text(lang, Txt::Saved2faOff)),
129 _ => None,
130 };
131 let flash = Flash {
132 notice: flash_notice.map(str::to_owned),
133 ..Flash::default()
134 };
135 render_security(cx, viewer.clone(), flash).await
136}
137
138/// `POST /account/security/password`.
139#[page(POST "/account/security/password")]
140async fn change_password(cx: &Cx, Form(form): Form<PasswordForm>) -> Result<impl View> {
141 let viewer = require_csrf(cx, &form.csrf).await?;
142 let state = app_context::<AppState>(cx);
143 let lang = page_lang(cx, Some(&viewer));
144 if let Some(problem) = password_problem(state, &viewer, &form.current_password).await? {
145 return render_security(cx, viewer.clone(), Flash::alert(text(lang, problem))).await;
146 }
147 if form.new_password != form.new_password_again {
148 return render_security(
149 cx,
150 viewer.clone(),
151 Flash::alert(text(lang, Txt::ErrPasswordsDiffer)),
152 )
153 .await;
154 }
155 if let Err(violation) = check_policy(&form.new_password, &viewer.user.email, &viewer.user.name)
156 {
157 let message = policy_problem(lang, violation);
158 return render_security(cx, viewer.clone(), Flash::alert(message)).await;
159 }
160 if verify_password_async(form.new_password.clone(), viewer.user.password_hash.clone()).await? {
161 return render_security(
162 cx,
163 viewer.clone(),
164 Flash::alert(text(lang, Txt::ErrPasswordSame)),
165 )
166 .await;
167 }
168
169 let hash = hash_password_async(form.new_password.clone()).await?;
170 // One transaction: the new hash, and the end of every other session of the person with the old
171 // password. This session stays signed in.
172 let ended = state
173 .store
174 .change_password(&viewer.user.id, &hash, &viewer.session.id)
175 .await?;
176 changed(state, &viewer);
177 record(
178 cx,
179 Actor::User(&viewer.user.id),
180 AuditAction::PasswordChanged,
181 Some(("user", &viewer.user.id)),
182 json!({ "sessions_ended": ended.len() }),
183 )
184 .await;
185 mail::notify(
186 &state.store,
187 &state.key,
188 &viewer.user,
189 lang,
190 Notice::PasswordChanged,
191 )
192 .await;
193 Err(see_other("/account/security?notice=saved-password").into())
194}
195
196/// `POST /account/security/2fa/start`: starts an enrolment. Turning on needs no code; replacing an
197/// authenticator of an account that already has two-factor sign-in needs its current code.
198#[page(POST "/account/security/2fa/start")]
199async fn start_enrolment(cx: &Cx, Form(form): Form<StartForm>) -> Result<impl View> {
200 let viewer = require_csrf(cx, &form.csrf).await?;
201 let state = app_context::<AppState>(cx);
202 let lang = page_lang(cx, Some(&viewer));
203 if viewer.user.totp_enabled() {
204 if form.code.trim().is_empty() {
205 return render_security(
206 cx,
207 viewer.clone(),
208 Flash::alert(text(lang, Txt::ErrCodeMissing)),
209 )
210 .await;
211 }
212 if state.reserve_second_factor(&viewer.user.id).is_err() {
213 return render_security(
214 cx,
215 viewer.clone(),
216 Flash::alert(text(lang, Txt::ErrThrottled)),
217 )
218 .await;
219 }
220 if check_second_factor(&state.store, &state.key, &viewer.user, &form.code)
221 .await?
222 .is_none()
223 {
224 return render_security(
225 cx,
226 viewer.clone(),
227 Flash::alert(text(lang, Txt::ErrCodeInvalid)),
228 )
229 .await;
230 }
231 state.refund_second_factor(&viewer.user.id);
232 } else if let Some(problem) = password_problem(state, &viewer, &form.current_password).await? {
233 // Turning two-factor sign-in on is a change of the account, so the password is needed too.
234 return render_security(cx, viewer.clone(), Flash::alert(text(lang, problem))).await;
235 }
236 let secret = totp::new_secret();
237 let sealed = secret::seal(&state.key, secret::purpose::TOTP_SECRET, &secret)?;
238 state
239 .store
240 .set_totp_pending(&viewer.user.id, &sealed)
241 .await?;
242 Err(see_other("/account/security").into())
243}
244
245/// `POST /account/security/2fa/confirm`: the first code from the new authenticator turns
246/// two-factor sign-in on, and issues the recovery codes, shown once.
247#[page(POST "/account/security/2fa/confirm")]
248async fn confirm_enrolment(cx: &Cx, Form(form): Form<CodeForm>) -> Result<impl View> {
249 let viewer = require_csrf(cx, &form.csrf).await?;
250 let state = app_context::<AppState>(cx);
251 let lang = page_lang(cx, Some(&viewer));
252 let Some(sealed) = state.store.totp_pending(&viewer.user.id).await? else {
253 return render_security(
254 cx,
255 viewer.clone(),
256 Flash::alert(text(lang, Txt::ErrNoPending)),
257 )
258 .await;
259 };
260 let shared = secret::open(&state.key, secret::purpose::TOTP_SECRET, &sealed)?;
261 let last = viewer
262 .user
263 .totp_last_step
264 .and_then(|step| u64::try_from(step).ok());
265 let Some(step) = totp::verify(&shared, form.code.trim(), totp::step_for(unix_now()), last)
266 else {
267 return render_security(
268 cx,
269 viewer.clone(),
270 Flash::alert(text(lang, Txt::ErrCodeInvalid)),
271 )
272 .await;
273 };
274
275 let codes = issue_codes();
276 let hashes: Vec<String> = codes
277 .iter()
278 .map(|code| totp::recovery_code_hash(&state.key, code))
279 .collect();
280 // The other sessions end with the first factor (see `Store::enable_totp`); this one stays.
281 let enabled = state
282 .store
283 .enable_totp(
284 &viewer.user.id,
285 &sealed,
286 step,
287 &hashes,
288 Some(&viewer.session.id),
289 )
290 .await?;
291 // A parallel confirmation of the same enrolment got there first: its codes are the ones shown.
292 if !enabled {
293 return render_security(
294 cx,
295 viewer.clone(),
296 Flash::alert(text(lang, Txt::ErrNoPending)),
297 )
298 .await;
299 }
300 changed(state, &viewer);
301 record(
302 cx,
303 Actor::User(&viewer.user.id),
304 AuditAction::TotpEnabled,
305 Some(("user", &viewer.user.id)),
306 json!({ "recovery_codes": codes.len() }),
307 )
308 .await;
309 mail::notify(
310 &state.store,
311 &state.key,
312 &viewer.user,
313 lang,
314 Notice::TwoFactorOn,
315 )
316 .await;
317 // Reload the person, so the page shows two-factor sign-in as on.
318 let user = state
319 .store
320 .user_by_id(&viewer.user.id)
321 .await?
322 .ok_or(im_core::Error::NotFound)?;
323 let viewer = Viewer { user, ..viewer };
324 let flash = Flash {
325 notice: Some(text(lang, Txt::Saved2faOn).to_owned()),
326 codes,
327 ..Flash::default()
328 };
329 render_security(cx, viewer.clone(), flash).await
330}
331
332/// `POST /account/security/2fa/disable`: needs the password and a second factor.
333#[page(POST "/account/security/2fa/disable")]
334async fn disable_two_factor(cx: &Cx, Form(form): Form<DisableForm>) -> Result<impl View> {
335 let viewer = require_csrf(cx, &form.csrf).await?;
336 let state = app_context::<AppState>(cx);
337 let lang = page_lang(cx, Some(&viewer));
338 if !viewer.user.totp_enabled() {
339 return Err(see_other("/account/security").into());
340 }
341 if let Some(problem) = password_problem(state, &viewer, &form.current_password).await? {
342 return render_security(cx, viewer.clone(), Flash::alert(text(lang, problem))).await;
343 }
344 if form.code.trim().is_empty() {
345 return render_security(
346 cx,
347 viewer.clone(),
348 Flash::alert(text(lang, Txt::ErrCodeMissing)),
349 )
350 .await;
351 }
352 if state.reserve_second_factor(&viewer.user.id).is_err() {
353 return render_security(
354 cx,
355 viewer.clone(),
356 Flash::alert(text(lang, Txt::ErrThrottled)),
357 )
358 .await;
359 }
360 if check_second_factor(&state.store, &state.key, &viewer.user, &form.code)
361 .await?
362 .is_none()
363 {
364 return render_security(
365 cx,
366 viewer.clone(),
367 Flash::alert(text(lang, Txt::ErrCodeInvalid)),
368 )
369 .await;
370 }
371
372 // The other sessions end with the second factor (see `Store::disable_totp`); this one stays.
373 state
374 .store
375 .disable_totp(&viewer.user.id, Some(&viewer.session.id))
376 .await?;
377 state.clear_second_factor(&viewer.user.id);
378 changed(state, &viewer);
379 record(
380 cx,
381 Actor::User(&viewer.user.id),
382 AuditAction::TotpDisabled,
383 Some(("user", &viewer.user.id)),
384 json!({}),
385 )
386 .await;
387 mail::notify(
388 &state.store,
389 &state.key,
390 &viewer.user,
391 lang,
392 Notice::TwoFactorOff,
393 )
394 .await;
395 Err(see_other("/account/security?notice=saved-2fa-off").into())
396}
397
398/// `POST /account/security/recovery`: replaces the recovery codes. The old codes stop working.
399#[page(POST "/account/security/recovery")]
400async fn regenerate_recovery(cx: &Cx, Form(form): Form<RecoveryForm>) -> Result<impl View> {
401 let viewer = require_csrf(cx, &form.csrf).await?;
402 let state = app_context::<AppState>(cx);
403 let lang = page_lang(cx, Some(&viewer));
404 if !viewer.user.totp_enabled() {
405 return Err(see_other("/account/security").into());
406 }
407 if let Some(problem) = password_problem(state, &viewer, &form.current_password).await? {
408 return render_security(cx, viewer.clone(), Flash::alert(text(lang, problem))).await;
409 }
410
411 let codes = issue_codes();
412 let hashes: Vec<String> = codes
413 .iter()
414 .map(|code| totp::recovery_code_hash(&state.key, code))
415 .collect();
416 state
417 .store
418 .replace_recovery_codes(&viewer.user.id, &hashes)
419 .await?;
420 record(
421 cx,
422 Actor::User(&viewer.user.id),
423 AuditAction::RecoveryCodesIssued,
424 Some(("user", &viewer.user.id)),
425 json!({ "count": codes.len() }),
426 )
427 .await;
428 mail::notify(
429 &state.store,
430 &state.key,
431 &viewer.user,
432 lang,
433 Notice::RecoveryCodes,
434 )
435 .await;
436 let flash = Flash {
437 codes,
438 ..Flash::default()
439 };
440 render_security(cx, viewer.clone(), flash).await
441}
442
443/// Fresh recovery codes, in the form people type them (`xxxx-xxxx`).
444fn issue_codes() -> Vec<String> {
445 (0..RECOVERY_CODES)
446 .map(|_| totp::new_recovery_code())
447 .collect()
448}
449
450/// Checks the password of the signed-in person, counted against the same limit as sign-in. The attempt is
451/// counted before the check, so parallel guesses cannot all pass. `None` when the password is right;
452/// otherwise the message to show: the throttle's, or the wrong-password one. Wrong passwords on this page
453/// count toward the sign-in limit, so guessing here locks sign-in too.
454pub async fn password_problem(
455 state: &AppState,
456 viewer: &Viewer,
457 given: &str,
458) -> Result<Option<Txt>> {
459 let limit = user_key(&viewer.user.email);
460 if state
461 .throttle
462 .reserve(&limit, LOGIN_USER_LIMIT, Instant::now())
463 .is_err()
464 {
465 return Ok(Some(Txt::ErrThrottled));
466 }
467 if verify_password_async(given.to_owned(), viewer.user.password_hash.clone()).await? {
468 state.throttle.clear(&limit);
469 return Ok(None);
470 }
471 Ok(Some(Txt::ErrWrongPassword))
472}
473
474/// Tells the open account pages that the person's security changed.
475fn changed(state: &AppState, viewer: &Viewer) {
476 state.live.bump(&Topic::Account(viewer.user.id.clone()));
477}
478
479/// Builds the QR code of a secret as a `data:` image, so no request leaves the page for it.
480fn enrolment_of(state: &AppState, viewer: &Viewer, sealed: &str) -> Result<Enrolment> {
481 let shared = secret::open(&state.key, secret::purpose::TOTP_SECRET, sealed)?;
482 let link = totp::otpauth_uri(&viewer.user.email, &shared);
483 let code = qrcode::QrCode::new(link.as_bytes())
484 .map_err(|error| topcoat::Error::msg(error.to_string()))?;
485 let svg = code
486 .render::<qrcode::render::svg::Color>()
487 .min_dimensions(240, 240)
488 .build();
489 Ok(Enrolment {
490 secret: totp::base32_encode(&shared),
491 link,
492 qr: format!("data:image/svg+xml;base64,{}", BASE64.encode(svg)),
493 })
494}
495
496/// The security page: reads what the sections show, then renders them.
497async fn render_security(cx: &Cx, viewer: Viewer, flash: Flash) -> Result<impl View> {
498 let state = app_context::<AppState>(cx);
499 let lang = page_lang(cx, Some(&viewer));
500 let pending = match state.store.totp_pending(&viewer.user.id).await? {
501 Some(sealed) => Some(enrolment_of(state, &viewer, &sealed)?),
502 None => None,
503 };
504 let enabled = viewer.user.totp_enabled();
505 let unused = if enabled {
506 state.store.unused_recovery_codes(&viewer.user.id).await?
507 } else {
508 0
509 };
510 let info = ViewerInfo::of(&viewer);
511 let csrf = viewer.session.csrf_token.clone();
512 Ok(security_view(
513 cx, lang, info, csrf, enabled, unused, pending, flash,
514 ))
515}
516
517/// The markup of the security page. It owns everything it shows, so it can outlive the handler.
518#[allow(clippy::too_many_arguments)]
519fn security_view(
520 cx: &Cx,
521 lang: Lang,
522 info: ViewerInfo,
523 csrf: String,
524 enabled: bool,
525 unused: u64,
526 pending: Option<Enrolment>,
527 flash: Flash,
528) -> impl View {
529 let has_pending = pending.is_some();
530 let Flash {
531 notice: flash_notice,
532 alert: flash_alert,
533 codes,
534 } = flash;
535 view! { cx =>
536 shell(title: text(lang, Txt::SecurityTitle), lang: lang, viewer: Some(info),
537 <section class="stack">
538 <h1>(text(lang, Txt::SecurityTitle))</h1>
539 if let Some(message) = flash_notice {
540 notice(message: message)
541 }
542 if let Some(message) = flash_alert {
543 alert(message: message)
544 }
545
546 <section class="card stack">
547 <h2>(text(lang, Txt::PasswordSection))</h2>
548 <p class="muted">(text(lang, Txt::PasswordHelp))</p>
549 <form method="post" action="/account/security/password" class="stack">
550 <input type="hidden" name="csrf" value=(csrf.clone())>
551 field(label: text(lang, Txt::CurrentPassword), name: "current_password", kind: "password", autocomplete: "current-password", value: String::new())
552 field(label: text(lang, Txt::NewPassword), name: "new_password", kind: "password", autocomplete: "new-password", value: String::new())
553 field(label: text(lang, Txt::NewPasswordAgain), name: "new_password_again", kind: "password", autocomplete: "new-password", value: String::new())
554 <p class="hint">(text(lang, Txt::PasswordHint))</p>
555 <button type="submit" class="button primary">(text(lang, Txt::ChangePassword))</button>
556 </form>
557 </section>
558
559 <section class="card stack">
560 <h2>(text(lang, Txt::TwoFactorSection))</h2>
561 if enabled {
562 <p>(text(lang, Txt::TwoFactorOnText))</p>
563 } else {
564 <p>(text(lang, Txt::TwoFactorOffText))</p>
565 }
566 if let Some(pending) = pending {
567 enrolment_block(lang: lang, csrf: csrf.clone(), secret: pending.secret, link: pending.link, qr: pending.qr)
568 }
569 if enabled {
570 <section class="stack">
571 <h3>(text(lang, Txt::ReplaceTitle))</h3>
572 <p class="muted">(text(lang, Txt::ReplaceHelp))</p>
573 <form method="post" action="/account/security/2fa/start" class="stack">
574 <input type="hidden" name="csrf" value=(csrf.clone())>
575 field(label: text(lang, Txt::CodeFromApp), name: "code", kind: "text", autocomplete: "one-time-code", value: String::new())
576 <button type="submit" class="button ghost">(text(lang, Txt::ReplaceButton))</button>
577 </form>
578 </section>
579
580 <section class="stack">
581 <h3>(text(lang, Txt::RecoveryTitle))</h3>
582 <p class="muted">(text(lang, Txt::RecoveryHelp))</p>
583 <p>(recovery_left(lang, unused))</p>
584 <p class="muted">(text(lang, Txt::RegenerateHelp))</p>
585 <form method="post" action="/account/security/recovery" class="stack">
586 <input type="hidden" name="csrf" value=(csrf.clone())>
587 field(label: text(lang, Txt::CurrentPassword), name: "current_password", kind: "password", autocomplete: "current-password", value: String::new())
588 <button type="submit" class="button ghost">(text(lang, Txt::RegenerateCodes))</button>
589 </form>
590 </section>
591
592 <section class="stack">
593 <h3>(text(lang, Txt::DisableTitle))</h3>
594 <p class="muted">(text(lang, Txt::DisableHelp))</p>
595 <form method="post" action="/account/security/2fa/disable" class="stack">
596 <input type="hidden" name="csrf" value=(csrf.clone())>
597 field(label: text(lang, Txt::CurrentPassword), name: "current_password", kind: "password", autocomplete: "current-password", value: String::new())
598 field(label: text(lang, Txt::CodeFromApp), name: "code", kind: "text", autocomplete: "one-time-code", value: String::new())
599 <button type="submit" class="button danger">(text(lang, Txt::TurnOff))</button>
600 </form>
601 </section>
602 } else if !has_pending {
603 <form method="post" action="/account/security/2fa/start" class="stack">
604 <input type="hidden" name="csrf" value=(csrf.clone())>
605 field(label: text(lang, Txt::CurrentPassword), name: "current_password", kind: "password", autocomplete: "current-password", value: String::new())
606 <button type="submit" class="button primary">(text(lang, Txt::TurnOn))</button>
607 </form>
608 }
609 if !codes.is_empty() {
610 <section class="stack codes">
611 <h3>(text(lang, Txt::NewCodesTitle))</h3>
612 <p class="warning">(text(lang, Txt::CodesShownOnce))</p>
613 <ul class="codes-list">
614 for code in codes {
615 <li><code>(code)</code></li>
616 }
617 </ul>
618 </section>
619 }
620 </section>
621 </section>
622 )
623 }
624}
625
626/// A pending enrolment: the QR code, the secret to type, and the form that confirms the first code.
627#[component]
628async fn enrolment_block(
629 lang: Lang,
630 csrf: String,
631 secret: String,
632 link: String,
633 qr: String,
634) -> Result<impl View> {
635 Ok(view! {
636 <section class="enrolment stack">
637 <h3>(text(lang, Txt::PendingTitle))</h3>
638 <p class="muted">(text(lang, Txt::PendingHelp))</p>
639 <img class="qr" src=(qr) alt=(text(lang, Txt::QrAlt)) width="240" height="240">
640 <p><span class="field-label">(text(lang, Txt::SecretKey))</span> <code class="secret">(secret)</code></p>
641 <p><a href=(link)>(text(lang, Txt::SetupLink))</a></p>
642 <form method="post" action="/account/security/2fa/confirm" class="stack">
643 <input type="hidden" name="csrf" value=(csrf)>
644 field(label: text(lang, Txt::CodeFromApp), name: "code", kind: "text", autocomplete: "one-time-code", value: String::new())
645 <button type="submit" class="button primary">(text(lang, Txt::TurnOn))</button>
646 </form>
647 </section>
648 })
649}