From 55eedaf45ceb12aabb3bd75fd8d1536d189410e3 Mon Sep 17 00:00:00 2001 From: VirtualMachinist Date: Fri, 13 Nov 2026 16:08:45 -0500 Subject: [PATCH 1/2] fix(pairing): per-client challenge limit and constant-time compares - README: only Serve's HTTP-proxy mode satisfies the local-only gate; a raw or TLS-terminated TCP forward, or any proxy without X-Forwarded-For, defeats it. - Test a challenge replay: the second use is refused and no grant or pairing state changes. - Replace the hand-rolled constant-time compare with subtle::ConstantTimeEq; take_token and take_ticket still scan every entry. - Key the challenge rate limit on the proxied client (X-Forwarded-For, then the Tailscale identity headers) instead of one global bucket; the 429 is unchanged. - Bump rustix 1.1.5 to 1.1.6 for RUSTSEC-2026-0486 so cargo deny passes. --- Cargo.lock | 5 +- README.md | 2 + crates/pendant-bridge/Cargo.toml | 1 + crates/pendant-bridge/src/pairing.rs | 52 +++++----- crates/pendant-bridge/src/routes.rs | 142 ++++++++++++++++++++++++++- 5 files changed, 174 insertions(+), 28 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4b4751e..244d486 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -677,6 +677,7 @@ dependencies = [ "pendant-web", "serde", "serde_json", + "subtle", "tempfile", "thiserror", "tokio", @@ -892,9 +893,9 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.5" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ "bitflags", "errno", diff --git a/README.md b/README.md index 4bcfb27..ead6507 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,8 @@ tailscale serve --bg --https=8443 http://127.0.0.1:8780 Pendant HTTPS is port `8443`, proxying `http://127.0.0.1:8780`. Port `443` is not the Pendant route. Set `PENDANT_SERVE_ORIGIN` to the exact origin a browser sends on that route. Leaving it unset makes those requests `403`. +Only Serve's HTTP-proxy mode is supported, with exactly that command. The local-only gate on pairing trusts the forwarding header Serve adds, so a raw TCP forward, a TLS-terminated TCP forward, or any other proxy that does not add `X-Forwarded-For` defeats the gate. Do not use one. + ## Security - Tailnet-only. Pendant listens on loopback. Reach it through Tailscale Serve, not the public internet. diff --git a/crates/pendant-bridge/Cargo.toml b/crates/pendant-bridge/Cargo.toml index c437100..2f951bd 100644 --- a/crates/pendant-bridge/Cargo.toml +++ b/crates/pendant-bridge/Cargo.toml @@ -19,6 +19,7 @@ pendant-herdr = { path = "../pendant-herdr" } pendant-web = { path = "../pendant-web" } serde.workspace = true serde_json.workspace = true +subtle = "2.6" thiserror.workspace = true tokio.workspace = true tokio-stream.workspace = true diff --git a/crates/pendant-bridge/src/pairing.rs b/crates/pendant-bridge/src/pairing.rs index ce45ba7..215560e 100644 --- a/crates/pendant-bridge/src/pairing.rs +++ b/crates/pendant-bridge/src/pairing.rs @@ -15,6 +15,7 @@ use base64::engine::general_purpose::STANDARD; use base64::Engine; use p256::ecdsa::signature::Verifier; use p256::ecdsa::{Signature, VerifyingKey}; +use subtle::ConstantTimeEq; /// Session takeover is not implemented. pub const TAKEOVER: bool = false; @@ -24,6 +25,8 @@ pub const DEVICE_SIGNATURE: &str = "ecdsa-p256-sha256"; const GRANT_TTL: Duration = Duration::from_secs(30); const MAX_CHALLENGES: usize = 64; +/// Bound on client keys held by the challenge rate limiter. +const MAX_CLIENTS: usize = 1024; #[derive(Clone)] pub struct Pairing { @@ -37,7 +40,7 @@ struct Inner { challenge_window: Duration, nonces: Vec, challenges: Vec, - recent: Vec, + recent: HashMap>, devices: HashMap, grants: HashMap, } @@ -71,7 +74,7 @@ impl Pairing { challenge_window: Duration::from_secs(1), nonces: Vec::new(), challenges: Vec::new(), - recent: Vec::new(), + recent: HashMap::new(), devices: HashMap::new(), grants: HashMap::new(), })), @@ -107,7 +110,9 @@ impl Pairing { nonce } - pub fn issue_challenge(&self) -> Result { + /// Challenges are rate limited per client key, so one client cannot delay + /// another. The key comes from the proxy identity, never the request body. + pub fn issue_challenge(&self, client: &str) -> Result { let mut inner = self.inner.lock().expect("pairing"); let now = Instant::now(); let ttl = inner.challenge_ttl; @@ -116,14 +121,19 @@ impl Pairing { inner .challenges .retain(|ticket| now.saturating_duration_since(ticket.issued) <= ttl); - inner - .recent - .retain(|issued| now.saturating_duration_since(*issued) <= window); - if inner.recent.len() >= rate { + inner.recent.retain(|_, issued| { + issued.retain(|at| now.saturating_duration_since(*at) <= window); + !issued.is_empty() + }); + if inner.recent.len() >= MAX_CLIENTS && !inner.recent.contains_key(client) { + return Err(AuthError::RateLimited); + } + let issued = inner.recent.entry(client.to_string()).or_default(); + if issued.len() >= rate { return Err(AuthError::RateLimited); } let challenge = random_token(); - inner.recent.push(now); + issued.push(now); if inner.challenges.len() >= MAX_CHALLENGES { inner.challenges.remove(0); } @@ -364,23 +374,10 @@ fn push_capped(items: &mut Vec, item: String) { items.push(item); } -fn ct_eq(left: &str, right: &str) -> bool { - let left = left.as_bytes(); - let right = right.as_bytes(); - if left.len() != right.len() { - return false; - } - let mut diff = 0u8; - for (a, b) in left.iter().zip(right.iter()) { - diff |= a ^ b; - } - diff == 0 -} - fn take_token(items: &mut Vec, token: &str) -> bool { let mut found = None; for (index, item) in items.iter().enumerate() { - if ct_eq(item, token) { + if bool::from(item.as_bytes().ct_eq(token.as_bytes())) { found = Some(index); } } @@ -398,7 +395,7 @@ fn take_ticket(inner: &mut Inner, token: &str) -> bool { let mut found = None; for (index, ticket) in inner.challenges.iter().enumerate() { let fresh = now.saturating_duration_since(ticket.issued) <= ttl; - if fresh && ct_eq(&ticket.token, token) { + if fresh && bool::from(ticket.token.as_bytes().ct_eq(token.as_bytes())) { found = Some(index); } } @@ -406,7 +403,14 @@ fn take_ticket(inner: &mut Inner, token: &str) -> bool { .challenges .retain(|ticket| now.saturating_duration_since(ticket.issued) <= ttl || found.is_some()); if let Some(index) = found { - if index < inner.challenges.len() && ct_eq(&inner.challenges[index].token, token) { + if index < inner.challenges.len() + && bool::from( + inner.challenges[index] + .token + .as_bytes() + .ct_eq(token.as_bytes()), + ) + { inner.challenges.remove(index); return true; } diff --git a/crates/pendant-bridge/src/routes.rs b/crates/pendant-bridge/src/routes.rs index 062b794..8d4156e 100644 --- a/crates/pendant-bridge/src/routes.rs +++ b/crates/pendant-bridge/src/routes.rs @@ -401,8 +401,8 @@ async fn pair_qr(State(state): State, headers: HeaderMap) -> Response .into_response() } -async fn issue_challenge(State(state): State) -> Response { - match state.pairing.issue_challenge() { +async fn issue_challenge(State(state): State, headers: HeaderMap) -> Response { + match state.pairing.issue_challenge(&client_key(&headers)) { Ok(challenge) => Json(json!({ "challenge": challenge })).into_response(), Err(AuthError::RateLimited) => ( StatusCode::TOO_MANY_REQUESTS, @@ -552,6 +552,43 @@ fn proxy_forwarded(headers: &HeaderMap) -> bool { headers.get("forwarded").is_some() || headers.get("x-forwarded-for").is_some() } +/// Rate-limit key for challenge issue. Serve writes `X-Forwarded-For` after it +/// strips client headers, so it is the proxied caller's address; its identity +/// headers are the fallback. A local caller that sends neither shares `local`. +fn client_key(headers: &HeaderMap) -> String { + if let Some(forwarded) = header_value(headers, "x-forwarded-for") { + if let Some(first) = forwarded.split(',').next() { + let first = first.trim(); + if !first.is_empty() { + return normalize_client(first); + } + } + } + for name in [ + "tailscale-user-login", + "tailscale-user-name", + "tailscale-user-profile", + "tailscale-user-id", + ] { + if let Some(identity) = header_value(headers, name) { + return truncate_key(identity); + } + } + "local".to_string() +} + +/// Serve supplies `host:port`; the port changes per connection, so drop it. +fn normalize_client(value: &str) -> String { + if let Ok(addr) = value.parse::() { + return addr.ip().to_string(); + } + truncate_key(value) +} + +fn truncate_key(value: &str) -> String { + value.chars().take(64).collect() +} + fn local_only(state: &AppState, headers: &HeaderMap) -> Result<(), Response> { let host = headers.get(HOST).and_then(|value| value.to_str().ok()); // A loopback Host is not enough: the proxy dials 127.0.0.1 and can forward that Host. @@ -1456,4 +1493,105 @@ mod tests { assert_eq!(status, 403); assert!(raw.contains("bad_signature")); } + + #[tokio::test] + async fn a_challenge_replay_is_refused_and_leaves_state_alone() { + let dir = tempfile::tempdir_in("/tmp").unwrap(); + let scratch = dir.path().join(".config/herdr/sessions/g1/herdr.sock"); + spawn_mock(&scratch, Arc::new(Mutex::new(Vec::new()))); + let port = serve_on(&scratch).await; + let phone = enroll(port).await; + let challenge = fresh_challenge(port).await; + let sig = phone.sign_b64(&pairing::grant_message(&phone.id, &challenge)); + let grant_body = serde_json::json!({ + "device_id": phone.id, + "sig": sig, + "challenge": challenge, + }) + .to_string(); + let (status, _) = http(port, "POST", "/v1/grant", &grant_body).await; + assert_eq!(status, 200); + let (status, raw) = http(port, "POST", "/v1/grant", &grant_body).await; + assert_eq!(status, 403); + assert!(raw.contains("bad_signature")); + // The refused replay released no grant and dropped no device: a signed + // write on the grant opened above still passes. + let (status, raw) = signed( + port, + &phone, + "POST", + "/v1/agents/w1:p1/prompt", + "hello", + r#"{"prompt":"hello"}"#, + ) + .await; + assert_eq!(status, 200, "{raw}"); + } + + #[tokio::test] + async fn challenge_rate_is_per_client_not_global() { + let dir = tempfile::tempdir_in("/tmp").unwrap(); + let scratch = dir.path().join(".config/herdr/sessions/g1/herdr.sock"); + spawn_mock(&scratch, Arc::new(Mutex::new(Vec::new()))); + let limited = serve_with( + &scratch, + pairing::Pairing::with_challenge_limit(2, std::time::Duration::from_secs(30)), + None, + ) + .await; + let host = format!("127.0.0.1:{limited}"); + // Same address, different connection ports: one client key. + let (status, _) = http_headers( + limited, + "GET", + "/v1/challenge", + "", + &host, + &[("x-forwarded-for", "198.51.100.7:4001")], + ) + .await; + assert_eq!(status, 200); + let (status, _) = http_headers( + limited, + "GET", + "/v1/challenge", + "", + &host, + &[("x-forwarded-for", "198.51.100.7:4002")], + ) + .await; + assert_eq!(status, 200); + let (status, raw) = http_headers( + limited, + "GET", + "/v1/challenge", + "", + &host, + &[("x-forwarded-for", "198.51.100.7:4003")], + ) + .await; + assert_eq!(status, 429); + assert!(raw.contains("rate_limited")); + // Another client key still gets a challenge in the same window. + let (status, _) = http_headers( + limited, + "GET", + "/v1/challenge", + "", + &host, + &[("x-forwarded-for", "198.51.100.8:4004")], + ) + .await; + assert_eq!(status, 200); + let (status, _) = http_headers( + limited, + "GET", + "/v1/challenge", + "", + &host, + &[("tailscale-user-login", "phone@example.com")], + ) + .await; + assert_eq!(status, 200); + } } From 293550aaf8fbb51262ac708bd43fda4515d2d28d Mon Sep 17 00:00:00 2001 From: VirtualMachinist Date: Fri, 13 Nov 2026 16:19:17 -0500 Subject: [PATCH 2/2] fix(pairing): key the challenge limiter on the trusted hop The caller writes everything to the left of the hop the proxy appends, so the right-most X-Forwarded-For element is the only trusted one; key on it, trimmed and with any port dropped. Earlier elements no longer mint a new bucket. Fold the Tailscale identity headers to lower case before truncating, so case variants of one identity share a bucket. Tests: a rate-2 caller rotating the leading element of a two-hop header still gets 429, and two case variants of one identity share a bucket. The rotation test fails on the previous keying. --- crates/pendant-bridge/src/routes.rs | 95 ++++++++++++++++++++++++++--- 1 file changed, 87 insertions(+), 8 deletions(-) diff --git a/crates/pendant-bridge/src/routes.rs b/crates/pendant-bridge/src/routes.rs index 8d4156e..cfdc66d 100644 --- a/crates/pendant-bridge/src/routes.rs +++ b/crates/pendant-bridge/src/routes.rs @@ -552,15 +552,17 @@ fn proxy_forwarded(headers: &HeaderMap) -> bool { headers.get("forwarded").is_some() || headers.get("x-forwarded-for").is_some() } -/// Rate-limit key for challenge issue. Serve writes `X-Forwarded-For` after it -/// strips client headers, so it is the proxied caller's address; its identity -/// headers are the fallback. A local caller that sends neither shares `local`. +/// Rate-limit key for challenge issue. Serve appends the proxied caller to +/// `X-Forwarded-For` after it strips client headers, so the right-most element +/// is the trusted one; earlier elements are caller-written. The identity +/// headers are the fallback, case-folded. A local caller that sends neither +/// shares `local`. fn client_key(headers: &HeaderMap) -> String { if let Some(forwarded) = header_value(headers, "x-forwarded-for") { - if let Some(first) = forwarded.split(',').next() { - let first = first.trim(); - if !first.is_empty() { - return normalize_client(first); + if let Some(trusted) = forwarded.rsplit(',').next() { + let trusted = trusted.trim(); + if !trusted.is_empty() { + return normalize_client(trusted); } } } @@ -571,7 +573,7 @@ fn client_key(headers: &HeaderMap) -> String { "tailscale-user-id", ] { if let Some(identity) = header_value(headers, name) { - return truncate_key(identity); + return truncate_key(&identity.to_lowercase()); } } "local".to_string() @@ -1594,4 +1596,81 @@ mod tests { .await; assert_eq!(status, 200); } + + #[tokio::test] + async fn challenge_rate_ignores_a_rotated_leading_forwarded_element() { + let dir = tempfile::tempdir_in("/tmp").unwrap(); + let scratch = dir.path().join(".config/herdr/sessions/g1/herdr.sock"); + spawn_mock(&scratch, Arc::new(Mutex::new(Vec::new()))); + let limited = serve_with( + &scratch, + pairing::Pairing::with_challenge_limit(2, std::time::Duration::from_secs(30)), + None, + ) + .await; + let host = format!("127.0.0.1:{limited}"); + // The caller writes everything to the left of the trusted hop; only the + // right-most element, appended by the proxy, keys the bucket. + for (left, port) in [("10.9.9.1", 4000), ("10.9.9.2", 4001)] { + let forwarded = format!("{left}, 198.51.100.7:{port}"); + let (status, _) = http_headers( + limited, + "GET", + "/v1/challenge", + "", + &host, + &[("x-forwarded-for", forwarded.as_str())], + ) + .await; + assert_eq!(status, 200); + } + let (status, raw) = http_headers( + limited, + "GET", + "/v1/challenge", + "", + &host, + &[("x-forwarded-for", "10.9.9.3, 198.51.100.7:4002")], + ) + .await; + assert_eq!(status, 429); + assert!(raw.contains("rate_limited")); + } + + #[tokio::test] + async fn challenge_rate_folds_identity_case() { + let dir = tempfile::tempdir_in("/tmp").unwrap(); + let scratch = dir.path().join(".config/herdr/sessions/g1/herdr.sock"); + spawn_mock(&scratch, Arc::new(Mutex::new(Vec::new()))); + let limited = serve_with( + &scratch, + pairing::Pairing::with_challenge_limit(2, std::time::Duration::from_secs(30)), + None, + ) + .await; + let host = format!("127.0.0.1:{limited}"); + for identity in ["PHONE@Example.com", "phone@example.COM"] { + let (status, _) = http_headers( + limited, + "GET", + "/v1/challenge", + "", + &host, + &[("tailscale-user-login", identity)], + ) + .await; + assert_eq!(status, 200); + } + let (status, raw) = http_headers( + limited, + "GET", + "/v1/challenge", + "", + &host, + &[("tailscale-user-login", "Phone@Example.Com")], + ) + .await; + assert_eq!(status, 429); + assert!(raw.contains("rate_limited")); + } }