diff --git a/README.md b/README.md index 2ec05e2..130e909 100644 --- a/README.md +++ b/README.md @@ -21,8 +21,9 @@ move files in production, read [SECURITY.md](SECURITY.md) first and expect header protection, 0-RTT resume (`--encrypt`); optional Ed25519 server authentication (`--server-key`) - **Authenticated senders** — a daemon can accept only the senders it has - been given the keys for, and refuse anonymous ones (`--allow-peer`, - `--require-peer-auth`); see + been given the keys for, refuse anonymous ones, and take signed expiring + grants scoped to one directory (`--allow-peer`, `--require-peer-auth`, + `--trust-anchor`); see [Who may send to a daemon](#who-may-send-to-a-daemon) - **Compressed** — per-chunk zstd with a per-packet flag (`--compression balanced`) @@ -235,6 +236,55 @@ read nothing, so a sender configured with one still transfers to a daemon that has never heard of client authentication. Verified against a pre-existing daemon binary, not only in tests. +### Narrower, expiring permissions + +`--allow-peer` says *this sender may write here*, and keeps saying it until +somebody edits the configuration. Where permissions are handed out per job, +that is the wrong granularity. A **grant** is the narrower statement — this +sender, into this directory, until this time — signed by a key the daemon +was told to trust: + +```bash +# Once: a signing key. Its public half is the anchor daemons are given. +favonius-daemon keygen --output anchor.key +favonius-daemon pubkey --identity anchor.key # prints the anchor + +# Per job: issue a grant. Prints hex to hand to the sender. +favonius-daemon grant --anchor anchor.key \ + --source --destination \ + --prefix /srv/in/nightly --run-id job-42 --ttl-secs 300 + +# The daemon accepts grants from that anchor, and requires one +favonius-daemon --dest-root /srv/in --identity daemon.key \ + --trust-anchor --require-grant + +# The sender presents it +favonius send big.tar "host:7801:/srv/in/nightly/big.tar" \ + --encrypt --identity sender.key --grant +``` + +A grant names the sender it is for, the **daemon** it is for, a path prefix +and an expiry, and the daemon checks all four offline — no callback, no +directory service. Naming the daemon matters: without it, a permission to +write to one machine would be accepted by every machine trusting the same +anchor. Expiry is the only revocation here; a grant cannot be recalled, it +runs out, which is why the default TTL is minutes. + +`--trust-anchor` may be repeated, and that is what makes rotating the +signing key possible without a flag day: publish the new anchor, let daemons +accept both, switch issuance, then drop the retired one. + +`--require-grant` implies `--require-peer-auth`, because a grant names its +bearer and demanding one from a sender that proved nothing would be +demanding a document nobody checked the bearer of. + +**0-RTT resume is refused while any of this is in force.** A resumed session +carries no identity and no grant, so honouring one would let a sender +authorised for five minutes and one directory keep writing anywhere under +`--dest-root` for as long as its ticket lived. Such daemons do not issue +tickets either, so senders never attempt a reconnection that would be +rejected. + **Two limits worth knowing.** `--require-peer-auth` disables the TCP fallback, which has no handshake and therefore no way to authenticate anyone — leaving it listening would publish a door with no lock beside one diff --git a/crates/ahp-cli/src/main.rs b/crates/ahp-cli/src/main.rs index 01b5391..b6bf0fe 100644 --- a/crates/ahp-cli/src/main.rs +++ b/crates/ahp-cli/src/main.rs @@ -94,6 +94,12 @@ enum Command { /// is calling. Requires --encrypt. #[arg(long)] identity: Option, + /// A signed permission to present to the daemon: hex, or a file + /// containing it. Issued by whatever holds the daemon's trust + /// anchor. Requires --identity, since a grant names the sender it + /// was issued for. + #[arg(long)] + grant: Option, /// Refuse to transfer unless the daemon confirms it authenticated /// this client. Without it, a daemon too old to understand the /// identity accepts the transfer and never says it ignored it. @@ -242,7 +248,7 @@ async fn main() -> Result<(), Box> { return Ok(()); } - Command::Send { source, destination, compression, congestion, ack_mode, streams, pacing, transport, encrypt, header_protect, resume, server_key, identity, require_peer_auth, adaptive, policy_path, include, exclude, dry_run, bandwidth_limit } => { + Command::Send { source, destination, compression, congestion, ack_mode, streams, pacing, transport, encrypt, header_protect, resume, server_key, identity, grant, require_peer_auth, adaptive, policy_path, include, exclude, dry_run, bandwidth_limit } => { // No code path reads this. It was destructured away with `..`, // so `--bandwidth-limit 10` capped nothing and said nothing — // the user asked for a rate limit and got line rate. Fail @@ -364,6 +370,25 @@ async fn main() -> Result<(), Box> { ); std::process::exit(2); } + let grant_blob = match grant.as_deref() { + Some(value) => match ahp_crypto::signatures::parse_hex_blob(value) { + Ok(b) => Some(b), + Err(e) => { eprintln!("Error: --grant {e}"); std::process::exit(2); } + }, + None => None, + }; + // A grant travels appended to the identity that it names, so + // one without an identity would arrive unattached to anyone + // and be ignored — silently, which is the failure worth + // refusing outright. + if grant_blob.is_some() && client_identity.is_none() { + eprintln!( + "Error: --grant needs --identity: a grant names the sender it was \ + issued for, and the daemon checks it against the identity that \ + authenticated." + ); + std::process::exit(2); + } if client_identity.is_some() && !encrypt { eprintln!( "Error: --identity needs --encrypt: the identity is presented inside \ @@ -446,7 +471,8 @@ async fn main() -> Result<(), Box> { let failed = run_ahp_sends( remote_addr, &items, cc_profile, ack, streams, &pacing, encrypt, compress_profile, resume, adaptive_policy.as_mut(), header_protect, - pinned_key, client_identity.as_ref(), require_peer_auth, + pinned_key, client_identity.as_ref(), grant_blob.as_deref(), + require_peer_auth, ).await; if failed > 0 { eprintln!("{failed} of {} transfer(s) failed.", items.len()); @@ -642,7 +668,7 @@ async fn main() -> Result<(), Box> { // unauthenticated rather than half-authenticated. A // daemon running --require-peer-auth will refuse it. remote_addr, &items, cc_profile, AckMode::Bitmap, streams, "auto", - encrypt, compress_profile, false, None, false, None, None, false, + encrypt, compress_profile, false, None, false, None, None, None, false, ).await; } @@ -843,6 +869,7 @@ async fn run_ahp_sends( header_protect: bool, pinned_key: Option<[u8; 32]>, client_identity: Option<&ahp_crypto::signatures::SigningIdentity>, + grant: Option<&[u8]>, require_peer_auth: bool, ) -> usize { let multi = items.len() > 1; @@ -857,7 +884,7 @@ async fn run_ahp_sends( match net_sender::send_file( remote_addr, src, dst, cc_profile, ack, streams, pacing, encrypt, compress_profile, resume, adaptive_policy.as_deref(), header_protect, pinned_key, - client_identity, require_peer_auth, + client_identity, grant, require_peer_auth, ).await { Ok(stats) => { sent_bytes += stats.bytes_sent; diff --git a/crates/ahp-cli/src/net_sender.rs b/crates/ahp-cli/src/net_sender.rs index ac5bf53..d9d6d84 100644 --- a/crates/ahp-cli/src/net_sender.rs +++ b/crates/ahp-cli/src/net_sender.rs @@ -1929,6 +1929,9 @@ pub async fn send_file( // `None` sends an unauthenticated HELLO — what every client did before // this existed. client_identity: Option<&ahp_crypto::signatures::SigningIdentity>, + // An opaque signed permission, presented alongside the identity. The + // client does not read it: it was issued for the daemon to check. + grant: Option<&[u8]>, // Abort unless the daemon says it checked us. Without it, a daemon too // old to understand the appended material completes the transfer // happily and the client cannot tell it was never authenticated. @@ -2024,6 +2027,7 @@ pub async fn send_file( &kp.public, &local_nonce, offer.as_ref().map(|(pk, sig)| (pk, sig)), + grant, ) } else { vec![0x00] // flags: plaintext @@ -2535,6 +2539,12 @@ a time; retry when it is free", match recv_ctrl(&socket, &mut recv_buf, Duration::from_secs(2)).await { Ok(pkt) => match pkt.header.packet_type { PacketType::AckBitmap => { manifest_acked = true; break; } + // The daemon refused after reading the manifest — the + // destination is outside what it will accept from this + // sender. Final, like the handshake refusal: retrying sends + // the same manifest to the same answer and then reports a + // timeout, which names the wrong problem. + PacketType::Error => return Err(DEST_REFUSED.into()), PacketType::ResumeAck => { if pkt.payload.len() > 1 { let prefix = pkt.payload[0]; @@ -4368,6 +4378,11 @@ async fn recv_hello_ack_or_refusal( } } +/// The daemon accepted this sender but not this destination. +const DEST_REFUSED: &str = "the daemon refused the destination path: this sender is not \ +permitted to write there. If it runs --require-grant, the grant's path prefix does not \ +cover the destination; its log says what was asked for and what was permitted."; + /// Marker for a refusal, so the retry loop can tell it from a timeout. /// Compared by identity of the message, which is why it is a constant. const PEER_REFUSED: &str = "the daemon refused this transfer before it began: it did not \ @@ -5391,6 +5406,7 @@ mod tests { false, None, None, + None, false, ) .await; diff --git a/crates/ahp-cli/tests/peer_auth.rs b/crates/ahp-cli/tests/peer_auth.rs index 12feccb..988534d 100644 --- a/crates/ahp-cli/tests/peer_auth.rs +++ b/crates/ahp-cli/tests/peer_auth.rs @@ -22,6 +22,7 @@ use ahp_cli::net_sender::send_file; use ahp_compression::CompressionProfile; use ahp_congestion::CongestionProfile; use ahp_crypto::signatures::SigningIdentity; +use ahp_crypto::grant::Grant; use ahp_daemon::peer_auth::PeerPolicy; use ahp_proto::data::AckMode; use std::net::SocketAddr; @@ -82,8 +83,25 @@ struct Daemon { server_key: [u8; 32], } +/// Start a loopback daemon under a policy built from its own identity. +/// +/// The policy is built *here* rather than passed in, because a grant names +/// the daemon it was issued for: the policy has to be told the identity the +/// daemon will actually run with, and the two must be the same key. +async fn start_daemon_with( + make_policy: impl FnOnce([u8; 32]) -> PeerPolicy, +) -> Option { + let identity = SigningIdentity::generate(); + let own = identity.public_bytes(); + start_daemon_inner(make_policy(own), identity).await +} + /// Start a loopback daemon under `policy`. async fn start_daemon(policy: PeerPolicy) -> Option { + start_daemon_inner(policy, SigningIdentity::generate()).await +} + +async fn start_daemon_inner(policy: PeerPolicy, identity: SigningIdentity) -> Option { let base = free_port_run(2)?; let control: SocketAddr = format!("127.0.0.1:{base}").parse().unwrap(); let data: SocketAddr = format!("127.0.0.1:{}", base + 1).parse().unwrap(); @@ -92,7 +110,6 @@ async fn start_daemon(policy: PeerPolicy) -> Option { let dest_root = dir.path().to_path_buf(); let root = dest_root.clone(); - let identity = SigningIdentity::generate(); let server_key = identity.public_bytes(); tokio::spawn(async move { @@ -118,6 +135,16 @@ async fn attempt( name: &str, client_identity: Option<&SigningIdentity>, require_peer_auth: bool, +) -> bool { + attempt_with_grant(daemon, name, client_identity, None, require_peer_auth).await +} + +async fn attempt_with_grant( + daemon: &Daemon, + name: &str, + client_identity: Option<&SigningIdentity>, + grant: Option<&[u8]>, + require_peer_auth: bool, ) -> bool { let src_dir = Scratch::new("peer-auth-src").expect("scratch"); let source = src_dir.path().join("payload.bin"); @@ -141,6 +168,7 @@ async fn attempt( false, Some(daemon.server_key), client_identity, + grant, require_peer_auth, ), ) @@ -250,3 +278,252 @@ async fn an_allowlist_without_require_still_admits_anonymous_senders() { assert!(attempt(&d, "anon.bin", None, false).await, "migration posture refused a plain sender"); assert!(landed(&d, "anon.bin")); } + +// ── Grants ──────────────────────────────────────────────────────────────── + +fn grant_bytes( + anchor: &SigningIdentity, + source: [u8; 32], + destination: [u8; 32], + prefix: &str, + not_after: u64, +) -> Vec { + Grant { + source, + destination, + not_after, + run_id: "run-under-test".into(), + path_prefix: prefix.into(), + } + .sign(anchor) +} + +fn in_five_minutes() -> u64 { + ahp_crypto::grant::now_unix() + 300 +} + +#[tokio::test] +async fn a_valid_grant_transfers() { + let anchor = SigningIdentity::generate(); + let client = SigningIdentity::generate(); + let anchor_pub = anchor.public_bytes(); + let Some(d) = start_daemon_with(|own| { + PeerPolicy::new([], true).with_trust_anchors([anchor_pub], true, Some(own)) + }) + .await + else { + eprintln!("skipped: no free ports"); + return; + }; + let g = grant_bytes( + &anchor, + client.public_bytes(), + d.server_key, + d.dest_root.to_str().unwrap(), + in_five_minutes(), + ); + assert!( + attempt_with_grant(&d, "ok.bin", Some(&client), Some(&g), true).await, + "a valid grant was refused" + ); + assert!(landed(&d, "ok.bin")); +} + +#[tokio::test] +async fn an_authenticated_sender_without_a_grant_writes_nothing() { + // The whole point of --require-grant: being a known sender is no longer + // enough on its own. + let anchor = SigningIdentity::generate(); + let client = SigningIdentity::generate(); + let anchor_pub = anchor.public_bytes(); + let Some(d) = start_daemon_with(|own| { + PeerPolicy::new([], true).with_trust_anchors([anchor_pub], true, Some(own)) + }) + .await + else { + eprintln!("skipped: no free ports"); + return; + }; + assert!(!attempt(&d, "nogrant.bin", Some(&client), false).await); + assert!(!landed(&d, "nogrant.bin"), "a sender with no grant wrote a file"); +} + +#[tokio::test] +async fn a_grant_from_an_untrusted_issuer_writes_nothing() { + let anchor = SigningIdentity::generate(); + let impostor = SigningIdentity::generate(); + let client = SigningIdentity::generate(); + let anchor_pub = anchor.public_bytes(); + let Some(d) = start_daemon_with(|own| { + PeerPolicy::new([], true).with_trust_anchors([anchor_pub], true, Some(own)) + }) + .await + else { + eprintln!("skipped: no free ports"); + return; + }; + let g = grant_bytes( + &impostor, + client.public_bytes(), + d.server_key, + d.dest_root.to_str().unwrap(), + in_five_minutes(), + ); + assert!(!attempt_with_grant(&d, "forged.bin", Some(&client), Some(&g), false).await); + assert!(!landed(&d, "forged.bin"), "a forged grant wrote a file"); +} + +#[tokio::test] +async fn an_expired_grant_writes_nothing() { + let anchor = SigningIdentity::generate(); + let client = SigningIdentity::generate(); + let anchor_pub = anchor.public_bytes(); + let Some(d) = start_daemon_with(|own| { + PeerPolicy::new([], true).with_trust_anchors([anchor_pub], true, Some(own)) + }) + .await + else { + eprintln!("skipped: no free ports"); + return; + }; + let g = grant_bytes( + &anchor, + client.public_bytes(), + d.server_key, + d.dest_root.to_str().unwrap(), + ahp_crypto::grant::now_unix() - 1, + ); + assert!(!attempt_with_grant(&d, "stale.bin", Some(&client), Some(&g), false).await); + assert!(!landed(&d, "stale.bin"), "an expired grant wrote a file"); +} + +#[tokio::test] +async fn a_grant_issued_for_another_daemon_writes_nothing() { + // Without the destination binding, one permission would be a permission + // everywhere the same anchor is trusted. + let anchor = SigningIdentity::generate(); + let client = SigningIdentity::generate(); + let anchor_pub = anchor.public_bytes(); + let Some(d) = start_daemon_with(|own| { + PeerPolicy::new([], true).with_trust_anchors([anchor_pub], true, Some(own)) + }) + .await + else { + eprintln!("skipped: no free ports"); + return; + }; + let elsewhere = SigningIdentity::generate().public_bytes(); + let g = grant_bytes( + &anchor, + client.public_bytes(), + elsewhere, + d.dest_root.to_str().unwrap(), + in_five_minutes(), + ); + assert!(!attempt_with_grant(&d, "wrongdest.bin", Some(&client), Some(&g), false).await); + assert!(!landed(&d, "wrongdest.bin"), "a grant for another daemon wrote a file"); +} + +#[tokio::test] +async fn a_write_outside_the_granted_prefix_is_refused() { + // The path scope is enforced after the manifest names a destination, + // which is a different code path from everything above — and the one + // that would silently do nothing if it were never wired up. + let anchor = SigningIdentity::generate(); + let client = SigningIdentity::generate(); + let anchor_pub = anchor.public_bytes(); + let Some(d) = start_daemon_with(|own| { + PeerPolicy::new([], true).with_trust_anchors([anchor_pub], true, Some(own)) + }) + .await + else { + eprintln!("skipped: no free ports"); + return; + }; + // Permit only a subdirectory, then try to write beside it. + let permitted = d.dest_root.join("allowed"); + std::fs::create_dir_all(&permitted).expect("mkdir"); + let g = grant_bytes( + &anchor, + client.public_bytes(), + d.server_key, + permitted.to_str().unwrap(), + in_five_minutes(), + ); + + assert!( + attempt_with_grant(&d, "allowed/inside.bin", Some(&client), Some(&g), true).await, + "a write inside the prefix was refused" + ); + assert!(landed(&d, "allowed/inside.bin")); + + assert!( + !attempt_with_grant(&d, "outside.bin", Some(&client), Some(&g), false).await, + "a write outside the prefix succeeded" + ); + assert!(!landed(&d, "outside.bin"), "a write outside the granted prefix landed"); +} + +#[tokio::test] +async fn a_daemon_that_accepts_grants_still_serves_a_sender_that_brings_none() { + // Anchors configured but not required: the migration posture again, one + // layer up. Grants are checked when presented and their absence is not + // an error. + let anchor = SigningIdentity::generate(); + let client = SigningIdentity::generate(); + let anchor_pub = anchor.public_bytes(); + let Some(d) = start_daemon_with(|own| { + PeerPolicy::new([], true).with_trust_anchors([anchor_pub], false, Some(own)) + }) + .await + else { + eprintln!("skipped: no free ports"); + return; + }; + assert!(attempt(&d, "nogrant.bin", Some(&client), false).await, "refused without a grant"); + assert!(landed(&d, "nogrant.bin")); +} + +#[tokio::test] +async fn a_second_transfer_cannot_skip_the_checks_by_resuming() { + // The hole this pins shut: a successful transfer used to earn a 0-RTT + // session ticket, and a HELLO carrying a ticket took a branch that ran + // none of the authorisation checks. A sender authorised for one + // directory and five minutes could then write anywhere under + // --dest-root for as long as the ticket lived. + // + // The client caches tickets per process, so doing both transfers in one + // test is what makes this reachable at all. + let anchor = SigningIdentity::generate(); + let client = SigningIdentity::generate(); + let anchor_pub = anchor.public_bytes(); + let Some(d) = start_daemon_with(|own| { + PeerPolicy::new([], true).with_trust_anchors([anchor_pub], true, Some(own)) + }) + .await + else { + eprintln!("skipped: no free ports"); + return; + }; + + let g = grant_bytes( + &anchor, + client.public_bytes(), + d.server_key, + d.dest_root.to_str().unwrap(), + in_five_minutes(), + ); + assert!( + attempt_with_grant(&d, "first.bin", Some(&client), Some(&g), true).await, + "the authorised transfer should succeed" + ); + assert!(landed(&d, "first.bin")); + + // Same process, same client, now with no grant at all. If a ticket from + // the first transfer could be replayed, this would land. + assert!( + !attempt(&d, "second.bin", Some(&client), false).await, + "a second transfer got in without presenting a grant" + ); + assert!(!landed(&d, "second.bin"), "a resumed session wrote a file it was not granted"); +} diff --git a/crates/ahp-cli/tests/per_stream_ports.rs b/crates/ahp-cli/tests/per_stream_ports.rs index d5a4ab0..bbce1d0 100644 --- a/crates/ahp-cli/tests/per_stream_ports.rs +++ b/crates/ahp-cli/tests/per_stream_ports.rs @@ -147,6 +147,7 @@ async fn transfer( header_protect, None, None, + None, false, ), ) @@ -241,7 +242,7 @@ async fn per_stream_ports_transfer_every_byte() { daemon.control, &source, dest.to_str().unwrap(), None, // auto AckMode::Bitmap, 4, "auto", false, CompressionProfile::None, - false, None, false, None, None, false, + false, None, false, None, None, None, false, ), ) .await @@ -317,7 +318,7 @@ async fn more_senders_than_sockets_all_complete() { send_file( control, &src, dest.to_str().unwrap(), Some(CongestionProfile::Classic), AckMode::Bitmap, 2, "auto", - false, CompressionProfile::None, false, None, false, None, None, false, + false, CompressionProfile::None, false, None, false, None, None, None, false, ), ) .await diff --git a/crates/ahp-crypto/src/grant.rs b/crates/ahp-crypto/src/grant.rs new file mode 100644 index 0000000..0c47d6f --- /dev/null +++ b/crates/ahp-crypto/src/grant.rs @@ -0,0 +1,538 @@ +// Favonius — high-performance file transfer over UDP +// Copyright (c) 2025-2026 Vantino SàRL +// SPDX-License-Identifier: Apache-2.0 + +//! A signed, expiring permission to write somewhere. +//! +//! `--allow-peer` says *this sender may write here*, and says it until +//! somebody edits the daemon's configuration. That is the right granularity +//! for an operator with a handful of machines and the wrong one for anything +//! that issues permissions per job: it cannot say *this sender, into this +//! directory, for the next few minutes*. +//! +//! A grant is that narrower statement, signed by a **trust anchor** the +//! daemon was configured with. The daemon verifies it offline — no callback, +//! no directory service, no network of any kind — which is what keeps this +//! usable by an operator who has nothing but two machines and a key, and what +//! keeps this crate from acquiring a dependency on whatever issued the grant. +//! +//! # What a grant binds +//! +//! - **Which sender.** The `source` identity must be the one that +//! authenticated on this connection, so a captured grant is useless to +//! anyone who cannot also prove that identity. +//! - **Which destination.** The `destination` identity names the daemon it +//! is for. Without this, a grant would be accepted by *any* daemon +//! trusting the same anchor, so a permission to write to one machine would +//! be a permission to write to all of them. +//! - **Which paths**, as a prefix. +//! - **Until when.** Expiry is the revocation mechanism. A grant that lives +//! minutes does not need a revocation list, which is the point: a +//! revocation list is the thing short expiry exists to avoid. +//! +//! # What it does not do +//! +//! It does not authenticate the sender — the offer signature does that, and +//! a grant is only meaningful alongside one. It does not survive a clock +//! that is badly wrong; see [`Grant::verify`]. + +use crate::signatures::{SigningIdentity, VerifyingKeyRef}; +use crate::CryptoError; + +/// Domain tag. Distinct from every other signature this crate makes, so a +/// grant signature can never be presented as a handshake or offer signature, +/// nor either of those as a grant. +const GRANT_DOMAIN: &[u8] = b"AHP-GRANT-SIG-v1"; + +/// Wire version, so a daemon can refuse a grant it does not understand +/// rather than misread its fields. +const GRANT_VERSION: u8 = 1; + +/// The longest a string field may be. Generous for a path, small enough that +/// a malformed length cannot make a daemon allocate arbitrarily. +const MAX_FIELD: usize = 4096; + +/// A permission to write, before it has been checked. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Grant { + /// Ed25519 identity of the sender this grant is for. + pub source: [u8; 32], + /// Ed25519 identity of the daemon this grant is for. + pub destination: [u8; 32], + /// Unix seconds after which this grant means nothing. + pub not_after: u64, + /// Opaque to this crate: whatever issued the grant uses it to tie the + /// permission back to the job that asked for it. Carried so it can be + /// logged at the receiving end, which is where somebody investigating + /// an unexpected write will be looking. + pub run_id: String, + /// Absolute path prefix the sender may write under. + pub path_prefix: String, +} + +/// A grant whose signature, expiry and destination have been checked. +/// +/// Deliberately a separate type: the path check happens later — the +/// requested path is not known at handshake time — and a `Grant` that has +/// merely been parsed must not be mistaken for one that has been verified. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct VerifiedGrant(Grant); + +impl VerifiedGrant { + pub fn grant(&self) -> &Grant { + &self.0 + } + + /// Whether `path` falls under this grant's prefix. + /// + /// A plain `starts_with` on strings would accept `/srv/incoming-evil` + /// for a prefix of `/srv/incoming`, so a prefix that does not already + /// end in a separator is compared as though it did. Equality with the + /// prefix itself is allowed: a grant for a file names that file. + pub fn permits_path(&self, path: &str) -> bool { + let prefix = &self.0.path_prefix; + if prefix.is_empty() { + return false; + } + if path == prefix { + return true; + } + let with_sep = + if prefix.ends_with('/') { prefix.clone() } else { format!("{prefix}/") }; + path.starts_with(&with_sep) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum GrantError { + /// Not a grant, or truncated, or a length field that does not fit. + Malformed, + /// A version this build does not understand. + UnsupportedVersion(u8), + /// The signature does not verify against any configured anchor. + NotSignedByAnAnchor, + /// Expired, with how long ago in seconds. + Expired { by_secs: u64 }, + /// Issued for a different daemon. + WrongDestination, + /// Issued for a different sender than the one that authenticated. + WrongSource, + /// The verifier could not read its own clock, so expiry cannot be + /// checked. Refused rather than waved through — see [`Grant::verify`]. + NoUsableClock, +} + +impl std::fmt::Display for GrantError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Malformed => write!(f, "grant is malformed"), + Self::UnsupportedVersion(v) => write!(f, "grant version {v} is not supported"), + Self::NotSignedByAnAnchor => { + write!(f, "grant is not signed by a configured trust anchor") + } + Self::Expired { by_secs } => write!(f, "grant expired {by_secs}s ago"), + Self::WrongDestination => write!(f, "grant was issued for a different daemon"), + Self::WrongSource => write!(f, "grant was issued for a different sender"), + Self::NoUsableClock => write!( + f, + "this host's clock is before 2020, so a grant's expiry cannot be checked; \ + set the time (NTP, or an RTC) before requiring grants" + ), + } + } +} + +impl std::error::Error for GrantError {} + +/// Unix seconds at the start of 2020. +/// +/// A host whose clock predates this has not set it — a Raspberry Pi with no +/// real-time clock boots in 1970, and one whose NTP has never run stays +/// there. Any expiry check against such a clock is meaningless, and the +/// meaningless answer it gives is *"not expired"*, which is the wrong way to +/// be wrong. +const CLOCK_SANITY_FLOOR: u64 = 1_577_836_800; + +impl Grant { + /// Serialise the signed portion: domain tag, then every field. + fn signing_bytes(&self) -> Vec { + let mut b = Vec::with_capacity(GRANT_DOMAIN.len() + 32 + 32 + 8 + 4 + 64); + b.extend_from_slice(GRANT_DOMAIN); + b.push(GRANT_VERSION); + b.extend_from_slice(&self.source); + b.extend_from_slice(&self.destination); + b.extend_from_slice(&self.not_after.to_be_bytes()); + push_str(&mut b, &self.run_id); + push_str(&mut b, &self.path_prefix); + b + } + + /// Sign this grant with a trust anchor's key, producing wire bytes. + pub fn sign(&self, anchor: &SigningIdentity) -> Vec { + let mut out = self.signing_bytes(); + let signature = anchor.sign(&out); + // The domain tag is not transmitted: both ends know it, and a + // verifier rebuilds the signed bytes from the parsed fields. Sending + // it would let a peer choose it. + out.drain(..GRANT_DOMAIN.len()); + out.extend_from_slice(&signature); + out + } + + /// Parse wire bytes into a grant and its signature. + pub fn parse(bytes: &[u8]) -> Result<(Self, [u8; 64]), GrantError> { + // version + source + destination + not_after + two length prefixes + // + signature + if bytes.len() < 1 + 32 + 32 + 8 + 2 + 2 + 64 { + return Err(GrantError::Malformed); + } + let version = bytes[0]; + if version != GRANT_VERSION { + return Err(GrantError::UnsupportedVersion(version)); + } + let mut at = 1; + let mut source = [0u8; 32]; + source.copy_from_slice(&bytes[at..at + 32]); + at += 32; + let mut destination = [0u8; 32]; + destination.copy_from_slice(&bytes[at..at + 32]); + at += 32; + let mut na = [0u8; 8]; + na.copy_from_slice(&bytes[at..at + 8]); + let not_after = u64::from_be_bytes(na); + at += 8; + + let run_id = take_str(bytes, &mut at)?; + let path_prefix = take_str(bytes, &mut at)?; + + if bytes.len() != at + 64 { + // Not "at least": trailing bytes after the signature would be + // unsigned content, and a field nobody signed has no business + // travelling inside something whose whole purpose is to be + // signed. + return Err(GrantError::Malformed); + } + let mut signature = [0u8; 64]; + signature.copy_from_slice(&bytes[at..at + 64]); + + Ok((Self { source, destination, not_after, run_id, path_prefix }, signature)) + } + + /// Parse and check a grant. + /// + /// `anchors` are the public keys this daemon was configured to trust; + /// `destination` is this daemon's own identity; `source` is the identity + /// that actually authenticated on this connection; `now` is unix + /// seconds. + /// + /// Expiry is checked **once, here**, at handshake time. It is not + /// rechecked mid-transfer: the sender is bound to the session keys by + /// then, and expiring a running transfer would kill a six-hour copy for + /// a permission that was valid when it started, buying nothing. + /// + /// A clock that is obviously unset is refused rather than tolerated, + /// because tolerating it silently converts every expiry into "never". + pub fn verify( + bytes: &[u8], + anchors: &[[u8; 32]], + destination: &[u8; 32], + source: &[u8; 32], + now: u64, + ) -> Result { + let (grant, signature) = Self::parse(bytes)?; + + // Signature first. Every check after this reads fields that only + // mean something once they are known to be the issuer's words. + let signed = grant.signing_bytes(); + let ok = anchors.iter().any(|a| { + VerifyingKeyRef::from_bytes(a) + .map(|k| k.verify(&signed, &signature).is_ok()) + .unwrap_or(false) + }); + if !ok { + return Err(GrantError::NotSignedByAnAnchor); + } + + if &grant.destination != destination { + return Err(GrantError::WrongDestination); + } + if &grant.source != source { + return Err(GrantError::WrongSource); + } + if now < CLOCK_SANITY_FLOOR { + return Err(GrantError::NoUsableClock); + } + if now > grant.not_after { + return Err(GrantError::Expired { by_secs: now - grant.not_after }); + } + Ok(VerifiedGrant(grant)) + } +} + +/// Current unix seconds, or 0 when the clock is before the epoch. +/// +/// 0 is deliberately a value [`Grant::verify`] refuses: an unreadable clock +/// must not become a passing expiry check. +pub fn now_unix() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +fn push_str(buf: &mut Vec, s: &str) { + buf.extend_from_slice(&(s.len() as u16).to_be_bytes()); + buf.extend_from_slice(s.as_bytes()); +} + +fn take_str(bytes: &[u8], at: &mut usize) -> Result { + if bytes.len() < *at + 2 { + return Err(GrantError::Malformed); + } + let len = u16::from_be_bytes([bytes[*at], bytes[*at + 1]]) as usize; + *at += 2; + if len > MAX_FIELD || bytes.len() < *at + len { + return Err(GrantError::Malformed); + } + let s = std::str::from_utf8(&bytes[*at..*at + len]) + .map_err(|_| GrantError::Malformed)? + .to_string(); + *at += len; + Ok(s) +} + +impl From for CryptoError { + fn from(_: GrantError) -> Self { + CryptoError::SignatureInvalid + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const NOW: u64 = 1_800_000_000; // well after the sanity floor + + fn grant_for(source: [u8; 32], destination: [u8; 32]) -> Grant { + Grant { + source, + destination, + not_after: NOW + 300, + run_id: "run-1234".into(), + path_prefix: "/srv/incoming/nightly".into(), + } + } + + struct Fixture { + anchor: SigningIdentity, + source: [u8; 32], + destination: [u8; 32], + } + + fn fixture() -> Fixture { + Fixture { + anchor: SigningIdentity::generate(), + source: SigningIdentity::generate().public_bytes(), + destination: SigningIdentity::generate().public_bytes(), + } + } + + #[test] + fn a_valid_grant_verifies_and_round_trips() { + let f = fixture(); + let g = grant_for(f.source, f.destination); + let bytes = g.sign(&f.anchor); + let v = Grant::verify( + &bytes, + &[f.anchor.public_bytes()], + &f.destination, + &f.source, + NOW, + ) + .expect("verifies"); + assert_eq!(v.grant(), &g, "fields did not survive the wire"); + } + + #[test] + fn a_grant_signed_by_an_unknown_key_is_refused() { + let f = fixture(); + let bytes = grant_for(f.source, f.destination).sign(&SigningIdentity::generate()); + assert_eq!( + Grant::verify(&bytes, &[f.anchor.public_bytes()], &f.destination, &f.source, NOW), + Err(GrantError::NotSignedByAnAnchor) + ); + } + + #[test] + fn any_configured_anchor_may_have_signed_it() { + // Why the anchor list is a list: rotation. Publish the new anchor, + // let daemons accept both, switch issuance, retire the old one. With + // one anchor at a time, rotating means reconfiguring every daemon in + // the estate in the same window. + let f = fixture(); + let old = SigningIdentity::generate(); + let bytes = grant_for(f.source, f.destination).sign(&f.anchor); + let anchors = [old.public_bytes(), f.anchor.public_bytes()]; + assert!(Grant::verify(&bytes, &anchors, &f.destination, &f.source, NOW).is_ok()); + } + + #[test] + fn a_tampered_field_breaks_the_signature() { + let f = fixture(); + let mut bytes = grant_for(f.source, f.destination).sign(&f.anchor); + // Push the expiry far into the future: the field an attacker most + // wants to edit. + let at = 1 + 32 + 32; + bytes[at..at + 8].copy_from_slice(&u64::MAX.to_be_bytes()); + assert_eq!( + Grant::verify(&bytes, &[f.anchor.public_bytes()], &f.destination, &f.source, NOW), + Err(GrantError::NotSignedByAnAnchor) + ); + } + + #[test] + fn a_grant_for_another_daemon_is_refused() { + // Without this, a grant to write to one machine is a grant to write + // to every machine trusting the same anchor. + let f = fixture(); + let elsewhere = SigningIdentity::generate().public_bytes(); + let bytes = grant_for(f.source, elsewhere).sign(&f.anchor); + assert_eq!( + Grant::verify(&bytes, &[f.anchor.public_bytes()], &f.destination, &f.source, NOW), + Err(GrantError::WrongDestination) + ); + } + + #[test] + fn a_grant_for_another_sender_is_refused() { + // A grant captured off the wire is useless to anyone who cannot also + // prove the identity it names. + let f = fixture(); + let bytes = grant_for(f.source, f.destination).sign(&f.anchor); + let someone_else = SigningIdentity::generate().public_bytes(); + assert_eq!( + Grant::verify( + &bytes, + &[f.anchor.public_bytes()], + &f.destination, + &someone_else, + NOW + ), + Err(GrantError::WrongSource) + ); + } + + #[test] + fn an_expired_grant_is_refused_and_says_by_how_much() { + let f = fixture(); + let bytes = grant_for(f.source, f.destination).sign(&f.anchor); + let err = Grant::verify( + &bytes, + &[f.anchor.public_bytes()], + &f.destination, + &f.source, + NOW + 301, + ) + .unwrap_err(); + assert_eq!(err, GrantError::Expired { by_secs: 1 }); + } + + #[test] + fn an_unset_clock_refuses_rather_than_accepting_everything() { + // A Pi with no RTC boots in 1970. Every grant looks unexpired to + // that clock, which is the wrong way to be wrong. + let f = fixture(); + let bytes = grant_for(f.source, f.destination).sign(&f.anchor); + assert_eq!( + Grant::verify(&bytes, &[f.anchor.public_bytes()], &f.destination, &f.source, 0), + Err(GrantError::NoUsableClock) + ); + // And the message says what to do about it. + assert!(GrantError::NoUsableClock.to_string().contains("NTP")); + } + + #[test] + fn malformed_and_truncated_input_is_refused_without_panicking() { + let f = fixture(); + let bytes = grant_for(f.source, f.destination).sign(&f.anchor); + for n in 0..bytes.len() { + // Every truncation must be an error, never a panic and never an + // accidental accept. + let r = Grant::verify( + &bytes[..n], + &[f.anchor.public_bytes()], + &f.destination, + &f.source, + NOW, + ); + assert!(r.is_err(), "truncation to {n} bytes was accepted"); + } + let mut extra = bytes.clone(); + extra.push(0); + assert_eq!( + Grant::verify(&extra, &[f.anchor.public_bytes()], &f.destination, &f.source, NOW), + Err(GrantError::Malformed), + "unsigned trailing bytes were tolerated" + ); + } + + #[test] + fn an_unknown_version_is_refused_rather_than_misread() { + let f = fixture(); + let mut bytes = grant_for(f.source, f.destination).sign(&f.anchor); + bytes[0] = 99; + assert_eq!( + Grant::verify(&bytes, &[f.anchor.public_bytes()], &f.destination, &f.source, NOW), + Err(GrantError::UnsupportedVersion(99)) + ); + } + + // ── Path scoping ────────────────────────────────────────────────────── + + fn verified(prefix: &str) -> VerifiedGrant { + let f = fixture(); + let mut g = grant_for(f.source, f.destination); + g.path_prefix = prefix.into(); + let bytes = g.sign(&f.anchor); + Grant::verify(&bytes, &[f.anchor.public_bytes()], &f.destination, &f.source, NOW).unwrap() + } + + #[test] + fn a_path_under_the_prefix_is_permitted() { + let v = verified("/srv/incoming"); + assert!(v.permits_path("/srv/incoming/a.bin")); + assert!(v.permits_path("/srv/incoming/deep/a.bin")); + assert!(v.permits_path("/srv/incoming"), "the prefix itself names a file"); + } + + #[test] + fn a_sibling_sharing_the_prefix_string_is_not_permitted() { + // The bug a plain starts_with would ship: /srv/incoming-evil begins + // with /srv/incoming. + let v = verified("/srv/incoming"); + assert!(!v.permits_path("/srv/incoming-evil/a.bin")); + assert!(!v.permits_path("/srv/incomingevil")); + } + + #[test] + fn a_path_outside_the_prefix_is_not_permitted() { + let v = verified("/srv/incoming"); + assert!(!v.permits_path("/etc/cron.d/pwn")); + assert!(!v.permits_path("/srv/other/a.bin")); + } + + #[test] + fn a_trailing_separator_in_the_prefix_behaves_the_same() { + let v = verified("/srv/incoming/"); + assert!(v.permits_path("/srv/incoming/a.bin")); + assert!(!v.permits_path("/srv/incoming-evil/a.bin")); + } + + #[test] + fn an_empty_prefix_permits_nothing() { + // Fail closed: an issuer that forgot to set a prefix must not have + // written "anywhere". + assert!(!verified("").permits_path("/srv/incoming/a.bin")); + assert!(!verified("").permits_path("/")); + } +} diff --git a/crates/ahp-crypto/src/lib.rs b/crates/ahp-crypto/src/lib.rs index af01786..3aaf205 100644 --- a/crates/ahp-crypto/src/lib.rs +++ b/crates/ahp-crypto/src/lib.rs @@ -15,6 +15,7 @@ pub mod key_schedule; pub mod key_update; pub mod packet_protection; pub mod session_ticket; +pub mod grant; pub mod signatures; use bytes::Bytes; diff --git a/crates/ahp-crypto/src/signatures.rs b/crates/ahp-crypto/src/signatures.rs index 04b1b00..893342f 100644 --- a/crates/ahp-crypto/src/signatures.rs +++ b/crates/ahp-crypto/src/signatures.rs @@ -189,6 +189,27 @@ pub fn parse_identity_pin(value: &str) -> Result<[u8; 32], String> { Ok(out) } +/// Parse a variable-length blob given as hex, or as a path to a file +/// containing hex. +/// +/// Same two spellings as [`parse_identity_pin`], for the same reason, but +/// without a fixed length: a grant grows with the paths it names. +pub fn parse_hex_blob(value: &str) -> Result, String> { + let trimmed = value.trim(); + let looks_hex = !trimmed.is_empty() + && trimmed.len().is_multiple_of(2) + && trimmed.chars().all(|c| c.is_ascii_hexdigit()); + let hex = if looks_hex { + trimmed.to_string() + } else { + std::fs::read_to_string(trimmed) + .map_err(|e| format!("{trimmed} is neither hex nor a readable file ({e})"))? + .trim() + .to_string() + }; + hex_decode(&hex).ok_or_else(|| format!("{trimmed} does not contain valid hex")) +} + /// Hex-encode helper (no external dep). pub fn hex_encode(bytes: &[u8]) -> String { bytes.iter().map(|b| format!("{b:02x}")).collect() diff --git a/crates/ahp-daemon/src/main.rs b/crates/ahp-daemon/src/main.rs index 7acc75e..8cd672e 100644 --- a/crates/ahp-daemon/src/main.rs +++ b/crates/ahp-daemon/src/main.rs @@ -82,6 +82,24 @@ struct Args { #[arg(long = "allow-peer")] allow_peer: Vec, + /// A public key whose signature makes a grant worth reading: 64 hex + /// characters, or a file containing them. Repeat to accept more than + /// one. + /// + /// More than one is what makes rotating the issuing key possible + /// without a flag day: accept both while the change is rolled out, then + /// drop the retired one. + #[arg(long = "trust-anchor")] + trust_anchor: Vec, + + /// Require a valid grant, not merely a known sender. + /// + /// Implies --require-peer-auth: a grant names the sender it was issued + /// for, so demanding one from a sender that proved no identity would be + /// demanding a document nobody checked the bearer of. + #[arg(long)] + require_grant: bool, + /// Refuse senders that do not authenticate. /// /// Off by default: turning it on by default would stop every existing @@ -100,6 +118,47 @@ enum Command { #[arg(long, default_value = "favonius-identity.key")] output: std::path::PathBuf, }, + /// Print the public key of an existing identity file + /// + /// `keygen` prints it once, at creation. This answers the same question + /// later, which is when it is usually asked: an operator filling in + /// `--allow-peer` or `--trust-anchor` on another machine has the key + /// file and not the terminal it was created in. + Pubkey { + #[arg(long)] + identity: std::path::PathBuf, + }, + /// Issue a signed grant permitting one sender to write one place + /// + /// A grant is what lets something outside this daemon hand out narrow, + /// expiring permissions without that thing having to speak the wire + /// protocol or link this code: it invokes this subcommand and passes the + /// hex to the sender. + Grant { + /// Identity key file to sign with. Its public key is what daemons + /// must be given as `--trust-anchor`. + #[arg(long)] + anchor: std::path::PathBuf, + /// Public key of the sender this grant is for (hex or a file). + #[arg(long)] + source: String, + /// Public key of the daemon this grant is for (hex or a file). + #[arg(long)] + destination: String, + /// Absolute path prefix the sender may write under. + #[arg(long)] + prefix: String, + /// Free-form identifier recorded in the grant and logged by the + /// daemon that accepts it. + #[arg(long, default_value = "")] + run_id: String, + /// How long the grant is valid, in seconds. + /// + /// Short by default, because expiry is the only revocation this + /// design has: a grant cannot be recalled, it can only run out. + #[arg(long, default_value_t = 300)] + ttl_secs: u64, + }, } #[tokio::main] @@ -114,6 +173,43 @@ async fn main() -> Result<(), Box> { .with_target(true) .init(); + if let Some(Command::Pubkey { identity }) = &args.command { + let id = ahp_crypto::signatures::SigningIdentity::load_from_file(identity)?; + println!("{}", ahp_crypto::signatures::hex_encode(&id.public_bytes())); + return Ok(()); + } + + if let Some(Command::Grant { anchor, source, destination, prefix, run_id, ttl_secs }) = + &args.command + { + let anchor_key = ahp_crypto::signatures::SigningIdentity::load_from_file(anchor)?; + let source = ahp_crypto::signatures::parse_identity_pin(source) + .map_err(|e| format!("--source: {e}"))?; + let destination = ahp_crypto::signatures::parse_identity_pin(destination) + .map_err(|e| format!("--destination: {e}"))?; + if !std::path::Path::new(prefix).is_absolute() { + // A relative prefix would be compared against the absolute path + // the daemon resolved, and would never match — a grant that + // silently permits nothing is worse than one that is refused. + return Err(format!("--prefix {prefix} must be an absolute path").into()); + } + let now = ahp_crypto::grant::now_unix(); + if now == 0 { + return Err("this host's clock is unset, so a grant's expiry would be \ + meaningless; set the time before issuing grants" + .into()); + } + let grant = ahp_crypto::grant::Grant { + source, + destination, + not_after: now + ttl_secs, + run_id: run_id.clone(), + path_prefix: prefix.clone(), + }; + println!("{}", ahp_crypto::signatures::hex_encode(&grant.sign(&anchor_key))); + return Ok(()); + } + if let Some(Command::Keygen { output }) = &args.command { let identity = ahp_crypto::signatures::SigningIdentity::generate(); identity.save_to_file(output)?; @@ -140,8 +236,41 @@ async fn main() -> Result<(), Box> { .map_err(|e| format!("--allow-peer {value}: {e}"))?, ); } - let peer_policy = - ahp_daemon::peer_auth::PeerPolicy::new(allowed, args.require_peer_auth); + let mut anchors = Vec::with_capacity(args.trust_anchor.len()); + for value in &args.trust_anchor { + anchors.push( + ahp_crypto::signatures::parse_identity_pin(value) + .map_err(|e| format!("--trust-anchor {value}: {e}"))?, + ); + } + // A daemon that checks grants must know its own identity: a grant names + // the daemon it was issued for, and without that this one cannot tell a + // permission meant for it from one meant for another machine trusting + // the same anchor. Refused at startup rather than at 03:00. + if args.require_grant && identity.is_none() { + eprintln!( + "favonius-daemon: --require-grant needs --identity.\n\ + \n\ + A grant names the daemon it was issued for. Without an identity\n\ + this daemon cannot tell a grant meant for it from one meant for\n\ + another machine trusting the same anchor, so every grant would\n\ + have to be accepted or refused blind." + ); + std::process::exit(2); + } + if args.require_grant && anchors.is_empty() { + eprintln!( + "favonius-daemon: --require-grant needs at least one --trust-anchor;\n\ + with none, no grant can ever verify and every transfer would be refused." + ); + std::process::exit(2); + } + let peer_policy = ahp_daemon::peer_auth::PeerPolicy::new(allowed, args.require_peer_auth) + .with_trust_anchors( + anchors, + args.require_grant, + identity.as_ref().map(|i| i.public_bytes()), + ); // Refuse to start in the configuration that hands an unauthenticated // peer arbitrary file write. Verified on 2026-08-11: with no @@ -181,14 +310,14 @@ async fn main() -> Result<(), Box> { // anybody. Leaving it listening while the UDP path demands an identity // would publish a door with no lock beside a door with one — the // policy would be worth nothing, and worse, it would read as enforced. - if args.require_peer_auth && !args.no_tcp_fallback { + if (args.require_peer_auth || args.require_grant) && !args.no_tcp_fallback { tracing::warn!( "--require-peer-auth disables the TCP fallback: it has no handshake and \ therefore no way to authenticate a sender. Transfers from clients whose \ network drops UDP will fail until they can reach the UDP port." ); } - if !args.no_tcp_fallback && !args.require_peer_auth { + if !args.no_tcp_fallback && !args.require_peer_auth && !args.require_grant { let fb_root = args.dest_root.clone(); match tokio::net::TcpListener::bind(control_addr).await { Ok(l) => { diff --git a/crates/ahp-daemon/src/net_receiver.rs b/crates/ahp-daemon/src/net_receiver.rs index aa4d662..10014fc 100644 --- a/crates/ahp-daemon/src/net_receiver.rs +++ b/crates/ahp-daemon/src/net_receiver.rs @@ -1918,6 +1918,10 @@ async fn handle_transfer( capabilities |= ahp_proto::hello::CAP_PEER_AUTH; } + // Set when the sender presented a grant that verified. Its path scope + // is applied after the MANIFEST names a destination — see below. + let mut permitted_paths: Option = None; + // ── Key exchange + HELLO_ACK ───────────────────────────────────────── let hello_flag = if !hello_payload.is_empty() { hello_payload[0] } else { 0x00 }; // HELLO_ACK payload: [1-byte mode] [mode material (DH material for full @@ -1935,14 +1939,25 @@ async fn handle_transfer( // derived or a socket is committed, so a refused sender costs // nothing but the packet it sent. let presented = hello.peer_auth.as_ref().map(|(id, sig)| (id, sig)); - match peer_policy.decide(presented, &peer_public, &peer_nonce) { - crate::peer_auth::Decision::Authenticated(id) => { + match peer_policy.decide( + presented, + hello.grant.as_deref(), + &peer_public, + &peer_nonce, + ahp_crypto::grant::now_unix(), + ) { + crate::peer_auth::Decision::Authenticated { identity, grant } => { tracing::info!( conn_id, peer = %peer, - identity = %ahp_crypto::signatures::hex_encode(&id[..4]), + identity = %ahp_crypto::signatures::hex_encode(&identity[..4]), + run = grant.as_ref().map(|g| g.grant().run_id.clone()), "sender authenticated" ); + // Held for the path check below: which paths this grant + // permits cannot be decided here, because the destination + // arrives in the MANIFEST. + permitted_paths = grant; } crate::peer_auth::Decision::Anonymous => {} crate::peer_auth::Decision::Refused(why) => { @@ -1997,6 +2012,32 @@ async fn handle_transfer( tracing::info!("encryption: X25519 + AES-256-GCM established (anonymous — no daemon identity)"); } (Some(keys), ack_payload) + } else if hello_flag == 0x02 && peer_policy.is_enforcing() { + // 0-RTT resume bypasses the authorisation checks entirely, so a + // daemon that enforces a policy refuses it and makes the sender do + // the full handshake. + // + // The existing note below is right that a resumed session inherits + // *server* authentication from the ticket: the client already chose + // to trust that daemon once. It does not follow for the other + // direction. A grant carries an expiry and a path prefix; a ticket + // carries neither, so honouring one would let a sender that was + // authorised for five minutes and one directory keep writing + // anywhere under --dest-root for as long as the ticket lived. + // + // Found by a test that transferred once within its grant and then + // wrote outside it, and succeeded: the second HELLO carried a + // ticket, so none of the checks above ran. + tracing::warn!( + conn_id, + peer = %peer, + "refusing a 0-RTT resume: this daemon enforces a peer policy, and a resumed \ + session carries no identity or grant to check" + ); + let _ = send_ctrl_with_payload( + ctrl_socket, peer, PacketType::Error, conn_id, seq, &[], + ).await; + return Ok(None); } else if hello_flag == 0x02 { // 0-RTT resume with session ticket. A successful resume carries the // fresh server nonce in the ack; the client mixes it into its key @@ -2063,6 +2104,30 @@ async fn handle_transfer( } } } + // The grant narrows what --dest-root already allows; it never widens + // it. Checked after confinement so the path compared is the rewritten + // absolute one — comparing the sender's own string would let `..` do + // the work the prefix check is there to prevent. + if let Some(grant) = &permitted_paths { + if !grant.permits_path(&manifest.dest_path) { + tracing::warn!( + conn_id, + peer = %peer, + dest = %manifest.dest_path, + prefix = %grant.grant().path_prefix, + run = %grant.grant().run_id, + "rejecting transfer: destination is outside the grant's path prefix" + ); + // Same reason-free ERROR as the handshake refusal: the sender + // fails immediately instead of retransmitting its manifest into + // silence, and what was permitted stays in this log. + let _ = send_ctrl_with_payload( + ctrl_socket, peer, PacketType::Error, conn_id, seq, &[], + ).await; + return Err("destination is outside the permitted path prefix".into()); + } + } + tracing::info!( file = %manifest.file_name, size = manifest.file_size, @@ -2385,7 +2450,14 @@ async fn handle_transfer( m.packets_sent.inc_by(n_received); } - if session_keys.is_some() && n_received >= manifest.total_chunks { + // Not issued at all when a policy is in force: the resume path refuses + // such tickets anyway, so handing one out would only teach the sender to + // attempt a reconnection this daemon will reject. Declining here keeps + // the two ends agreeing about what is possible. + if session_keys.is_some() + && n_received >= manifest.total_chunks + && !peer_policy.is_enforcing() + { if let Some(ref keys) = session_keys { let issued = ticket_key .lock() diff --git a/crates/ahp-daemon/src/peer_auth.rs b/crates/ahp-daemon/src/peer_auth.rs index 70ac398..d861f00 100644 --- a/crates/ahp-daemon/src/peer_auth.rs +++ b/crates/ahp-daemon/src/peer_auth.rs @@ -31,13 +31,20 @@ use std::collections::BTreeSet; +use ahp_crypto::grant::{Grant, VerifiedGrant}; use ahp_crypto::signatures::{hex_encode, VerifyingKeyRef}; /// What the daemon decided about a sender. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Decision { - /// The sender proved an identity that is on the allowlist. - Authenticated([u8; 32]), + /// The sender proved an identity the policy accepts, and — when it + /// presented one — a grant that checked out. The grant travels with the + /// decision because the path it permits cannot be checked yet: the + /// destination path arrives in the MANIFEST, after this handshake. + Authenticated { + identity: [u8; 32], + grant: Option, + }, /// The sender did not authenticate, and this daemon does not insist. /// The historical behaviour, and still the default. Anonymous, @@ -57,6 +64,17 @@ impl Decision { pub struct PeerPolicy { allowed: BTreeSet<[u8; 32]>, require: bool, + /// Public keys whose signature makes a grant worth reading. A list, not + /// one key, because that is what makes rotation possible without a flag + /// day: publish the new anchor, let daemons accept both, switch + /// issuance, retire the old one. + anchors: Vec<[u8; 32]>, + require_grant: bool, + /// This daemon's own identity. A grant names the daemon it was issued + /// for, and without knowing which daemon it is, this one cannot tell a + /// permission meant for it from a permission meant for another machine + /// trusting the same anchor. + own_identity: Option<[u8; 32]>, } impl PeerPolicy { @@ -69,13 +87,48 @@ impl PeerPolicy { /// unauthenticated ones still work, so the allowlist can be populated /// and verified before it starts turning anybody away. pub fn new(allowed: impl IntoIterator, require: bool) -> Self { - Self { allowed: allowed.into_iter().collect(), require } + Self { + allowed: allowed.into_iter().collect(), + require, + anchors: Vec::new(), + require_grant: false, + own_identity: None, + } + } + + /// Accept grants signed by `anchors`, addressed to `own_identity`. + /// + /// `require_grant` implies requiring authentication, and is forced here + /// rather than left to the caller: a grant names the sender it is for, + /// so demanding one from a sender that proved no identity would be + /// demanding a document nobody checked the bearer of. + pub fn with_trust_anchors( + mut self, + anchors: impl IntoIterator, + require_grant: bool, + own_identity: Option<[u8; 32]>, + ) -> Self { + self.anchors = anchors.into_iter().collect(); + self.require_grant = require_grant; + self.own_identity = own_identity; + if require_grant { + self.require = true; + } + self + } + + pub fn requires_grant(&self) -> bool { + self.require_grant + } + + pub fn anchor_count(&self) -> usize { + self.anchors.len() } /// Whether this daemon will turn anyone away. Used to decide whether /// to advertise the capability and what to say at startup. pub fn is_enforcing(&self) -> bool { - self.require || !self.allowed.is_empty() + self.require || !self.allowed.is_empty() || !self.anchors.is_empty() } pub fn allowed_count(&self) -> usize { @@ -90,8 +143,10 @@ impl PeerPolicy { pub fn decide( &self, presented: Option<(&[u8; 32], &[u8; 64])>, + grant_bytes: Option<&[u8]>, ephemeral_pub: &[u8; 32], nonce: &[u8], + now: u64, ) -> Decision { let Some((identity, signature)) = presented else { return if self.require { @@ -131,7 +186,48 @@ impl PeerPolicy { )); } - Decision::Authenticated(*identity) + // ── The grant, if this daemon deals in them ────────────────────── + let grant = match grant_bytes { + Some(bytes) if !self.anchors.is_empty() => { + // A daemon that accepts grants must know its own identity, + // or it cannot check that one was addressed to it. Treated + // as a refusal rather than as "skip the check": the + // alternative is accepting a permission meant for another + // machine. + let Some(destination) = self.own_identity else { + return Decision::Refused( + "a grant was presented but this daemon has no --identity, so it \ + cannot tell whether the grant was issued for it" + .into(), + ); + }; + match Grant::verify(bytes, &self.anchors, &destination, identity, now) { + Ok(v) => Some(v), + Err(e) => { + return Decision::Refused(format!( + "sender {} presented a grant that did not check out: {e}", + hex_encode(&identity[..4]) + )) + } + } + } + // Presented one, but this daemon trusts nobody to issue them, so + // there is nothing to verify it against. Ignored rather than + // refused: the sender may simply be talking to a daemon that + // does not use grants, which is not its mistake. + Some(_) => None, + None => None, + }; + + if self.require_grant && grant.is_none() { + return Decision::Refused(format!( + "sender {} authenticated but presented no valid grant, and this daemon \ + requires one", + hex_encode(&identity[..4]) + )); + } + + Decision::Authenticated { identity: *identity, grant } } } @@ -142,6 +238,13 @@ mod tests { const EPH: [u8; 32] = [7u8; 32]; const NONCE: [u8; 16] = [9u8; 16]; + /// Any time after the clock-sanity floor; grants below set their own. + const NOW: u64 = 1_800_000_000; + + /// `decide` for the cases that involve no grant. + fn decide(p: &PeerPolicy, presented: Option<(&[u8; 32], &[u8; 64])>) -> Decision { + p.decide(presented, None, &EPH, &NONCE, NOW) + } fn offer(id: &SigningIdentity) -> ([u8; 32], [u8; 64]) { (id.public_bytes(), id.sign_client_offer(&EPH, &NONCE)) @@ -153,13 +256,13 @@ mod tests { // the daemon breaks every existing deployment. let p = PeerPolicy::default(); assert!(!p.is_enforcing()); - assert_eq!(p.decide(None, &EPH, &NONCE), Decision::Anonymous); + assert_eq!(decide(&p, None), Decision::Anonymous); } #[test] fn requiring_auth_refuses_a_sender_that_offers_none() { let p = PeerPolicy::new([], true); - assert!(p.decide(None, &EPH, &NONCE).is_refused()); + assert!(decide(&p, None).is_refused()); } #[test] @@ -169,7 +272,7 @@ mod tests { let id = SigningIdentity::generate(); let (pk, sig) = offer(&id); let p = PeerPolicy::new([], true); - assert_eq!(p.decide(Some((&pk, &sig)), &EPH, &NONCE), Decision::Authenticated(pk)); + assert_eq!(decide(&p, Some((&pk, &sig))), Decision::Authenticated { identity: pk, grant: None }); } #[test] @@ -177,7 +280,7 @@ mod tests { let id = SigningIdentity::generate(); let (pk, sig) = offer(&id); let p = PeerPolicy::new([pk], true); - assert_eq!(p.decide(Some((&pk, &sig)), &EPH, &NONCE), Decision::Authenticated(pk)); + assert_eq!(decide(&p, Some((&pk, &sig))), Decision::Authenticated { identity: pk, grant: None }); } #[test] @@ -188,7 +291,7 @@ mod tests { let stranger = SigningIdentity::generate(); let (pk, sig) = offer(&stranger); let p = PeerPolicy::new([allowed.public_bytes()], true); - assert!(p.decide(Some((&pk, &sig)), &EPH, &NONCE).is_refused()); + assert!(decide(&p, Some((&pk, &sig))).is_refused()); } #[test] @@ -200,7 +303,7 @@ mod tests { let pk = allowed.public_bytes(); let sig = attacker.sign_client_offer(&EPH, &NONCE); let p = PeerPolicy::new([pk], true); - let d = p.decide(Some((&pk, &sig)), &EPH, &NONCE); + let d = decide(&p, Some((&pk, &sig))); assert!(d.is_refused(), "{d:?}"); // Refused for the signature, not for membership — otherwise the // check order would leak whether that key is on the list. @@ -215,8 +318,8 @@ mod tests { let id = SigningIdentity::generate(); let (pk, sig) = offer(&id); let p = PeerPolicy::new([pk], true); - assert!(p.decide(Some((&pk, &sig)), &[8u8; 32], &NONCE).is_refused()); - assert!(p.decide(Some((&pk, &sig)), &EPH, &[10u8; 16]).is_refused()); + assert!(p.decide(Some((&pk, &sig)), None, &[8u8; 32], &NONCE, NOW).is_refused()); + assert!(p.decide(Some((&pk, &sig)), None, &EPH, &[10u8; 16], NOW).is_refused()); } #[test] @@ -227,7 +330,7 @@ mod tests { let id = SigningIdentity::generate(); let p = PeerPolicy::new([id.public_bytes()], false); assert!(p.is_enforcing()); - assert_eq!(p.decide(None, &EPH, &NONCE), Decision::Anonymous); + assert_eq!(decide(&p, None), Decision::Anonymous); } #[test] @@ -236,7 +339,7 @@ mod tests { let stranger = SigningIdentity::generate(); let (pk, sig) = offer(&stranger); let p = PeerPolicy::new([allowed.public_bytes()], false); - assert!(p.decide(Some((&pk, &sig)), &EPH, &NONCE).is_refused()); + assert!(decide(&p, Some((&pk, &sig))).is_refused()); } #[test] @@ -244,7 +347,153 @@ mod tests { // All-zeros is not a valid Ed25519 point. It is also the first // thing anybody tries. let p = PeerPolicy::new([], true); - let d = p.decide(Some((&[0u8; 32], &[0u8; 64])), &EPH, &NONCE); + let d = decide(&p, Some((&[0u8; 32], &[0u8; 64]))); assert!(d.is_refused(), "{d:?}"); } + + // ── Grants ──────────────────────────────────────────────────────────── + + use ahp_crypto::grant::Grant; + + fn a_grant(source: [u8; 32], destination: [u8; 32], prefix: &str) -> Grant { + Grant { + source, + destination, + not_after: NOW + 300, + run_id: "run-1".into(), + path_prefix: prefix.into(), + } + } + + struct GrantFixture { + anchor: SigningIdentity, + client: SigningIdentity, + daemon_id: [u8; 32], + } + + fn grant_fixture() -> GrantFixture { + GrantFixture { + anchor: SigningIdentity::generate(), + client: SigningIdentity::generate(), + daemon_id: SigningIdentity::generate().public_bytes(), + } + } + + fn policy_with_grants(f: &GrantFixture, require_grant: bool) -> PeerPolicy { + PeerPolicy::new([], true).with_trust_anchors( + [f.anchor.public_bytes()], + require_grant, + Some(f.daemon_id), + ) + } + + #[test] + fn a_valid_grant_is_carried_into_the_decision() { + let f = grant_fixture(); + let (pk, sig) = offer(&f.client); + let bytes = a_grant(pk, f.daemon_id, "/srv/in").sign(&f.anchor); + let p = policy_with_grants(&f, true); + match p.decide(Some((&pk, &sig)), Some(&bytes), &EPH, &NONCE, NOW) { + Decision::Authenticated { grant: Some(g), .. } => { + // The path scope has to survive to the caller: it is applied + // later, when the manifest names a destination. + assert!(g.permits_path("/srv/in/a.bin")); + assert!(!g.permits_path("/etc/cron.d/pwn")); + } + other => panic!("expected an authenticated decision with a grant: {other:?}"), + } + } + + #[test] + fn requiring_a_grant_refuses_a_sender_that_brings_none() { + let f = grant_fixture(); + let (pk, sig) = offer(&f.client); + let p = policy_with_grants(&f, true); + assert!(p.decide(Some((&pk, &sig)), None, &EPH, &NONCE, NOW).is_refused()); + } + + #[test] + fn a_grant_issued_to_another_sender_is_refused() { + // The grant must be bound to the identity that actually + // authenticated, or a grant captured off the wire would be usable by + // anyone who replayed it. + let f = grant_fixture(); + let (pk, sig) = offer(&f.client); + let someone_else = SigningIdentity::generate().public_bytes(); + let bytes = a_grant(someone_else, f.daemon_id, "/srv/in").sign(&f.anchor); + let p = policy_with_grants(&f, true); + assert!(p.decide(Some((&pk, &sig)), Some(&bytes), &EPH, &NONCE, NOW).is_refused()); + } + + #[test] + fn a_grant_from_an_untrusted_issuer_is_refused() { + let f = grant_fixture(); + let (pk, sig) = offer(&f.client); + let bytes = a_grant(pk, f.daemon_id, "/srv/in").sign(&SigningIdentity::generate()); + let p = policy_with_grants(&f, true); + assert!(p.decide(Some((&pk, &sig)), Some(&bytes), &EPH, &NONCE, NOW).is_refused()); + } + + #[test] + fn an_expired_grant_is_refused() { + let f = grant_fixture(); + let (pk, sig) = offer(&f.client); + let bytes = a_grant(pk, f.daemon_id, "/srv/in").sign(&f.anchor); + let p = policy_with_grants(&f, true); + assert!(p.decide(Some((&pk, &sig)), Some(&bytes), &EPH, &NONCE, NOW + 301).is_refused()); + } + + #[test] + fn a_daemon_with_no_identity_refuses_a_grant_rather_than_skipping_the_check() { + // It cannot tell whether the grant was addressed to it. Skipping + // would accept a permission meant for another machine. + let f = grant_fixture(); + let (pk, sig) = offer(&f.client); + let bytes = a_grant(pk, f.daemon_id, "/srv/in").sign(&f.anchor); + let p = PeerPolicy::new([], true) + .with_trust_anchors([f.anchor.public_bytes()], true, None); + assert!(p.decide(Some((&pk, &sig)), Some(&bytes), &EPH, &NONCE, NOW).is_refused()); + } + + #[test] + fn requiring_a_grant_also_requires_authentication() { + // A grant names its bearer. Demanding one from a sender that proved + // nothing would be demanding a document nobody checked the bearer + // of, so the constructor forces the stricter of the two. + let f = grant_fixture(); + let p = PeerPolicy::new([], false) + .with_trust_anchors([f.anchor.public_bytes()], true, Some(f.daemon_id)); + assert!(p.decide(None, None, &EPH, &NONCE, NOW).is_refused()); + } + + #[test] + fn a_daemon_with_no_anchors_ignores_a_grant_rather_than_refusing_it() { + // The sender may just be talking to a daemon that does not use + // grants. That is not the sender's mistake, and refusing would make + // a client configured for one estate unusable against another. + let f = grant_fixture(); + let (pk, sig) = offer(&f.client); + let bytes = a_grant(pk, f.daemon_id, "/srv/in").sign(&f.anchor); + let p = PeerPolicy::new([pk], true); + match p.decide(Some((&pk, &sig)), Some(&bytes), &EPH, &NONCE, NOW) { + Decision::Authenticated { grant, .. } => assert!(grant.is_none()), + other => panic!("expected acceptance without a grant: {other:?}"), + } + } + + #[test] + fn any_configured_anchor_may_have_issued_the_grant() { + // Rotation, at the policy layer: both anchors are accepted during + // the overlap, so the estate is never reconfigured in one window. + let f = grant_fixture(); + let retiring = SigningIdentity::generate(); + let (pk, sig) = offer(&f.client); + let bytes = a_grant(pk, f.daemon_id, "/srv/in").sign(&retiring); + let p = PeerPolicy::new([], true).with_trust_anchors( + [f.anchor.public_bytes(), retiring.public_bytes()], + true, + Some(f.daemon_id), + ); + assert!(!p.decide(Some((&pk, &sig)), Some(&bytes), &EPH, &NONCE, NOW).is_refused()); + } } diff --git a/crates/ahp-proto/src/hello.rs b/crates/ahp-proto/src/hello.rs index 9ac9edd..e6309fa 100644 --- a/crates/ahp-proto/src/hello.rs +++ b/crates/ahp-proto/src/hello.rs @@ -193,6 +193,7 @@ pub fn encode_hello_full( ephemeral_pub: &[u8; 32], nonce: &[u8; 16], peer_auth: Option<(&[u8; 32], &[u8; 64])>, + grant: Option<&[u8]>, ) -> Vec { let mut buf = Vec::with_capacity(HELLO_FULL_DH_LEN + PEER_AUTH_LEN); buf.push(HELLO_FULL_DH); @@ -201,12 +202,21 @@ pub fn encode_hello_full( if let Some((identity_pub, signature)) = peer_auth { buf.extend_from_slice(identity_pub); buf.extend_from_slice(signature); + // Length-prefixed, and only ever after auth material: a grant names + // the sender it is for, so one arriving without a proven identity + // could not be checked against anything and has no meaning. The + // encoder refuses to produce that shape rather than leaving the + // decoder to decide what it would mean. + if let Some(grant) = grant { + buf.extend_from_slice(&(grant.len() as u16).to_be_bytes()); + buf.extend_from_slice(grant); + } } buf } /// A parsed full-DH HELLO. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq)] pub struct HelloFull { pub ephemeral_pub: [u8; 32], pub nonce: [u8; 16], @@ -214,6 +224,11 @@ pub struct HelloFull { /// Absent means the client did not authenticate — which is every client /// built before this existed, and is not by itself an error. pub peer_auth: Option<([u8; 32], [u8; 64])>, + /// An opaque signed permission, when the client presented one. This + /// crate does not interpret it: parsing and checking belong to whatever + /// holds the trust anchors, and a wire format that understood the + /// contents would have to be revised every time they changed. + pub grant: Option>, } /// Decode a full-DH HELLO payload. `None` when it is not one, or is short. @@ -232,16 +247,31 @@ pub fn decode_hello_full(payload: &[u8]) -> Option { nonce.copy_from_slice(&payload[33..HELLO_FULL_DH_LEN]); let auth_end = HELLO_FULL_DH_LEN + PEER_AUTH_LEN; - let peer_auth = if payload.len() >= auth_end { + let mut peer_auth = None; + let mut grant = None; + if payload.len() >= auth_end { let mut identity_pub = [0u8; 32]; identity_pub.copy_from_slice(&payload[HELLO_FULL_DH_LEN..HELLO_FULL_DH_LEN + 32]); let mut signature = [0u8; 64]; signature.copy_from_slice(&payload[HELLO_FULL_DH_LEN + 32..auth_end]); - Some((identity_pub, signature)) - } else { - None - }; - Some(HelloFull { ephemeral_pub, nonce, peer_auth }) + peer_auth = Some((identity_pub, signature)); + + // A grant, if one follows. A truncated or over-long length reads as + // "no grant" rather than as an error: this is an append point, and a + // decoder that rejected what it could not fully parse would make the + // next extension a breaking change. A daemon that requires a grant + // refuses the absence, which is where that decision belongs. + if let Some(len_bytes) = payload.get(auth_end..auth_end + 2) { + let len = u16::from_be_bytes([len_bytes[0], len_bytes[1]]) as usize; + let start = auth_end + 2; + if let Some(bytes) = payload.get(start..start + len) { + if len > 0 { + grant = Some(bytes.to_vec()); + } + } + } + } + Some(HelloFull { ephemeral_pub, nonce, peer_auth, grant }) } /// Magic + bitfield. @@ -641,8 +671,8 @@ mod tests { /// reads out of an unauthenticated one. #[test] fn appending_client_auth_does_not_disturb_the_fixed_prefix() { - let plain = encode_hello_full(&EPH, &HN, None); - let authed = encode_hello_full(&EPH, &HN, Some((&CID, &CSIG))); + let plain = encode_hello_full(&EPH, &HN, None, None); + let authed = encode_hello_full(&EPH, &HN, Some((&CID, &CSIG)), None); assert_eq!(plain.len(), HELLO_FULL_DH_LEN); assert_eq!( @@ -658,7 +688,7 @@ mod tests { #[test] fn client_auth_round_trips() { - let buf = encode_hello_full(&EPH, &HN, Some((&CID, &CSIG))); + let buf = encode_hello_full(&EPH, &HN, Some((&CID, &CSIG)), None); let got = decode_hello_full(&buf).expect("decodes"); assert_eq!(got.ephemeral_pub, EPH); assert_eq!(got.nonce, HN); @@ -669,7 +699,7 @@ mod tests { fn an_unauthenticated_hello_reports_no_peer_auth() { // The negative control: without it the test above passes for a // decoder that invents auth material. - let buf = encode_hello_full(&EPH, &HN, None); + let buf = encode_hello_full(&EPH, &HN, None, None); assert_eq!(decode_hello_full(&buf).expect("decodes").peer_auth, None); } @@ -678,7 +708,7 @@ mod tests { // A half-written append must never decode into a partial identity // that then fails verification for the wrong reason — or worse, // matches something. - let mut buf = encode_hello_full(&EPH, &HN, Some((&CID, &CSIG))); + let mut buf = encode_hello_full(&EPH, &HN, Some((&CID, &CSIG)), None); buf.truncate(HELLO_FULL_DH_LEN + 40); assert_eq!(decode_hello_full(&buf).expect("decodes").peer_auth, None); } @@ -688,7 +718,7 @@ mod tests { assert!(decode_hello_full(&[]).is_none()); assert!(decode_hello_full(&[0x00]).is_none()); // Right flag, one byte short of the fixed prefix. - let mut buf = encode_hello_full(&EPH, &HN, None); + let mut buf = encode_hello_full(&EPH, &HN, None, None); buf.truncate(HELLO_FULL_DH_LEN - 1); assert!(decode_hello_full(&buf).is_none()); } @@ -703,4 +733,58 @@ mod tests { assert_eq!(data_port_count(both), 4, "the count survives the new bit"); assert!(both & CAP_PEER_AUTH != 0); } + + // ── HELLO carrying a grant ──────────────────────────────────────────── + + #[test] + fn a_grant_round_trips_after_the_auth_material() { + let grant = b"opaque signed permission".to_vec(); + let buf = encode_hello_full(&EPH, &HN, Some((&CID, &CSIG)), Some(&grant)); + let got = decode_hello_full(&buf).expect("decodes"); + assert_eq!(got.peer_auth, Some((CID, CSIG))); + assert_eq!(got.grant.as_deref(), Some(&grant[..])); + } + + #[test] + fn a_grant_does_not_disturb_what_older_peers_read() { + // The same compatibility property as the auth append, one layer out: + // a daemon that predates grants reads the fixed prefix, then the + // auth material it does understand, and ignores the rest. + let grant = b"opaque".to_vec(); + let with = encode_hello_full(&EPH, &HN, Some((&CID, &CSIG)), Some(&grant)); + let without = encode_hello_full(&EPH, &HN, Some((&CID, &CSIG)), None); + assert_eq!(&with[..without.len()], &without[..]); + let older_view = decode_hello_full(&without).expect("decodes"); + assert_eq!(older_view.peer_auth, Some((CID, CSIG))); + assert_eq!(older_view.grant, None); + } + + #[test] + fn a_grant_without_auth_material_is_never_encoded() { + // A grant names the sender it is for. Without a proven identity + // there is nothing to check it against, so the shape is refused at + // the encoder rather than left for a decoder to interpret. + let grant = b"opaque".to_vec(); + let buf = encode_hello_full(&EPH, &HN, None, Some(&grant)); + assert_eq!(buf.len(), HELLO_FULL_DH_LEN); + assert_eq!(decode_hello_full(&buf).expect("decodes").grant, None); + } + + #[test] + fn a_truncated_grant_reads_as_absent_not_as_a_short_grant() { + // A half-arrived grant must not verify against anything. Absent is + // the safe reading: a daemon requiring one refuses. + let grant = b"opaque signed permission".to_vec(); + let mut buf = encode_hello_full(&EPH, &HN, Some((&CID, &CSIG)), Some(&grant)); + buf.truncate(buf.len() - 4); + let got = decode_hello_full(&buf).expect("decodes"); + assert_eq!(got.peer_auth, Some((CID, CSIG)), "auth survives"); + assert_eq!(got.grant, None, "a partial grant was surfaced"); + } + + #[test] + fn a_zero_length_grant_is_absent() { + let buf = encode_hello_full(&EPH, &HN, Some((&CID, &CSIG)), Some(&[])); + assert_eq!(decode_hello_full(&buf).expect("decodes").grant, None); + } }