diff --git a/crates/im-core/src/config.rs b/crates/im-core/src/config.rs index 0c7b959..8122b66 100644 --- a/crates/im-core/src/config.rs +++ b/crates/im-core/src/config.rs @@ -373,17 +373,33 @@ impl Config { } } -/// Checks that `base_url` is an http(s) origin with a path of at most `/`. +/// Checks that `base_url` is an origin with a path of at most `/`. It must be https, except for a localhost +/// or loopback host, where plain http never leaves the machine (the same rule as the SMTP `tls = "none"`). fn validate_base_url(url: &str) -> Result<()> { - let rest = url - .strip_prefix("https://") - .or_else(|| url.strip_prefix("http://")) - .ok_or_else(|| Error::Config("base_url must start with http:// or https://".into()))?; + let (secure, rest) = match url.strip_prefix("https://") { + Some(rest) => (true, rest), + None => ( + false, + url.strip_prefix("http://").ok_or_else(|| { + Error::Config("base_url must start with http:// or https://".into()) + })?, + ), + }; if rest.is_empty() || rest.ends_with('/') || url.chars().any(char::is_whitespace) { return Err(Error::Config( "base_url must be an origin with no trailing slash or spaces".into(), )); } + let authority = rest.split('/').next().unwrap_or(rest); + let host = match authority.strip_prefix('[') { + Some(bracketed) => bracketed.split(']').next().unwrap_or(bracketed), + None => authority.split(':').next().unwrap_or(authority), + }; + if !secure && !is_localhost(host) { + return Err(Error::Config( + "base_url must use https:// unless its host is localhost or a loopback address".into(), + )); + } Ok(()) } @@ -400,7 +416,7 @@ mod tests { #[test] fn plaintext_smtp_is_refused_unless_the_host_is_localhost() { - let base = "database = \"d\"\ndata_dir = \"x\"\nlisten = \"127.0.0.1:1\"\nbase_url = \"http://a\"\n"; + let base = "database = \"d\"\ndata_dir = \"x\"\nlisten = \"127.0.0.1:1\"\nbase_url = \"https://a\"\n"; let remote = format!( "{base}[smtp]\nhost = \"mail.example.com\"\ntls = \"none\"\nfrom = \"im@example.com\"\n" ); @@ -412,4 +428,17 @@ mod tests { let no_from = format!("{base}[smtp]\nhost = \"mail.example.com\"\n"); assert!(Config::parse(&no_from).is_err()); } + + #[test] + fn plain_http_base_url_is_refused_unless_the_host_is_loopback() { + let base_url = |url: &str| { + format!( + "database = \"d\"\ndata_dir = \"x\"\nlisten = \"127.0.0.1:1\"\nbase_url = \"{url}\"\n" + ) + }; + assert!(Config::parse(&base_url("http://id.example.com")).is_err()); + assert!(Config::parse(&base_url("http://127.0.0.1:7650")).is_ok()); + assert!(Config::parse(&base_url("http://[::1]:7650")).is_ok()); + assert!(Config::parse(&base_url("https://id.example.com")).is_ok()); + } } diff --git a/crates/im-core/src/model.rs b/crates/im-core/src/model.rs index 4dedc5f..5ee46c9 100644 --- a/crates/im-core/src/model.rs +++ b/crates/im-core/src/model.rs @@ -5,7 +5,7 @@ //! Timestamps are the stored text form from `time.rs`. /// A person who can sign in. `id` is the OIDC `sub` once OIDC exists, and is never reused. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq)] pub struct User { /// ULID. pub id: String, @@ -43,6 +43,32 @@ pub struct User { pub updated_at: String, } +/// Prints every field, except that the password hash and the sealed TOTP secret print as ``, so a +/// debug log never holds them. +impl std::fmt::Debug for User { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("User") + .field("id", &self.id) + .field("email", &self.email) + .field("name", &self.name) + .field("password_hash", &format_args!("")) + .field("is_admin", &self.is_admin) + .field("disabled_at", &self.disabled_at) + .field("totp_secret_sealed", &format_args!("")) + .field("totp_enabled_at", &self.totp_enabled_at) + .field("totp_last_step", &self.totp_last_step) + .field("locale", &self.locale) + .field("locale_auto", &self.locale_auto) + .field("zoneinfo", &self.zoneinfo) + .field("theme", &self.theme) + .field("photo_mime", &self.photo_mime) + .field("picture_version", &self.picture_version) + .field("created_at", &self.created_at) + .field("updated_at", &self.updated_at) + .finish() + } +} + impl User { /// True when two-factor sign-in is on: the secret is stored and enrolment was confirmed. pub fn totp_enabled(&self) -> bool { @@ -81,7 +107,7 @@ pub mod amr { } /// A browser session. The cookie holds the token; the row holds only its hash. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq)] pub struct Session { /// ULID. This is the OIDC `sid` once OIDC exists. pub id: String, @@ -109,6 +135,26 @@ pub struct Session { pub amr: String, } +/// Prints every field, except that the token hash and the CSRF token print as ``. +impl std::fmt::Debug for Session { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Session") + .field("id", &self.id) + .field("user_id", &self.user_id) + .field("token_hash", &format_args!("")) + .field("csrf_token", &format_args!("")) + .field("created_at", &self.created_at) + .field("expires_at", &self.expires_at) + .field("hard_expires_at", &self.hard_expires_at) + .field("last_seen_at", &self.last_seen_at) + .field("ip", &self.ip) + .field("user_agent", &self.user_agent) + .field("auth_time", &self.auth_time) + .field("amr", &self.amr) + .finish() + } +} + /// What an audit entry is about. The variants are the values stored in `audit_log.action`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum AuditAction { diff --git a/crates/im-core/src/store/mod.rs b/crates/im-core/src/store/mod.rs index f43f21f..52354e7 100644 --- a/crates/im-core/src/store/mod.rs +++ b/crates/im-core/src/store/mod.rs @@ -70,6 +70,7 @@ impl Store { let path_str = path.to_str().ok_or_else(|| { Error::Config(format!("database path is not UTF-8: {}", path.display())) })?; + create_private_files(path)?; let db = Builder::new_local(path_str).build().await.map_err(db_err)?; let conn = db.connect().map_err(db_err)?; apply_pragmas(&conn).await?; @@ -170,6 +171,28 @@ impl Store { } } +/// Creates the database file and its `-wal` and `-shm` sidecars as empty 0600 files when they do not exist, +/// so turso never creates them with the umask default. A file that exists is left alone here. +fn create_private_files(path: &Path) -> Result<()> { + use std::os::unix::fs::OpenOptionsExt; + + for suffix in ["", "-wal", "-shm"] { + let mut name = path.as_os_str().to_owned(); + name.push(suffix); + match std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(std::path::PathBuf::from(name)) + { + Ok(_) => {} + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {} + Err(e) => return Err(e.into()), + } + } + Ok(()) +} + /// Makes the database file and its `-wal` and `-shm` sidecars private (mode 0600). They hold every row, /// including sealed secrets, so no other local user may read them whatever the process umask was. Runs /// after the connections are open, when the sidecars exist. diff --git a/crates/im-web/src/auth.rs b/crates/im-web/src/auth.rs index 7a11940..7c13043 100644 --- a/crates/im-web/src/auth.rs +++ b/crates/im-web/src/auth.rs @@ -271,7 +271,7 @@ fn pre_csrf_cookie(token: String) -> Cookie<'static> { } /// A password-verified sign-in that waits for its second factor. -#[derive(Debug, Clone, PartialEq, Eq)] +#[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, @@ -283,6 +283,18 @@ pub struct Pending { 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. diff --git a/crates/im-web/src/backups.rs b/crates/im-web/src/backups.rs index 2892d96..6226c1a 100644 --- a/crates/im-web/src/backups.rs +++ b/crates/im-web/src/backups.rs @@ -169,14 +169,15 @@ async fn write_and_prune( Ok(set) } -/// Sends one dead-man ping. Failures are logged; they never fail the backup. +/// Sends one dead-man ping. Failures are logged; they never fail the backup. The URL holds the healthcheck +/// id, a secret, so a transport error is logged without it. async fn ping(http: &reqwest::Client, url: &str) { match http.get(url).send().await { Ok(response) if response.status().is_success() => {} Ok(response) => { tracing::warn!(status = %response.status(), "dead-man ping answered with an error"); } - Err(error) => tracing::warn!(error = %error, "dead-man ping failed"), + Err(error) => tracing::warn!(error = %error.without_url(), "dead-man ping failed"), } } diff --git a/crates/im-web/src/boot.rs b/crates/im-web/src/boot.rs index f23b0c1..1a2816b 100644 --- a/crates/im-web/src/boot.rs +++ b/crates/im-web/src/boot.rs @@ -10,7 +10,7 @@ use std::os::unix::fs::PermissionsExt; use std::path::Path; use std::sync::{Arc, RwLock}; -use im_core::config::{Config, PolicyConfig}; +use im_core::config::{Config, PolicyConfig, SmtpTls}; use im_core::photo::MAX_UPLOAD_BYTES; use im_core::secret; use im_core::store::Store; @@ -69,6 +69,7 @@ pub async fn serve(config_path: &Path) -> im_core::Result<()> { let listen = config.listen; let _lock = lock_data_dir(&config.data_dir)?; let state = open_state(config).await?; + warn_weak_settings(&state); let listener = TcpListener::bind(listen).await.map_err(|error| { std::io::Error::new(error.kind(), format!("cannot bind {listen}: {error}")) @@ -126,6 +127,29 @@ pub async fn serve(config_path: &Path) -> im_core::Result<()> { Ok(()) } +/// Logs one warning for each setting that weakens the instance or does not fit its deployment. The server +/// still starts: each is a choice an operator may have made on purpose. The policy is the one in effect, +/// so an administrator's saved setting counts too. +fn warn_weak_settings(state: &AppState) { + let config = &state.config; + if !state.policy().require_2fa_for_admins { + tracing::warn!( + "require_2fa_for_admins is off: administrators may sign in without two-factor sign-in" + ); + } + if config.smtp.tls == SmtpTls::None { + tracing::warn!("smtp tls is none: mail is sent to the relay without encryption"); + } + if !config.backup.enabled() { + tracing::warn!("backups are not configured: no scheduled copy of the database is made"); + } + if config.trusted_proxies.is_empty() && config.listen.ip().is_loopback() { + tracing::warn!( + "trusted_proxies is empty while listen is a loopback address: behind a proxy, every client shares one IP for throttling" + ); + } +} + /// Creates the data directory and opens the key and the database. Everything the router needs /// that touches the disk is ready when this returns. The signing keys are made ready too, so the /// first token can be signed. The operator commands use this as well. @@ -165,6 +189,7 @@ pub(crate) async fn open_state(config: Config) -> im_core::Result { live: Arc::new(LiveHub::default()), backup: Arc::new(BackupTrigger::default()), throttle: Arc::new(Throttle::default()), + two_factor_days: Arc::new(Throttle::two_factor_days()), photo_uploads: Arc::new(Throttle::photo_uploads()), email_changes: Arc::new(Throttle::email_changes()), per_minute: Arc::new(Throttle::per_minute()), @@ -291,6 +316,7 @@ mod tests { live: Arc::new(LiveHub::default()), backup: Arc::new(BackupTrigger::default()), throttle: Arc::new(Throttle::default()), + two_factor_days: Arc::new(Throttle::two_factor_days()), photo_uploads: Arc::new(Throttle::photo_uploads()), email_changes: Arc::new(Throttle::email_changes()), per_minute: Arc::new(Throttle::per_minute()), diff --git a/crates/im-web/src/mail/mod.rs b/crates/im-web/src/mail/mod.rs index da0a6f1..ea00c2a 100644 --- a/crates/im-web/src/mail/mod.rs +++ b/crates/im-web/src/mail/mod.rs @@ -40,7 +40,7 @@ pub enum Notice { } /// One kind of mail, with the values its text needs. A link is already built by the caller. -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy)] pub enum Mail<'a> { /// An administrator invited the recipient to create an account. Invite { @@ -101,6 +101,56 @@ pub enum Mail<'a> { }, } +/// Prints every value except the links, which print as ``: each link carries a token. +impl std::fmt::Debug for Mail<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Mail::Invite { days, .. } => f + .debug_struct("Invite") + .field("link", &format_args!("")) + .field("days", days) + .finish(), + Mail::Reset { minutes, .. } => f + .debug_struct("Reset") + .field("link", &format_args!("")) + .field("minutes", minutes) + .finish(), + Mail::EmailOld { + new_email, hours, .. + } => f + .debug_struct("EmailOld") + .field("link", &format_args!("")) + .field("new_email", new_email) + .field("hours", hours) + .finish(), + Mail::EmailNew { hours, .. } => f + .debug_struct("EmailNew") + .field("link", &format_args!("")) + .field("hours", hours) + .finish(), + Mail::EmailDone { new_email } => f + .debug_struct("EmailDone") + .field("new_email", new_email) + .finish(), + Mail::EmailTaken { issuer } => f + .debug_struct("EmailTaken") + .field("issuer", issuer) + .finish(), + Mail::Security(notice) => f.debug_tuple("Security").field(notice).finish(), + Mail::Notice { subject, body } => f + .debug_struct("Notice") + .field("subject", subject) + .field("body", body) + .finish(), + Mail::Test { subject, body } => f + .debug_struct("Test") + .field("subject", subject) + .field("body", body) + .finish(), + } + } +} + impl Mail<'_> { /// The stored kind, one of the values `mail_outbox.kind` allows. pub fn kind(&self) -> &'static str { diff --git a/crates/im-web/src/pages/login.rs b/crates/im-web/src/pages/login.rs index 4599bcc..388d7ea 100644 --- a/crates/im-web/src/pages/login.rs +++ b/crates/im-web/src/pages/login.rs @@ -33,8 +33,7 @@ use crate::i18n::Lang; use crate::i18n::account::{Txt, text}; use crate::state::AppState; use crate::throttle::{ - LOGIN_AUDIT_LIMIT, LOGIN_IP_LIMIT, LOGIN_USER_LIMIT, TWO_FACTOR_USER_LIMIT, ip_key, - login_audit_key, two_factor_key, user_key, + LOGIN_AUDIT_LIMIT, LOGIN_IP_LIMIT, LOGIN_USER_LIMIT, ip_key, login_audit_key, user_key, }; use crate::views::{alert, field, page_lang, shell}; @@ -227,11 +226,7 @@ async fn two_factor_submit(cx: &Cx, Form(form): Form) -> Result) -> Result { - state.throttle.clear(&limit); + state.clear_second_factor(&user.id); clear_pending_login(cx); match finish_sign_in(cx, &user, method, &pending.next).await? { Some(redirect) => Err(redirect), diff --git a/crates/im-web/src/pages/security.rs b/crates/im-web/src/pages/security.rs index d91ee6b..134cd77 100644 --- a/crates/im-web/src/pages/security.rs +++ b/crates/im-web/src/pages/security.rs @@ -26,7 +26,7 @@ use crate::i18n::account::{Txt, policy_problem, recovery_left, text}; use crate::live::Topic; use crate::mail::{self, Notice}; use crate::state::AppState; -use crate::throttle::{LOGIN_USER_LIMIT, TWO_FACTOR_USER_LIMIT, two_factor_key, user_key}; +use crate::throttle::{LOGIN_USER_LIMIT, user_key}; use crate::views::{ViewerInfo, alert, field, notice, page_lang, shell}; /// How many recovery codes one issue gives. @@ -209,12 +209,7 @@ async fn start_enrolment(cx: &Cx, Form(form): Form) -> Result) -> Result) -> Result) -> Result bool { let mut response = match http.get(&target).send().await { Ok(response) => response, Err(error) => { - tracing::warn!(service = %key, error = %error, "service probe failed"); + tracing::warn!(service = %key, error = %error.without_url(), "service probe failed"); return false; } }; diff --git a/crates/im-web/src/state.rs b/crates/im-web/src/state.rs index 2e54c08..c7edae7 100644 --- a/crates/im-web/src/state.rs +++ b/crates/im-web/src/state.rs @@ -1,6 +1,7 @@ //! The state shared by every route. Topcoat hands it to each handler through the app context. use std::sync::{Arc, PoisonError, RwLock}; +use std::time::{Duration, Instant}; use im_core::config::{Config, PolicyConfig}; use im_core::store::Store; @@ -9,7 +10,7 @@ use tokio::sync::{Semaphore, watch}; use crate::api::directory::StreamSlots; use crate::backups::BackupTrigger; use crate::live::LiveHub; -use crate::throttle::Throttle; +use crate::throttle::{TWO_FACTOR_DAY_LIMIT, TWO_FACTOR_USER_LIMIT, Throttle, two_factor_key}; /// Everything a request handler reaches through the app context. Every field is cheap to clone. #[derive(Clone)] @@ -30,6 +31,8 @@ pub struct AppState { pub backup: Arc, /// Failed sign-in and second-factor counters. pub throttle: Arc, + /// Failed second-factor checks per account, one day window (see `throttle::TWO_FACTOR_DAY_LIMIT`). + pub two_factor_days: Arc, /// Profile photo uploads per account, one hour window (see `throttle::PHOTO_UPLOAD_LIMIT`). pub photo_uploads: Arc, /// Email-change requests per account, one hour window (see `throttle::EMAIL_CHANGE_LIMIT`). @@ -67,4 +70,32 @@ impl AppState { .write() .unwrap_or_else(PoisonError::into_inner) = policy; } + + /// Counts one second-factor attempt of `user_id` against both the short and the day window. Nothing + /// is counted when either refuses; the wait of the refusing window comes back. + pub fn reserve_second_factor(&self, user_id: &str) -> Result<(), Duration> { + let key = two_factor_key(user_id); + let now = Instant::now(); + self.two_factor_days + .reserve(&key, TWO_FACTOR_DAY_LIMIT, now)?; + self.throttle + .reserve(&key, TWO_FACTOR_USER_LIMIT, now) + .inspect_err(|_| self.two_factor_days.refund(&key)) + } + + /// Forgets the second-factor failures of `user_id` after a correct code: the short window is cleared, + /// and the day window gives back the attempt just counted. + pub fn clear_second_factor(&self, user_id: &str) { + let key = two_factor_key(user_id); + self.throttle.clear(&key); + self.two_factor_days.refund(&key); + } + + /// Gives back the attempt just counted in both windows, for a correct code that keeps the short + /// window as it was. + pub fn refund_second_factor(&self, user_id: &str) { + let key = two_factor_key(user_id); + self.throttle.refund(&key); + self.two_factor_days.refund(&key); + } } diff --git a/crates/im-web/src/throttle.rs b/crates/im-web/src/throttle.rs index 0515608..be94bd9 100644 --- a/crates/im-web/src/throttle.rs +++ b/crates/im-web/src/throttle.rs @@ -40,6 +40,14 @@ pub const LOGIN_IP_LIMIT: usize = 30; /// Failed second-factor checks allowed per user inside [`WINDOW`]. pub const TWO_FACTOR_USER_LIMIT: usize = 10; +/// Failed second-factor checks allowed per user inside [`TWO_FACTOR_DAY_WINDOW`]. It works beside +/// [`TWO_FACTOR_USER_LIMIT`], so a guesser who pauses between windows still runs out. +pub const TWO_FACTOR_DAY_LIMIT: usize = 30; + +/// Length of the second-factor day window: 24 hours. Kept on its own [`Throttle`] (see +/// [`Throttle::two_factor_days`]), because a throttle has one window for all its keys. +pub const TWO_FACTOR_DAY_WINDOW: Duration = Duration::from_secs(24 * 60 * 60); + /// Reset-link requests allowed per normalised email address inside [`WINDOW`]. Every request counts, known /// address or not, so the limit leaks nothing about the account. pub const FORGOT_EMAIL_LIMIT: usize = 3; @@ -138,6 +146,11 @@ impl Throttle { Self::with_limits(EMAIL_CHANGE_WINDOW, MAX_KEYS) } + /// The day-long counters of second-factor checks: 24 hour window, the same key cap. + pub fn two_factor_days() -> Self { + Self::with_limits(TWO_FACTOR_DAY_WINDOW, MAX_KEYS) + } + /// Counters with a custom window and key cap. Tests use short windows. pub fn with_limits(window: Duration, max_keys: usize) -> Self { Self { diff --git a/docs/architecture.md b/docs/architecture.md index 028b89a..48837c5 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -148,7 +148,7 @@ way; the throttle still counts every failure. **settings**: `key` PK, `value`, `updated_at` (UI overrides and sealed SMTP password). -Files beside the DB in `data_dir`: `im.key`, `photos/` (0600, written by temp file + fsync + rename). Photo upload and removal run under one +The database file and its `-wal` and `-shm` sidecars are created 0600 before turso opens them, and chmod'd again after. Files beside the DB in `data_dir`: `im.key`, `photos/` (0600, written by temp file + fsync + rename). Photo upload and removal run under one process-wide lock (`photo_lock`), so a removal cannot delete a file a parallel upload has just put in place. --- @@ -206,7 +206,7 @@ redirects). Other errors redirect to the client with `error=` and `state`. - Login order (forge): pre-CSRF → throttle (account key and IP key) → lookup (unknown → dummy verify) → password → disabled check (revealed only after a correct password) → 2FA step or session. - Pending 2FA: sealed cookie `__Host-im_pending` (`user_id|expires|next|amr`), SameSite=Strict, 5 minutes. -- Second factor: 6 digits → TOTP with replay guard; `xxxx-xxxx` → recovery code (consumed). Throttled per user. +- Second factor: 6 digits → TOTP with replay guard; `xxxx-xxxx` → recovery code (consumed). Throttled per user: 10 failures per 15 minutes and 30 per 24 hours. - Session: 30 days idle-extended up to `session_max_days` (policy), cookie `__Host-im_session`. At most `max_sessions` per user: the oldest is ended (with back-channel) when exceeded. - Limits beyond the failure counters (`throttle.rs`, in memory, refused with `429` or an OAuth error):