Skip to main content

vtcode_safety/sandboxing/network_proxy/
mod.rs

1//! Local HTTP CONNECT / SOCKS5 proxy used to enforce hostname allowlists.
2//!
3//! The OS sandbox cannot inspect `connect()` destinations (seccomp BPF sees a
4//! pointer, not the sockaddr contents), so exact domain rules are enforced by
5//! a loopback proxy: the sandbox permits connections only to the proxy, and
6//! the proxy resolves DNS **after** deciding that a hostname is allowed.
7//! Deny rules take precedence over allow rules; anything unmatched is denied.
8
9#![expect(
10    unused_results,
11    reason = "Detached per-connection tasks and byte-copy counts are intentionally discarded."
12)]
13
14use std::net::{IpAddr, SocketAddr};
15use std::sync::Arc;
16use std::time::Duration;
17
18use anyhow::{Context, Result, anyhow, bail};
19use tokio::io::{AsyncReadExt, AsyncWriteExt, copy_bidirectional};
20use tokio::net::{TcpListener, TcpStream};
21use tokio::task::JoinHandle;
22use tokio::time::timeout;
23use tracing::warn;
24
25use crate::sandboxing::NetworkAllowlistEntry;
26
27#[cfg(test)]
28mod tests;
29
30const IO_TIMEOUT: Duration = Duration::from_secs(30);
31const MAX_HTTP_HEADER: usize = 8 * 1024;
32
33/// Effect of a domain rule.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum DomainRuleAction {
36    Allow,
37    Deny,
38}
39
40/// One hostname rule. Domains are case-insensitive; `*.example.com` also
41/// matches the bare `example.com`, matching the existing allowlist semantics.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct DomainRule {
44    pub domain: String,
45    pub port: u16,
46    pub action: DomainRuleAction,
47}
48
49impl DomainRule {
50    #[must_use]
51    pub fn allow(domain: impl Into<String>, port: u16) -> Self {
52        Self {
53            domain: domain.into(),
54            port,
55            action: DomainRuleAction::Allow,
56        }
57    }
58
59    #[must_use]
60    pub fn deny(domain: impl Into<String>, port: u16) -> Self {
61        Self {
62            domain: domain.into(),
63            port,
64            action: DomainRuleAction::Deny,
65        }
66    }
67
68    fn matches(&self, host: &str, port: u16) -> bool {
69        if self.port != port {
70            return false;
71        }
72        let host = host.trim_end_matches('.').to_ascii_lowercase();
73        let pattern = self.domain.trim_end_matches('.').to_ascii_lowercase();
74        if let Some(suffix) = pattern.strip_prefix("*.") {
75            host == suffix || host.ends_with(&format!(".{suffix}"))
76        } else {
77            host == pattern
78        }
79    }
80}
81
82/// Decision for a proxy request. Unknown destinations are denied.
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub enum ProxyDecision {
85    Allow,
86    Deny,
87}
88
89/// Ordered domain rules; deny wins, then allow, then default deny.
90#[derive(Debug, Clone, Default, PartialEq, Eq)]
91pub struct DomainPolicy {
92    rules: Vec<DomainRule>,
93}
94
95impl DomainPolicy {
96    #[must_use]
97    pub fn new(rules: Vec<DomainRule>) -> Self {
98        Self { rules }
99    }
100
101    /// Build an allow-only policy from the sandbox config's allowlist.
102    #[must_use]
103    pub fn from_allowlist(entries: &[NetworkAllowlistEntry]) -> Self {
104        Self::new(
105            entries
106                .iter()
107                .map(|entry| DomainRule::allow(entry.domain.clone(), entry.port))
108                .collect(),
109        )
110    }
111
112    #[must_use]
113    pub fn decide(&self, host: &str, port: u16) -> ProxyDecision {
114        if self
115            .rules
116            .iter()
117            .any(|rule| rule.action == DomainRuleAction::Deny && rule.matches(host, port))
118        {
119            return ProxyDecision::Deny;
120        }
121        if self
122            .rules
123            .iter()
124            .any(|rule| rule.action == DomainRuleAction::Allow && rule.matches(host, port))
125        {
126            return ProxyDecision::Allow;
127        }
128        ProxyDecision::Deny
129    }
130}
131
132/// Whether this platform can restrict a child to the proxy exactly.
133///
134/// macOS Seatbelt can allow only the proxy's loopback ports under `(deny
135/// default)`. Linux cannot: seccomp cannot inspect `connect()` destinations
136/// and this build has no network-namespace relay, so hostname allowlists stay
137/// fail-closed there rather than granting unrestricted IP sockets.
138#[must_use]
139pub const fn proxy_enforcement_available() -> bool {
140    cfg!(target_os = "macos")
141}
142
143/// Loopback addresses the sandbox must allow outbound to.
144#[derive(Debug, Clone, Copy, PartialEq, Eq)]
145pub struct ProxyEndpoints {
146    pub http: SocketAddr,
147    pub socks5: SocketAddr,
148}
149
150impl ProxyEndpoints {
151    /// Environment variables that route common HTTP clients through the proxy.
152    /// The sandbox's environment allowlist drops unknown variables, so these
153    /// are injected after sanitization.
154    #[must_use]
155    pub fn env_vars(&self) -> Vec<(&'static str, String)> {
156        // Use `localhost`, which is also the host the Seatbelt profile permits.
157        let http = format!("http://localhost:{}", self.http.port());
158        let socks = format!("socks5://localhost:{}", self.socks5.port());
159        vec![
160            ("HTTP_PROXY", http.clone()),
161            ("http_proxy", http.clone()),
162            ("HTTPS_PROXY", http.clone()),
163            ("https_proxy", http.clone()),
164            ("ALL_PROXY", socks.clone()),
165            ("all_proxy", socks),
166            // Override any inherited bypass list: an unmatched host must go
167            // through the policy-enforcing proxy, never direct.
168            ("NO_PROXY", String::new()),
169            ("no_proxy", String::new()),
170            ("PIP_PROXY", http.clone()),
171            ("NPM_CONFIG_PROXY", http.clone()),
172            ("NPM_CONFIG_HTTPS_PROXY", http.clone()),
173            ("CARGO_HTTP_PROXY", http),
174        ]
175    }
176}
177
178/// Running proxy. Dropping it stops both accept loops.
179pub struct NetworkProxy {
180    endpoints: ProxyEndpoints,
181    http_task: JoinHandle<()>,
182    socks_task: JoinHandle<()>,
183}
184
185impl NetworkProxy {
186    #[must_use]
187    pub fn endpoints(&self) -> ProxyEndpoints {
188        self.endpoints
189    }
190}
191
192impl Drop for NetworkProxy {
193    fn drop(&mut self) {
194        self.http_task.abort();
195        self.socks_task.abort();
196    }
197}
198
199/// Start HTTP and SOCKS5 listeners on ephemeral loopback ports.
200pub async fn start_proxy(policy: DomainPolicy) -> Result<NetworkProxy> {
201    let http_listener = TcpListener::bind(("127.0.0.1", 0)).await.context("bind loopback HTTP proxy")?;
202    let socks_listener = TcpListener::bind(("127.0.0.1", 0))
203        .await
204        .context("bind loopback SOCKS5 proxy")?;
205    let endpoints = ProxyEndpoints {
206        http: http_listener.local_addr().context("HTTP proxy local address")?,
207        socks5: socks_listener.local_addr().context("SOCKS5 proxy local address")?,
208    };
209    let policy = Arc::new(policy);
210    let http_policy = Arc::clone(&policy);
211    let http_task = tokio::spawn(async move { serve_http(http_listener, http_policy).await });
212    let socks_task = tokio::spawn(async move { serve_socks(socks_listener, policy).await });
213    Ok(NetworkProxy { endpoints, http_task, socks_task })
214}
215
216async fn serve_http(listener: TcpListener, policy: Arc<DomainPolicy>) {
217    loop {
218        match listener.accept().await {
219            Ok((stream, _)) => {
220                let policy = Arc::clone(&policy);
221                tokio::spawn(async move {
222                    if let Err(error) = handle_http(stream, policy).await {
223                        warn!(%error, "HTTP proxy request failed");
224                    }
225                });
226            }
227            Err(error) => {
228                warn!(%error, "HTTP proxy accept failed");
229                return;
230            }
231        }
232    }
233}
234
235async fn serve_socks(listener: TcpListener, policy: Arc<DomainPolicy>) {
236    loop {
237        match listener.accept().await {
238            Ok((stream, _)) => {
239                let policy = Arc::clone(&policy);
240                tokio::spawn(async move {
241                    if let Err(error) = handle_socks(stream, policy).await {
242                        warn!(%error, "SOCKS5 proxy request failed");
243                    }
244                });
245            }
246            Err(error) => {
247                warn!(%error, "SOCKS5 proxy accept failed");
248                return;
249            }
250        }
251    }
252}
253
254async fn handle_http(mut client: TcpStream, policy: Arc<DomainPolicy>) -> Result<()> {
255    let mut header = Vec::new();
256    let mut chunk = [0u8; 1024];
257    loop {
258        if header.len() > MAX_HTTP_HEADER {
259            bail!("HTTP proxy request header too large");
260        }
261        let read = timeout(IO_TIMEOUT, client.read(&mut chunk))
262            .await
263            .context("HTTP proxy read timeout")??;
264        if read == 0 {
265            return Ok(());
266        }
267        let bytes = chunk.get(..read).ok_or_else(|| anyhow!("HTTP proxy read exceeded buffer"))?;
268        header.extend_from_slice(bytes);
269        if header.windows(4).any(|window| window == b"\r\n\r\n") {
270            break;
271        }
272    }
273    let after_request_line = header
274        .windows(2)
275        .position(|window| window == b"\r\n")
276        .ok_or_else(|| anyhow!("HTTP proxy request line missing"))?
277        + 2;
278    let request_line = std::str::from_utf8(
279        header
280            .get(..after_request_line.saturating_sub(2))
281            .ok_or_else(|| anyhow!("short HTTP header"))?,
282    )
283    .context("HTTP proxy request line is not UTF-8")?
284    .lines()
285    .next()
286    .unwrap_or_default();
287    let mut parts = request_line.split_whitespace();
288    let method = parts.next().unwrap_or_default();
289    let target = parts.next().unwrap_or_default();
290
291    let (host, port, is_connect) = if method.eq_ignore_ascii_case("CONNECT") {
292        let (host, port) = parse_host_port(target, 443)?;
293        (host, port, true)
294    } else if target.starts_with("http://") || target.starts_with("https://") {
295        let (host, port) = parse_url_authority(target)?;
296        (host, port, false)
297    } else {
298        bail!("HTTP proxy requires CONNECT or an absolute-form URL");
299    };
300
301    if policy.decide(&host, port) == ProxyDecision::Deny {
302        client
303            .write_all(b"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
304            .await
305            .context("write HTTP proxy denial")?;
306        return Ok(());
307    }
308
309    // DNS resolution happens only after the hostname passed the policy check.
310    let mut upstream = timeout(IO_TIMEOUT, TcpStream::connect((host.as_str(), port)))
311        .await
312        .context("HTTP proxy connect timeout")?
313        .context("HTTP proxy upstream connect")?;
314    if is_connect {
315        client
316            .write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n")
317            .await
318            .context("write CONNECT reply")?;
319    } else {
320        let origin_form = target
321            .strip_prefix("http://")
322            .or_else(|| target.strip_prefix("https://"))
323            .and_then(|rest| rest.find('/').and_then(|index| rest.get(index..)))
324            .unwrap_or("/");
325        let rewritten = format!("{method} {origin_form} HTTP/1.1\r\n");
326        upstream
327            .write_all(rewritten.as_bytes())
328            .await
329            .context("forward HTTP request line")?;
330        upstream
331            // Keep the original headers and the terminating blank line; only
332            // the request line is rewritten from absolute to origin form.
333            .write_all(header.get(after_request_line..).ok_or_else(|| anyhow!("short HTTP header"))?)
334            .await
335            .context("forward HTTP headers")?;
336    }
337    copy_bidirectional(&mut client, &mut upstream)
338        .await
339        .context("relay HTTP proxy traffic")?;
340    Ok(())
341}
342
343async fn handle_socks(mut client: TcpStream, policy: Arc<DomainPolicy>) -> Result<()> {
344    let mut greeting = [0u8; 258];
345    let read = timeout(IO_TIMEOUT, client.read(&mut greeting))
346        .await
347        .context("SOCKS5 greeting timeout")??;
348    if read < 2 || greeting[0] != 5 {
349        bail!("unsupported SOCKS5 greeting");
350    }
351    client.write_all(&[5, 0]).await.context("write SOCKS5 greeting reply")?;
352
353    let mut request = [0u8; 4];
354    timeout(IO_TIMEOUT, client.read_exact(&mut request))
355        .await
356        .context("SOCKS5 request timeout")?
357        .context("SOCKS5 request header")?;
358    if request[0] != 5 || request[1] != 1 {
359        client.write_all(&[5, 7, 0, 1, 0, 0, 0, 0, 0, 0]).await?;
360        bail!("unsupported SOCKS5 command");
361    }
362
363    let host = match request[3] {
364        1 => {
365            let mut octets = [0u8; 4];
366            client.read_exact(&mut octets).await.context("SOCKS5 IPv4 address")?;
367            IpAddr::from(octets).to_string()
368        }
369        3 => {
370            let mut length = [0u8; 1];
371            client.read_exact(&mut length).await.context("SOCKS5 domain length")?;
372            let mut bytes = vec![0u8; usize::from(length[0])];
373            client.read_exact(&mut bytes).await.context("SOCKS5 domain")?;
374            String::from_utf8(bytes).context("SOCKS5 domain is not UTF-8")?
375        }
376        4 => {
377            let mut octets = [0u8; 16];
378            client.read_exact(&mut octets).await.context("SOCKS5 IPv6 address")?;
379            IpAddr::from(octets).to_string()
380        }
381        _ => bail!("unsupported SOCKS5 address type"),
382    };
383    let mut port_bytes = [0u8; 2];
384    client.read_exact(&mut port_bytes).await.context("SOCKS5 port")?;
385    let port = u16::from_be_bytes(port_bytes);
386
387    if policy.decide(&host, port) == ProxyDecision::Deny {
388        client
389            .write_all(&[5, 2, 0, 1, 0, 0, 0, 0, 0, 0])
390            .await
391            .context("write SOCKS5 denial")?;
392        return Ok(());
393    }
394
395    // Do not resolve the hostname until after the policy decision.
396    let mut upstream = timeout(IO_TIMEOUT, TcpStream::connect((host.as_str(), port)))
397        .await
398        .context("SOCKS5 connect timeout")?
399        .context("SOCKS5 upstream connect")?;
400    client
401        .write_all(&[5, 0, 0, 1, 0, 0, 0, 0, 0, 0])
402        .await
403        .context("write SOCKS5 success")?;
404    copy_bidirectional(&mut client, &mut upstream)
405        .await
406        .context("relay SOCKS5 traffic")?;
407    Ok(())
408}
409
410fn parse_host_port(target: &str, default_port: u16) -> Result<(String, u16)> {
411    let host = target.trim().trim_end_matches('/');
412    if let Some((host, port)) = host.rsplit_once(':') {
413        let port = port.parse::<u16>().context("invalid proxy port")?;
414        Ok((host.trim_matches(['[', ']']).to_string(), port))
415    } else {
416        Ok((host.to_string(), default_port))
417    }
418}
419
420fn parse_url_authority(target: &str) -> Result<(String, u16)> {
421    let rest = target
422        .strip_prefix("http://")
423        .or_else(|| target.strip_prefix("https://"))
424        .ok_or_else(|| anyhow!("unsupported proxy URL scheme"))?;
425    let authority = rest.split('/').next().unwrap_or_default();
426    let authority = authority.rsplit('@').next().unwrap_or_default();
427    let default_port = if target.starts_with("https://") { 443 } else { 80 };
428    parse_host_port(authority, default_port)
429}