| 1 | use crate::network_policy::{Decision, NetworkPolicy, NetworkPolicyDecider}; |
| 2 | use anyhow::{anyhow, bail}; |
| 3 | use codewhale_tools::ToolError; |
| 4 | use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; |
| 5 | use std::time::Duration; |
| 6 | |
| 7 | /// Wall-clock bound for one pre-flight DNS resolution. The resolution runs |
| 8 | /// before the guarded request (and once per redirect), so a hung resolver |
| 9 | /// would otherwise stall the tool far beyond the documented request timeout |
| 10 | /// envelope of the calling fetch tool. |
| 11 | pub const DNS_PREFLIGHT_TIMEOUT: Duration = Duration::from_secs(10); |
| 12 | |
| 13 | /// DNS pin returned when a hostname was resolved to a validated public IP. |
| 14 | /// Callers should pass this to `reqwest::ClientBuilder::resolve` so the |
| 15 | /// connection uses the pre-validated address instead of re-resolving. |
| 16 | pub type DnsPin = Option<(String, IpAddr)>; |
| 17 | |
| 18 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 19 | pub enum PrivateTargets { |
| 20 | Refuse, |
| 21 | TypedLocalHosts, |
| 22 | } |
| 23 | |
| 24 | /// Build the transport used after a destination has passed SSRF validation. |
| 25 | /// Ambient HTTP(S)/SOCKS proxies are deliberately disabled: a proxy would |
| 26 | /// receive the original hostname, resolve it again outside this process, and |
| 27 | /// bypass the validated DNS pin. |
| 28 | pub fn guarded_reqwest_client_builder() -> reqwest::ClientBuilder { |
| 29 | codewhale_release::tls::reqwest_client_builder().no_proxy() |
| 30 | } |
| 31 | |
| 32 | #[derive(Clone, Copy, Debug, Default)] |
| 33 | pub struct PublicAddressResolver; |
| 34 | |
| 35 | impl reqwest::dns::Resolve for PublicAddressResolver { |
| 36 | fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving { |
| 37 | let host = name.as_str().to_string(); |
| 38 | Box::pin(async move { |
| 39 | let addrs: Vec<SocketAddr> = tokio::time::timeout( |
| 40 | DNS_PREFLIGHT_TIMEOUT, |
| 41 | tokio::net::lookup_host((host.as_str(), 0u16)), |
| 42 | ) |
| 43 | .await |
| 44 | .map_err(|_| format!("timed out resolving {host}"))? |
| 45 | .map_err(|error| format!("could not resolve {host}: {error}"))? |
| 46 | .collect(); |
| 47 | if let Some(addr) = addrs.iter().find(|addr| is_restricted_ip(&addr.ip())) { |
| 48 | return Err(format!( |
| 49 | "{host} resolved to restricted address {} (private/loopback/link-local/metadata); registry-admitted providers must resolve to public addresses", |
| 50 | addr.ip() |
| 51 | ) |
| 52 | .into()); |
| 53 | } |
| 54 | if addrs.is_empty() { |
| 55 | return Err(format!("{host} resolved to no addresses").into()); |
| 56 | } |
| 57 | let addrs: reqwest::dns::Addrs = Box::new(addrs.into_iter()); |
| 58 | Ok(addrs) |
| 59 | }) |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | pub fn public_address_reqwest_client_builder() -> reqwest::ClientBuilder { |
| 64 | guarded_reqwest_client_builder().dns_resolver(PublicAddressResolver) |
| 65 | } |
| 66 | |
| 67 | const CLOUD_METADATA_V4: [Ipv4Addr; 4] = [ |
| 68 | Ipv4Addr::new(169, 254, 169, 254), |
| 69 | Ipv4Addr::new(100, 100, 100, 200), |
| 70 | Ipv4Addr::new(168, 63, 129, 16), |
| 71 | Ipv4Addr::new(192, 0, 0, 192), |
| 72 | ]; |
| 73 | |
| 74 | const CLOUD_METADATA_V6: [Ipv6Addr; 2] = [ |
| 75 | Ipv6Addr::new(0xfd00, 0x0ec2, 0, 0, 0, 0, 0, 0x0254), |
| 76 | Ipv6Addr::new(0xfd20, 0x00ce, 0, 0, 0, 0, 0, 0x0254), |
| 77 | ]; |
| 78 | |
| 79 | /// Check if an IP address is loopback, private, link-local, cloud-metadata, |
| 80 | /// multicast, or reserved — all addresses that should not be reachable via |
| 81 | /// an LLM-initiated fetch request (SSRF prevention). |
| 82 | pub fn is_restricted_ip(ip: &IpAddr) -> bool { |
| 83 | if is_cloud_metadata_ip(ip) { |
| 84 | return true; |
| 85 | } |
| 86 | match ip { |
| 87 | IpAddr::V4(v4) => { |
| 88 | v4.is_loopback() |
| 89 | || v4.is_private() |
| 90 | || v4.is_link_local() |
| 91 | || v4.is_multicast() |
| 92 | || v4.is_broadcast() |
| 93 | || v4.is_unspecified() |
| 94 | || v4.octets()[0] == 0 |
| 95 | // 100.64.0.0/10 — Carrier-grade NAT (CGNAT / shared address space) |
| 96 | || matches!(v4.octets(), [100, 64..=127, ..]) |
| 97 | // 198.18.0.0/15 — IETF benchmark testing |
| 98 | || matches!(v4.octets(), [198, 18..=19, ..]) |
| 99 | // 240.0.0.0/4 — reserved (former Class E) |
| 100 | || v4.octets()[0] >= 240 |
| 101 | } |
| 102 | IpAddr::V6(v6) => { |
| 103 | // IPv4-mapped IPv6 addresses (::ffff:a.b.c.d) are refused whole, so |
| 104 | // ::ffff:127.0.0.1 and the like cannot bypass the IPv4 rules. |
| 105 | if v6.is_unspecified() || matches!(v6.segments(), [0, 0, 0, 0, 0, 0xffff, ..]) { |
| 106 | return true; |
| 107 | } |
| 108 | // A translator on the path reaches the embedded IPv4 target, so a |
| 109 | // prefix must not hide a restricted address. |
| 110 | if embedded_ipv4(*v6) |
| 111 | .iter() |
| 112 | .any(|v4| is_restricted_ip(&IpAddr::V4(*v4))) |
| 113 | { |
| 114 | return true; |
| 115 | } |
| 116 | v6.is_loopback() |
| 117 | || v6.is_multicast() |
| 118 | || matches!(v6.segments(), [0xfc00..=0xfdff, ..]) // ULA fc00::/7 |
| 119 | || matches!(v6.segments(), [0xfe80..=0xfebf, ..]) // Link-local fe80::/10 |
| 120 | || matches!(v6.segments(), [0xfec0..=0xfeff, ..]) // Site-local fec0::/10 |
| 121 | || matches!(v6.segments(), [0x2002, ..]) // 6to4 2002::/16 |
| 122 | || matches!(v6.segments(), [0x2001, 0x0000, ..]) // Teredo 2001::/32 |
| 123 | || matches!(v6.segments(), [0, 0, 0, 0, 0, 0, ..]) // IPv4-compatible ::a.b.c.d |
| 124 | || matches!(v6.segments(), [0, 0, 0, 0, 0xffff, 0, ..]) |
| 125 | } |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | fn local_use_nat64_ipv4_layouts(v6: Ipv6Addr) -> Option<[Ipv4Addr; 4]> { |
| 130 | if !matches!(v6.segments(), [0x0064, 0xff9b, 0x0001, ..]) { |
| 131 | return None; |
| 132 | } |
| 133 | let o = v6.octets(); |
| 134 | Some([ |
| 135 | Ipv4Addr::new(o[6], o[7], o[9], o[10]), |
| 136 | Ipv4Addr::new(o[7], o[9], o[10], o[11]), |
| 137 | Ipv4Addr::new(o[9], o[10], o[11], o[12]), |
| 138 | Ipv4Addr::new(o[12], o[13], o[14], o[15]), |
| 139 | ]) |
| 140 | } |
| 141 | |
| 142 | pub fn is_cloud_metadata_ip(ip: &IpAddr) -> bool { |
| 143 | match ip { |
| 144 | IpAddr::V4(v4) => v4.is_link_local() || CLOUD_METADATA_V4.contains(v4), |
| 145 | IpAddr::V6(v6) => { |
| 146 | matches!(v6.segments(), [0xfe80..=0xfebf, ..]) |
| 147 | || CLOUD_METADATA_V6.contains(v6) |
| 148 | || embedded_ipv4(*v6) |
| 149 | .iter() |
| 150 | .any(|v4| is_cloud_metadata_ip(&IpAddr::V4(*v4))) |
| 151 | || local_use_nat64_ipv4_layouts(*v6) |
| 152 | .into_iter() |
| 153 | .flatten() |
| 154 | .any(|v4| is_cloud_metadata_ip(&IpAddr::V4(v4))) |
| 155 | } |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | pub fn embedded_ipv4_addrs(v6: Ipv6Addr) -> Vec<Ipv4Addr> { |
| 160 | let mut addrs = embedded_ipv4(v6); |
| 161 | if let Some(local_nat64) = local_use_nat64_ipv4_layouts(v6) { |
| 162 | addrs.extend(local_nat64); |
| 163 | } |
| 164 | addrs |
| 165 | } |
| 166 | |
| 167 | fn embedded_ipv4(v6: Ipv6Addr) -> Vec<Ipv4Addr> { |
| 168 | let octets = v6.octets(); |
| 169 | let tail = Ipv4Addr::new(octets[12], octets[13], octets[14], octets[15]); |
| 170 | let from_halves = |high: u16, low: u16| { |
| 171 | Ipv4Addr::new((high >> 8) as u8, high as u8, (low >> 8) as u8, low as u8) |
| 172 | }; |
| 173 | match v6.segments() { |
| 174 | [0, 0, 0, 0, 0, 0xffff, ..] | [0, 0, 0, 0, 0xffff, 0, ..] | [0, 0, 0, 0, 0, 0, ..] => { |
| 175 | vec![tail] |
| 176 | } |
| 177 | [0x0064, 0xff9b, 0, 0, 0, 0, ..] => vec![tail], |
| 178 | [0x0064, 0xff9b, 0x0001, 0, 0, 0, ..] => vec![tail], |
| 179 | [0x0064, 0xff9b, 0x0001, a, b, c, d, e] => { |
| 180 | let layout_48 = Ipv4Addr::new((a >> 8) as u8, a as u8, b as u8, (c >> 8) as u8); |
| 181 | if d | e == 0 { |
| 182 | vec![layout_48] |
| 183 | } else { |
| 184 | vec![layout_48, tail] |
| 185 | } |
| 186 | } |
| 187 | [0x2002, high, low, ..] => vec![from_halves(high, low)], |
| 188 | [ |
| 189 | 0x2001, |
| 190 | 0x0000, |
| 191 | server_high, |
| 192 | server_low, |
| 193 | _, |
| 194 | _, |
| 195 | client_high, |
| 196 | client_low, |
| 197 | ] => { |
| 198 | vec![ |
| 199 | from_halves(server_high, server_low), |
| 200 | from_halves(!client_high, !client_low), |
| 201 | ] |
| 202 | } |
| 203 | _ => Vec::new(), |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | fn is_local_network_ip(ip: &IpAddr) -> bool { |
| 208 | if is_cloud_metadata_ip(ip) { |
| 209 | return false; |
| 210 | } |
| 211 | match ip { |
| 212 | IpAddr::V4(v4) => { |
| 213 | v4.is_loopback() || v4.is_private() || matches!(v4.octets(), [100, 64..=127, ..]) |
| 214 | } |
| 215 | IpAddr::V6(v6) => v6.is_loopback() || matches!(v6.segments(), [0xfc00..=0xfdff, ..]), |
| 216 | } |
| 217 | } |
| 218 | |
| 219 | fn is_localhost_name(bare: &str) -> bool { |
| 220 | bare == "localhost" || bare == "localhost.localdomain" || bare.ends_with(".localhost") |
| 221 | } |
| 222 | |
| 223 | fn is_localhost_wildcard(bare: &str) -> bool { |
| 224 | let Some(suffix) = bare.strip_prefix("*.").or_else(|| bare.strip_prefix('.')) else { |
| 225 | return false; |
| 226 | }; |
| 227 | if suffix.is_empty() { |
| 228 | return false; |
| 229 | } |
| 230 | let policy = NetworkPolicy { |
| 231 | allow: vec![bare.to_string()], |
| 232 | ..NetworkPolicy::default() |
| 233 | }; |
| 234 | policy.explicitly_allows("localhost.localdomain") |
| 235 | || policy.explicitly_allows("sub.localhost") |
| 236 | || is_localhost_name(&format!("sub.{suffix}")) |
| 237 | } |
| 238 | |
| 239 | fn literal_ip(host: &str) -> Option<IpAddr> { |
| 240 | host.strip_prefix('[') |
| 241 | .and_then(|rest| rest.strip_suffix(']')) |
| 242 | .unwrap_or(host) |
| 243 | .parse() |
| 244 | .ok() |
| 245 | } |
| 246 | |
| 247 | fn visibly_local_host(bare: &str) -> bool { |
| 248 | is_localhost_name(bare) || literal_ip(bare).is_some_and(|ip| is_local_network_ip(&ip)) |
| 249 | } |
| 250 | |
| 251 | pub fn is_visibly_local_host(host: &str) -> bool { |
| 252 | let bare = bare_host(host); |
| 253 | visibly_local_host(&bare) || is_localhost_wildcard(&bare) |
| 254 | } |
| 255 | |
| 256 | fn bare_host(host: &str) -> String { |
| 257 | host.trim().trim_end_matches('.').to_ascii_lowercase() |
| 258 | } |
| 259 | |
| 260 | pub fn fetch_target_host(url: &reqwest::Url) -> Result<String, ToolError> { |
| 261 | if url.scheme() != "http" && url.scheme() != "https" { |
| 262 | return Err(ToolError::invalid_input( |
| 263 | "only http:// and https:// URLs are supported", |
| 264 | )); |
| 265 | } |
| 266 | |
| 267 | url.host_str() |
| 268 | .map(str::to_ascii_lowercase) |
| 269 | .ok_or_else(|| ToolError::invalid_input("URL must include a host")) |
| 270 | } |
| 271 | |
| 272 | fn explicitly_allowed(decider: Option<&NetworkPolicyDecider>, bare: &str) -> bool { |
| 273 | decider.is_some_and(|decider| decider.policy().explicitly_allows(bare)) |
| 274 | } |
| 275 | |
| 276 | pub fn is_typed_local_host( |
| 277 | decider: Option<&NetworkPolicyDecider>, |
| 278 | host: &str, |
| 279 | private: PrivateTargets, |
| 280 | ) -> bool { |
| 281 | if private != PrivateTargets::TypedLocalHosts { |
| 282 | return false; |
| 283 | } |
| 284 | let bare = bare_host(host); |
| 285 | visibly_local_host(&bare) && explicitly_allowed(decider, &bare) |
| 286 | } |
| 287 | |
| 288 | fn restricted_host_hint(host: &str, private: PrivateTargets) -> String { |
| 289 | match private { |
| 290 | PrivateTargets::Refuse => { |
| 291 | "this request never reaches local or private addresses".to_string() |
| 292 | } |
| 293 | PrivateTargets::TypedLocalHosts if visibly_local_host(&bare_host(host)) => format!( |
| 294 | "add {host:?} with `/network allow {host}` (or `network.allow` in config) to permit it" |
| 295 | ), |
| 296 | PrivateTargets::TypedLocalHosts => { |
| 297 | "`/network allow` admits only a localhost name or a private IP address that you \ |
| 298 | typed, and never a cloud metadata address" |
| 299 | .to_string() |
| 300 | } |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | pub async fn validate_fetch_destination( |
| 305 | host: String, |
| 306 | decider: Option<&NetworkPolicyDecider>, |
| 307 | tool: &str, |
| 308 | resolve: bool, |
| 309 | private: PrivateTargets, |
| 310 | ) -> Result<DnsPin, ToolError> { |
| 311 | // SSRF protection: reject localhost names and private/link-local/loopback |
| 312 | // IP literals; when `resolve` is set, also resolve the hostname and reject |
| 313 | // restricted answers. A caller that passes `TypedLocalHosts` lets a |
| 314 | // `network.allow` entry admit a localhost name or private IP literal the |
| 315 | // person typed. Cloud metadata stays blocked either way. |
| 316 | let bare = bare_host(&host); |
| 317 | let typed_local = is_typed_local_host(decider, &bare, private); |
| 318 | if !typed_local && is_localhost_name(&bare) { |
| 319 | return Err(ToolError::permission_denied(format!( |
| 320 | "requests to localhost are not allowed; {}", |
| 321 | restricted_host_hint(&bare, private) |
| 322 | ))); |
| 323 | } |
| 324 | // Normalize bracketed IPv6 literals before the literal-IP check so they |
| 325 | // route through the same restricted-IP policy as unbracketed forms |
| 326 | // (GHSA-88gh-2526-gfrr). |
| 327 | if let Some(ip) = literal_ip(&bare) { |
| 328 | if is_restricted_ip(&ip) && !(typed_local && is_local_network_ip(&ip)) { |
| 329 | return Err(ToolError::permission_denied(format!( |
| 330 | "IP {ip} is a restricted address (private/loopback/link-local); {}", |
| 331 | restricted_host_hint(&bare, private) |
| 332 | ))); |
| 333 | } |
| 334 | return Ok(None); |
| 335 | } |
| 336 | if !resolve { |
| 337 | return Ok(None); |
| 338 | } |
| 339 | |
| 340 | let addrs = tokio::time::timeout( |
| 341 | DNS_PREFLIGHT_TIMEOUT, |
| 342 | tokio::net::lookup_host((host.as_str(), 0u16)), |
| 343 | ) |
| 344 | .await |
| 345 | .map_err(|_| { |
| 346 | ToolError::permission_denied(format!("timed out resolving host before {tool} request")) |
| 347 | })? |
| 348 | .map_err(|e| { |
| 349 | ToolError::permission_denied(format!("could not resolve host before {tool} request: {e}")) |
| 350 | })?; |
| 351 | let mut first_valid: Option<IpAddr> = None; |
| 352 | for addr in addrs { |
| 353 | validate_dns_resolved_ip(&host, &addr.ip(), decider, tool, private)?; |
| 354 | if first_valid.is_none() { |
| 355 | first_valid = Some(addr.ip()); |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | let Some(validated_ip) = first_valid else { |
| 360 | return Err(ToolError::permission_denied(format!( |
| 361 | "host resolved to no addresses before {tool} request" |
| 362 | ))); |
| 363 | }; |
| 364 | Ok(Some((host, validated_ip))) |
| 365 | } |
| 366 | |
| 367 | pub fn validate_dns_resolved_ip( |
| 368 | host: &str, |
| 369 | ip: &IpAddr, |
| 370 | decider: Option<&NetworkPolicyDecider>, |
| 371 | tool: &str, |
| 372 | private: PrivateTargets, |
| 373 | ) -> Result<(), ToolError> { |
| 374 | if !is_restricted_ip(ip) { |
| 375 | return Ok(()); |
| 376 | } |
| 377 | |
| 378 | let bare = bare_host(host); |
| 379 | if is_localhost_name(&bare) && ip.is_loopback() && is_typed_local_host(decider, &bare, private) |
| 380 | { |
| 381 | return Ok(()); |
| 382 | } |
| 383 | |
| 384 | // A fake-IP exception requires both an explicitly trusted hostname and an |
| 385 | // explicitly trusted placeholder CIDR. The CIDR parser admits only subnets |
| 386 | // inside 198.18.0.0/15, so real private/loopback/link-local/metadata/ULA |
| 387 | // addresses remain blocked even when the hostname is trusted. |
| 388 | if let Some(decider) = decider |
| 389 | && decider.is_trusted_fakeip_addr(ip) |
| 390 | && decider.trusts_proxy_fakeip_host(host) |
| 391 | { |
| 392 | decider.record_trusted_proxy_fakeip_allow(host, tool); |
| 393 | return Ok(()); |
| 394 | } |
| 395 | |
| 396 | Err(ToolError::permission_denied(format!( |
| 397 | "resolved IP {ip} is a restricted address (private/loopback/link-local); {}", |
| 398 | match private { |
| 399 | PrivateTargets::Refuse => restricted_host_hint(host, private), |
| 400 | PrivateTargets::TypedLocalHosts => |
| 401 | "`/network allow` does not admit a host name that resolves to a private address" |
| 402 | .to_string(), |
| 403 | } |
| 404 | ))) |
| 405 | } |
| 406 | |
| 407 | pub type RedirectCheck = dyn Fn(&reqwest::Url) -> anyhow::Result<()> + Send + Sync; |
| 408 | |
| 409 | pub struct GuardedGet<'a> { |
| 410 | url: &'a str, |
| 411 | network: &'a NetworkPolicy, |
| 412 | tool: &'a str, |
| 413 | private: PrivateTargets, |
| 414 | if_none_match: Option<&'a str>, |
| 415 | accept: Option<&'a str>, |
| 416 | connect_timeout: Duration, |
| 417 | total_timeout: Duration, |
| 418 | max_redirects: usize, |
| 419 | redirect_check: Option<&'a RedirectCheck>, |
| 420 | trust_first_hop: bool, |
| 421 | } |
| 422 | |
| 423 | impl<'a> GuardedGet<'a> { |
| 424 | pub fn new( |
| 425 | url: &'a str, |
| 426 | network: &'a NetworkPolicy, |
| 427 | tool: &'a str, |
| 428 | private: PrivateTargets, |
| 429 | ) -> Self { |
| 430 | Self { |
| 431 | url, |
| 432 | network, |
| 433 | tool, |
| 434 | private, |
| 435 | if_none_match: None, |
| 436 | accept: None, |
| 437 | connect_timeout: Duration::from_secs(10), |
| 438 | total_timeout: Duration::from_secs(60), |
| 439 | max_redirects: 5, |
| 440 | redirect_check: None, |
| 441 | trust_first_hop: false, |
| 442 | } |
| 443 | } |
| 444 | |
| 445 | #[must_use] |
| 446 | pub fn if_none_match(mut self, etag: Option<&'a str>) -> Self { |
| 447 | self.if_none_match = etag; |
| 448 | self |
| 449 | } |
| 450 | |
| 451 | #[must_use] |
| 452 | pub fn accept(mut self, accept: &'a str) -> Self { |
| 453 | self.accept = Some(accept); |
| 454 | self |
| 455 | } |
| 456 | |
| 457 | #[must_use] |
| 458 | pub fn timeouts(mut self, connect: Duration, total: Duration) -> Self { |
| 459 | self.connect_timeout = connect; |
| 460 | self.total_timeout = total; |
| 461 | self |
| 462 | } |
| 463 | |
| 464 | #[must_use] |
| 465 | pub fn max_redirects(mut self, max_redirects: usize) -> Self { |
| 466 | self.max_redirects = max_redirects; |
| 467 | self |
| 468 | } |
| 469 | |
| 470 | #[must_use] |
| 471 | pub fn redirect_check(mut self, check: &'a RedirectCheck) -> Self { |
| 472 | self.redirect_check = Some(check); |
| 473 | self |
| 474 | } |
| 475 | |
| 476 | #[cfg(any(test, feature = "test-support"))] |
| 477 | #[must_use] |
| 478 | pub fn trust_first_hop(mut self) -> Self { |
| 479 | self.trust_first_hop = true; |
| 480 | self |
| 481 | } |
| 482 | |
| 483 | pub async fn send(self) -> anyhow::Result<reqwest::Response> { |
| 484 | let decider = NetworkPolicyDecider::new(self.network.clone(), None); |
| 485 | let mut current = reqwest::Url::parse(self.url).map_err(|_| anyhow!("invalid url"))?; |
| 486 | let mut trusted = self.trust_first_hop; |
| 487 | for _ in 0..=self.max_redirects { |
| 488 | let host = fetch_target_host(¤t)?; |
| 489 | if matches!(self.network.decide(&host), Decision::Deny) { |
| 490 | bail!("network policy denies {host}"); |
| 491 | } |
| 492 | let local = is_typed_local_host(Some(&decider), &host, self.private); |
| 493 | let proxy = if trusted || local { |
| 494 | None |
| 495 | } else { |
| 496 | crate::proxy::configured_mcp_proxy(¤t, false, |key| std::env::var(key))? |
| 497 | }; |
| 498 | let pin = if std::mem::take(&mut trusted) { |
| 499 | None |
| 500 | } else { |
| 501 | validate_fetch_destination( |
| 502 | host, |
| 503 | Some(&decider), |
| 504 | self.tool, |
| 505 | proxy.is_none(), |
| 506 | self.private, |
| 507 | ) |
| 508 | .await? |
| 509 | }; |
| 510 | let mut builder = guarded_reqwest_client_builder() |
| 511 | .redirect(reqwest::redirect::Policy::none()) |
| 512 | .connect_timeout(self.connect_timeout) |
| 513 | .timeout(self.total_timeout); |
| 514 | if let Some(proxy) = proxy { |
| 515 | builder = builder.proxy(proxy); |
| 516 | } else if let Some((host, ip)) = pin { |
| 517 | builder = builder.resolve(&host, SocketAddr::new(ip, 0)); |
| 518 | } |
| 519 | let client = builder.build().map_err(|err| { |
| 520 | anyhow!("building the download client failed: {}", err.without_url()) |
| 521 | })?; |
| 522 | let mut request = client.get(current.clone()); |
| 523 | if let Some(etag) = self.if_none_match { |
| 524 | request = request.header(reqwest::header::IF_NONE_MATCH, etag); |
| 525 | } |
| 526 | if let Some(accept) = self.accept { |
| 527 | request = request.header(reqwest::header::ACCEPT, accept); |
| 528 | } |
| 529 | let origin = current.origin().ascii_serialization(); |
| 530 | let response = request.send().await.map_err(|err| { |
| 531 | anyhow::Error::new(err.without_url()).context(format!("failed to GET {origin}")) |
| 532 | })?; |
| 533 | if !response.status().is_redirection() { |
| 534 | return Ok(response); |
| 535 | } |
| 536 | let Some(location) = response |
| 537 | .headers() |
| 538 | .get(reqwest::header::LOCATION) |
| 539 | .and_then(|value| value.to_str().ok()) |
| 540 | else { |
| 541 | return Ok(response); |
| 542 | }; |
| 543 | let next = response |
| 544 | .url() |
| 545 | .join(location) |
| 546 | .map_err(|_| anyhow!("invalid redirect location from {origin}"))?; |
| 547 | if let Some(check) = self.redirect_check { |
| 548 | check(&next)?; |
| 549 | } |
| 550 | if current.scheme() == "https" && next.scheme() != "https" { |
| 551 | bail!("redirect from {origin} would downgrade HTTPS"); |
| 552 | } |
| 553 | current = next; |
| 554 | } |
| 555 | bail!( |
| 556 | "too many redirects from {}; the limit is {}", |
| 557 | reqwest::Url::parse(self.url) |
| 558 | .map(|url| url.origin().ascii_serialization()) |
| 559 | .unwrap_or_default(), |
| 560 | self.max_redirects |
| 561 | ) |
| 562 | } |
| 563 | } |
| 564 | |
| 565 | #[cfg(test)] |
| 566 | mod tests { |
| 567 | use super::*; |
| 568 | |
| 569 | #[tokio::test] |
| 570 | async fn public_address_resolver_refuses_names_that_resolve_to_loopback() { |
| 571 | use reqwest::dns::Resolve as _; |
| 572 | use std::str::FromStr as _; |
| 573 | let error = match PublicAddressResolver |
| 574 | .resolve(reqwest::dns::Name::from_str("localhost").expect("name")) |
| 575 | .await |
| 576 | { |
| 577 | Ok(addrs) => panic!( |
| 578 | "localhost admitted: {:?}", |
| 579 | addrs.collect::<Vec<SocketAddr>>() |
| 580 | ), |
| 581 | Err(error) => error.to_string(), |
| 582 | }; |
| 583 | assert!(error.contains("restricted address"), "{error}"); |
| 584 | } |
| 585 | #[cfg(not(windows))] |
| 586 | use std::io::{Read, Write}; |
| 587 | #[cfg(not(windows))] |
| 588 | use std::net::{Ipv4Addr, SocketAddr, TcpListener}; |
| 589 | #[cfg(not(windows))] |
| 590 | use std::process::Command; |
| 591 | #[cfg(not(windows))] |
| 592 | use std::sync::Arc; |
| 593 | #[cfg(not(windows))] |
| 594 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 595 | #[cfg(not(windows))] |
| 596 | use std::time::{Duration, Instant}; |
| 597 | |
| 598 | #[cfg(not(windows))] |
| 599 | #[derive(Clone, Copy, Debug)] |
| 600 | enum AmbientProxyKind { |
| 601 | Http, |
| 602 | HttpsConnect, |
| 603 | SocksRemoteDns, |
| 604 | } |
| 605 | |
| 606 | #[cfg(not(windows))] |
| 607 | fn spawn_accept_probe( |
| 608 | stop: Arc<AtomicBool>, |
| 609 | respond_http: bool, |
| 610 | drain_http_headers: bool, |
| 611 | ) -> (u16, std::thread::JoinHandle<bool>) { |
| 612 | let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind probe listener"); |
| 613 | let port = listener.local_addr().expect("probe address").port(); |
| 614 | listener |
| 615 | .set_nonblocking(true) |
| 616 | .expect("nonblocking probe listener"); |
| 617 | let handle = std::thread::spawn(move || { |
| 618 | let deadline = Instant::now() + Duration::from_secs(5); |
| 619 | loop { |
| 620 | match listener.accept() { |
| 621 | Ok((mut stream, _)) => { |
| 622 | // Accepted sockets inherit nonblocking from the listener |
| 623 | // on several Unixes. Restore blocking mode before timed |
| 624 | // header reads so a not-yet-ready socket is not treated |
| 625 | // as a hard failure (WouldBlock / EAGAIN). |
| 626 | stream |
| 627 | .set_nonblocking(false) |
| 628 | .expect("blocking probe stream"); |
| 629 | if drain_http_headers { |
| 630 | stream |
| 631 | .set_read_timeout(Some(Duration::from_secs(2))) |
| 632 | .expect("probe read timeout"); |
| 633 | let mut request = Vec::new(); |
| 634 | let mut chunk = [0_u8; 1024]; |
| 635 | while !request.windows(4).any(|window| window == b"\r\n\r\n") { |
| 636 | let read = match stream.read(&mut chunk) { |
| 637 | Ok(n) => n, |
| 638 | Err(err) |
| 639 | if matches!( |
| 640 | err.kind(), |
| 641 | std::io::ErrorKind::WouldBlock |
| 642 | | std::io::ErrorKind::TimedOut |
| 643 | | std::io::ErrorKind::Interrupted |
| 644 | ) => |
| 645 | { |
| 646 | continue; |
| 647 | } |
| 648 | Err(err) => panic!("read probe request: {err}"), |
| 649 | }; |
| 650 | if read == 0 { |
| 651 | break; |
| 652 | } |
| 653 | request.extend_from_slice(&chunk[..read]); |
| 654 | if Instant::now() >= deadline { |
| 655 | break; |
| 656 | } |
| 657 | } |
| 658 | } |
| 659 | if respond_http { |
| 660 | let _ = stream.write_all( |
| 661 | b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok", |
| 662 | ); |
| 663 | } |
| 664 | return true; |
| 665 | } |
| 666 | Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => {} |
| 667 | Err(err) => panic!("probe accept failed: {err}"), |
| 668 | } |
| 669 | if stop.load(Ordering::SeqCst) || Instant::now() >= deadline { |
| 670 | return false; |
| 671 | } |
| 672 | std::thread::sleep(Duration::from_millis(10)); |
| 673 | } |
| 674 | }); |
| 675 | (port, handle) |
| 676 | } |
| 677 | |
| 678 | #[cfg(not(windows))] |
| 679 | fn run_ambient_proxy_probe(kind: AmbientProxyKind, guarded: bool) -> (bool, bool) { |
| 680 | let stop = Arc::new(AtomicBool::new(false)); |
| 681 | let (target_port, target_handle) = spawn_accept_probe( |
| 682 | Arc::clone(&stop), |
| 683 | matches!( |
| 684 | kind, |
| 685 | AmbientProxyKind::Http | AmbientProxyKind::SocksRemoteDns |
| 686 | ), |
| 687 | matches!( |
| 688 | kind, |
| 689 | AmbientProxyKind::Http | AmbientProxyKind::SocksRemoteDns |
| 690 | ), |
| 691 | ); |
| 692 | let (proxy_port, proxy_handle) = spawn_accept_probe(Arc::clone(&stop), true, false); |
| 693 | |
| 694 | let mut command = Command::new(std::env::current_exe().expect("current test executable")); |
| 695 | command.args([ |
| 696 | "--exact", |
| 697 | "guard::tests::guarded_transport_proxy_probe_child", |
| 698 | "--ignored", |
| 699 | "--nocapture", |
| 700 | ]); |
| 701 | for key in [ |
| 702 | "HTTP_PROXY", |
| 703 | "http_proxy", |
| 704 | "HTTPS_PROXY", |
| 705 | "https_proxy", |
| 706 | "ALL_PROXY", |
| 707 | "all_proxy", |
| 708 | "NO_PROXY", |
| 709 | "no_proxy", |
| 710 | "REQUEST_METHOD", |
| 711 | ] { |
| 712 | command.env_remove(key); |
| 713 | } |
| 714 | command |
| 715 | .env("CODEWHALE_PROXY_PROBE_CHILD", "1") |
| 716 | .env( |
| 717 | "CODEWHALE_PROXY_PROBE_GUARDED", |
| 718 | if guarded { "1" } else { "0" }, |
| 719 | ) |
| 720 | .env("CODEWHALE_PROXY_PROBE_TARGET_PORT", target_port.to_string()); |
| 721 | match kind { |
| 722 | AmbientProxyKind::Http => { |
| 723 | let proxy = format!("http://127.0.0.1:{proxy_port}"); |
| 724 | command |
| 725 | .env("CODEWHALE_PROXY_PROBE_SCHEME", "http") |
| 726 | .env("HTTP_PROXY", &proxy) |
| 727 | .env("http_proxy", proxy); |
| 728 | } |
| 729 | AmbientProxyKind::HttpsConnect => { |
| 730 | let proxy = format!("http://127.0.0.1:{proxy_port}"); |
| 731 | command |
| 732 | .env("CODEWHALE_PROXY_PROBE_SCHEME", "https") |
| 733 | .env("HTTPS_PROXY", &proxy) |
| 734 | .env("https_proxy", proxy); |
| 735 | } |
| 736 | AmbientProxyKind::SocksRemoteDns => { |
| 737 | let proxy = format!("socks5h://127.0.0.1:{proxy_port}"); |
| 738 | command |
| 739 | .env("CODEWHALE_PROXY_PROBE_SCHEME", "http") |
| 740 | .env("ALL_PROXY", &proxy) |
| 741 | .env("all_proxy", proxy); |
| 742 | } |
| 743 | } |
| 744 | |
| 745 | let output = command.output().expect("run proxy probe child"); |
| 746 | stop.store(true, Ordering::SeqCst); |
| 747 | let target_hit = target_handle.join().expect("join target probe"); |
| 748 | let proxy_hit = proxy_handle.join().expect("join proxy probe"); |
| 749 | assert!( |
| 750 | output.status.success(), |
| 751 | "proxy probe child failed for {kind:?} guarded={guarded}:\nstdout:\n{}\nstderr:\n{}", |
| 752 | String::from_utf8_lossy(&output.stdout), |
| 753 | String::from_utf8_lossy(&output.stderr), |
| 754 | ); |
| 755 | (target_hit, proxy_hit) |
| 756 | } |
| 757 | |
| 758 | #[cfg(not(windows))] |
| 759 | #[tokio::test] |
| 760 | #[ignore = "subprocess helper for ambient proxy regression test"] |
| 761 | async fn guarded_transport_proxy_probe_child() { |
| 762 | if std::env::var_os("CODEWHALE_PROXY_PROBE_CHILD").is_none() { |
| 763 | return; |
| 764 | } |
| 765 | let guarded = std::env::var("CODEWHALE_PROXY_PROBE_GUARDED").as_deref() == Ok("1"); |
| 766 | let scheme = std::env::var("CODEWHALE_PROXY_PROBE_SCHEME").expect("probe scheme"); |
| 767 | let target_port = std::env::var("CODEWHALE_PROXY_PROBE_TARGET_PORT") |
| 768 | .expect("probe target port") |
| 769 | .parse::<u16>() |
| 770 | .expect("numeric target port"); |
| 771 | let host = "guarded-proxy-probe.example.invalid"; |
| 772 | let builder = if guarded { |
| 773 | guarded_reqwest_client_builder() |
| 774 | } else { |
| 775 | codewhale_release::tls::reqwest_client_builder() |
| 776 | }; |
| 777 | let client = builder |
| 778 | .timeout(Duration::from_secs(2)) |
| 779 | .resolve( |
| 780 | host, |
| 781 | SocketAddr::new(Ipv4Addr::LOCALHOST.into(), target_port), |
| 782 | ) |
| 783 | .build() |
| 784 | .expect("build proxy probe client"); |
| 785 | let result = client |
| 786 | .get(format!("{scheme}://{host}:{target_port}/")) |
| 787 | .send() |
| 788 | .await; |
| 789 | if guarded && scheme == "http" { |
| 790 | assert!( |
| 791 | result.is_ok(), |
| 792 | "guarded HTTP target should answer: {result:?}" |
| 793 | ); |
| 794 | } |
| 795 | } |
| 796 | |
| 797 | #[cfg(not(windows))] |
| 798 | #[test] |
| 799 | fn guarded_transport_bypasses_ambient_http_https_and_remote_dns_socks_proxies() { |
| 800 | for kind in [ |
| 801 | AmbientProxyKind::Http, |
| 802 | AmbientProxyKind::HttpsConnect, |
| 803 | AmbientProxyKind::SocksRemoteDns, |
| 804 | ] { |
| 805 | let (unguarded_target, unguarded_proxy) = run_ambient_proxy_probe(kind, false); |
| 806 | assert!( |
| 807 | unguarded_proxy && !unguarded_target, |
| 808 | "control client must demonstrate ambient {kind:?} proxy interception" |
| 809 | ); |
| 810 | |
| 811 | let (guarded_target, guarded_proxy) = run_ambient_proxy_probe(kind, true); |
| 812 | assert!( |
| 813 | guarded_target && !guarded_proxy, |
| 814 | "guarded client must preserve its DNS pin and bypass ambient {kind:?} proxy" |
| 815 | ); |
| 816 | } |
| 817 | } |
| 818 | |
| 819 | #[test] |
| 820 | fn rejects_private_localhost_literal() { |
| 821 | assert!(is_restricted_ip(&"127.0.0.1".parse().unwrap())); |
| 822 | assert!(is_restricted_ip(&"::1".parse().unwrap())); |
| 823 | } |
| 824 | |
| 825 | #[test] |
| 826 | fn rejects_private_rfc1918() { |
| 827 | assert!(is_restricted_ip(&"10.0.0.1".parse().unwrap())); |
| 828 | assert!(is_restricted_ip(&"172.16.0.1".parse().unwrap())); |
| 829 | assert!(is_restricted_ip(&"192.168.1.1".parse().unwrap())); |
| 830 | } |
| 831 | |
| 832 | #[test] |
| 833 | fn rejects_cloud_metadata() { |
| 834 | assert!(is_restricted_ip(&"169.254.169.254".parse().unwrap())); |
| 835 | } |
| 836 | |
| 837 | #[test] |
| 838 | fn rejects_this_network_block() { |
| 839 | assert!(is_restricted_ip(&"0.1.2.3".parse().unwrap())); |
| 840 | assert!(is_restricted_ip(&"0.0.0.0".parse().unwrap())); |
| 841 | } |
| 842 | |
| 843 | #[test] |
| 844 | fn rejects_link_local() { |
| 845 | assert!(is_restricted_ip(&"169.254.1.1".parse().unwrap())); |
| 846 | } |
| 847 | |
| 848 | #[test] |
| 849 | fn rejects_cgnat() { |
| 850 | assert!(is_restricted_ip(&"100.64.0.1".parse().unwrap())); |
| 851 | assert!(!is_restricted_ip(&"100.63.0.1".parse().unwrap())); |
| 852 | assert!(!is_restricted_ip(&"100.128.0.1".parse().unwrap())); |
| 853 | } |
| 854 | |
| 855 | #[test] |
| 856 | fn rejects_ipv6_ula() { |
| 857 | assert!(is_restricted_ip(&"fc00::1".parse().unwrap())); |
| 858 | assert!(is_restricted_ip(&"fd12:3456::1".parse().unwrap())); |
| 859 | } |
| 860 | |
| 861 | #[test] |
| 862 | fn rejects_ipv4_mapped_ipv6() { |
| 863 | // ::ffff:127.0.0.1 — IPv4-mapped IPv6 loopback bypass |
| 864 | assert!(is_restricted_ip(&"::ffff:127.0.0.1".parse().unwrap())); |
| 865 | assert!(is_restricted_ip(&"::ffff:10.0.0.1".parse().unwrap())); |
| 866 | assert!(is_restricted_ip(&"::ffff:169.254.169.254".parse().unwrap())); |
| 867 | assert!(is_restricted_ip(&"::ffff:192.168.1.1".parse().unwrap())); |
| 868 | // :: (unspecified) |
| 869 | assert!(is_restricted_ip(&"::".parse().unwrap())); |
| 870 | } |
| 871 | |
| 872 | #[test] |
| 873 | fn allows_public_ips() { |
| 874 | assert!(!is_restricted_ip(&"8.8.8.8".parse().unwrap())); |
| 875 | assert!(!is_restricted_ip(&"1.1.1.1".parse().unwrap())); |
| 876 | assert!(!is_restricted_ip(&"93.184.216.34".parse().unwrap())); |
| 877 | assert!(!is_restricted_ip(&"2606:4700::1".parse().unwrap())); |
| 878 | } |
| 879 | |
| 880 | #[test] |
| 881 | fn restricted_dns_result_is_denied_without_proxy_opt_in() { |
| 882 | let ip = "198.18.0.1".parse().unwrap(); |
| 883 | |
| 884 | let err = |
| 885 | validate_dns_resolved_ip("github.com", &ip, None, "fetch_url", PrivateTargets::Refuse) |
| 886 | .expect_err("fake-IP DNS result must be denied by default"); |
| 887 | |
| 888 | assert!(format!("{err}").contains("resolved IP 198.18.0.1 is a restricted address")); |
| 889 | } |
| 890 | |
| 891 | #[test] |
| 892 | fn proxy_host_and_fakeip_cidr_allow_matching_placeholder() { |
| 893 | use crate::network_policy::{Decision, NetworkPolicy, NetworkPolicyDecider}; |
| 894 | |
| 895 | let policy = NetworkPolicy { |
| 896 | default: Decision::Allow.into(), |
| 897 | allow: Vec::new(), |
| 898 | deny: Vec::new(), |
| 899 | proxy: vec!["github.com".to_string()], |
| 900 | proxy_fake_ip_cidrs: vec!["198.18.0.0/15".to_string()], |
| 901 | audit: false, |
| 902 | }; |
| 903 | let decider = NetworkPolicyDecider::new(policy, None); |
| 904 | let ip = "198.18.0.1".parse().unwrap(); |
| 905 | |
| 906 | validate_dns_resolved_ip( |
| 907 | "github.com", |
| 908 | &ip, |
| 909 | Some(&decider), |
| 910 | "fetch_url", |
| 911 | PrivateTargets::Refuse, |
| 912 | ) |
| 913 | .expect("matching host and fake-IP CIDR should allow the placeholder"); |
| 914 | } |
| 915 | |
| 916 | #[test] |
| 917 | fn proxy_host_without_fakeip_cidr_does_not_allow_restricted_dns() { |
| 918 | use crate::network_policy::{Decision, NetworkPolicy, NetworkPolicyDecider}; |
| 919 | |
| 920 | let policy = NetworkPolicy { |
| 921 | default: Decision::Allow.into(), |
| 922 | allow: Vec::new(), |
| 923 | deny: Vec::new(), |
| 924 | proxy: vec!["github.com".to_string()], |
| 925 | proxy_fake_ip_cidrs: Vec::new(), |
| 926 | audit: false, |
| 927 | }; |
| 928 | let decider = NetworkPolicyDecider::new(policy, None); |
| 929 | let ip = "198.18.0.1".parse().unwrap(); |
| 930 | |
| 931 | validate_dns_resolved_ip( |
| 932 | "github.com", |
| 933 | &ip, |
| 934 | Some(&decider), |
| 935 | "fetch_url", |
| 936 | PrivateTargets::Refuse, |
| 937 | ) |
| 938 | .expect_err("hostname trust alone must not allow a restricted address"); |
| 939 | } |
| 940 | |
| 941 | #[test] |
| 942 | fn fakeip_cidr_without_proxy_host_does_not_allow_restricted_dns() { |
| 943 | use crate::network_policy::{Decision, NetworkPolicy, NetworkPolicyDecider}; |
| 944 | |
| 945 | let policy = NetworkPolicy { |
| 946 | default: Decision::Allow.into(), |
| 947 | allow: Vec::new(), |
| 948 | deny: Vec::new(), |
| 949 | proxy: Vec::new(), |
| 950 | proxy_fake_ip_cidrs: vec!["198.18.0.0/15".to_string()], |
| 951 | audit: false, |
| 952 | }; |
| 953 | let decider = NetworkPolicyDecider::new(policy, None); |
| 954 | let ip = "198.18.0.1".parse().unwrap(); |
| 955 | |
| 956 | validate_dns_resolved_ip( |
| 957 | "github.com", |
| 958 | &ip, |
| 959 | Some(&decider), |
| 960 | "fetch_url", |
| 961 | PrivateTargets::Refuse, |
| 962 | ) |
| 963 | .expect_err("fake-IP CIDR alone must not allow an untrusted hostname"); |
| 964 | } |
| 965 | |
| 966 | #[test] |
| 967 | fn proxy_host_never_exempts_real_private_or_local_addresses() { |
| 968 | use crate::network_policy::{Decision, NetworkPolicy, NetworkPolicyDecider}; |
| 969 | |
| 970 | let policy = NetworkPolicy { |
| 971 | default: Decision::Allow.into(), |
| 972 | allow: Vec::new(), |
| 973 | deny: Vec::new(), |
| 974 | proxy: vec!["github.com".to_string()], |
| 975 | proxy_fake_ip_cidrs: vec![ |
| 976 | "198.18.0.0/15".to_string(), |
| 977 | "127.0.0.0/8".to_string(), |
| 978 | "10.0.0.0/8".to_string(), |
| 979 | "169.254.0.0/16".to_string(), |
| 980 | ], |
| 981 | audit: false, |
| 982 | }; |
| 983 | let decider = NetworkPolicyDecider::new(policy, None); |
| 984 | |
| 985 | for ip in [ |
| 986 | "127.0.0.1", |
| 987 | "10.0.0.1", |
| 988 | "192.168.1.1", |
| 989 | "169.254.169.254", |
| 990 | "fc00::1", |
| 991 | ] { |
| 992 | let ip = ip.parse().unwrap(); |
| 993 | assert!( |
| 994 | validate_dns_resolved_ip( |
| 995 | "github.com", |
| 996 | &ip, |
| 997 | Some(&decider), |
| 998 | "fetch_url", |
| 999 | PrivateTargets::Refuse |
| 1000 | ) |
| 1001 | .is_err(), |
| 1002 | "{ip} must remain restricted" |
| 1003 | ); |
| 1004 | } |
| 1005 | } |
| 1006 | |
| 1007 | #[test] |
| 1008 | fn proxy_opt_in_does_not_allow_unlisted_host() { |
| 1009 | use crate::network_policy::{Decision, NetworkPolicy, NetworkPolicyDecider}; |
| 1010 | |
| 1011 | let policy = NetworkPolicy { |
| 1012 | default: Decision::Allow.into(), |
| 1013 | allow: Vec::new(), |
| 1014 | deny: Vec::new(), |
| 1015 | proxy: vec!["github.com".to_string()], |
| 1016 | proxy_fake_ip_cidrs: vec!["198.18.0.0/15".to_string()], |
| 1017 | audit: false, |
| 1018 | }; |
| 1019 | let decider = NetworkPolicyDecider::new(policy, None); |
| 1020 | let ip = "198.18.0.1".parse().unwrap(); |
| 1021 | |
| 1022 | let err = validate_dns_resolved_ip( |
| 1023 | "example.com", |
| 1024 | &ip, |
| 1025 | Some(&decider), |
| 1026 | "fetch_url", |
| 1027 | PrivateTargets::Refuse, |
| 1028 | ) |
| 1029 | .expect_err("proxy opt-in must be scoped to configured hosts"); |
| 1030 | |
| 1031 | assert!(format!("{err}").contains("resolved IP 198.18.0.1 is a restricted address")); |
| 1032 | } |
| 1033 | |
| 1034 | #[test] |
| 1035 | fn proxy_dns_allow_is_audited() { |
| 1036 | use crate::network_policy::{ |
| 1037 | Decision, NetworkAuditor, NetworkPolicy, NetworkPolicyDecider, |
| 1038 | }; |
| 1039 | use tempfile::tempdir; |
| 1040 | |
| 1041 | let dir = tempdir().expect("tempdir"); |
| 1042 | let auditor = NetworkAuditor::new(dir.path().join("audit.log"), true); |
| 1043 | let policy = NetworkPolicy { |
| 1044 | default: Decision::Allow.into(), |
| 1045 | allow: Vec::new(), |
| 1046 | deny: Vec::new(), |
| 1047 | proxy: vec!["github.com".to_string()], |
| 1048 | proxy_fake_ip_cidrs: vec!["198.18.0.0/15".to_string()], |
| 1049 | audit: true, |
| 1050 | }; |
| 1051 | let decider = NetworkPolicyDecider::new(policy, Some(auditor)); |
| 1052 | let ip = "198.18.0.1".parse().unwrap(); |
| 1053 | |
| 1054 | validate_dns_resolved_ip( |
| 1055 | "github.com", |
| 1056 | &ip, |
| 1057 | Some(&decider), |
| 1058 | "fetch_url", |
| 1059 | PrivateTargets::Refuse, |
| 1060 | ) |
| 1061 | .expect("proxy DNS allow"); |
| 1062 | |
| 1063 | let body = std::fs::read_to_string(dir.path().join("audit.log")).expect("audit log"); |
| 1064 | assert!(body.contains("github.com")); |
| 1065 | assert!(body.contains("TrustedProxyFakeIp-Allow")); |
| 1066 | } |
| 1067 | fn allow_decider(hosts: &[&str]) -> NetworkPolicyDecider { |
| 1068 | use crate::network_policy::NetworkPolicy; |
| 1069 | let policy = NetworkPolicy { |
| 1070 | default: Decision::Prompt.into(), |
| 1071 | allow: hosts.iter().map(|host| host.to_string()).collect(), |
| 1072 | deny: Vec::new(), |
| 1073 | proxy: Vec::new(), |
| 1074 | proxy_fake_ip_cidrs: Vec::new(), |
| 1075 | audit: false, |
| 1076 | }; |
| 1077 | NetworkPolicyDecider::new(policy, None) |
| 1078 | } |
| 1079 | |
| 1080 | #[test] |
| 1081 | fn allow_listed_name_never_admits_a_private_dns_answer() { |
| 1082 | let decider = allow_decider(&["skills.example"]); |
| 1083 | for private in [PrivateTargets::Refuse, PrivateTargets::TypedLocalHosts] { |
| 1084 | for ip in [ |
| 1085 | "127.0.0.1", |
| 1086 | "10.0.0.5", |
| 1087 | "192.168.1.1", |
| 1088 | "100.64.1.2", |
| 1089 | "100.100.100.200", |
| 1090 | "169.254.170.2", |
| 1091 | "169.254.169.254", |
| 1092 | "::1", |
| 1093 | "fd00:ec2::254", |
| 1094 | "::ffff:169.254.169.254", |
| 1095 | "64:ff9b::a9fe:a9fe", |
| 1096 | ] { |
| 1097 | let ip = ip.parse().unwrap(); |
| 1098 | assert!( |
| 1099 | validate_dns_resolved_ip( |
| 1100 | "skills.example", |
| 1101 | &ip, |
| 1102 | Some(&decider), |
| 1103 | "skill_install", |
| 1104 | private |
| 1105 | ) |
| 1106 | .is_err(), |
| 1107 | "{ip} must stay refused for an allow-listed name under {private:?}" |
| 1108 | ); |
| 1109 | } |
| 1110 | } |
| 1111 | } |
| 1112 | |
| 1113 | #[test] |
| 1114 | fn a_typed_localhost_name_resolves_to_loopback_only() { |
| 1115 | let decider = allow_decider(&["localhost", "dev.localhost"]); |
| 1116 | let admit = |host: &str, ip: &str, private| { |
| 1117 | validate_dns_resolved_ip( |
| 1118 | host, |
| 1119 | &ip.parse().unwrap(), |
| 1120 | Some(&decider), |
| 1121 | "fetch_url", |
| 1122 | private, |
| 1123 | ) |
| 1124 | }; |
| 1125 | for host in ["localhost", "dev.localhost"] { |
| 1126 | admit(host, "127.0.0.1", PrivateTargets::TypedLocalHosts).expect(host); |
| 1127 | admit(host, "::1", PrivateTargets::TypedLocalHosts).expect(host); |
| 1128 | for ip in ["10.0.0.5", "100.64.1.2", "169.254.169.254", "fd00::1"] { |
| 1129 | admit(host, ip, PrivateTargets::TypedLocalHosts).expect_err(ip); |
| 1130 | } |
| 1131 | admit(host, "127.0.0.1", PrivateTargets::Refuse).expect_err(host); |
| 1132 | } |
| 1133 | let unlisted = allow_decider(&[]); |
| 1134 | validate_dns_resolved_ip( |
| 1135 | "localhost", |
| 1136 | &"127.0.0.1".parse().unwrap(), |
| 1137 | Some(&unlisted), |
| 1138 | "fetch_url", |
| 1139 | PrivateTargets::TypedLocalHosts, |
| 1140 | ) |
| 1141 | .expect_err("a localhost name the person did not list stays refused"); |
| 1142 | } |
| 1143 | |
| 1144 | #[tokio::test] |
| 1145 | async fn a_typed_local_literal_is_admitted_only_when_listed_and_asked_for() { |
| 1146 | for literal in [ |
| 1147 | "127.0.0.1", |
| 1148 | "10.1.2.3", |
| 1149 | "192.168.0.9", |
| 1150 | "100.64.1.2", |
| 1151 | "[::1]", |
| 1152 | "[fd12:3456::1]", |
| 1153 | ] { |
| 1154 | let decider = allow_decider(&[literal]); |
| 1155 | validate_fetch_destination( |
| 1156 | literal.to_string(), |
| 1157 | Some(&decider), |
| 1158 | "fetch_url", |
| 1159 | true, |
| 1160 | PrivateTargets::TypedLocalHosts, |
| 1161 | ) |
| 1162 | .await |
| 1163 | .expect(literal); |
| 1164 | validate_fetch_destination( |
| 1165 | literal.to_string(), |
| 1166 | Some(&decider), |
| 1167 | "fetch_url", |
| 1168 | true, |
| 1169 | PrivateTargets::Refuse, |
| 1170 | ) |
| 1171 | .await |
| 1172 | .expect_err(literal); |
| 1173 | validate_fetch_destination( |
| 1174 | literal.to_string(), |
| 1175 | Some(&allow_decider(&[])), |
| 1176 | "fetch_url", |
| 1177 | true, |
| 1178 | PrivateTargets::TypedLocalHosts, |
| 1179 | ) |
| 1180 | .await |
| 1181 | .expect_err(literal); |
| 1182 | } |
| 1183 | let decider = allow_decider(&["::1"]); |
| 1184 | validate_fetch_destination( |
| 1185 | "[::1]".to_string(), |
| 1186 | Some(&decider), |
| 1187 | "fetch_url", |
| 1188 | true, |
| 1189 | PrivateTargets::TypedLocalHosts, |
| 1190 | ) |
| 1191 | .await |
| 1192 | .expect("an unbracketed entry names the bracketed literal"); |
| 1193 | } |
| 1194 | |
| 1195 | #[tokio::test] |
| 1196 | async fn typed_and_allowed_literals_outside_the_local_ranges_stay_refused() { |
| 1197 | for literal in [ |
| 1198 | "169.254.169.254", |
| 1199 | "169.254.170.2", |
| 1200 | "169.254.1.1", |
| 1201 | "100.100.100.200", |
| 1202 | "168.63.129.16", |
| 1203 | "0.0.0.0", |
| 1204 | "198.18.0.1", |
| 1205 | "224.0.0.1", |
| 1206 | "[::ffff:127.0.0.1]", |
| 1207 | "[::ffff:10.0.0.5]", |
| 1208 | "[::ffff:169.254.169.254]", |
| 1209 | "[64:ff9b::a9fe:a9fe]", |
| 1210 | "[64:ff9b::a00:1]", |
| 1211 | "[2002:a9fe:a9fe::1]", |
| 1212 | "[2001:0:a9fe:a9fe::1]", |
| 1213 | "[fd00:ec2::254]", |
| 1214 | "[fd20:ce::254]", |
| 1215 | "[fe80::1]", |
| 1216 | "[fec0::1]", |
| 1217 | "[::]", |
| 1218 | ] { |
| 1219 | let decider = allow_decider(&[literal]); |
| 1220 | for private in [PrivateTargets::Refuse, PrivateTargets::TypedLocalHosts] { |
| 1221 | validate_fetch_destination( |
| 1222 | literal.to_string(), |
| 1223 | Some(&decider), |
| 1224 | "fetch_url", |
| 1225 | true, |
| 1226 | private, |
| 1227 | ) |
| 1228 | .await |
| 1229 | .expect_err(literal); |
| 1230 | } |
| 1231 | } |
| 1232 | } |
| 1233 | |
| 1234 | #[test] |
| 1235 | fn cloud_metadata_set_covers_provider_endpoints_and_embedded_forms() { |
| 1236 | for literal in [ |
| 1237 | "169.254.169.254", |
| 1238 | "169.254.170.2", |
| 1239 | "169.254.0.23", |
| 1240 | "100.100.100.200", |
| 1241 | "168.63.129.16", |
| 1242 | "192.0.0.192", |
| 1243 | "fd00:ec2::254", |
| 1244 | "fd20:ce::254", |
| 1245 | "fe80::1", |
| 1246 | "febf::1", |
| 1247 | "::ffff:169.254.169.254", |
| 1248 | "::169.254.169.254", |
| 1249 | "::ffff:0:a9fe:a9fe", |
| 1250 | "64:ff9b::a9fe:a9fe", |
| 1251 | "64:ff9b:1::a9fe:a9fe", |
| 1252 | "64:ff9b:1:8a9:fe:a9fe::", |
| 1253 | "64:ff9b:1:864:64:64c8::", |
| 1254 | "64:ff9b:1:808:a9:fea9:fe00:0", |
| 1255 | "64:ff9b:1:808:64:6464:c800:0", |
| 1256 | "2002:a9fe:a9fe::1", |
| 1257 | "2001:0:a9fe:a9fe::1", |
| 1258 | "2001:0:4136:e378:8000:63bf:5601:5601", |
| 1259 | ] { |
| 1260 | let ip = literal.parse().unwrap(); |
| 1261 | assert!(is_restricted_ip(&ip), "{literal} must be restricted"); |
| 1262 | } |
| 1263 | for literal in [ |
| 1264 | "169.254.169.254", |
| 1265 | "169.254.170.2", |
| 1266 | "100.100.100.200", |
| 1267 | "fd00:ec2::254", |
| 1268 | "fe80::1", |
| 1269 | "::ffff:169.254.169.254", |
| 1270 | "64:ff9b::a9fe:a9fe", |
| 1271 | "64:ff9b:1::a9fe:a9fe", |
| 1272 | "64:ff9b:1:8a9:fe:a9fe::", |
| 1273 | "64:ff9b:1:864:64:64c8::", |
| 1274 | "64:ff9b:1:808:a9:fea9:fe00:0", |
| 1275 | "64:ff9b:1:808:64:6464:c800:0", |
| 1276 | "2002:a9fe:a9fe::1", |
| 1277 | ] { |
| 1278 | let ip = literal.parse().unwrap(); |
| 1279 | assert!(is_cloud_metadata_ip(&ip), "{literal} must be metadata"); |
| 1280 | } |
| 1281 | for literal in [ |
| 1282 | "10.0.0.5", |
| 1283 | "127.0.0.1", |
| 1284 | "100.64.1.2", |
| 1285 | "fd12::1", |
| 1286 | "::1", |
| 1287 | "8.8.8.8", |
| 1288 | ] { |
| 1289 | let ip = literal.parse().unwrap(); |
| 1290 | assert!(!is_cloud_metadata_ip(&ip), "{literal} is not metadata"); |
| 1291 | } |
| 1292 | for literal in [ |
| 1293 | "64:ff9b::808:808", |
| 1294 | "64:ff9b:1::808:808", |
| 1295 | "64:ff9b:1:808:808::", |
| 1296 | "64:ff9b:1:abcd::808:808", |
| 1297 | "64:ff9b:1:808:8:808:800:0", |
| 1298 | ] { |
| 1299 | let ip = literal.parse().unwrap(); |
| 1300 | assert!(!is_cloud_metadata_ip(&ip), "{literal} is not metadata"); |
| 1301 | assert!(!is_restricted_ip(&ip), "{literal} must stay allowed"); |
| 1302 | } |
| 1303 | } |
| 1304 | |
| 1305 | #[test] |
| 1306 | fn translated_and_local_use_nat64_forms_embedding_internal_addresses_are_restricted() { |
| 1307 | for literal in [ |
| 1308 | "64:ff9b:1::a9fe:a9fe", |
| 1309 | "64:ff9b:1::a00:1", |
| 1310 | "64:ff9b:1:abcd::a00:1", |
| 1311 | "64:ff9b:1:a00:1::", |
| 1312 | "64:ff9b:1:7f00:1::", |
| 1313 | "::ffff:0:a9fe:a9fe", |
| 1314 | "::ffff:0:7f00:1", |
| 1315 | ] { |
| 1316 | assert!( |
| 1317 | is_restricted_ip(&literal.parse().unwrap()), |
| 1318 | "{literal} must be restricted" |
| 1319 | ); |
| 1320 | } |
| 1321 | for literal in [ |
| 1322 | "64:ff9b::808:808", |
| 1323 | "64:ff9b:1::808:808", |
| 1324 | "64:ff9b:1:808:8::", |
| 1325 | ] { |
| 1326 | assert!( |
| 1327 | !is_restricted_ip(&literal.parse().unwrap()), |
| 1328 | "{literal} embeds a public address and must stay allowed" |
| 1329 | ); |
| 1330 | } |
| 1331 | } |
| 1332 | |
| 1333 | fn serve_once(response: String) -> (u16, std::sync::Arc<std::sync::atomic::AtomicUsize>) { |
| 1334 | use std::io::{Read, Write}; |
| 1335 | use std::sync::atomic::{AtomicUsize, Ordering}; |
| 1336 | let listener = |
| 1337 | std::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0)).expect("bind fixture"); |
| 1338 | let port = listener.local_addr().expect("fixture address").port(); |
| 1339 | let hits = std::sync::Arc::new(AtomicUsize::new(0)); |
| 1340 | let counter = std::sync::Arc::clone(&hits); |
| 1341 | std::thread::spawn(move || { |
| 1342 | for stream in listener.incoming() { |
| 1343 | let Ok(mut stream) = stream else { return }; |
| 1344 | counter.fetch_add(1, Ordering::SeqCst); |
| 1345 | let mut chunk = [0_u8; 1024]; |
| 1346 | let _ = stream.read(&mut chunk); |
| 1347 | let _ = stream.write_all(response.as_bytes()); |
| 1348 | } |
| 1349 | }); |
| 1350 | (port, hits) |
| 1351 | } |
| 1352 | |
| 1353 | fn redirect_to(location: &str) -> String { |
| 1354 | format!( |
| 1355 | "HTTP/1.1 302 Found\r\nLocation: {location}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" |
| 1356 | ) |
| 1357 | } |
| 1358 | |
| 1359 | fn policy_allowing(hosts: &[&str]) -> NetworkPolicy { |
| 1360 | NetworkPolicy { |
| 1361 | default: Decision::Prompt.into(), |
| 1362 | allow: hosts.iter().map(|host| host.to_string()).collect(), |
| 1363 | deny: Vec::new(), |
| 1364 | proxy: Vec::new(), |
| 1365 | proxy_fake_ip_cidrs: Vec::new(), |
| 1366 | audit: false, |
| 1367 | } |
| 1368 | } |
| 1369 | |
| 1370 | #[tokio::test] |
| 1371 | async fn a_hop_to_an_allow_listed_local_literal_is_refused_unless_the_caller_asks() { |
| 1372 | use std::sync::atomic::Ordering; |
| 1373 | let ok = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok"; |
| 1374 | let (internal, internal_hits) = serve_once(ok.to_string()); |
| 1375 | let (entry, _) = serve_once(redirect_to(&format!("http://127.0.0.1:{internal}/secret"))); |
| 1376 | let policy = policy_allowing(&["127.0.0.1"]); |
| 1377 | let url = format!("http://127.0.0.1:{entry}/start"); |
| 1378 | |
| 1379 | let refused = GuardedGet::new(&url, &policy, "skill_install", PrivateTargets::Refuse) |
| 1380 | .trust_first_hop() |
| 1381 | .send() |
| 1382 | .await; |
| 1383 | let error = format!( |
| 1384 | "{:#}", |
| 1385 | refused.expect_err("an installer-style download must refuse the hop") |
| 1386 | ); |
| 1387 | assert!(error.contains("restricted address"), "{error}"); |
| 1388 | assert!(!error.contains("secret"), "{error}"); |
| 1389 | assert_eq!(internal_hits.load(Ordering::SeqCst), 0); |
| 1390 | |
| 1391 | let admitted = GuardedGet::new(&url, &policy, "fetch_url", PrivateTargets::TypedLocalHosts) |
| 1392 | .trust_first_hop() |
| 1393 | .send() |
| 1394 | .await |
| 1395 | .expect("a typed local literal is admitted when the caller asks for it"); |
| 1396 | assert_eq!(admitted.status(), reqwest::StatusCode::OK); |
| 1397 | assert_eq!(internal_hits.load(Ordering::SeqCst), 1); |
| 1398 | } |
| 1399 | |
| 1400 | #[tokio::test] |
| 1401 | async fn a_hop_to_an_unlisted_local_literal_is_refused_even_for_a_caller_that_asks() { |
| 1402 | use std::sync::atomic::Ordering; |
| 1403 | let ok = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok"; |
| 1404 | let (internal, internal_hits) = serve_once(ok.to_string()); |
| 1405 | let (entry, _) = serve_once(redirect_to(&format!("http://127.0.0.1:{internal}/"))); |
| 1406 | let policy = policy_allowing(&[]); |
| 1407 | let url = format!("http://127.0.0.1:{entry}/start"); |
| 1408 | |
| 1409 | GuardedGet::new( |
| 1410 | &url, |
| 1411 | &policy, |
| 1412 | "config_import", |
| 1413 | PrivateTargets::TypedLocalHosts, |
| 1414 | ) |
| 1415 | .trust_first_hop() |
| 1416 | .send() |
| 1417 | .await |
| 1418 | .expect_err("the hop must be refused"); |
| 1419 | assert_eq!(internal_hits.load(Ordering::SeqCst), 0); |
| 1420 | } |
| 1421 | |
| 1422 | #[tokio::test] |
| 1423 | async fn the_redirect_check_runs_before_a_hop_is_followed() { |
| 1424 | let (entry, _) = serve_once(redirect_to("http://example.invalid/x?token=secret-value")); |
| 1425 | let policy = policy_allowing(&[]); |
| 1426 | let url = format!("http://127.0.0.1:{entry}/start"); |
| 1427 | let check = |
| 1428 | |_: &reqwest::Url| -> anyhow::Result<()> { anyhow::bail!("hop refused by caller") }; |
| 1429 | |
| 1430 | let error = GuardedGet::new(&url, &policy, "config_import", PrivateTargets::Refuse) |
| 1431 | .trust_first_hop() |
| 1432 | .redirect_check(&check) |
| 1433 | .send() |
| 1434 | .await |
| 1435 | .expect_err("the caller's check refuses the hop"); |
| 1436 | let rendered = format!("{error:#}"); |
| 1437 | assert!(rendered.contains("hop refused by caller"), "{rendered}"); |
| 1438 | assert!(!rendered.contains("secret-value"), "{rendered}"); |
| 1439 | } |
| 1440 | |
| 1441 | #[test] |
| 1442 | fn visibly_local_host_covers_localhost_wildcards() { |
| 1443 | for host in [ |
| 1444 | "localhost", |
| 1445 | "localhost..", |
| 1446 | "localhost.localdomain", |
| 1447 | "dev.localhost", |
| 1448 | ".localdomain", |
| 1449 | "*.localdomain", |
| 1450 | "*.LOCALDOMAIN..", |
| 1451 | ".localhost", |
| 1452 | "*.localhost", |
| 1453 | ".dev.localhost", |
| 1454 | "*.dev.localhost", |
| 1455 | "127.0.0.1", |
| 1456 | "10.0.0.5", |
| 1457 | "[::1]", |
| 1458 | "fd00::1", |
| 1459 | ] { |
| 1460 | assert!( |
| 1461 | is_visibly_local_host(host), |
| 1462 | "{host} must be classified as visibly local" |
| 1463 | ); |
| 1464 | } |
| 1465 | for host in [ |
| 1466 | "example.com", |
| 1467 | ".example.com", |
| 1468 | "*.example.com", |
| 1469 | ".localhost.localdomain", |
| 1470 | "*.localhost.localdomain", |
| 1471 | "8.8.8.8", |
| 1472 | "169.254.169.254", |
| 1473 | "fe80::1", |
| 1474 | ] { |
| 1475 | assert!( |
| 1476 | !is_visibly_local_host(host), |
| 1477 | "{host} must not be classified as visibly local" |
| 1478 | ); |
| 1479 | } |
| 1480 | } |
| 1481 | |
| 1482 | #[tokio::test] |
| 1483 | async fn trailing_dot_localhost_and_ip_literals_fail_fast() { |
| 1484 | for resolve in [false, true] { |
| 1485 | for host in [ |
| 1486 | "localhost..", |
| 1487 | "LOCALHOST..", |
| 1488 | "dev.localhost..", |
| 1489 | "localhost.localdomain..", |
| 1490 | ] { |
| 1491 | let err = validate_fetch_destination( |
| 1492 | host.to_string(), |
| 1493 | None, |
| 1494 | "fetch_url", |
| 1495 | resolve, |
| 1496 | PrivateTargets::TypedLocalHosts, |
| 1497 | ) |
| 1498 | .await |
| 1499 | .expect_err("trailing-dot localhost name must fail fast"); |
| 1500 | assert!( |
| 1501 | format!("{err}").contains("requests to localhost are not allowed"), |
| 1502 | "{host} (resolve={resolve}) got unexpected error: {err}" |
| 1503 | ); |
| 1504 | } |
| 1505 | |
| 1506 | for literal in ["127.0.0.1..", "[::1].."] { |
| 1507 | let err = validate_fetch_destination( |
| 1508 | literal.to_string(), |
| 1509 | None, |
| 1510 | "fetch_url", |
| 1511 | resolve, |
| 1512 | PrivateTargets::TypedLocalHosts, |
| 1513 | ) |
| 1514 | .await |
| 1515 | .expect_err("trailing-dot local IP literal must fail fast"); |
| 1516 | assert!( |
| 1517 | format!("{err}").contains("restricted address"), |
| 1518 | "{literal} (resolve={resolve}) got unexpected error: {err}" |
| 1519 | ); |
| 1520 | } |
| 1521 | } |
| 1522 | } |
| 1523 | } |
| 1524 |