Skip to main content

agentmux_srv/server/streamed_browser/
address_proxy.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The one way out for the server's Chromium: a SOCKS5 proxy on the loopback address that connects only where
5//! `address_policy` allows. Chromium is told to use it for every connection (page loads, scripts, WebSocket, and
6//! the browser's own requests), to ask it for name resolution too, and to refuse a local lookup, so a page cannot
7//! reach the cloud metadata address, a private range, or this server's own ports, by an address or by a name.
8//!
9//! The proxy resolves the name itself, judges every address the name resolved to (one refused address refuses the
10//! name), and connects to an address it judged: it never resolves a second time, so a name that answers with a
11//! public address first and a private one later gets nothing from the second answer.
12
13use std::future::Future;
14use std::io;
15use std::net::{IpAddr, Ipv4Addr, SocketAddr};
16use std::sync::Arc;
17use std::time::Duration;
18
19use tokio::io::{AsyncReadExt, AsyncWriteExt};
20use tokio::net::{TcpListener, TcpStream};
21use tokio::sync::Semaphore;
22
23use super::address_policy;
24
25/// How long a client has to say what it wants, and how long a connection may take to open.
26const HANDSHAKE: Duration = Duration::from_secs(10);
27const CONNECT: Duration = Duration::from_secs(15);
28/// The most connections open at once: a page that opens thousands is held to this.
29const MAX_OPEN: usize = 512;
30
31/// SOCKS5 reply codes (RFC 1928 section 6).
32const OK: u8 = 0;
33const NOT_ALLOWED: u8 = 2;
34const HOST_UNREACHABLE: u8 = 4;
35const REFUSED: u8 = 5;
36const BAD_COMMAND: u8 = 7;
37const BAD_ADDRESS_TYPE: u8 = 8;
38
39/// What a client asked to connect to.
40#[derive(Debug, Clone, PartialEq)]
41pub enum Target {
42    Ip(IpAddr),
43    Name(String),
44}
45
46/// Turns a name into addresses. The system's resolver in use; a scripted one in the tests.
47pub trait Resolve: Send + Sync + 'static {
48    fn resolve(&self, name: &str, port: u16) -> impl Future<Output = io::Result<Vec<IpAddr>>> + Send;
49}
50
51pub struct SystemResolver;
52
53impl Resolve for SystemResolver {
54    async fn resolve(&self, name: &str, port: u16) -> io::Result<Vec<IpAddr>> {
55        Ok(tokio::net::lookup_host((name, port)).await?.map(|a| a.ip()).collect())
56    }
57}
58
59/// The addresses a connection to `target` on `port` may go to, in the order to try them, or the SOCKS5 reply that
60/// refuses it. Every address the name resolved to has to pass the policy, and only those are tried (a name that
61/// answers `::1` and `127.0.0.1` reaches a development server on either).
62pub async fn plan<R: Resolve>(resolver: &R, target: &Target, port: u16, own_ports: &[u16]) -> Result<Vec<SocketAddr>, u8> {
63    let addrs = match target {
64        Target::Ip(ip) => vec![*ip],
65        Target::Name(name) => match resolver.resolve(name, port).await {
66            Ok(a) if !a.is_empty() => a,
67            _ => return Err(HOST_UNREACHABLE),
68        },
69    };
70    for ip in &addrs {
71        if let Err(why) = address_policy::check(*ip, port, own_ports) {
72            tracing::info!(target: "streamed-browser", port, why, "address proxy: refused a connection");
73            return Err(NOT_ALLOWED);
74        }
75    }
76    Ok(addrs.into_iter().map(|ip| SocketAddr::new(ip, port)).collect())
77}
78
79/// Connect to the first of `addrs` that answers, each within the connect limit. The reply for the last failure.
80async fn connect_first(addrs: &[SocketAddr]) -> Result<TcpStream, u8> {
81    let mut code = HOST_UNREACHABLE;
82    for addr in addrs {
83        match tokio::time::timeout(CONNECT, TcpStream::connect(addr)).await {
84            Ok(Ok(s)) => return Ok(s),
85            Ok(Err(e)) if e.kind() == io::ErrorKind::ConnectionRefused => code = REFUSED,
86            _ => code = HOST_UNREACHABLE,
87        }
88    }
89    Err(code)
90}
91
92/// The client's request: the address it wants and the port.
93async fn read_request(s: &mut TcpStream) -> Result<(Target, u16), u8> {
94    let mut head = [0u8; 4];
95    s.read_exact(&mut head).await.map_err(|_| REFUSED)?;
96    if head[0] != 5 {
97        return Err(REFUSED);
98    }
99    // The whole request is read before any refusal, so a client that sent more than was read is not reset (a reset
100    // can overtake the reply) and gets the reply.
101    let target = match head[3] {
102        1 => {
103            let mut b = [0u8; 4];
104            s.read_exact(&mut b).await.map_err(|_| REFUSED)?;
105            Target::Ip(IpAddr::V4(Ipv4Addr::from(b)))
106        }
107        4 => {
108            let mut b = [0u8; 16];
109            s.read_exact(&mut b).await.map_err(|_| REFUSED)?;
110            Target::Ip(IpAddr::from(b))
111        }
112        3 => {
113            let len = s.read_u8().await.map_err(|_| REFUSED)? as usize;
114            let mut b = vec![0u8; len];
115            s.read_exact(&mut b).await.map_err(|_| REFUSED)?;
116            Target::Name(String::from_utf8(b).map_err(|_| BAD_ADDRESS_TYPE)?)
117        }
118        _ => return Err(BAD_ADDRESS_TYPE),
119    };
120    let port = s.read_u16().await.map_err(|_| REFUSED)?;
121    if head[1] != 1 {
122        return Err(BAD_COMMAND);
123    }
124    Ok((target, port))
125}
126
127async fn reply(s: &mut TcpStream, code: u8) {
128    // Version, reply, reserved, IPv4 address type, the (unused) bound address and port.
129    let _ = s.write_all(&[5, code, 0, 1, 0, 0, 0, 0, 0, 0]).await;
130}
131
132/// One client: greeting, request, a checked connection, then bytes both ways.
133async fn serve_one<R: Resolve>(mut client: TcpStream, resolver: Arc<R>) {
134    let handshake = async {
135        let mut greeting = [0u8; 2];
136        client.read_exact(&mut greeting).await.ok()?;
137        let mut methods = vec![0u8; greeting[1] as usize];
138        client.read_exact(&mut methods).await.ok()?;
139        // Only "no authentication": the proxy listens on the loopback address of a machine the page's own code can
140        // reach, but it only connects where the policy allows, so there is nothing for a password to protect.
141        if greeting[0] != 5 || !methods.contains(&0) {
142            let _ = client.write_all(&[5, 0xff]).await;
143            return None;
144        }
145        client.write_all(&[5, 0]).await.ok()?;
146        Some(read_request(&mut client).await)
147    };
148    let Ok(Some(request)) = tokio::time::timeout(HANDSHAKE, handshake).await else { return };
149    let (target, port) = match request {
150        Ok(r) => r,
151        Err(code) => return reply(&mut client, code).await,
152    };
153    let addrs = match plan(&*resolver, &target, port, &own_ports_with_proxy()).await {
154        Ok(a) => a,
155        Err(code) => return reply(&mut client, code).await,
156    };
157    let mut upstream = match connect_first(&addrs).await {
158        Ok(s) => s,
159        Err(code) => return reply(&mut client, code).await,
160    };
161    reply(&mut client, OK).await;
162    let _ = tokio::io::copy_bidirectional(&mut client, &mut upstream).await;
163}
164
165/// This server's own ports, this proxy's, and the development-server router's.
166fn own_ports_with_proxy() -> Vec<u16> {
167    let mut ports = address_policy::own_ports();
168    ports.extend(PROXY_PORT.get());
169    ports.push(crate::backend::dev_proxy::port());
170    ports
171}
172
173static PROXY_PORT: std::sync::OnceLock<u16> = std::sync::OnceLock::new();
174
175/// Accept clients on `listener` until the process ends.
176async fn accept_loop<R: Resolve>(listener: TcpListener, resolver: Arc<R>) {
177    let open = Arc::new(Semaphore::new(MAX_OPEN));
178    loop {
179        let Ok((client, _)) = listener.accept().await else {
180            // A persistent failure (out of descriptors) must not spin.
181            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
182            continue;
183        };
184        let Ok(permit) = open.clone().try_acquire_owned() else { continue };
185        let resolver = resolver.clone();
186        tokio::spawn(async move {
187            serve_one(client, resolver).await;
188            drop(permit);
189        });
190    }
191}
192
193/// The setting that fixes the proxy's loopback port (a container whose browser policy names the port); unset, the system chooses.
194pub const PORT_ENV: &str = "AGENTMUX_STREAMED_BROWSER_PROXY_PORT";
195
196/// Start the proxy on a loopback port (the one in `PORT_ENV`, else the system's choosing), once; the port is the same for every later call.
197pub async fn start() -> io::Result<u16> {
198    static STARTED: tokio::sync::OnceCell<u16> = tokio::sync::OnceCell::const_new();
199    STARTED
200        .get_or_try_init(|| async {
201            let want = std::env::var(PORT_ENV).ok().and_then(|v| v.parse::<u16>().ok()).unwrap_or(0);
202            let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, want)).await?;
203            let port = listener.local_addr()?.port();
204            let _ = PROXY_PORT.set(port);
205            address_policy::note_ports_from_env();
206            tokio::spawn(accept_loop(listener, Arc::new(SystemResolver)));
207            Ok(port)
208        })
209        .await
210        .copied()
211}
212
213#[cfg(test)]
214mod tests {
215    use super::*;
216    use std::collections::VecDeque;
217    use std::sync::Mutex;
218
219    /// A resolver that answers from a script, one answer per call, so a name can change its answer.
220    struct Scripted(Mutex<VecDeque<Vec<IpAddr>>>);
221
222    impl Scripted {
223        fn new(answers: &[&[&str]]) -> Self {
224            Self(Mutex::new(answers.iter().map(|a| a.iter().map(|s| s.parse().unwrap()).collect()).collect()))
225        }
226    }
227
228    impl Resolve for Scripted {
229        async fn resolve(&self, _name: &str, _port: u16) -> io::Result<Vec<IpAddr>> {
230            Ok(self.0.lock().unwrap().pop_front().unwrap_or_default())
231        }
232    }
233
234    fn name(n: &str) -> Target {
235        Target::Name(n.to_string())
236    }
237
238    #[tokio::test]
239    async fn a_name_that_resolves_to_a_private_address_is_refused() {
240        let lan = [std::net::Ipv4Addr::new(10, 0, 0, 5), std::net::Ipv4Addr::new(192, 168, 1, 1)].map(|a| a.to_string());
241        for answer in [lan[0].as_str(), "169.254.170.2", lan[1].as_str(), "fd00:ec2::254", "127.0.0.1"] {
242            let r = Scripted::new(&[&[answer]]);
243            // 127.0.0.1 is refused here because the port is one of the server's own.
244            let got = plan(&r, &name("evil.example"), 8190, &[8190]).await;
245            assert_eq!(got, Err(NOT_ALLOWED), "{answer}");
246        }
247    }
248
249    #[tokio::test]
250    async fn a_name_with_one_private_address_among_public_ones_is_refused() {
251        let lan = std::net::Ipv4Addr::new(10, 0, 0, 5).to_string();
252        let r = Scripted::new(&[&["93.184.216.34", lan.as_str()]]);
253        assert_eq!(plan(&r, &name("mixed.example"), 443, &[]).await, Err(NOT_ALLOWED));
254    }
255
256    #[tokio::test]
257    async fn a_name_that_answers_public_first_and_private_later_gets_nothing_from_the_later_answer() {
258        // The rebinding trick: the first lookup is public, the next is the metadata address.
259        let r = Scripted::new(&[&["93.184.216.34"], &["169.254.170.2"]]);
260        // The first connection is planned for the public address the policy saw...
261        assert_eq!(plan(&r, &name("rebind.example"), 80, &[]).await, Ok(vec![SocketAddr::new("93.184.216.34".parse().unwrap(), 80)]));
262        // ...and a new connection asks again and is refused. A connection already planned never resolves again,
263        // because `serve_one` connects to the planned address itself.
264        assert_eq!(plan(&r, &name("rebind.example"), 80, &[]).await, Err(NOT_ALLOWED));
265    }
266
267    #[tokio::test]
268    async fn every_judged_address_of_a_name_is_offered_in_order() {
269        // `localhost` answers `::1` first; a development server listening on IPv4 only is reached on the second.
270        let r = Scripted::new(&[&["::1", "127.0.0.1"]]);
271        let got = plan(&r, &name("localhost"), 3000, &[]).await.unwrap();
272        assert_eq!(got, vec![SocketAddr::new("::1".parse().unwrap(), 3000), SocketAddr::new("127.0.0.1".parse().unwrap(), 3000)]);
273    }
274
275    #[tokio::test]
276    async fn the_connection_falls_through_to_the_next_address_when_the_first_is_refused() {
277        let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
278        let live = listener.local_addr().unwrap();
279        // Port 1 on the loopback address nothing listens on: refused at once.
280        let dead = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 1);
281        assert!(connect_first(&[dead, live]).await.is_ok());
282        assert_eq!(connect_first(&[dead]).await.err(), Some(REFUSED));
283    }
284
285    #[test]
286    fn the_development_server_router_is_one_of_the_servers_own_ports() {
287        assert!(own_ports_with_proxy().contains(&crate::backend::dev_proxy::port()));
288    }
289
290    #[tokio::test]
291    async fn an_address_given_directly_is_judged_without_a_lookup() {
292        let r = Scripted::new(&[]);
293        assert_eq!(plan(&r, &Target::Ip("169.254.170.2".parse().unwrap()), 80, &[]).await, Err(NOT_ALLOWED));
294        assert_eq!(plan(&r, &Target::Ip("::ffff:a00:1".parse().unwrap()), 80, &[]).await, Err(NOT_ALLOWED));
295        assert!(plan(&r, &Target::Ip("8.8.8.8".parse().unwrap()), 443, &[]).await.is_ok());
296    }
297
298    #[tokio::test]
299    async fn a_name_that_does_not_resolve_is_unreachable() {
300        let r = Scripted::new(&[&[]]);
301        assert_eq!(plan(&r, &name("nothing.example"), 443, &[]).await, Err(HOST_UNREACHABLE));
302    }
303
304    /// A SOCKS5 client: connect to the proxy, ask for `request`, and return the reply code and the open socket.
305    async fn ask(proxy: u16, request: &[u8]) -> (u8, TcpStream) {
306        let mut s = TcpStream::connect((Ipv4Addr::LOCALHOST, proxy)).await.unwrap();
307        s.write_all(&[5, 1, 0]).await.unwrap();
308        let mut method = [0u8; 2];
309        s.read_exact(&mut method).await.unwrap();
310        assert_eq!(method, [5, 0]);
311        s.write_all(request).await.unwrap();
312        let mut rep = [0u8; 10];
313        s.read_exact(&mut rep).await.unwrap();
314        (rep[1], s)
315    }
316
317    fn connect_ip(ip: [u8; 4], port: u16) -> Vec<u8> {
318        let mut r = vec![5, 1, 0, 1];
319        r.extend(ip);
320        r.extend(port.to_be_bytes());
321        r
322    }
323
324    fn connect_name(name: &str, port: u16) -> Vec<u8> {
325        let mut r = vec![5, 1, 0, 3, name.len() as u8];
326        r.extend(name.as_bytes());
327        r.extend(port.to_be_bytes());
328        r
329    }
330
331    /// A proxy on a test port with a scripted resolver, and an echo server on the loopback address.
332    async fn proxy_and_echo(resolver: Scripted) -> (u16, u16) {
333        let echo = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
334        let echo_port = echo.local_addr().unwrap().port();
335        tokio::spawn(async move {
336            while let Ok((mut c, _)) = echo.accept().await {
337                tokio::spawn(async move {
338                    let mut buf = [0u8; 64];
339                    while let Ok(n) = c.read(&mut buf).await {
340                        if n == 0 || c.write_all(&buf[..n]).await.is_err() {
341                            break;
342                        }
343                    }
344                });
345            }
346        });
347        let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
348        let proxy_port = listener.local_addr().unwrap().port();
349        tokio::spawn(accept_loop(listener, Arc::new(resolver)));
350        (proxy_port, echo_port)
351    }
352
353    #[tokio::test]
354    async fn the_proxy_carries_a_connection_to_a_loopback_development_server() {
355        let (proxy, echo) = proxy_and_echo(Scripted::new(&[])).await;
356        let (code, mut s) = ask(proxy, &connect_ip([127, 0, 0, 1], echo)).await;
357        assert_eq!(code, OK);
358        s.write_all(b"hello").await.unwrap();
359        let mut back = [0u8; 5];
360        s.read_exact(&mut back).await.unwrap();
361        assert_eq!(&back, b"hello");
362    }
363
364    #[tokio::test]
365    async fn a_page_cannot_reach_a_private_range_or_the_metadata_address_through_the_proxy() {
366        let (proxy, _) = proxy_and_echo(Scripted::new(&[])).await;
367        for ip in [[169, 254, 170, 2], [169, 254, 169, 254], [10, 1, 2, 3], [192, 168, 0, 1], [172, 16, 0, 9]] {
368            let (code, _) = ask(proxy, &connect_ip(ip, 80)).await;
369            assert_eq!(code, NOT_ALLOWED, "{ip:?}");
370        }
371    }
372
373    #[tokio::test]
374    async fn a_page_cannot_reach_this_servers_own_ports_through_the_proxy() {
375        let (proxy, echo) = proxy_and_echo(Scripted::new(&[])).await;
376        // The echo server stands for one of the server's own listeners: once its port is noted, it is refused.
377        address_policy::note_own_port(echo);
378        let (code, _) = ask(proxy, &connect_ip([127, 0, 0, 1], echo)).await;
379        assert_eq!(code, NOT_ALLOWED);
380        let (code, _) = ask(proxy, &connect_name("localhost", echo)).await;
381        // `localhost` goes to the scripted resolver, which has no answer: unreachable, never a connection.
382        assert_ne!(code, OK);
383    }
384
385    #[tokio::test]
386    async fn a_name_that_turns_private_on_its_second_lookup_is_carried_once_and_then_refused() {
387        // First lookup: the loopback address of a development server (allowed). Second: a private address.
388        let lan = std::net::Ipv4Addr::new(10, 0, 0, 1).to_string();
389        let (proxy, echo) = proxy_and_echo(Scripted::new(&[&["127.0.0.1"], &[lan.as_str()]])).await;
390        let (code, _) = ask(proxy, &connect_name("rebind.example", echo)).await;
391        assert_eq!(code, OK);
392        let (code, _) = ask(proxy, &connect_name("rebind.example", echo)).await;
393        assert_eq!(code, NOT_ALLOWED);
394    }
395
396    #[tokio::test]
397    async fn only_connect_is_served() {
398        let (proxy, _) = proxy_and_echo(Scripted::new(&[])).await;
399        // BIND (2) and UDP ASSOCIATE (3) are refused: the proxy opens outgoing TCP connections and nothing else.
400        for command in [2u8, 3] {
401            let (code, _) = ask(proxy, &[5, command, 0, 1, 127, 0, 0, 1, 0, 80]).await;
402            assert_eq!(code, BAD_COMMAND);
403        }
404    }
405}