Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions crates/pendant-bridge/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
52 changes: 28 additions & 24 deletions crates/pendant-bridge/src/pairing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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 {
Expand All @@ -37,7 +40,7 @@ struct Inner {
challenge_window: Duration,
nonces: Vec<String>,
challenges: Vec<Ticket>,
recent: Vec<Instant>,
recent: HashMap<String, Vec<Instant>>,
devices: HashMap<String, Device>,
grants: HashMap<String, Grant>,
}
Expand Down Expand Up @@ -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(),
})),
Expand Down Expand Up @@ -107,7 +110,9 @@ impl Pairing {
nonce
}

pub fn issue_challenge(&self) -> Result<String, AuthError> {
/// 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<String, AuthError> {
let mut inner = self.inner.lock().expect("pairing");
let now = Instant::now();
let ttl = inner.challenge_ttl;
Expand All @@ -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);
}
Expand Down Expand Up @@ -364,23 +374,10 @@ fn push_capped(items: &mut Vec<String>, 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<String>, 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);
}
}
Expand All @@ -398,15 +395,22 @@ 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);
}
}
inner
.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;
}
Expand Down
221 changes: 219 additions & 2 deletions crates/pendant-bridge/src/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -401,8 +401,8 @@ async fn pair_qr(State(state): State<AppState>, headers: HeaderMap) -> Response
.into_response()
}

async fn issue_challenge(State(state): State<AppState>) -> Response {
match state.pairing.issue_challenge() {
async fn issue_challenge(State(state): State<AppState>, 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,
Expand Down Expand Up @@ -552,6 +552,45 @@ 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 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(trusted) = forwarded.rsplit(',').next() {
let trusted = trusted.trim();
if !trusted.is_empty() {
return normalize_client(trusted);
}
}
}
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.to_lowercase());
}
}
"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::<std::net::SocketAddr>() {
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.
Expand Down Expand Up @@ -1456,4 +1495,182 @@ 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);
}

#[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"));
}
}
Loading