From a96d491f5a8327a0c1be837ea7c670ffbf33a0ea Mon Sep 17 00:00:00 2001 From: John Coffey Date: Fri, 20 Nov 2026 12:04:17 -0700 Subject: [PATCH 1/5] WebDAV: uploaded files can't run as pages on the server's origin A file stored over WebDAV was served with whatever content type its uploader gave it, and with no Content-Disposition or sandbox policy. An HTML or SVG file opened in a browser ran as a page of the mail server's own origin, the one that serves the sign-in page and JMAP. Any account that can store a file could leave one for someone else to open. Every file answer (GET, HEAD, ranges, 416) now carries "Content-Security-Policy: default-src 'none'; frame-ancestors 'none'; sandbox" and nosniff, so a document has an opaque origin and no scripts. Only raster images, audio, video and plain text are offered for display; HTML, XHTML, SVG, XML, PDF and anything unknown download as attachments. WebDAV clients ignore both headers. Test: in the WebDAV suite, user_content stores HTML, XHTML, SVG, PDF, untyped, text and PNG files and checks both headers on GET, HEAD and a range request. On main the HTML file came back as text/html with neither header. Reported privately in a security review. --- crates/dav/src/file/get.rs | 100 +++++++++++++++++++++++++++++-- tests/src/webdav/mod.rs | 2 + tests/src/webdav/user_content.rs | 88 +++++++++++++++++++++++++++ 3 files changed, 185 insertions(+), 5 deletions(-) create mode 100644 tests/src/webdav/user_content.rs diff --git a/crates/dav/src/file/get.rs b/crates/dav/src/file/get.rs index 934aa49c..25034e52 100644 --- a/crates/dav/src/file/get.rs +++ b/crates/dav/src/file/get.rs @@ -2,6 +2,8 @@ * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC * * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL + * + * Modified by Coffey Labs in 2026 for INBUXA. */ use crate::{ @@ -127,6 +129,7 @@ impl FileGetRequestHandler for Server { Some(Some(range)) => Some(range.start as usize..range.end as usize), Some(None) => { return Ok(HttpResponse::new(StatusCode::RANGE_NOT_SATISFIABLE) + .with_header(hyper::header::CONTENT_SECURITY_POLICY, FILE_CSP) .with_accept_ranges() .with_etag(etag) .with_content_range(format!("bytes */{size}"))); @@ -134,11 +137,15 @@ impl FileGetRequestHandler for Server { None => None, }; - let response = HttpResponse::new(StatusCode::OK) - .with_content_type(content_type.unwrap_or("application/octet-stream")) - .with_etag(etag) - .with_last_modified(last_modified) - .with_accept_ranges(); + let content_type = content_type.unwrap_or("application/octet-stream"); + let response = user_content_policy( + HttpResponse::new(StatusCode::OK) + .with_content_type(content_type) + .with_etag(etag) + .with_last_modified(last_modified) + .with_accept_ranges(), + content_type, + ); if is_head { return Ok(response.with_content_length(size)); @@ -166,3 +173,86 @@ impl FileGetRequestHandler for Server { .with_binary_body(contents)) } } + +/// inbuxa: a stored file is whatever its uploader sent, under the type they +/// claimed, and it is served on the same origin as the sign-in page, JMAP and +/// the console's API. Opened in a browser, an uploaded HTML or SVG page would +/// run as this server. So every file answer carries a sandbox policy, which +/// gives the document an opaque origin and no scripts, and only types that +/// can't hold active content are offered for display; everything else is a +/// download. WebDAV clients ignore both headers. +/// `frame-ancestors` is here so the default HTML headers don't add a second +/// policy of their own (security_headers.rs). +const FILE_CSP: &str = "default-src 'none'; frame-ancestors 'none'; sandbox"; + +fn user_content_policy(response: HttpResponse, content_type: &str) -> HttpResponse { + let response = response + .with_header(hyper::header::X_CONTENT_TYPE_OPTIONS, "nosniff") + .with_header(hyper::header::CONTENT_SECURITY_POLICY, FILE_CSP); + if shown_inline(content_type) { + response + } else { + response.with_content_disposition("attachment") + } +} + +/// Types a browser shows without running anything: raster images, audio, +/// video and plain text. SVG, HTML, XML, PDF and anything unknown download. +fn shown_inline(content_type: &str) -> bool { + let essence = content_type + .split(';') + .next() + .unwrap_or_default() + .trim() + .to_ascii_lowercase(); + matches!( + essence.as_str(), + "image/png" + | "image/jpeg" + | "image/gif" + | "image/webp" + | "image/avif" + | "image/bmp" + | "text/plain" + ) || ((essence.starts_with("audio/") || essence.starts_with("video/")) + && !essence.contains("xml")) +} + +#[cfg(test)] +mod tests { + use super::shown_inline; + + #[test] + fn active_types_download() { + for ty in [ + "text/html", + "TEXT/HTML; charset=utf-8", + "application/xhtml+xml", + "image/svg+xml", + "text/xml", + "application/xml", + "application/pdf", + "text/javascript", + "application/octet-stream", + "", + "garbage", + " text/html ", + ] { + assert!(!shown_inline(ty), "{ty:?} must download"); + } + } + + #[test] + fn passive_types_show() { + for ty in [ + "image/png", + "image/jpeg", + "IMAGE/WEBP", + "text/plain; charset=utf-8", + "audio/mpeg", + "video/mp4", + ] { + assert!(shown_inline(ty), "{ty:?} should show inline"); + } + } +} diff --git a/tests/src/webdav/mod.rs b/tests/src/webdav/mod.rs index fcb04ce7..9569efef 100644 --- a/tests/src/webdav/mod.rs +++ b/tests/src/webdav/mod.rs @@ -44,6 +44,7 @@ pub mod principals; pub mod prop; pub mod put_get; pub mod sync; +pub mod user_content; // inbuxa: uploaded files never run on this origin #[tokio::test(flavor = "multi_thread")] pub async fn webdav_tests() { @@ -189,6 +190,7 @@ pub async fn webdav_tests() { basic::test(&test).await; put_get::test(&test).await; file_tasks::test(&test).await; + user_content::test(&test).await; mkcol::test(&test).await; copy_move::test(&test, assisted_discovery).await; prop::test(&test, assisted_discovery).await; diff --git a/tests/src/webdav/user_content.rs b/tests/src/webdav/user_content.rs new file mode 100644 index 00000000..c80b2974 --- /dev/null +++ b/tests/src/webdav/user_content.rs @@ -0,0 +1,88 @@ +/* + * SPDX-FileCopyrightText: 2026 Coffey Labs LLC + * + * SPDX-License-Identifier: AGPL-3.0-only + */ + +// inbuxa: a stored file is served on the server's own origin, so an uploaded +// page must never run there. Every file answer carries a sandbox policy, and +// anything that could hold active content downloads instead of displaying. + +use crate::utils::server::TestServer; +use hyper::StatusCode; + +const BASE: &str = "/dav/file/john%40example.com"; +const CSP: &str = "default-src 'none'; frame-ancestors 'none'; sandbox"; + +pub async fn test(test: &TestServer) { + println!("Running WebDAV user content tests..."); + let client = test.account("john@example.com").webdav_client(); + + for (name, content_type, body, download) in [ + ("page.html", "text/html", "", true), + ( + "page.xhtml", + "application/xhtml+xml; charset=utf-8", + "", + true, + ), + ( + "pic.svg", + "image/svg+xml", + "", + true, + ), + ("doc.pdf", "application/pdf", "%PDF-1.4", true), + ("none.bin", "", "x", true), + ("note.txt", "text/plain", "hello", false), + ("pic.png", "image/png", "png", false), + ] { + let path = format!("{BASE}/{name}"); + let headers: Vec<(&str, &str)> = if content_type.is_empty() { + vec![] + } else { + vec![("content-type", content_type)] + }; + client + .request_with_headers("PUT", &path, headers, body) + .await + .with_status(StatusCode::CREATED); + + for method in ["GET", "HEAD"] { + let response = client + .request(method, &path, "") + .await + .with_status(StatusCode::OK) + .with_header("content-security-policy", CSP) + .with_header("x-content-type-options", "nosniff"); + assert_eq!( + response + .headers + .get("content-disposition") + .map(String::as_str), + download.then_some("attachment"), + "{method} {name}" + ); + } + + // A range of the file is the same file + let response = client + .request_with_headers("GET", &path, [("range", "bytes=0-0")], "") + .await + .with_status(StatusCode::PARTIAL_CONTENT) + .with_header("content-security-policy", CSP); + assert_eq!( + response + .headers + .get("content-disposition") + .map(String::as_str), + download.then_some("attachment"), + "range {name}" + ); + + client + .request("DELETE", &path, "") + .await + .with_status(StatusCode::NO_CONTENT); + } +} -- 2.54.0 From b25283178047524b620ce4806ec6fe180ca66188 Mon Sep 17 00:00:00 2001 From: John Coffey Date: Fri, 20 Nov 2026 12:04:17 -0700 Subject: [PATCH 2/5] ACME: a tenant's provider reaches only public HTTPS addresses Tenant administrators can create ACME providers (sysAcmeProvider* is in the default tenant role), and creating one fetches its directory URL from the server, then follows the URLs the directory names. Nothing limited where those requests went, plain HTTP was allowed, and a non-2xx answer's body was returned in the JMAP error. A tenant administrator could make the server request an internal address and read part of the reply. For a provider with a memberTenantId, every ACME request must be HTTPS to a public address: IP literals are checked before sending, host names when they resolve (the resolver Web Push uses), and redirects aren't followed. The server's own providers are unchanged, so an internal ACME server still works there. For every provider, an error now carries only an RFC 7807 problem document's type and detail (bounded), never the raw body, and a parse error quotes at most 120 characters. Test: unit tests in acme::http refuse plain HTTP, private, link-local, loopback and mapped addresses, and a name resolving to loopback, before anything is sent; the tenant suite checks the same through x:AcmeProvider/set (with the DNS changes). Reported privately in a security review. --- crates/common/src/network/acme/account.rs | 10 +- crates/common/src/network/acme/directory.rs | 49 ++++- crates/common/src/network/acme/http.rs | 210 +++++++++++++++++++- crates/common/src/network/acme/mod.rs | 4 + 4 files changed, 253 insertions(+), 20 deletions(-) diff --git a/crates/common/src/network/acme/account.rs b/crates/common/src/network/acme/account.rs index 318ae9ba..daef040d 100644 --- a/crates/common/src/network/acme/account.rs +++ b/crates/common/src/network/acme/account.rs @@ -2,6 +2,8 @@ * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC * * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL + * + * Modified by Coffey Labs in 2026 for INBUXA. */ use super::jose::{Body, eab_sign, sign}; @@ -49,7 +51,12 @@ pub async fn acme_create_account( *contact = format!("mailto:{}", email); } - let directory = Directory::discover(&provider.directory, provider.max_retries as u32).await?; + let directory = Directory::discover( + &provider.directory, + provider.max_retries as u32, + provider.member_tenant_id.is_some(), + ) + .await?; let account_key = EcdsaKeyPair::generate_pkcs8(ALG, &SystemRandom::new()).unwrap(); let key_pair = EcdsaKeyPair::from_pkcs8(ALG, account_key.as_ref()) .map_err(|err| AcmeError::Crypto(format!("Failed to create ECDSA key pair: {}", err)))?; @@ -79,6 +86,7 @@ pub async fn acme_create_account( Method::POST, Some(body), provider.max_retries as u32, + directory.public_only, ) .await?, "Location", diff --git a/crates/common/src/network/acme/directory.rs b/crates/common/src/network/acme/directory.rs index 5f5d5bef..8c643688 100644 --- a/crates/common/src/network/acme/directory.rs +++ b/crates/common/src/network/acme/directory.rs @@ -2,6 +2,8 @@ * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC * * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL + * + * Modified by Coffey Labs in 2026 for INBUXA. */ // Adapted from rustls-acme (https://github.com/FlorianUekermann/rustls-acme), licensed under MIT/Apache-2.0. @@ -49,8 +51,12 @@ static ALG: &EcdsaSigningAlgorithm = &ECDSA_P256_SHA256_FIXED_SIGNING; impl AcmeRequestBuilder { pub async fn new(provider: AcmeProvider) -> AcmeResult { - let directory = - Directory::discover(&provider.directory, provider.max_retries as u32).await?; + let directory = Directory::discover( + &provider.directory, + provider.max_retries as u32, + provider.member_tenant_id.is_some(), + ) + .await?; let key_pair = EcdsaKeyPair::from_pkcs8( ALG, &URL_SAFE_NO_PAD @@ -83,7 +89,14 @@ impl AcmeRequestBuilder { url.as_ref(), payload, )?; - let response = https(url.as_ref(), Method::POST, Some(body), self.max_retries).await?; + let response = https( + url.as_ref(), + Method::POST, + Some(body), + self.max_retries, + self.directory.public_only, + ) + .await?; Ok(AcmeResponse { location: get_header(&response, "Location").ok(), @@ -188,19 +201,31 @@ impl AcmeRequestBuilder { } impl Directory { - pub async fn discover(url: impl AsRef, max_retries: u32) -> AcmeResult { - serde_json::from_str( - &https(url, Method::GET, None, max_retries) + pub async fn discover( + url: impl AsRef, + max_retries: u32, + public_only: bool, + ) -> AcmeResult { + let mut directory: Self = serde_json::from_str( + &https(url, Method::GET, None, max_retries, public_only) .await? .text() .await?, - ) - .map_err(Into::into) + )?; + directory.public_only = public_only; + Ok(directory) } pub async fn nonce(&self, max_retries: u32) -> AcmeResult { get_header( - &https(&self.new_nonce.as_str(), Method::HEAD, None, max_retries).await?, + &https( + &self.new_nonce.as_str(), + Method::HEAD, + None, + max_retries, + self.public_only, + ) + .await?, "replay-nonce", ) } @@ -210,9 +235,11 @@ impl AcmeResponse { pub fn parse(input: AcmeResponse) -> AcmeResult> { serde_json::from_str(&input.body) .map_err(|err| { + // inbuxa: a bounded excerpt, not the whole body (see http.rs) AcmeError::Invalid(format!( - "ACME response parsing error: {}, body: {}", - err, input.body + "ACME response parsing error: {}, body starts: {:?}", + err, + input.body.chars().take(120).collect::() )) }) .map(|body| AcmeResponse { diff --git a/crates/common/src/network/acme/http.rs b/crates/common/src/network/acme/http.rs index 9ed63db8..42e4a654 100644 --- a/crates/common/src/network/acme/http.rs +++ b/crates/common/src/network/acme/http.rs @@ -2,9 +2,15 @@ * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC * * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL + * + * Modified by Coffey Labs in 2026 for INBUXA. */ -use crate::network::acme::{AcmeError, AcmeResult}; +use crate::network::{ + acme::{AcmeError, AcmeResult}, + is_global_ip, + public_only::PublicOnly, +}; use chrono::{DateTime, Utc}; use hyper::{ Method, StatusCode, @@ -14,13 +20,26 @@ use reqwest::Response; use std::time::Duration; #[allow(unused_mut)] +/// +/// inbuxa: `public_only` is set for a tenant's own ACME provider. Its +/// administrator picks the directory URL and the directory names every URL +/// after it, so each request must be HTTPS to a public address, checked when +/// the name resolves, with no redirects (a redirect to an IP literal would +/// skip that check). pub(crate) async fn https( url: impl AsRef, method: Method, body: Option, max_retries: u32, + public_only: bool, ) -> AcmeResult { let url = url.as_ref(); + if public_only && !(starts_with_ignore_case(url, "https://") && has_public_ip_or_name(url)) { + return Err(AcmeError::Invalid(format!( + "A tenant's ACME provider must use a public HTTPS address: {}", + redact_url(url) + ))); + } #[allow(unused_mut)] #[allow(unused_assignments)] @@ -32,8 +51,14 @@ pub(crate) async fn https( url.starts_with("https://localhost") || url.starts_with("https://127.0.0.1"); } - let mut request = utils::http::http1_client_builder(allow_invalid_certs) - .timeout(Duration::from_secs(30)) + let mut client = + utils::http::http1_client_builder(allow_invalid_certs).timeout(Duration::from_secs(30)); + if public_only { + client = client + .public_only() + .redirect(reqwest::redirect::Policy::none()); + } + let mut request = client .build()? .request(method, url) .header(USER_AGENT, crate::USER_AGENT); @@ -62,12 +87,24 @@ pub(crate) async fn https( Err(AcmeError::Backoff { wait, max_retries }) } else { + // inbuxa: this message reaches the JMAP caller. Only an ACME problem + // document's own type and detail go into it, never the raw body of + // whatever answered. let status = response.status(); - let text = response.text().await.unwrap_or_default(); - Err(AcmeError::HttpStatus(format!( - "Unexpected status {}: {}", - status, text - ))) + let problem = if is_problem_document(&response) { + response + .json::() + .await + .map(|problem| problem.summary()) + .unwrap_or_default() + } else { + String::new() + }; + Err(AcmeError::HttpStatus(if problem.is_empty() { + format!("Unexpected status {status}") + } else { + format!("Unexpected status {status}: {problem}") + })) } } @@ -198,3 +235,160 @@ mod tests { assert!(links.is_empty()); } } + +/// inbuxa: the parts of an RFC 7807 problem document an ACME server explains +/// itself with (RFC 8555 section 6.7). +#[derive(serde::Deserialize)] +struct Problem { + #[serde(rename = "type", default)] + kind: String, + #[serde(default)] + detail: String, +} + +/// The longest detail passed on, in characters. +const MAX_PROBLEM_DETAIL: usize = 300; + +impl Problem { + fn summary(&self) -> String { + let detail: String = self + .detail + .chars() + .filter(|c| !c.is_control()) + .take(MAX_PROBLEM_DETAIL) + .collect(); + let kind: String = self + .kind + .chars() + .filter(|c| c.is_ascii_graphic()) + .take(100) + .collect(); + match (kind.is_empty(), detail.is_empty()) { + (false, false) => format!("{kind}: {detail}"), + (false, true) => kind, + (true, false) => detail, + (true, true) => String::new(), + } + } +} + +fn is_problem_document(response: &Response) -> bool { + response + .headers() + .get(CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .is_some_and(|value| { + value + .split(';') + .next() + .unwrap_or_default() + .trim() + .eq_ignore_ascii_case("application/problem+json") + }) +} + +/// The URL's host is a name (checked when it resolves) or a public IP +/// literal. Unlike `public_only::has_public_host`, test builds get no +/// loopback exception: no test reaches a tenant's ACME server. +fn has_public_ip_or_name(url: &str) -> bool { + let Some(host) = reqwest::Url::parse(url) + .ok() + .and_then(|url| url.host_str().map(str::to_string)) + else { + return false; + }; + let host = host + .strip_prefix('[') + .and_then(|host| host.strip_suffix(']')) + .unwrap_or(&host); + match host.parse::() { + Ok(ip) => is_global_ip(&ip), + Err(_) => true, + } +} + +fn starts_with_ignore_case(value: &str, prefix: &str) -> bool { + value + .get(..prefix.len()) + .is_some_and(|start| start.eq_ignore_ascii_case(prefix)) +} + +/// The URL without its query or any credentials, for an error message. +fn redact_url(url: &str) -> String { + match reqwest::Url::parse(url) { + Ok(mut url) => { + let _ = url.set_username(""); + let _ = url.set_password(None); + url.set_query(None); + url.set_fragment(None); + url.to_string() + } + Err(_) => "(not a URL)".to_string(), + } +} + +#[cfg(test)] +mod tenant_tests { + use super::*; + + fn outcome(result: &AcmeResult) -> String { + match result { + Ok(response) => format!("status {}", response.status()), + Err(err) => err.to_string(), + } + } + + #[tokio::test] + async fn tenant_destinations_are_checked_before_sending() { + for url in [ + "http://acme.example.com/dir", + "ftp://acme.example.com/dir", + "https://10.0.0.1/dir", + "https://169.254.169.254/latest/meta-data/", + "https://[fd00::1]/dir", + "https://[::ffff:192.168.1.1]/dir", + "https://127.0.0.1/dir", + "https://[::1]/dir", + "not a url", + ] { + let result = https(url, Method::GET, None, 0, true).await; + match &result { + Err(AcmeError::Invalid(message)) => { + assert!(message.contains("public HTTPS"), "{url}: {message}") + } + _ => panic!("{url}: expected a refusal, got {}", outcome(&result)), + } + } + } + + #[tokio::test] + async fn tenant_host_names_must_resolve_to_public_addresses() { + // localhost resolves to loopback: refused when it resolves, before + // anything is sent. + let result = https("https://localhost:9/dir", Method::GET, None, 0, true).await; + match &result { + Err(AcmeError::Http(err)) => assert!(err.is_connect() || err.is_request(), "{err}"), + _ => panic!("expected a resolver refusal, got {}", outcome(&result)), + } + } + + #[test] + fn problem_summary_is_bounded() { + let problem = Problem { + kind: "urn:ietf:params:acme:error:malformed".to_string(), + detail: format!("bad\nthing {}", "x".repeat(1000)), + }; + let summary = problem.summary(); + assert!(summary.starts_with("urn:ietf:params:acme:error:malformed: bad")); + assert!(!summary.contains('\n')); + assert!(summary.len() < 450, "{}", summary.len()); + } + + #[test] + fn redacted_urls_drop_credentials_and_query() { + assert_eq!( + redact_url("https://user:pw@acme.example.com/dir?token=1#x"), + "https://acme.example.com/dir" + ); + } +} diff --git a/crates/common/src/network/acme/mod.rs b/crates/common/src/network/acme/mod.rs index dd677a80..8f1b262a 100644 --- a/crates/common/src/network/acme/mod.rs +++ b/crates/common/src/network/acme/mod.rs @@ -83,6 +83,10 @@ pub struct Directory { pub new_nonce: String, pub new_account: String, pub new_order: String, + /// inbuxa: a tenant's provider, so every request goes only to public + /// HTTPS addresses (see `http::https`). + #[serde(skip)] + pub public_only: bool, } #[derive(Debug, Deserialize, Eq, PartialEq, Clone, Copy)] -- 2.54.0 From d422f67629a1b141d03c6cea94eaee9951b602b4 Mon Sep 17 00:00:00 2001 From: John Coffey Date: Fri, 20 Nov 2026 12:04:17 -0700 Subject: [PATCH 3/5] DNS: a tenant's DNS provider reaches only public addresses Tenant administrators can create DNS providers (sysDnsServer* is in the default tenant role). Several take an endpoint (cPanel, Plesk, PowerDNS, BlueCat, Infoblox, EdgeDNS, UltraDNS, Volcengine) and RFC 2136 takes a server address, so DNS updates could be aimed at loopback or a private service. Others build their URL from a region, zone id or domain, where a value such as "x@10.0.0.1/" moves the host. For a provider with a memberTenantId, checked each time it's saved and each time an updater is built from it: endpoints must be HTTPS to names that resolve only to public addresses, an RFC 2136 server must have a public address, and names that go into URLs may only hold letters, digits, '-', '_' and '.'. The server's own providers keep any destination; private DNS servers are a normal setup there. Test: unit tests in dns::tenant_endpoints; the tenant suite refuses tenant ACME and DNS providers aimed at private addresses or with a host-moving region, and still creates the server's own RFC 2136 provider on a private address. Reported privately in a security review. --- crates/common/src/network/dns/mod.rs | 3 + .../src/network/dns/tenant_endpoints.rs | 246 ++++++++++++++++++ crates/common/src/network/dns/update.rs | 2 + tests/src/system/tenant.rs | 112 ++++++++ 4 files changed, 363 insertions(+) create mode 100644 crates/common/src/network/dns/tenant_endpoints.rs diff --git a/crates/common/src/network/dns/mod.rs b/crates/common/src/network/dns/mod.rs index d2670fe0..f3d44bf5 100644 --- a/crates/common/src/network/dns/mod.rs +++ b/crates/common/src/network/dns/mod.rs @@ -2,8 +2,11 @@ * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC * * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL + * + * Modified by Coffey Labs in 2026 for INBUXA. */ pub mod records; pub mod resolve; +pub mod tenant_endpoints; // inbuxa: a tenant's DNS provider stays on public addresses pub mod update; diff --git a/crates/common/src/network/dns/tenant_endpoints.rs b/crates/common/src/network/dns/tenant_endpoints.rs new file mode 100644 index 00000000..4ed99d16 --- /dev/null +++ b/crates/common/src/network/dns/tenant_endpoints.rs @@ -0,0 +1,246 @@ +/* + * SPDX-FileCopyrightText: 2026 Coffey Labs LLC + * + * SPDX-License-Identifier: AGPL-3.0-only + */ + +//! A tenant's own DNS provider may only talk to public addresses. +//! +//! Some providers take an endpoint (cPanel, Plesk, PowerDNS, Infoblox, ...) +//! and RFC 2136 takes a server address, so a tenant administrator could aim +//! the server's DNS updates at a loopback or private service and read +//! something back in the error. Others build their URL from a region or zone +//! name, where a crafted value (`x@10.0.0.1/`) could move the host. For a +//! provider owned by a tenant, endpoints must be HTTPS to names that resolve +//! only to public addresses, an RFC 2136 server must be a public address, and +//! names that go into URLs must be plain names. The server's own providers, +//! which only a server administrator can create, keep any destination: +//! private DNS servers are a normal setup there. +//! +//! This runs each time a provider is saved and each time an updater is built +//! from it, so a name that later moves to a private address is caught at the +//! next use. + +use super::super::is_global_ip; +use registry::schema::{prelude::ObjectInner, structs::DnsServer}; +use reqwest::Url; +use std::net::IpAddr; + +/// The endpoint and URL-name fields of a tenant's provider, or `Ok(())` for +/// a provider the server owns. +pub async fn check_tenant_dns_server(server: &DnsServer) -> Result<(), String> { + if ObjectInner::DnsServer(server.clone()) + .member_tenant_id() + .is_none() + { + return Ok(()); + } + let fields = TenantFields::of(server); + if fields.plain_http { + return Err("A tenant's DNS provider must use HTTPS (scheme)".to_string()); + } + + for (field, name) in fields.names { + if !is_plain_name(name) { + return Err(format!( + "{field} may only contain letters, digits, '-', '_' and '.'" + )); + } + } + if let Some(ip) = fields.rfc2136 { + if !is_global_ip(&ip) { + return Err(format!( + "A tenant's DNS server must have a public address, not {ip}" + )); + } + } + for (field, endpoint) in fields.endpoints { + check_endpoint(field, endpoint).await?; + } + Ok(()) +} + +#[derive(Default)] +struct TenantFields<'x> { + endpoints: Vec<(&'static str, &'x str)>, + names: Vec<(&'static str, &'x str)>, + rfc2136: Option, + plain_http: bool, +} + +impl<'x> TenantFields<'x> { + fn of(server: &'x DnsServer) -> Self { + let mut fields = TenantFields::default(); + match server { + DnsServer::Tsig(server) => fields.rfc2136 = Some(server.host.0), + DnsServer::BluecatV2(server) => fields.endpoints.push(("baseUrl", &server.base_url)), + DnsServer::Cpanel(server) => fields.endpoints.push(("baseUrl", &server.base_url)), + DnsServer::Plesk(server) => fields.endpoints.push(("baseUrl", &server.base_url)), + DnsServer::EdgeDns(server) => fields.endpoints.push(("host", &server.host)), + DnsServer::Infoblox(server) => fields.endpoints.push(("host", &server.host)), + DnsServer::PowerDns(server) => { + fields + .endpoints + .extend(server.endpoint.as_deref().map(|e| ("endpoint", e))); + fields + .names + .extend(server.server_id.as_deref().map(|e| ("serverId", e))); + } + DnsServer::UltraDns(server) => { + fields + .endpoints + .extend(server.endpoint.as_deref().map(|e| ("endpoint", e))); + } + DnsServer::Volcengine(server) => { + if let Some(host) = server.host.as_deref() { + fields.endpoints.push(("host", host)); + } + fields + .names + .extend(server.region.as_deref().map(|e| ("region", e))); + if server + .scheme + .as_deref() + .is_some_and(|scheme| !scheme.eq_ignore_ascii_case("https")) + { + fields.plain_http = true; + } + } + DnsServer::Route53(server) => { + fields.names.push(("region", &server.region)); + fields.names.extend( + server + .hosted_zone_id + .as_deref() + .map(|e| ("hostedZoneId", e)), + ); + } + DnsServer::Lightsail(server) => { + fields + .names + .extend(server.region.as_deref().map(|e| ("region", e))); + fields + .names + .extend(server.domain.as_deref().map(|e| ("domain", e))); + } + DnsServer::Alidns(server) => { + fields + .names + .extend(server.region.as_deref().map(|e| ("region", e))); + } + DnsServer::TencentCloud(server) => { + fields + .names + .extend(server.region.as_deref().map(|e| ("region", e))); + } + DnsServer::HuaweiCloud(server) => fields.names.push(("region", &server.region)), + DnsServer::OracleCloud(server) => fields.names.push(("region", &server.region)), + _ => {} + } + fields + } +} + +/// A value that can sit inside a host name or a path segment and not move +/// the host: no '@', ':', '/', '?', '#', '%' or spaces. +fn is_plain_name(value: &str) -> bool { + !value.is_empty() + && value.len() <= 253 + && value + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.')) +} + +/// An endpoint, given as a URL or a bare `host[:port]` (which providers +/// reach over HTTPS), must be HTTPS to a name whose every address is public. +async fn check_endpoint(field: &str, endpoint: &str) -> Result<(), String> { + let endpoint = endpoint.trim(); + let url = if endpoint.contains("://") { + Url::parse(endpoint) + } else { + Url::parse(&format!("https://{endpoint}")) + } + .map_err(|_| format!("{field} is not a valid address"))?; + + if url.scheme() != "https" { + return Err(format!("A tenant's DNS provider must use HTTPS ({field})")); + } + if !url.username().is_empty() || url.password().is_some() { + return Err(format!("{field} may not contain credentials")); + } + let host = url + .host_str() + .ok_or_else(|| format!("{field} has no host"))? + .trim_start_matches('[') + .trim_end_matches(']') + .to_string(); + + if let Ok(ip) = host.parse::() { + return if is_global_ip(&ip) { + Ok(()) + } else { + Err(format!( + "A tenant's DNS provider must use a public address ({field})" + )) + }; + } + + let addrs = + tokio::net::lookup_host((host.as_str(), url.port_or_known_default().unwrap_or(443))) + .await + .map_err(|_| format!("{field}: {host} does not resolve"))? + .collect::>(); + if addrs.is_empty() || addrs.iter().any(|addr| !is_global_ip(&addr.ip())) { + return Err(format!( + "A tenant's DNS provider must use a public address ({field}: {host})" + )); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn plain_names() { + for ok in [ + "eu-west-1", + "cn-hangzhou", + "Z123ABC", + "example.com", + "localhost_1", + ] { + assert!(is_plain_name(ok), "{ok}"); + } + for bad in ["", "x@10.0.0.1/", "a/b", "a:1", "a?b", "a#b", "a%2f", "a b"] { + assert!(!is_plain_name(bad), "{bad}"); + } + } + + #[tokio::test] + async fn endpoints() { + for bad in [ + "http://dns.example.com/api", + "https://127.0.0.1/api", + "https://10.1.2.3:2083", + "10.1.2.3:2083", + "https://[::1]/", + "https://[fd00::1]/", + "https://169.254.169.254/", + "https://user:pw@8.8.8.8/", + "https://localhost/", + "localhost:8081", + "ftp://8.8.8.8/", + ] { + assert!(check_endpoint("endpoint", bad).await.is_err(), "{bad}"); + } + for ok in [ + "https://8.8.8.8/api", + "8.8.8.8:2083", + "https://[2606:4700::1111]/", + ] { + assert!(check_endpoint("endpoint", ok).await.is_ok(), "{ok}"); + } + } +} diff --git a/crates/common/src/network/dns/update.rs b/crates/common/src/network/dns/update.rs index 2ada2d15..4b10d5fb 100644 --- a/crates/common/src/network/dns/update.rs +++ b/crates/common/src/network/dns/update.rs @@ -104,6 +104,8 @@ pub static DNS_RECORDS: std::sync::LazyLock< impl DnsUpdater { pub async fn build(server: DnsServer, core: Arc) -> Result { + // inbuxa: a tenant's provider only reaches public addresses (F3) + super::tenant_endpoints::check_tenant_dns_server(&server).await?; match server { DnsServer::Tsig(server) => Ok(DnsUpdater { polling_interval: server.polling_interval.into_inner(), diff --git a/tests/src/system/tenant.rs b/tests/src/system/tenant.rs index 0412eea2..0e7a512c 100644 --- a/tests/src/system/tenant.rs +++ b/tests/src/system/tenant.rs @@ -1297,6 +1297,8 @@ pub async fn test(test: &mut TestServer) { .assert_destroyed(&[domain]); } } + tenant_outbound_requests(&admin, t_id).await; + for tenant in [t_id, u_id, p_id, q_id, d_id] { admin .registry_destroy(ObjectType::Tenant, [tenant]) @@ -1306,6 +1308,116 @@ pub async fn test(test: &mut TestServer) { let _ = u_domain; } +/// A tenant's own ACME and DNS providers only reach public HTTPS addresses, +/// and names that go into a provider's URL can't move its host (security +/// batch 11, F2 and F3). The server's own providers keep any destination. +async fn tenant_outbound_requests(admin: &Account, tenant: Id) { + use registry::schema::{ + enums::{IpProtocol, TsigAlgorithm}, + structs::{ + AcmeProvider, DnsServer, DnsServerRoute53, DnsServerTsig, SecretKey, SecretKeyValue, + }, + }; + use registry::types::duration::Duration; + + // ACME: an internal or plain-HTTP directory is refused before any request + for directory in [ + "https://10.0.0.1/dir", + "https://169.254.169.254/latest/meta-data/", + "http://acme.example.org/dir", + "https://[::1]/dir", + ] { + admin + .registry_create_object_expect_err(AcmeProvider { + directory: directory.to_string(), + contact: Map::new(vec!["mailto:ops@t.example.org".to_string()]), + member_tenant_id: Some(tenant), + ..Default::default() + }) + .await + .assert_type(SetErrorType::InvalidProperties) + .assert_description_contains("public HTTPS"); + } + // ... and a host name that resolves to loopback is refused when it resolves + let err = admin + .registry_create_object_expect_err(AcmeProvider { + directory: "https://localhost:1/dir".to_string(), + contact: Map::new(vec!["mailto:ops@t.example.org".to_string()]), + member_tenant_id: Some(tenant), + ..Default::default() + }) + .await; + err.assert_type(SetErrorType::InvalidProperties); + // The server's own provider isn't held to it: it fails only on the + // connection, and the refused body isn't reflected either way + let err = admin + .registry_create_object_expect_err(AcmeProvider { + directory: "https://127.0.0.1:1/dir".to_string(), + contact: Map::new(vec!["mailto:ops@example.org".to_string()]), + ..Default::default() + }) + .await; + err.assert_type(SetErrorType::InvalidProperties); + assert!( + !err.description + .as_deref() + .unwrap_or_default() + .contains("public HTTPS"), + "server-owned ACME provider: {err:?}" + ); + + // DNS: RFC 2136 to a private address, and a region that moves the host + let tsig = |host: &str, member_tenant_id: Option| { + DnsServer::Tsig(DnsServerTsig { + host: host.parse().unwrap(), + port: 53, + key_name: "update-key".to_string(), + key: SecretKey::Value(SecretKeyValue { + secret: "c2VjcmV0".into(), + }), + protocol: IpProtocol::Udp, + tsig_algorithm: TsigAlgorithm::HmacSha256, + description: "tenant outbound test".to_string(), + member_tenant_id, + timeout: Duration::from_millis(1_000), + ttl: Duration::from_millis(60_000), + polling_interval: Duration::from_millis(100), + propagation_timeout: Duration::from_millis(1_000), + propagation_delay: None, + }) + }; + for host in ["10.0.0.53", "127.0.0.1", "fd00::53"] { + admin + .registry_create_object_expect_err(tsig(host, Some(tenant))) + .await + .assert_type(SetErrorType::InvalidProperties) + .assert_description_contains("public address"); + } + let route53 = |region: &str| { + DnsServer::Route53(DnsServerRoute53 { + access_key_id: "AKIDEXAMPLE".to_string(), + secret_access_key: SecretKey::Value(SecretKeyValue { + secret: "secret".into(), + }), + region: region.to_string(), + description: "tenant outbound test".to_string(), + member_tenant_id: Some(tenant), + ..Default::default() + }) + }; + admin + .registry_create_object_expect_err(route53("x@10.0.0.1/")) + .await + .assert_type(SetErrorType::InvalidProperties) + .assert_description_contains("region may only contain"); + // A private DNS server is a normal setup for the server's own provider + let server_owned = admin.registry_create_object(tsig("10.0.0.53", None)).await; + admin + .registry_destroy(ObjectType::DnsServer, [server_owned]) + .await + .assert_destroyed(&[server_owned]); +} + /// Acceptance test 15 (compat): INBUXA's existing tenants, their members and /// quotas read back unchanged, and each tenant admin sees what it saw before. /// -- 2.54.0 From a579b6d04e3b9d9fd87078a6cc46eaa85f1cb5db Mon Sep 17 00:00:00 2001 From: John Coffey Date: Fri, 20 Nov 2026 12:04:17 -0700 Subject: [PATCH 4/5] OIDC directories: a tenant's reaches only public HTTPS addresses An OpenID Connect directory fetches discovery, JWKS, user info and introspection from the server. A directory a tenant manages (only when a server administrator delegates sysDirectory*, which tenants don't have by default) could point those at internal addresses. For a directory with a memberTenantId, the issuer, introspection, jwks_uri and userinfo URLs must be HTTPS and not a private IP literal, host names are checked when they resolve, and redirects aren't followed. Server-owned directories are unchanged. Test builds let a tenant's directory use loopback, as push and reports do, because the harness runs Keycloak on localhost. is_global_ip and the public-only resolver move from common to utils, unchanged, so the directory crate (below common) can use them; common re-exports both. Test: oidc::config::tenant_url_tests. Reported privately in a security review. --- crates/common/src/network/mod.rs | 79 +------------ crates/common/src/network/public_only.rs | 26 +--- crates/directory/src/backend/oidc/config.rs | 99 +++++++++++++++- crates/directory/src/backend/oidc/lookup.rs | 1 + crates/directory/src/backend/oidc/mod.rs | 3 + crates/utils/src/lib.rs | 1 + crates/utils/src/public_ip.rs | 124 ++++++++++++++++++++ 7 files changed, 231 insertions(+), 102 deletions(-) create mode 100644 crates/utils/src/public_ip.rs diff --git a/crates/common/src/network/mod.rs b/crates/common/src/network/mod.rs index 2b70c3ea..0e56ab69 100644 --- a/crates/common/src/network/mod.rs +++ b/crates/common/src/network/mod.rs @@ -19,7 +19,7 @@ use std::fmt::Debug; use std::{ borrow::Cow, io, - net::{IpAddr, Ipv4Addr, Ipv6Addr}, + net::IpAddr, sync::Arc, time::{Duration, Instant}, }; @@ -303,81 +303,8 @@ impl Debug for TcpAcceptor { } } -pub fn is_global_ip(ip: &IpAddr) -> bool { - match ip { - IpAddr::V4(ip) => is_global_ipv4(ip), - IpAddr::V6(ip) => is_global_ipv6(ip), - } -} - -fn is_global_ipv4(ip: &Ipv4Addr) -> bool { - let [a, b, c, _] = ip.octets(); - let is_this_network = a == 0; - let is_shared = a == 100 && (64..128).contains(&b); - let is_protocol_assignment = a == 192 && b == 0 && c == 0; - let is_benchmarking = a == 198 && (b & 0xfe) == 18; - let is_relay_6to4 = a == 192 && b == 88 && c == 99; - let is_reserved = a >= 240; - - !(ip.is_unspecified() - || ip.is_loopback() - || ip.is_private() - || ip.is_link_local() - || ip.is_multicast() - || ip.is_broadcast() - || ip.is_documentation() - || is_this_network - || is_shared - || is_protocol_assignment - || is_benchmarking - || is_relay_6to4 - || is_reserved) -} - -fn is_global_ipv6(ip: &Ipv6Addr) -> bool { - if ip.is_unspecified() || ip.is_loopback() || ip.is_multicast() { - return false; - } - - if let Some(ip) = ip.to_ipv4() { - return is_global_ipv4(&ip); - } - - let segments = ip.segments(); - - if segments[0] == 0x2002 { - return is_global_ipv4(&Ipv4Addr::from( - ((segments[1] as u32) << 16) | segments[2] as u32, - )); - } - - if segments[0] == 0x0064 && segments[1] == 0xff9b { - let is_well_known_prefix = - segments[2] == 0 && segments[3] == 0 && segments[4] == 0 && segments[5] == 0; - - return is_well_known_prefix - && is_global_ipv4(&Ipv4Addr::from( - ((segments[6] as u32) << 16) | segments[7] as u32, - )); - } - - let is_unique_local = (segments[0] & 0xfe00) == 0xfc00; - let is_link_local = (segments[0] & 0xffc0) == 0xfe80; - let is_site_local = (segments[0] & 0xffc0) == 0xfec0; - let is_discard_only = - segments[0] == 0x0100 && segments[1] == 0 && segments[2] == 0 && segments[3] == 0; - let is_documentation = segments[0] == 0x2001 && segments[1] == 0x0db8; - let is_teredo = segments[0] == 0x2001 && segments[1] == 0; - let is_orchid = segments[0] == 0x2001 && (segments[1] & 0xfff0) == 0x0020; - - !(is_unique_local - || is_link_local - || is_site_local - || is_discard_only - || is_documentation - || is_teredo - || is_orchid) -} +// inbuxa: moved to utils so crates below common can use it +pub use utils::public_ip::is_global_ip; pub fn ip_to_bytes(ip: &IpAddr) -> Vec { match ip { diff --git a/crates/common/src/network/public_only.rs b/crates/common/src/network/public_only.rs index 567be0a7..7335c5be 100644 --- a/crates/common/src/network/public_only.rs +++ b/crates/common/src/network/public_only.rs @@ -13,10 +13,7 @@ //! [`has_public_host`] before sending. use super::is_global_ip; -use reqwest::{ - ClientBuilder, Url, - dns::{Addrs, Name, Resolve, Resolving}, -}; +use reqwest::{ClientBuilder, Url}; use std::net::IpAddr; pub trait PublicOnly { @@ -27,26 +24,7 @@ pub trait PublicOnly { impl PublicOnly for ClientBuilder { fn public_only(self) -> Self { - self.no_proxy().dns_resolver(PublicResolver) - } -} - -struct PublicResolver; - -impl Resolve for PublicResolver { - fn resolve(&self, name: Name) -> Resolving { - Box::pin(async move { - let addrs = tokio::net::lookup_host((name.as_str(), 0)) - .await? - .filter(|addr| is_global_ip(&addr.ip())) - .collect::>(); - - if !addrs.is_empty() { - Ok(Box::new(addrs.into_iter()) as Addrs) - } else { - Err(format!("{} has no public address", name.as_str()).into()) - } - }) + utils::public_ip::public_only(self) } } diff --git a/crates/directory/src/backend/oidc/config.rs b/crates/directory/src/backend/oidc/config.rs index 3d6cd1e4..8bfe7aae 100644 --- a/crates/directory/src/backend/oidc/config.rs +++ b/crates/directory/src/backend/oidc/config.rs @@ -75,6 +75,7 @@ impl OpenIdDirectory { }; Self::new(OidcConfig { + public_only: config.member_tenant_id.is_some(), issue_url: config.issuer_url, require_aud: config.require_audience, require_scopes: config.require_scopes.into_inner(), @@ -90,9 +91,21 @@ impl OpenIdDirectory { } pub async fn new(mut config: OidcConfig) -> Result { - let http = utils::http::http_client_builder(false) + let mut http = utils::http::http_client_builder(false) .user_agent("inbuxa/1.0") // types::brand!(); this crate does not depend on types - .timeout(Duration::from_secs(30)) + .timeout(Duration::from_secs(30)); + // inbuxa: a tenant's directory reaches only public addresses, with no + // redirects (a redirect to an IP literal would skip the resolver) + if config.public_only && !is_test_loopback(&config.issue_url) { + check_tenant_url("issuerUrl", &config.issue_url)?; + if let OpaqueTokens::Introspection(Introspection { url: Some(url), .. }) = + &config.opaque_tokens + { + check_tenant_url("introspectionUrl", url)?; + } + http = utils::public_ip::public_only(http).redirect(reqwest::redirect::Policy::none()); + } + let http = http .build() .map_err(|e| OidcError::Network(format!("HTTP client build failed: {e}")))?; @@ -115,6 +128,16 @@ impl OpenIdDirectory { } }; + // inbuxa: the provider names the rest of its URLs; a tenant's must be + // public too + if config.public_only && !is_test_loopback(&config.issue_url) { + check_tenant_url("jwks_uri", &document.jwks_uri)?; + check_tenant_url("userinfo_endpoint", &document.userinfo_endpoint)?; + if let Some(url) = &document.introspection_endpoint { + check_tenant_url("introspection_endpoint", url)?; + } + } + // inbuxa: http-directory-services-13 if let OpaqueTokens::Introspection(introspection) = &mut config.opaque_tokens && introspection.url.is_none() @@ -242,6 +265,51 @@ impl OpenIdDirectory { } } +/// The test harness runs its identity provider (Keycloak) on localhost, as +/// it serves push and reports on 127.0.0.1 (`common::network::public_only`). +/// Never true outside test builds. +fn is_test_loopback(_url: &str) -> bool { + #[cfg(feature = "test_mode")] + { + if let Some(host) = reqwest::Url::parse(_url) + .ok() + .and_then(|url| url.host_str().map(str::to_string)) + { + return host == "localhost" + || host + .trim_start_matches('[') + .trim_end_matches(']') + .parse::() + .is_ok_and(|ip| ip.is_loopback()); + } + } + false +} + +/// inbuxa: a URL a tenant's directory may use: HTTPS, and not an IP literal +/// outside the public range. Host names are checked when they resolve +/// (`utils::public_ip::public_only`). +pub(crate) fn check_tenant_url(field: &str, url: &str) -> Result<(), OidcError> { + let refused = || { + OidcError::Config(format!( + "A tenant's directory must use public HTTPS addresses ({field})" + )) + }; + let parsed = reqwest::Url::parse(url).map_err(|_| refused())?; + if parsed.scheme() != "https" { + return Err(refused()); + } + let host = parsed.host_str().ok_or_else(refused)?; + let host = host + .strip_prefix('[') + .and_then(|host| host.strip_suffix(']')) + .unwrap_or(host); + match host.parse::() { + Ok(ip) if !utils::public_ip::is_global_ip(&ip) => Err(refused()), + _ => Ok(()), + } +} + #[cfg(test)] mod tests { use super::*; @@ -273,3 +341,30 @@ mod tests { } } } + +#[cfg(test)] +mod tenant_url_tests { + use super::check_tenant_url; + + #[test] + fn tenant_directory_urls() { + for bad in [ + "http://idp.example.org", + "https://127.0.0.1/realms/x", + "https://10.0.0.5:8443/", + "https://[::1]/", + "https://[fd12::1]/", + "https://169.254.169.254/", + "not a url", + ] { + assert!(check_tenant_url("issuerUrl", bad).is_err(), "{bad}"); + } + for ok in [ + "https://idp.example.org/realms/x", + "https://8.8.8.8/", + "https://[2606:4700::1111]/", + ] { + assert!(check_tenant_url("issuerUrl", ok).is_ok(), "{ok}"); + } + } +} diff --git a/crates/directory/src/backend/oidc/lookup.rs b/crates/directory/src/backend/oidc/lookup.rs index 2899de66..66bcb83b 100644 --- a/crates/directory/src/backend/oidc/lookup.rs +++ b/crates/directory/src/backend/oidc/lookup.rs @@ -727,6 +727,7 @@ MCowBQYDK2VwAyEAXNXjqSjw780GFXxFztdFBUMpxRoFqsYWN55FXnvncCE= claim_groups: None, default_domain: None, opaque_tokens, + public_only: false, }, discovery: crate::backend::oidc::OidcDiscovery { url: "https://idp.example.org".to_string(), diff --git a/crates/directory/src/backend/oidc/mod.rs b/crates/directory/src/backend/oidc/mod.rs index 03338c54..d0567d50 100644 --- a/crates/directory/src/backend/oidc/mod.rs +++ b/crates/directory/src/backend/oidc/mod.rs @@ -25,6 +25,9 @@ pub struct OidcConfig { pub claim_groups: Option, pub default_domain: Option, pub opaque_tokens: OpaqueTokens, + /// inbuxa: a tenant's own directory, which may only reach public HTTPS + /// addresses (see `config::check_tenant_url`). + pub public_only: bool, } /// inbuxa: http-directory-services-13: what a bearer token that isn't a diff --git a/crates/utils/src/lib.rs b/crates/utils/src/lib.rs index 6ad12a86..b1c5de69 100644 --- a/crates/utils/src/lib.rs +++ b/crates/utils/src/lib.rs @@ -17,6 +17,7 @@ pub mod cron; pub mod glob; pub mod http; pub mod map; +pub mod public_ip; // inbuxa pub mod snowflake; pub mod template; pub mod tls; diff --git a/crates/utils/src/public_ip.rs b/crates/utils/src/public_ip.rs new file mode 100644 index 00000000..1f556edf --- /dev/null +++ b/crates/utils/src/public_ip.rs @@ -0,0 +1,124 @@ +/* + * SPDX-FileCopyrightText: 2026 Coffey Labs LLC + * + * SPDX-License-Identifier: AGPL-3.0-only + */ + +//! Public addresses, and an HTTP client that connects only to them. +//! +//! Requests to URLs that someone other than the server administrator chose +//! (a push endpoint, a report address, a tenant's provider) must not reach +//! inside the network. A host name is checked when it resolves, so a redirect +//! or a later re-resolution can't get round it. IP literals don't resolve: +//! callers check those with [`is_global_ip`] before sending. +//! +//! Moved here from `common::network` (is_global_ip) and +//! `common::network::public_only` (the resolver) so the directory crate, +//! which `common` depends on, can use them too. + +use reqwest::{ + ClientBuilder, + dns::{Addrs, Name, Resolve, Resolving}, +}; +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; + +/// Connect only to public addresses, and never through a proxy (which would +/// resolve the name itself, out of our sight). +pub fn public_only(builder: ClientBuilder) -> ClientBuilder { + builder.no_proxy().dns_resolver(PublicResolver) +} + +struct PublicResolver; + +impl Resolve for PublicResolver { + fn resolve(&self, name: Name) -> Resolving { + Box::pin(async move { + let addrs = tokio::net::lookup_host((name.as_str(), 0)) + .await? + .filter(|addr| is_global_ip(&addr.ip())) + .collect::>(); + + if !addrs.is_empty() { + Ok(Box::new(addrs.into_iter()) as Addrs) + } else { + Err(format!("{} has no public address", name.as_str()).into()) + } + }) + } +} + +pub fn is_global_ip(ip: &IpAddr) -> bool { + match ip { + IpAddr::V4(ip) => is_global_ipv4(ip), + IpAddr::V6(ip) => is_global_ipv6(ip), + } +} + +fn is_global_ipv4(ip: &Ipv4Addr) -> bool { + let [a, b, c, _] = ip.octets(); + let is_this_network = a == 0; + let is_shared = a == 100 && (64..128).contains(&b); + let is_protocol_assignment = a == 192 && b == 0 && c == 0; + let is_benchmarking = a == 198 && (b & 0xfe) == 18; + let is_relay_6to4 = a == 192 && b == 88 && c == 99; + let is_reserved = a >= 240; + + !(ip.is_unspecified() + || ip.is_loopback() + || ip.is_private() + || ip.is_link_local() + || ip.is_multicast() + || ip.is_broadcast() + || ip.is_documentation() + || is_this_network + || is_shared + || is_protocol_assignment + || is_benchmarking + || is_relay_6to4 + || is_reserved) +} + +fn is_global_ipv6(ip: &Ipv6Addr) -> bool { + if ip.is_unspecified() || ip.is_loopback() || ip.is_multicast() { + return false; + } + + if let Some(ip) = ip.to_ipv4() { + return is_global_ipv4(&ip); + } + + let segments = ip.segments(); + + if segments[0] == 0x2002 { + return is_global_ipv4(&Ipv4Addr::from( + ((segments[1] as u32) << 16) | segments[2] as u32, + )); + } + + if segments[0] == 0x0064 && segments[1] == 0xff9b { + let is_well_known_prefix = + segments[2] == 0 && segments[3] == 0 && segments[4] == 0 && segments[5] == 0; + + return is_well_known_prefix + && is_global_ipv4(&Ipv4Addr::from( + ((segments[6] as u32) << 16) | segments[7] as u32, + )); + } + + let is_unique_local = (segments[0] & 0xfe00) == 0xfc00; + let is_link_local = (segments[0] & 0xffc0) == 0xfe80; + let is_site_local = (segments[0] & 0xffc0) == 0xfec0; + let is_discard_only = + segments[0] == 0x0100 && segments[1] == 0 && segments[2] == 0 && segments[3] == 0; + let is_documentation = segments[0] == 0x2001 && segments[1] == 0x0db8; + let is_teredo = segments[0] == 0x2001 && segments[1] == 0; + let is_orchid = segments[0] == 0x2001 && (segments[1] & 0xfff0) == 0x0020; + + !(is_unique_local + || is_link_local + || is_site_local + || is_discard_only + || is_documentation + || is_teredo + || is_orchid) +} -- 2.54.0 From bd5bfb389299e8793c238421cfc322f2af7ce926 Mon Sep 17 00:00:00 2001 From: John Coffey Date: Fri, 20 Nov 2026 12:04:17 -0700 Subject: [PATCH 5/5] Passkeys: a challenge signs in once, even when sent twice at once A sign-in challenge and a registration ceremony were read, then deleted, in two steps. Two requests sent together with the same challenge could both read it before either deleted it. Each still needed a valid signed assertion, so this didn't let anyone in without the passkey, but PK-10 says a challenge is good once. Each reader now also takes a claim counter named after the key and what it read. Every in-memory store increments it atomically (Redis, SQL, the key-value stores, sharded or not), and only the first reader gets the challenge. A registration ticket that starts a new ceremony after a failed try gets a new claim. The counter expires with the challenge. Tests, in the passkey suite: 64 readers claiming one challenge at once get exactly one win, and a ticket's next ceremony is a new claim. The read-then-delete window is two back-to-back store calls, too short to hit reliably over HTTP, so the claim is tested directly; the same challenge sent six times at once over HTTP also signs in exactly once. Reported privately in a security review. --- crates/http/src/auth/passkey.rs | 56 +++++++++++++++++++++++++-------- tests/src/system/passkeys.rs | 43 +++++++++++++++++++++++++ 2 files changed, 86 insertions(+), 13 deletions(-) diff --git a/crates/http/src/auth/passkey.rs b/crates/http/src/auth/passkey.rs index a74f9cbf..3ffb9b26 100644 --- a/crates/http/src/auth/passkey.rs +++ b/crates/http/src/auth/passkey.rs @@ -39,7 +39,9 @@ use inbuxa_features::passkey::{self, Activated, HANDLE_LEN, Passkey}; use jmap::inbuxa::passkey::{allowed_for, settings}; use registry::schema::{enums::Permission, structs::Authentication}; use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; use store::{ + InMemoryStore, dispatch::lookup::KeyValue, rand::{RngExt, distr::Alphanumeric, rng}, write::now, @@ -166,6 +168,44 @@ fn challenge_key(id: &str) -> Vec { KeyValue::<()>::build_key(KV_PASSKEY_CEREMONY, key) } +/// Reads a challenge or ceremony and makes sure only one request gets it. +/// +/// Reading and then deleting is two steps, so two requests sent together +/// could both read it before either deleted it. Each reader also counts +/// itself on a claim counter for what it read, which every in-memory store +/// increments atomically (Redis, SQL, the key-value stores, sharded or not), +/// and only the first one is handed the value. The counter is named after +/// the value as well as the key: a registration ticket starts a new ceremony +/// under the same key after a failed try, and that one gets its own claim. +/// The counter expires with the challenge, so it needs no cleanup. +async fn take_once(server: &Server, key: Vec, ttl: u64) -> trc::Result> { + let store = server.in_memory_store(); + let Some(value) = store.key_get::(key.clone()).await? else { + return Ok(None); + }; + let first = claim_once(store, &key, &value, ttl).await?; + store.key_delete(key).await?; + Ok(first.then_some(value)) +} + +/// Counts a reader of `value` under `key`; true only for the first one. +/// Public for the race test, which calls it directly: two sign-ins rarely +/// land between a read and a delete over HTTP, but here they all do. +pub async fn claim_once( + store: &InMemoryStore, + key: &[u8], + value: &str, + ttl: u64, +) -> trc::Result { + let mut claim = key.to_vec(); + claim.push(b'!'); + claim.extend_from_slice(&Sha256::digest(value.as_bytes())[..16]); + store + .counter_incr(KeyValue::new(claim, 1).expires(ttl), true) + .await + .map(|claims| claims == 1) +} + /// A sign-in challenge between the two requests. #[derive(Serialize, Deserialize)] struct SignInCeremony { @@ -296,14 +336,9 @@ async fn check_assertion( return Err(refused("Unknown passkey challenge")); } let key = challenge_key(&assertion.challenge_id); - let Some(ceremony) = server - .in_memory_store() - .key_get::(key.clone()) - .await? - else { + let Some(ceremony) = take_once(server, key, CHALLENGE_SECONDS).await? else { return Err(refused("Unknown, used or expired passkey challenge")); }; - server.in_memory_store().key_delete(key).await?; let ceremony = serde_json::from_str::(&ceremony).map_err(|err| { trc::StoreEvent::DataCorruption .into_err() @@ -571,16 +606,11 @@ async fn finish( ticket: &str, credential: &RegisterPublicKeyCredential, ) -> trc::Result { - // Good once: read and deleted + // Good once: claimed, then deleted let key = ceremony_key(ticket); - let Some(ceremony) = server - .in_memory_store() - .key_get::(key.clone()) - .await? - else { + let Some(ceremony) = take_once(server, key, CEREMONY_SECONDS).await? else { return Ok(RegisterResponse::Expired); }; - server.in_memory_store().key_delete(key).await?; let ceremony = serde_json::from_str::(&ceremony).map_err(|err| { trc::StoreEvent::DataCorruption .into_err() diff --git a/tests/src/system/passkeys.rs b/tests/src/system/passkeys.rs index f6bc3823..0a63ea52 100644 --- a/tests/src/system/passkeys.rs +++ b/tests/src/system/passkeys.rs @@ -269,6 +269,49 @@ pub async fn test(test: &mut TestServer) { let key = registration(&user).await; let client_id = sign_in(&user, &key).await; policy(&admin, &user, &key, &client_id).await; + challenge_race(&key, &client_id).await; + claim_race(&test.server).await; +} + +/// H1, without HTTP in the way: many readers of one challenge, all at once, +/// and exactly one may use it. A ticket's next ceremony is a new claim. +pub async fn claim_race(server: &common::Server) { + let store = server.in_memory_store(); + let key = b"passkey-claim-race".to_vec(); + let claims = (0..64) + .map(|_| http::auth::passkey::claim_once(store, &key, "ceremony-1", 60)) + .collect::>(); + let won = futures::future::join_all(claims) + .await + .into_iter() + .filter(|claim| *claim.as_ref().unwrap()) + .count(); + assert_eq!( + won, 1, + "one challenge, read at once by 64, used {won} times" + ); + assert!( + http::auth::passkey::claim_once(store, &key, "ceremony-2", 60) + .await + .unwrap(), + "a new ceremony under the same ticket is its own claim" + ); +} + +/// PK-10 under load (security batch 11, H1): one challenge sent several +/// times at once signs in once. Each copy is signed with its own, higher +/// counter, so only the challenge being used up can stop the rest. +async fn challenge_race(key: &SoftKey, client_id: &str) { + let challenge = new_challenge().await; + let attempts = (0..6) + .map(|n| login(client_id, key.get(&challenge, 100 + n, ORIGIN))) + .collect::>(); + let responses = futures::future::join_all(attempts).await; + let signed_in = responses + .iter() + .filter(|response| response["type"] == "authenticated") + .count(); + assert_eq!(signed_in, 1, "{responses:?}"); } /// A software authenticator: one P-256 key, user verification always done. -- 2.54.0