diff --git a/CHANGELOG.md b/CHANGELOG.md index b6febf1d7..91e1ba4ff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,11 @@ starts with **Upgrade notes**: read them before you upgrade. The upgrade procedu ### Upgrade notes +- **Sessions cannot reach private addresses through the egress proxy.** The proxy now + refuses to connect to an allow-listed host whose name resolves to a loopback, private + (RFC 1918, CGNAT), link-local, metadata or other reserved address. A Git server, package + registry or other service that resolves only to such an address in your network is no + longer reachable from sessions, and no setting turns this off. ([#1849]) - **The GitHub `metadata:read` power covers less.** It gave every `GET` under `/repos///`. It now gives the repository itself and the metadata endpoints (events, forks, license, stargazers, subscribers, stats, rules, rulesets, topics, @@ -444,3 +449,4 @@ The first tagged release. See the [#1822]: https://github.com/cortexapps/engrams/pull/1822 [#1825]: https://github.com/cortexapps/engrams/pull/1825 [#1826]: https://github.com/cortexapps/engrams/pull/1826 +[#1849]: https://github.com/cortexapps/engrams/pull/1849 diff --git a/crates/engram-egress-proxy/src/bypass.rs b/crates/engram-egress-proxy/src/bypass.rs index f0f8779b4..e96904943 100644 --- a/crates/engram-egress-proxy/src/bypass.rs +++ b/crates/engram-egress-proxy/src/bypass.rs @@ -13,9 +13,8 @@ use std::sync::Arc; use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt}; -use tokio::net::TcpStream; -use crate::resolver::{ResolveError, UpstreamResolver}; +use crate::resolver::{connect_upstream, ResolveError, UpstreamResolver}; /// Splice `client` ↔ `upstream`. The proxy dials upstream by SNI /// (resolved via `resolver`) — *not* by `SO_ORIGINAL_DST`. This @@ -35,7 +34,7 @@ where C: AsyncRead + AsyncWrite + Unpin, { let upstream_addr = resolver.resolve(sni, port).await?; - let mut upstream = TcpStream::connect(upstream_addr).await?; + let mut upstream = connect_upstream(upstream_addr).await?; upstream.write_all(&peeked).await?; upstream.flush().await?; tokio::io::copy_bidirectional(&mut client, &mut upstream) diff --git a/crates/engram-egress-proxy/src/dns.rs b/crates/engram-egress-proxy/src/dns.rs index 99738feeb..31da13230 100644 --- a/crates/engram-egress-proxy/src/dns.rs +++ b/crates/engram-egress-proxy/src/dns.rs @@ -1,43 +1,13 @@ -//! Filtering DNS proxy for guest microVMs. -//! -//! The TCP/443 proxy enforces `manifest.network.allow_hosts` at SNI -//! peek time — but DNS itself was an unconditional ACCEPT to 1.1.1.1 -//! at the iptables layer, which is a classic exfil channel: a -//! compromised harness can encode data into subdomains of an -//! attacker-controlled name and queries leave the host even when -//! every TCP connection downstream is blocked. This module closes -//! that channel by REDIRECTing both `udp/53` and `tcp/53` to a -//! filtering DNS proxy that resolves only names already in -//! `allow_hosts` (the same `HostList` the TCP/443 path uses). -//! -//! Wire shape: -//! - **UDP** (the common case): receive a query, parse it via -//! `hickory-proto`, pull the first QNAME, check it against the -//! `SessionState` looked up by source-IP. Allowed → forward -//! verbatim to an upstream resolver and ship the response back -//! over the same socket. Denied → synthesize an `NXDOMAIN` -//! response (preserving the query's EDNS OPT if any) and send it -//! back. Queries from unknown source IPs (no `SessionState`) are -//! denied — we silently NXDOMAIN them so the guest's resolver -//! bails fast instead of timing out. -//! - **TCP** (the >512-byte fallback): same logic, with the 2-byte -//! length prefix DNS-over-TCP adds. -//! -//! Why this matters even though the FORWARD chain default-DROPs -//! everything: without this, the only thing protecting against -//! exfil was the *explicit* `ACCEPT VM→1.1.1.1:53` iptables rules, -//! which had to exist for any DNS to work. Removing those rules -//! and routing all DNS through this proxy means a guest can only -//! resolve names that the manifest's `allow_hosts` already permits -//! a TCP connection to. Resolution and connection are filtered -//! against the same list. +//! DNS proxy that applies each guest's hostname policy to one question per query. +//! UDP queries use random, unique upstream IDs; replies restore the guest's original ID. +//! TCP queries use a separate upstream connection for each exchange. use std::collections::HashMap; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; -use std::sync::Arc; +use std::sync::{Arc, LazyLock}; use std::time::Duration; -use hickory_proto::op::{Message, MessageType, ResponseCode}; +use hickory_proto::op::{Message, MessageType, Query, ResponseCode}; use hickory_proto::serialize::binary::BinDecodable; use parking_lot::Mutex; use tokio::io::{AsyncReadExt, AsyncWriteExt}; @@ -53,9 +23,7 @@ pub const DEFAULT_UPSTREAM: &str = "1.1.1.1:53"; /// what glibc's resolver does before retrying. const UDP_UPSTREAM_TIMEOUT: Duration = Duration::from_secs(5); -/// How long we'll wait on an upstream TCP exchange. TCP DNS is the -/// fallback for truncated UDP, so it should be at least as -/// patient as a fresh UDP retry. +/// Deadline for one upstream TCP exchange, connect through response. const TCP_UPSTREAM_TIMEOUT: Duration = Duration::from_secs(10); /// Max DNS message size we'll buffer. EDNS bumps the typical 512 @@ -71,19 +39,14 @@ pub async fn serve_udp( registry: Arc, upstream_addr: SocketAddr, ) -> std::io::Result<()> { - // One bound upstream socket per process. Responses come back - // here keyed by the DNS message ID; the demux loop dispatches - // them to the per-query reply targets. Production recursive - // resolvers randomize source ports for spoofing resistance; we - // sit host-side and only talk to a trusted upstream, so a - // single bound socket is fine. + // A shared socket carries queries with distinct upstream transaction IDs. let upstream = Arc::new(UdpSocket::bind("0.0.0.0:0").await?); tracing::info!( listen = %socket.local_addr()?, upstream = %upstream_addr, "engram-egress-proxy DNS/udp serving", ); - let pending: PendingMap = Arc::new(Mutex::new(HashMap::new())); + let pending = Arc::new(Mutex::new(PendingQueries::default())); // Demux loop: read upstream responses, look up the original // peer by message ID, send the bytes back. One task for the @@ -94,20 +57,17 @@ pub async fn serve_udp( tokio::spawn(async move { let mut buf = vec![0u8; MAX_DGRAM]; loop { - let (n, _) = match demux_upstream.recv_from(&mut buf).await { + let (n, src) = match demux_upstream.recv_from(&mut buf).await { Ok(p) => p, Err(e) => { tracing::warn!(error = %e, "upstream DNS recv failed; demux halting"); return; } }; - // DNS message ID is the first two bytes of the header. - if n < 12 { - continue; - } - let id = u16::from_be_bytes([buf[0], buf[1]]); - let entry = demux_pending.lock().remove(&id); - if let Some(peer) = entry { + let peer = demux_pending + .lock() + .accept_response(&mut buf[..n], src, upstream_addr); + if let Some(peer) = peer { let _ = demux_socket.send_to(&buf[..n], peer).await; } } @@ -136,11 +96,112 @@ pub async fn serve_udp( } } -type PendingMap = Arc>>; +type PendingMap = Arc>; + +struct PendingQuery { + peer: SocketAddr, + guest_id: u16, + question: Query, +} + +static SECURE_RANDOM: LazyLock<&'static dyn rustls::crypto::SecureRandom> = + LazyLock::new(|| rustls::crypto::ring::default_provider().secure_random); + +/// Upper bound on one guest's in-flight UDP queries, so one guest cannot +/// use all 65536 upstream IDs and deny DNS to the other guests on the host. +const MAX_PENDING_PER_GUEST: usize = 1024; + +#[derive(Default)] +struct PendingQueries { + entries: HashMap>, + per_guest: HashMap, +} + +impl PendingQueries { + /// Allocate an unpredictable upstream ID. An off-path sender must guess + /// it (and the source port) to forge a reply. + fn insert(&mut self, peer: SocketAddr, query: &Message) -> Option<(u16, Arc)> { + let mut start = [0u8; 2]; + SECURE_RANDOM.fill(&mut start).ok()?; + self.insert_from(u16::from_be_bytes(start), peer, query) + } + + /// Take the first free ID at or after `start`. + fn insert_from( + &mut self, + start: u16, + peer: SocketAddr, + query: &Message, + ) -> Option<(u16, Arc)> { + let question = query.queries().first()?.clone(); + if self.entries.len() > usize::from(u16::MAX) + || self.per_guest.get(&peer.ip()).copied().unwrap_or(0) >= MAX_PENDING_PER_GUEST + { + return None; + } + let mut id = start; + while self.entries.contains_key(&id) { + id = id.wrapping_add(1); + } + let entry = Arc::new(PendingQuery { + peer, + guest_id: query.id(), + question, + }); + self.entries.insert(id, entry.clone()); + *self.per_guest.entry(peer.ip()).or_default() += 1; + Some((id, entry)) + } + + fn remove(&mut self, id: u16) -> Option> { + let entry = self.entries.remove(&id)?; + if let std::collections::hash_map::Entry::Occupied(mut count) = + self.per_guest.entry(entry.peer.ip()) + { + *count.get_mut() -= 1; + if *count.get() == 0 { + count.remove(); + } + } + Some(entry) + } + + fn remove_if_current(&mut self, id: u16, token: &Arc) { + // The token remains alive until its timeout, even after an ID is reused. + if self + .entries + .get(&id) + .is_some_and(|entry| Arc::ptr_eq(entry, token)) + { + self.remove(id); + } + } + + fn accept_response( + &mut self, + packet: &mut [u8], + source: SocketAddr, + upstream: SocketAddr, + ) -> Option { + if source != upstream { + return None; + } + let response = Message::from_bytes(packet).ok()?; + let entry = self.entries.get(&response.id())?; + if response.message_type() != MessageType::Response + || response.queries() != std::slice::from_ref(&entry.question) + { + return None; + } + let entry = self.remove(response.id())?; + packet[..2].copy_from_slice(&entry.guest_id.to_be_bytes()); + Some(entry.peer) + } +} #[allow(clippy::too_many_arguments)] async fn handle_udp( - pkt: Vec, + mut pkt: Vec, peer: SocketAddr, registry: Arc, socket: Arc, @@ -161,17 +222,21 @@ async fn handle_udp( }; match decide(®istry, guest_ip, &query) { Decision::Allow => { - // Hold a slot for the upstream response before send to - // avoid racing the demux loop. Reaped by the timeout - // sweep below if no reply lands within UDP_UPSTREAM_TIMEOUT. - let id = query.id(); - pending.lock().insert(id, peer); + let allocation = pending.lock().insert(peer, &query); + let Some((id, token)) = allocation else { + let response = build_response(&query, ResponseCode::ServFail); + if let Ok(bytes) = response.to_vec() { + let _ = socket.send_to(&bytes, peer).await; + } + return; + }; + pkt[..2].copy_from_slice(&id.to_be_bytes()); if let Err(e) = upstream.send_to(&pkt, upstream_addr).await { tracing::debug!( peer = %peer, error = %e, "upstream DNS send failed", ); - pending.lock().remove(&id); + pending.lock().remove_if_current(id, &token); return; } // Reaper: if upstream never replies, drop the pending @@ -180,7 +245,7 @@ async fn handle_udp( let pending_for_reap = pending.clone(); tokio::spawn(async move { tokio::time::sleep(UDP_UPSTREAM_TIMEOUT).await; - pending_for_reap.lock().remove(&id); + pending_for_reap.lock().remove_if_current(id, &token); }); } Decision::Deny(reason) => { @@ -188,13 +253,13 @@ async fn handle_udp( peer = %peer, qname = ?query.queries().first().map(|q| q.name().to_utf8()), reason = ?reason, - "DNS denied; responding NXDOMAIN", + "DNS query denied", ); - let resp = build_nxdomain(&query); + let resp = build_response(&query, reason.response_code()); let bytes = match resp.to_vec() { Ok(b) => b, Err(e) => { - tracing::warn!(peer = %peer, error = %e, "encode NXDOMAIN failed"); + tracing::warn!(peer = %peer, error = %e, "encode DNS denial failed"); return; } }; @@ -266,11 +331,11 @@ async fn handle_tcp( stream.write_all(&resp).await?; stream.flush().await?; } - Decision::Deny(_) => { - let resp = build_nxdomain(&query); + Decision::Deny(reason) => { + let resp = build_response(&query, reason.response_code()); let bytes = resp .to_vec() - .map_err(|e| std::io::Error::other(format!("encode NXDOMAIN: {e}")))?; + .map_err(|e| std::io::Error::other(format!("encode DNS denial: {e}")))?; let len = u16::try_from(bytes.len()).map_err(std::io::Error::other)?; stream.write_all(&len.to_be_bytes()).await?; stream.write_all(&bytes).await?; @@ -281,9 +346,16 @@ async fn handle_tcp( } async fn forward_tcp(query_bytes: &[u8], upstream_addr: SocketAddr) -> std::io::Result> { - let mut up = tokio::time::timeout(TCP_UPSTREAM_TIMEOUT, TcpStream::connect(upstream_addr)) - .await - .map_err(|_| std::io::Error::other("upstream connect timeout"))??; + tokio::time::timeout( + TCP_UPSTREAM_TIMEOUT, + exchange_tcp(query_bytes, upstream_addr), + ) + .await + .map_err(|_| std::io::Error::new(std::io::ErrorKind::TimedOut, "upstream DNS timeout"))? +} + +async fn exchange_tcp(query_bytes: &[u8], upstream_addr: SocketAddr) -> std::io::Result> { + let mut up = TcpStream::connect(upstream_addr).await?; let len = u16::try_from(query_bytes.len()).map_err(std::io::Error::other)?; up.write_all(&len.to_be_bytes()).await?; up.write_all(query_bytes).await?; @@ -310,17 +382,26 @@ enum Decision { #[derive(Debug)] enum DenyReason { UnknownGuest, - NoQuery, + InvalidQuestionCount, NotInAllowList, } +impl DenyReason { + fn response_code(&self) -> ResponseCode { + match self { + Self::InvalidQuestionCount => ResponseCode::FormErr, + Self::UnknownGuest | Self::NotInAllowList => ResponseCode::NXDomain, + } + } +} + fn decide(registry: &Registry, guest_ip: Ipv4Addr, query: &Message) -> Decision { + let [q] = query.queries() else { + return Decision::Deny(DenyReason::InvalidQuestionCount); + }; let Some(state) = registry.lookup(guest_ip) else { return Decision::Deny(DenyReason::UnknownGuest); }; - let Some(q) = query.queries().first() else { - return Decision::Deny(DenyReason::NoQuery); - }; let qname = q .name() .to_utf8() @@ -333,21 +414,7 @@ fn decide(registry: &Registry, guest_ip: Ipv4Addr, query: &Message) -> Decision } } -/// May the guest resolve this name? -/// -/// This must answer the same question [`SessionState::decide`] answers for TCP, -/// or a host the proxy is willing to intercept is one the guest cannot look up. -/// A resolvable-but-refused name is fine (the connection is dropped); a -/// reachable-but-unresolvable one is a broken integration. -/// -/// So every source of reachability counts: the network allow-list, and any -/// secret, injection or observe spec that names the host. Injections used to be -/// missing, which only worked because a Google or Datadog host was ALSO in the -/// network allow-list. ADR 0109 stopped adding a Google host there — a failed -/// mint must leave nothing reachable — and that immediately made the inject -/// hosts unresolvable. -/// -/// A credential-exchange host is refused outright, matching `decide()`. +/// Apply the same host reachability rules as the TCP proxy. fn name_allowed(state: &SessionState, qname: &str) -> bool { // ADR 0118: the session's OWN apps resolve unconditionally — before the // deny-list and before the allow-list. A sibling app is not an egress @@ -369,14 +436,14 @@ fn name_allowed(state: &SessionState, qname: &str) -> bool { || state.observes.iter().any(|o| o.allow.matches(qname)) } -fn build_nxdomain(query: &Message) -> Message { +fn build_response(query: &Message, code: ResponseCode) -> Message { let mut resp = Message::new(); resp.set_id(query.id()); resp.set_message_type(MessageType::Response); resp.set_op_code(query.op_code()); resp.set_recursion_desired(query.recursion_desired()); resp.set_recursion_available(true); - resp.set_response_code(ResponseCode::NXDomain); + resp.set_response_code(code); for q in query.queries() { resp.add_query(q.clone()); } @@ -414,6 +481,265 @@ mod tests { r } + fn local_registry() -> Arc { + registry_with(SessionState { + session_id: SessionId::new(), + sandbox_id: engram_core::SandboxId::new(), + guest_ip: Ipv4Addr::LOCALHOST, + allow_all: false, + network_allow: HostList::from_manifest(&[], &["*.allowed.example".into()]).unwrap(), + secrets: Vec::new(), + injects: Vec::new(), + observes: Vec::new(), + guest_services: Vec::new(), + tunnels: Vec::new(), + apps: Vec::new(), + }) + } + + #[test] + fn same_guest_id_maps_to_distinct_pending_replies() { + let mut pending = PendingQueries::default(); + let first = make_query("a.allowed.example.", RecordType::A); + let second = make_query("b.allowed.example.", RecordType::AAAA); + let first_peer = "10.200.0.2:1234".parse().unwrap(); + let second_peer = "10.200.0.6:1234".parse().unwrap(); + let upstream = "1.1.1.1:53".parse().unwrap(); + let (first_id, _) = pending.insert(first_peer, &first).unwrap(); + let (second_id, _) = pending.insert(second_peer, &second).unwrap(); + assert_ne!(first_id, second_id); + for (id, peer, query) in [ + (second_id, second_peer, second), + (first_id, first_peer, first), + ] { + let mut response = build_response(&query, ResponseCode::NoError); + response.set_id(id); + let mut bytes = response.to_vec().unwrap(); + assert_eq!( + pending.accept_response(&mut bytes, upstream, upstream), + Some(peer) + ); + let response = Message::from_bytes(&bytes).unwrap(); + assert_eq!(response.id(), query.id()); + assert_eq!(response.queries(), query.queries()); + } + assert!(pending.entries.is_empty()); + } + + #[test] + fn question_count_is_checked_before_the_allow_list() { + let registry = local_registry(); + let mut query = make_query("a.allowed.example.", RecordType::A); + assert!(matches!( + decide(®istry, Ipv4Addr::LOCALHOST, &query), + Decision::Allow + )); + query.add_query(Query::query( + Name::from_str("denied.example.").unwrap(), + RecordType::A, + )); + for query in [Message::new(), query] { + let parsed = Message::from_bytes(&query.to_vec().unwrap()).unwrap(); + let Decision::Deny(reason) = decide(®istry, Ipv4Addr::LOCALHOST, &parsed) else { + panic!("invalid question count must be denied"); + }; + assert!(matches!(reason, DenyReason::InvalidQuestionCount)); + assert_eq!( + build_response(&parsed, reason.response_code()).response_code(), + ResponseCode::FormErr + ); + } + } + + #[test] + fn reaper_cannot_remove_a_reused_transaction_id() { + let mut pending = PendingQueries::default(); + let query = make_query("a.allowed.example.", RecordType::A); + let peer = "127.0.0.1:1234".parse().unwrap(); + let (id, old) = pending.insert_from(7, peer, &query).unwrap(); + pending.remove_if_current(id, &old); + let (new_id, new) = pending.insert_from(7, peer, &query).unwrap(); + assert_eq!(id, new_id); + pending.remove_if_current(id, &old); + assert!(Arc::ptr_eq(pending.entries.get(&id).unwrap(), &new)); + pending.remove_if_current(id, &new); + assert!(pending.entries.is_empty()); + assert!(pending.per_guest.is_empty()); + } + + #[test] + fn allocation_skips_taken_ids_and_wraps() { + let mut pending = PendingQueries::default(); + let query = make_query("a.allowed.example.", RecordType::A); + let ids: Vec = (0..3) + .map(|index| { + let peer = SocketAddr::from(([10, 200, 0, index], 53)); + pending.insert_from(u16::MAX, peer, &query).unwrap().0 + }) + .collect(); + assert_eq!(ids, [u16::MAX, 0, 1]); + } + + #[test] + fn one_guest_cannot_take_every_transaction_id() { + let mut pending = PendingQueries::default(); + let query = make_query("a.allowed.example.", RecordType::A); + let greedy = "10.200.0.2:1234".parse().unwrap(); + let (first_id, first) = pending.insert(greedy, &query).unwrap(); + for _ in 1..MAX_PENDING_PER_GUEST { + assert!(pending.insert(greedy, &query).is_some()); + } + assert!(pending.insert(greedy, &query).is_none()); + assert!(pending + .insert("10.200.0.6:1234".parse().unwrap(), &query) + .is_some()); + pending.remove_if_current(first_id, &first); + assert!(pending.insert(greedy, &query).is_some()); + } + + #[test] + fn unexpected_dns_replies_do_not_consume_pending_queries() { + let mut pending = PendingQueries::default(); + let query = make_query("a.allowed.example.", RecordType::A); + let peer = "127.0.0.1:1234".parse().unwrap(); + let upstream = "127.0.0.1:53".parse().unwrap(); + let (id, _) = pending.insert(peer, &query).unwrap(); + let mut response = build_response(&query, ResponseCode::NoError); + response.set_id(id); + let bytes = response.to_vec().unwrap(); + for source in ["127.0.0.2:53", "127.0.0.1:54"] { + assert!(pending + .accept_response(&mut bytes.clone(), source.parse().unwrap(), upstream) + .is_none()); + } + assert!(pending + .accept_response(&mut [0; 2], upstream, upstream) + .is_none()); + let mut wrong_question = build_response( + &make_query("b.allowed.example.", RecordType::A), + ResponseCode::NoError, + ); + wrong_question.set_id(id); + assert!(pending + .accept_response(&mut wrong_question.to_vec().unwrap(), upstream, upstream) + .is_none()); + let mut not_a_response = query.clone(); + not_a_response.set_id(id); + assert!(pending + .accept_response(&mut not_a_response.to_vec().unwrap(), upstream, upstream) + .is_none()); + let mut bytes = bytes; + assert_eq!( + pending.accept_response(&mut bytes, upstream, upstream), + Some(peer) + ); + assert_eq!(Message::from_bytes(&bytes).unwrap().id(), query.id()); + assert!(pending.entries.is_empty()); + } + + #[tokio::test] + async fn concurrent_guests_with_same_id_receive_their_own_answers() { + tokio::time::timeout(Duration::from_secs(3), async { + let upstream = UdpSocket::bind("127.0.0.1:0").await.unwrap(); + let proxy = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap()); + let proxy_addr = proxy.local_addr().unwrap(); + let task = tokio::spawn(serve_udp( + proxy, + local_registry(), + upstream.local_addr().unwrap(), + )); + let first = UdpSocket::bind("127.0.0.1:0").await.unwrap(); + let second = UdpSocket::bind("127.0.0.1:0").await.unwrap(); + let queries = [ + make_query("a.allowed.example.", RecordType::A), + make_query("b.allowed.example.", RecordType::AAAA), + ]; + first + .send_to(&queries[0].to_vec().unwrap(), proxy_addr) + .await + .unwrap(); + second + .send_to(&queries[1].to_vec().unwrap(), proxy_addr) + .await + .unwrap(); + let mut buf = [0; MAX_DGRAM]; + let mut forwarded = Vec::new(); + for _ in 0..2 { + let (n, peer) = upstream.recv_from(&mut buf).await.unwrap(); + forwarded.push((Message::from_bytes(&buf[..n]).unwrap(), peer)); + } + assert_ne!(forwarded[0].0.id(), forwarded[1].0.id()); + for (query, peer) in forwarded.into_iter().rev() { + let response = build_response(&query, ResponseCode::NoError); + upstream + .send_to(&response.to_vec().unwrap(), peer) + .await + .unwrap(); + } + for (socket, query) in [first, second].iter().zip(&queries) { + let (n, _) = socket.recv_from(&mut buf).await.unwrap(); + let response = Message::from_bytes(&buf[..n]).unwrap(); + assert_eq!(response.id(), query.id()); + assert_eq!(response.queries(), query.queries()); + } + task.abort(); + }) + .await + .expect("both guests receive their own replies"); + } + + #[tokio::test] + async fn udp_and_tcp_reject_zero_or_multiple_questions() { + tokio::time::timeout(Duration::from_secs(3), async { + let registry = local_registry(); + let upstream = UdpSocket::bind("127.0.0.1:0").await.unwrap(); + let upstream_addr = upstream.local_addr().unwrap(); + let udp_proxy = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap()); + let udp_addr = udp_proxy.local_addr().unwrap(); + let udp_task = tokio::spawn(serve_udp(udp_proxy, registry.clone(), upstream_addr)); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let tcp_addr = listener.local_addr().unwrap(); + let tcp_task = tokio::spawn(serve_tcp(listener, registry.clone(), upstream_addr)); + let client = UdpSocket::bind("127.0.0.1:0").await.unwrap(); + let mut tcp = TcpStream::connect(tcp_addr).await.unwrap(); + let mut multiple = make_query("a.allowed.example.", RecordType::A); + multiple.add_query(Query::query( + Name::from_str("denied.example.").unwrap(), + RecordType::A, + )); + for query in [Message::new(), multiple] { + assert!(matches!( + decide(®istry, Ipv4Addr::LOCALHOST, &query), + Decision::Deny(DenyReason::InvalidQuestionCount) + )); + let bytes = query.to_vec().unwrap(); + client.send_to(&bytes, udp_addr).await.unwrap(); + let mut buf = [0; MAX_DGRAM]; + let (n, _) = client.recv_from(&mut buf).await.unwrap(); + let response = Message::from_bytes(&buf[..n]).unwrap(); + assert_eq!(response.response_code(), ResponseCode::FormErr); + assert_eq!(response.id(), query.id()); + tcp.write_all(&u16::try_from(bytes.len()).unwrap().to_be_bytes()) + .await + .unwrap(); + tcp.write_all(&bytes).await.unwrap(); + let len = tcp.read_u16().await.unwrap() as usize; + tcp.read_exact(&mut buf[..len]).await.unwrap(); + let response = Message::from_bytes(&buf[..len]).unwrap(); + assert_eq!(response.response_code(), ResponseCode::FormErr); + assert_eq!(response.id(), query.id()); + assert_eq!( + upstream.try_recv_from(&mut buf).unwrap_err().kind(), + std::io::ErrorKind::WouldBlock + ); + } + udp_task.abort(); + tcp_task.abort(); + }) + .await + .expect("invalid question counts receive immediate errors"); + } + #[test] fn allows_exact_match_in_network_allow() { let state = SessionState { @@ -559,7 +885,7 @@ mod tests { #[test] fn nxdomain_response_preserves_id_and_question() { let q = make_query("evil.example.com.", RecordType::AAAA); - let resp = build_nxdomain(&q); + let resp = build_response(&q, ResponseCode::NXDomain); assert_eq!(resp.id(), q.id()); assert_eq!(resp.message_type(), MessageType::Response); assert_eq!(resp.response_code(), ResponseCode::NXDomain); @@ -602,13 +928,9 @@ mod tests { #[tokio::test] async fn udp_end_to_end_allowed_query_round_trips() { - // Wire a real socket-pair: a fake upstream UDP echoes a - // fixed A response; the proxy forwards an allowed query; - // the client receives the response. let upstream = UdpSocket::bind("127.0.0.1:0").await.unwrap(); let upstream_addr = upstream.local_addr().unwrap(); - // Upstream behaviour: turn the inbound query into a NOERROR - // answer with one A record pointing at 192.0.2.1 (TEST-NET-1). + // The fake upstream returns an empty successful response. let upstream_task = tokio::spawn(async move { let mut buf = vec![0u8; MAX_DGRAM]; let (n, peer) = upstream.recv_from(&mut buf).await.unwrap(); diff --git a/crates/engram-egress-proxy/src/intercept.rs b/crates/engram-egress-proxy/src/intercept.rs index 804ef35b0..d071c0ef8 100644 --- a/crates/engram-egress-proxy/src/intercept.rs +++ b/crates/engram-egress-proxy/src/intercept.rs @@ -24,7 +24,6 @@ use futures_util::stream::{FuturesUnordered, StreamExt}; use rustls::pki_types::ServerName; use rustls::{ClientConfig, ServerConfig}; use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; -use tokio::net::TcpStream; use tokio_rustls::{LazyConfigAcceptor, TlsConnector}; use engram_core::SessionId; @@ -36,7 +35,7 @@ use crate::inject; use crate::observe::{self, ObserveSink}; use crate::registry::{InjectEntry, InjectRefresher, ObserveEntry, SecretEntry}; use crate::replayed::Replayed; -use crate::resolver::{ResolveError, UpstreamResolver}; +use crate::resolver::{connect_upstream, ResolveError, UpstreamResolver}; use crate::substitute::substitute; /// Cap on the HTTP/1 request header block. The block MUST terminate inside this @@ -329,7 +328,7 @@ where // doubles as the ServerName for the upstream TLS handshake — // that's the host the cert chain should authenticate. let upstream_addr = resolver.resolve(sni, port).await?; - let upstream_tcp = TcpStream::connect(upstream_addr).await?; + let upstream_tcp = connect_upstream(upstream_addr).await?; let mut connection_client_cfg = (*client_cfg).clone(); connection_client_cfg .alpn_protocols @@ -2701,6 +2700,59 @@ mod hardening_tests { assert!(text.contains("accept: */*"), "{text}"); } + #[tokio::test] + async fn shared_stream_gate_rejects_traversal_before_injection() { + let entry = InjectEntry { + header_name: "authorization".into(), + header_template: "Bearer {}".into(), + allow: HostList::from_manifest(&["api.example".into()], &[]).unwrap(), + policy: RequestPolicy { + path_globs: vec!["/allowed/*".into()], + ..RequestPolicy::default() + }, + mint_source: None, + cred: RefreshableCred::new("test-token".into(), None), + }; + let gated = StreamContext { + sni: "api.example", + port: 443, + secrets: &[], + injects: &[&entry], + observes: &[], + foreign_placeholders: &[], + session_id: SessionId::new(), + sink: None, + refresher: None, + }; + for path in [ + "/allowed/../forbidden", + "/allowed/%2e%2e/forbidden", + "/allowed/%2f../forbidden", + "/allowed//forbidden", + ] { + assert!( + matches!( + evaluate_stream(&gated, "GET", path, None).await, + Err(InterceptError::RequestRejected { .. }) + ), + "{path}" + ); + } + for path in ["/allowed/item?query=%2f", "/allowed/group%2Fproject"] { + let plan = evaluate_stream(&gated, "GET", path, None).await.unwrap(); + assert_eq!(plan.matched.len(), 1, "{path}"); + } + // A host without injections has no path policy to bypass. + let ungated = StreamContext { + injects: &[], + ..gated + }; + let plan = evaluate_stream(&ungated, "GET", "/a//b/../c", None) + .await + .unwrap(); + assert!(plan.matched.is_empty()); + } + #[test] fn rejects_absolute_form_request_targets() { let target = inject::request_line( diff --git a/crates/engram-egress-proxy/src/registry.rs b/crates/engram-egress-proxy/src/registry.rs index ebd7ed7ba..94e731d36 100644 --- a/crates/engram-egress-proxy/src/registry.rs +++ b/crates/engram-egress-proxy/src/registry.rs @@ -6,9 +6,8 @@ //! registry maps `guest_ip → SessionState` for fast accept-time //! lookup. //! -//! `register` / `unregister` are called by the coordinator at session -//! create / destroy. We keep both maps (`by_guest_ip`, -//! `by_session`) so unregister-by-session-id is O(1). +//! Host policy updates register and unregister sessions. The guest-IP and +//! session-ID maps stay in sync so cleanup cannot remove another session. use std::collections::HashMap; use std::net::Ipv4Addr; @@ -303,22 +302,11 @@ impl GraphqlMatch { } } -/// ADR 0056: the request shapes a Plane-B injection gates + applies to. -/// Layered on top of the SNI host match. `methods` empty = any method; -/// `path_globs` empty = any path. -/// -/// `path_globs` are **glob patterns** — a `*` matches any run of characters -/// (including `/`) — matched against the whole request path (the connector op's -/// full `match.path`). So `POST /repos/o/r/pulls` matches `/repos/*/pulls` while -/// `POST /repos/o/r/git/refs` does not. (These were once truncated at the first -/// `*` and prefix-matched — a coarse over-match where `/repos/*/pulls` collapsed -/// to `/repos/` and the gate fired on *any* `/repos/…` request; fixed in #413, -/// renamed from `path_prefixes` to match.) -/// -/// ADR 0059: when `graphql` is `Some`, this entry gates a GraphQL operation — the -/// request must still satisfy `methods`/`path_globs` (the `POST /graphql` -/// endpoint), AND the body-parsed top-level operation must match. REST entries -/// leave `graphql` `None`; their `allows(method, path)` semantics are unchanged. +/// Request shapes permitted for a host-matched injection. +/// Empty method and path lists allow any method and any path. +/// Path globs match the whole target; `*` includes `/` unless the pattern has +/// a `segment:` or `segment-path:` prefix. GraphQL entries also require a +/// matching body-parsed operation and field. #[derive(Clone, Debug, Default)] pub struct RequestPolicy { pub methods: Vec, @@ -342,13 +330,19 @@ impl RequestPolicy { } /// Glob path match over the whole path; empty `path_globs` = any path. + /// A non-empty list matches only an unambiguous path (see + /// [`path_is_unambiguous`]), because the upstream must route the same + /// resource that the glob saw. /// A `segment:` prefix makes each `*` stop at `/`. `segment-path:` also /// excludes the query string from matching; Google Cloud policies and /// connector operations that gate one resource path use it, because /// clients add query parameters such as `alt=json` or `per_page`. pub fn path_matches(&self, path: &str) -> bool { - self.path_globs.is_empty() - || self.path_globs.iter().any(|pattern| { + if self.path_globs.is_empty() { + return true; + } + path_is_unambiguous(path) + && self.path_globs.iter().any(|pattern| { if let Some(pattern) = pattern.strip_prefix("segment-path:") { segment_glob_match(pattern, path.split_once('?').map_or(path, |(path, _)| path)) } else if let Some(pattern) = pattern.strip_prefix("segment:") { @@ -360,6 +354,59 @@ impl RequestPolicy { } } +/// Can an upstream normalize this request target to a different path? +/// +/// Rejects a fragment, an empty segment, a backslash, a control byte, an +/// encoded `%` (a second decoding pass), and a dot segment in any spelling: +/// literal, percent-encoded, with `;` parameters, or behind an encoded `/`. +/// An encoded `/` alone is accepted, because APIs such as GitLab, npm and +/// Cloud Storage use it inside one segment. The query string is not checked. +fn path_is_unambiguous(target: &str) -> bool { + if target == "*" { + return true; + } + if target.contains('#') { + return false; + } + let path = target.split_once('?').map_or(target, |(path, _)| path); + let Some(rest) = path.strip_prefix('/') else { + return false; + }; + !rest.contains("//") && rest.split('/').all(segment_is_unambiguous) +} + +fn segment_is_unambiguous(segment: &str) -> bool { + let Some(decoded) = percent_decode(segment) else { + return false; + }; + decoded + .iter() + .all(|&byte| !byte.is_ascii_control() && byte != b'\\' && byte != b'%') + && decoded.split(|&byte| byte == b'/').all(|piece| { + let name = piece.split(|&byte| byte == b';').next().unwrap_or(piece); + name != b"." && name != b".." + }) +} + +/// Decode `%XX` escapes. `None` for a malformed escape or a raw space or +/// control byte, which a request target cannot carry. +fn percent_decode(segment: &str) -> Option> { + let mut decoded = Vec::with_capacity(segment.len()); + let mut bytes = segment.bytes(); + while let Some(byte) = bytes.next() { + if byte == b'%' { + let high = char::from(bytes.next()?).to_digit(16)?; + let low = char::from(bytes.next()?).to_digit(16)?; + decoded.push(u8::try_from(high * 16 + low).ok()?); + } else if byte.is_ascii_control() || byte == b' ' { + return None; + } else { + decoded.push(byte); + } + } + Some(decoded) +} + /// Glob match: `*` matches any run of characters (including `/`); the pattern /// must match the ENTIRE `text`. Iterative with backtracking (O(n·m), no /// recursion blow-up). `*` is the only metacharacter — connector match paths use @@ -480,20 +527,23 @@ impl Registry { Self::default() } - /// Replaces any prior registration for this `session_id`. + /// Replace prior registrations for this session or guest IP. pub fn register(&self, state: SessionState) { let guest_ip = state.guest_ip; let session_id = state.session_id; let arc = Arc::new(state); let mut g = self.inner.write(); - // Remove any stale guest_ip mapping if the session moved - // (shouldn't happen — sandbox ids are stable — but defensive). + // A session can move to a different guest IP. if let Some(old_ip) = g.by_session.insert(session_id, guest_ip) { if old_ip != guest_ip { g.by_guest_ip.remove(&old_ip); } } - g.by_guest_ip.insert(guest_ip, arc); + if let Some(displaced) = g.by_guest_ip.insert(guest_ip, arc) { + if displaced.session_id != session_id { + g.by_session.remove(&displaced.session_id); + } + } } pub fn unregister(&self, session_id: SessionId) { @@ -828,6 +878,46 @@ mod tests { assert!(r.lookup(ip).is_none()); } + #[test] + fn reused_guest_ip_keeps_the_new_sessions_policy() { + let registry = Registry::new(); + let old = state(); + let old_id = old.session_id; + let new = state(); + let new_id = new.session_id; + let ip = new.guest_ip; + registry.register(old); + registry.register(new); + registry.unregister(old_id); + assert_eq!(registry.lookup(ip).unwrap().session_id, new_id); + assert_eq!(registry.session_ids(), vec![new_id]); + assert_eq!(registry.live_count(), 1); + registry.unregister(new_id); + assert!(registry.lookup(ip).is_none()); + assert_eq!(registry.live_count(), 0); + } + + #[test] + fn displaced_session_can_register_at_a_new_ip() { + let registry = Registry::new(); + let mut moved = state(); + let original_ip = moved.guest_ip; + let replacement = state(); + let replacement_id = replacement.session_id; + registry.register(moved.clone()); + registry.register(replacement); + moved.guest_ip = Ipv4Addr::new(10, 200, 0, 6); + let moved_ip = moved.guest_ip; + let moved_id = moved.session_id; + registry.register(moved); + assert_eq!( + registry.lookup(original_ip).unwrap().session_id, + replacement_id + ); + assert_eq!(registry.lookup(moved_ip).unwrap().session_id, moved_id); + assert_eq!(registry.live_count(), 2); + } + #[test] fn unregister_unknown_session_is_noop() { let r = Registry::new(); @@ -1090,6 +1180,76 @@ mod tests { assert_eq!(e.secret(), "stale"); } + #[test] + fn path_globs_reject_ambiguous_paths() { + for pattern in [ + "/allowed/*", + "segment:/allowed/*/forbidden", + "segment-path:/allowed/*/forbidden", + ] { + let policy = RequestPolicy { + path_globs: vec![pattern.into()], + ..RequestPolicy::default() + }; + assert!(policy.path_matches("/allowed/item/forbidden")); + for path in [ + "/allowed/../forbidden", + "/allowed/./forbidden", + "/allowed/%2e%2e/forbidden", + "/allowed/%2E./forbidden", + "/allowed/..;/forbidden", + "/allowed/%2e%2e;x=1/forbidden", + "/allowed/%2f../forbidden", + "/allowed/x%2F..%2Fforbidden", + "/allowed/%5c../forbidden", + "/allowed/%5C../forbidden", + "/allowed/\\../forbidden", + "/allowed//forbidden", + "/allowed/%252e%252e/forbidden", + "/allowed/%/forbidden", + "/allowed/%2/forbidden", + "/allowed/%zz/forbidden", + "/allowed/%00/forbidden", + "/allowed/%7f/forbidden", + "/allowed/a b/forbidden", + "/allowed/../forbidden?alt=json", + "//allowed/item/forbidden", + "/allowed/item/forbidden#fragment", + "allowed/item/forbidden", + ] { + assert!(!policy.path_matches(path), "{pattern}: {path}"); + } + } + } + + #[test] + fn path_globs_accept_encoded_slashes_and_ordinary_escapes() { + let policy = RequestPolicy { + path_globs: vec!["/allowed*".into()], + ..RequestPolicy::default() + }; + for path in [ + "/allowed/", + "/allowed/file.json", + "/allowed/...", + "/allowed/a%20b", + "/allowed/%E2%82%AC", + "/allowed/group%2Fproject/merge_requests", + "/allowed/lib%2Fclass%2Erb", + "/allowed/@scope%2fpackage", + "/allowed/item?next=../%2f//%5c", + ] { + assert!(policy.path_matches(path), "{path}"); + } + } + + #[test] + fn empty_path_globs_match_every_path() { + for path in ["/", "*", "/a//b", "/a/../b", "/a/%252e"] { + assert!(RequestPolicy::default().path_matches(path), "{path}"); + } + } + #[test] fn glob_match_semantics() { // No metacharacter → exact, whole-string match (the granularity fix: diff --git a/crates/engram-egress-proxy/src/resolver.rs b/crates/engram-egress-proxy/src/resolver.rs index 7bf7e9823..d7dfabb0d 100644 --- a/crates/engram-egress-proxy/src/resolver.rs +++ b/crates/engram-egress-proxy/src/resolver.rs @@ -1,21 +1,13 @@ -//! Upstream resolver for the proxy. -//! -//! When the proxy MITMs or bypasses a connection, it needs to dial -//! the *real* upstream. We dial by SNI (the hostname the guest's -//! TLS handshake claims) rather than by `SO_ORIGINAL_DST` (the IP -//! the guest chose) — the host is the TCB, so we trust the host's -//! resolution, not whatever the guest's resolver returned. This -//! also closes a DNS-rebinding-style attack: a guest can't dial -//! `evil.example.com` while sending SNI=`api.openai.com` to fool -//! the proxy into MITM'ing OpenAI bytes to evil. -//! -//! Tests inject a `StaticResolver` that maps a fixed hostname to a -//! local SocketAddr, so an in-VM e2e test can have curl hit a -//! loopback fake-upstream without owning a real DNS name. +//! Resolve upstreams by the SNI hostname through host DNS, then connect to +//! the selected public address. Guest-supplied destination IPs are not trusted. +//! Tests use `StaticResolver` to select local upstream servers explicitly. use std::collections::HashMap; -use std::net::SocketAddr; +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::sync::Arc; +use std::time::Duration; + +use tokio::net::TcpStream; #[async_trait::async_trait] pub trait UpstreamResolver: Send + Sync + std::fmt::Debug { @@ -25,6 +17,7 @@ pub trait UpstreamResolver: Send + Sync + std::fmt::Debug { #[derive(Debug)] pub enum ResolveError { NotFound(String), + NoGlobalIpv4(String), Io(std::io::Error), } @@ -32,6 +25,7 @@ impl std::fmt::Display for ResolveError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::NotFound(h) => write!(f, "no addresses for `{h}`"), + Self::NoGlobalIpv4(h) => write!(f, "no globally routable IPv4 addresses for `{h}`"), Self::Io(e) => write!(f, "io: {e}"), } } @@ -45,25 +39,54 @@ impl From for ResolveError { } } -/// Default production resolver: tokio's async getaddrinfo. Returns -/// the first IPv4 address; we only support IPv4 upstreams for now. +/// Resolve through host DNS and select the first globally routable IPv4 address. +/// IPv6 upstreams are not supported. #[derive(Debug, Default)] pub struct SystemResolver; #[async_trait::async_trait] impl UpstreamResolver for SystemResolver { async fn resolve(&self, host: &str, port: u16) -> Result { - let target = format!("{host}:{port}"); - let mut addrs = tokio::net::lookup_host(target).await?; - for a in addrs.by_ref() { - if a.ip().is_ipv4() { - return Ok(a); - } - } - Err(ResolveError::NotFound(host.to_string())) + let addrs = tokio::net::lookup_host((host, port)).await?; + select_global_ipv4(host, addrs) } } +fn select_global_ipv4( + host: &str, + addrs: impl IntoIterator, +) -> Result { + addrs + .into_iter() + .find(|addr| matches!(addr.ip(), IpAddr::V4(ip) if is_global_ipv4(ip))) + .ok_or_else(|| ResolveError::NoGlobalIpv4(host.to_string())) +} + +/// Exclude non-global IANA special-purpose ranges and multicast destinations. +fn is_global_ipv4(ip: Ipv4Addr) -> bool { + let [a, b, c, d] = ip.octets(); + !(ip.is_private() + || ip.is_loopback() + || ip.is_link_local() + || ip.is_documentation() + || a == 0 + || a >= 224 + || (a == 100 && (64..=127).contains(&b)) + || (a == 192 && b == 0 && c == 0 && d != 9 && d != 10) + || (a == 192 && b == 88 && c == 99) + || (a == 198 && (18..=19).contains(&b))) +} + +const UPSTREAM_CONNECT_TIMEOUT: Duration = Duration::from_secs(10); + +pub(crate) async fn connect_upstream(addr: SocketAddr) -> std::io::Result { + tokio::time::timeout(UPSTREAM_CONNECT_TIMEOUT, TcpStream::connect(addr)) + .await + .map_err(|_| { + std::io::Error::new(std::io::ErrorKind::TimedOut, "upstream connect timeout") + })? +} + /// Test / override resolver: returns a fixed SocketAddr per host. /// Misses fall through to NotFound (no fallback to system DNS — if /// you've handed the proxy a static map, you've asserted the names @@ -130,10 +153,87 @@ mod tests { } #[tokio::test] - async fn system_resolver_resolves_localhost() { - // localhost should always resolve. Skip on platforms where - // it doesn't (none I know of). - let a = SystemResolver.resolve("localhost", 80).await.unwrap(); - assert_eq!(a.port(), 80); + async fn system_resolver_rejects_non_global_addresses() { + for host in [ + "localhost", + "127.0.0.1", + "127.255.255.255", + "169.254.169.254", + "10.0.0.1", + "172.16.0.1", + "172.31.255.255", + "192.168.1.1", + "100.64.0.1", + "100.127.255.255", + "0.0.0.0", + "0.1.2.3", + "192.0.0.8", + "192.0.0.170", + "192.0.2.1", + "192.88.99.2", + "198.18.0.1", + "198.19.255.255", + "198.51.100.1", + "203.0.113.1", + "224.0.0.1", + "239.255.255.255", + "240.0.0.1", + "255.255.255.255", + "::1", + "::", + "fe80::1", + "fc00::1", + "::ffff:127.0.0.1", + ] { + assert!( + matches!( + SystemResolver.resolve(host, 443).await, + Err(ResolveError::NoGlobalIpv4(_)) + ), + "{host}" + ); + } + } + + #[tokio::test] + async fn system_resolver_accepts_global_ipv4() { + for host in [ + "93.184.216.34", + "1.1.1.1", + "100.63.255.255", + "100.128.0.1", + "172.15.255.255", + "172.32.0.1", + "192.0.0.9", + "192.0.0.10", + ] { + let addr = SystemResolver.resolve(host, 443).await.unwrap(); + assert_eq!(addr, format!("{host}:443").parse().unwrap()); + } + } + + #[test] + fn address_selection_skips_private_and_ipv6_results() { + let addrs = [ + "127.0.0.1:443", + "[::ffff:93.184.216.34]:443", + "10.0.0.1:443", + "93.184.216.34:443", + "1.1.1.1:443", + ] + .map(|a| a.parse().unwrap()); + assert_eq!(select_global_ipv4("example.com", addrs).unwrap(), addrs[3]); + assert!(matches!( + select_global_ipv4("example.com", []), + Err(ResolveError::NoGlobalIpv4(_)) + )); + } + + #[tokio::test] + async fn upstream_connect_returns_a_connected_stream() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let stream = connect_upstream(addr).await.unwrap(); + assert_eq!(stream.peer_addr().unwrap(), addr); } }