:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(error-tracking): block localhost and internal IPs in sourcemap fetches (#74557)
Hugues Pouillotfb818637583b
diff --git a/rust/common/dns/src/lib.rs b/rust/common/dns/src/lib.rsindex 8a383b254349..dc0b25b252fd 100644--- a/rust/common/dns/src/lib.rs+++ b/rust/common/dns/src/lib.rs@@ -1,5 +1,5 @@use std::error::Error as StdError;-use std::net::{IpAddr, SocketAddr, ToSocketAddrs};+use std::net::{IpAddr, Ipv4Addr, SocketAddr, ToSocketAddrs};use std::{fmt, io};use futures::FutureExt;@@ -25,20 +25,43 @@ pub(crate) type BoxError = Box<dyn StdError + Send + Sync>;/// Returns [`true`] if the IP appears to be a globally reachable IPv4.///-/// Trimmed down version of the unstable IpAddr::is_global, move to it when it's stable.+/// Covers every range the still-unstable `Ipv4Addr::is_global` rejects, and is deliberately+/// *stricter*: we also reject multicast, which std considers globally reachable. So don't+/// swap in `Ipv4Addr::is_global` when it stabilizes without re-adding that check - this+/// gates outbound fetches, and loosening it widens our SSRF surface.+///+/// IPv6 is rejected wholesale for now, as our infra does not route it.pub fn is_global_ip(ip: &IpAddr) -> bool {match ip {- IpAddr::V4(ip) => {- !(ip.octets()[0] == 0 // "This network"- || ip.is_private()- || ip.is_loopback()- || ip.is_link_local()- || ip.is_broadcast())- }+ IpAddr::V4(ip) => is_global_ipv4_addr(ip),IpAddr::V6(_) => false, // Our network does not currently support ipv6, let's ignore for now}}+fn is_global_ipv4_addr(ip: &Ipv4Addr) -> bool {+ let [a, b, c, d] = ip.octets();++ // Shared address space (100.64.0.0/10) — carrier-grade NAT, routinely internal.+ let is_shared = a == 100 && (b & 0b1100_0000) == 0b0100_0000;+ // IETF protocol assignments (192.0.0.0/24); only .9 and .10 are globally reachable.+ let is_ietf_protocol = a == 192 && b == 0 && c == 0 && d != 9 && d != 10;+ // Benchmarking range (198.18.0.0/15).+ let is_benchmarking = a == 198 && (b & 0xfe) == 18;+ // Reserved for future use (240.0.0.0/4); also covers the 255.255.255.255 broadcast address.+ let is_reserved = (a & 0xf0) == 0xf0;++ !(a == 0 // "This network" (0.0.0.0/8)+ || ip.is_private() // 10/8, 172.16/12, 192.168/16+ || is_shared+ || ip.is_loopback() // 127/8+ || ip.is_link_local() // 169.254/16, includes the cloud metadata IP+ || is_ietf_protocol+ || ip.is_documentation() // 192.0.2/24, 198.51.100/24, 203.0.113/24+ || is_benchmarking+ || ip.is_multicast() // 224.0.0.0/4+ || is_reserved)+}+fn is_global_ipv4(addr: &SocketAddr) -> bool {is_global_ip(&addr.ip())}@@ -130,10 +153,72 @@ impl aws_smithy_runtime_api::client::dns::ResolveDns for PublicIPv4SmithyResolve#[cfg(test)]mod tests {- use crate::{NoPublicIPv4Error, PublicIPv4Resolver};+ use crate::{is_global_ip, NoPublicIPv4Error, PublicIPv4Resolver};use reqwest::dns::{Name, Resolve};+ use std::net::IpAddr;use std::str::FromStr;+ fn is_global(ip: &str) -> bool {+ is_global_ip(&ip.parse::<IpAddr>().unwrap())+ }++ #[test]+ fn is_global_ip_allows_public_ipv4() {+ for ip in [+ "8.8.8.8",+ "1.1.1.1",+ "93.184.216.34", // example.com+ // The addresses immediately outside each blocked range. These pin the masks down:+ // a check that was one bit too wide would swallow these and go unnoticed.+ "100.63.255.255", // just below shared 100.64.0.0/10+ "100.128.0.0", // just above it+ "192.0.0.9", // carved out of 192.0.0.0/24 as globally reachable+ "192.0.0.10", // ditto+ "192.0.1.1", // just above 192.0.0.0/24+ "198.17.255.255", // just below benchmarking 198.18.0.0/15+ "198.20.0.0", // just above it+ "223.255.255.255", // just below multicast 224.0.0.0/4+ ] {+ assert!(is_global(ip), "expected {ip} to be treated as public");+ }+ }++ #[test]+ fn is_global_ip_rejects_internal_ranges() {+ for ip in [+ "127.0.0.1", // loopback / localhost+ "0.0.0.0", // unspecified / "this network"+ "10.0.0.1", // private+ "172.16.5.4", // private+ "192.168.1.1", // private+ "100.64.0.1", // shared / carrier-grade NAT+ "100.127.255.255",+ "169.254.0.1", // link-local+ "169.254.169.254", // the cloud metadata endpoint+ "192.0.0.1", // IETF protocol assignments+ "192.0.0.255",+ "192.0.2.1", // documentation+ "198.51.100.1", // documentation+ "203.0.113.1", // documentation+ "198.18.0.1", // benchmarking+ "198.19.255.255",+ "224.0.0.1", // multicast+ "239.255.255.255", // top of multicast+ "240.0.0.1", // reserved+ "255.255.255.255", // broadcast+ ] {+ assert!(!is_global(ip), "expected {ip} to be rejected");+ }+ }++ #[test]+ fn is_global_ip_rejects_all_ipv6() {+ // We do not route IPv6, so nothing resolves to a fetchable address, including+ // the IPv6 loopback which must never be reachable.+ assert!(!is_global("::1"));+ assert!(!is_global("2606:4700:4700::1111"));+ }+#[tokio::test]async fn it_resolves_google_com() {let resolver: PublicIPv4Resolver = PublicIPv4Resolver {};diff --git a/rust/cymbal/src/core/error.rs b/rust/cymbal/src/core/error.rsindex 897fbf3a4625..92194cd1cc99 100644--- a/rust/cymbal/src/core/error.rs+++ b/rust/cymbal/src/core/error.rs@@ -1,3 +1,4 @@+use std::error::Error as _;use std::sync::Arc;use aws_sdk_s3::primitives::ByteStreamError;@@ -119,6 +120,9 @@ pub enum JsResolveErr {// For redirect loops or too many redirects#[error("Redirect error while fetching: {0}")]RedirectError(String),+ // The url pointed at an address we refuse to fetch from, e.g. localhost or a private IP+ #[error("Refusing to fetch from non-public address: {0}")]+ BlockedUrl(String),#[error("JSDataError: {0}")]JSDataError(#[from] SymbolDataError),#[error("Invalid Source and Map")]@@ -244,6 +248,7 @@ impl JsResolveErr {| Self::HttpStatus(..)| Self::NetworkError(_)| Self::RedirectError(_) => "network_error",+ Self::BlockedUrl(_) => "blocked_url",Self::InvalidSourceMap(_)| Self::InvalidSourceUrl(_)| Self::InvalidSourceMapHeader(_)@@ -362,6 +367,12 @@ impl From<reqwest::Error> for JsResolveErr {}if e.is_redirect() {+ // Our redirect policy rejects hops with its own error, which reqwest wraps. Unwrap it+ // so a blocked hop keeps its reason and names the host, instead of being flattened+ // into a generic redirect failure.+ if let Some(inner) = e.source().and_then(|s| s.downcast_ref::<JsResolveErr>()) {+ return inner.clone();+ }return JsResolveErr::RedirectError(e.to_string());}diff --git a/rust/cymbal/src/core/symbolication/symbol_store/sourcemap.rs b/rust/cymbal/src/core/symbolication/symbol_store/sourcemap.rsindex b363668720f2..c328cbfa1dc2 100644--- a/rust/cymbal/src/core/symbolication/symbol_store/sourcemap.rs+++ b/rust/cymbal/src/core/symbolication/symbol_store/sourcemap.rs@@ -1,4 +1,4 @@-use std::{collections::HashMap, sync::Arc, time::Duration};+use std::{collections::HashMap, net::IpAddr, sync::Arc, time::Duration};use async_trait::async_trait;use base64::Engine;@@ -31,6 +31,46 @@ pub struct SourcemapProvider {pub client: reqwest::Client,pub chunk_id_rescue: Option<ChunkIdRescue>,pub max_response_bytes: usize,+ allow_internal_ips: bool,+}++/// How many redirects we follow. Installing a custom policy to vet each hop replaces reqwest's+/// default limit, so we have to impose our own.+const MAX_REDIRECTS: usize = 10;++/// Rejects URLs whose host is an IP literal that isn't globally routable.+///+/// `PublicIPv4Resolver` only ever sees hostnames: hyper skips DNS resolution+/// entirely when the host is already an IP literal, so `http://169.254.169.254/` or+/// `http://127.0.0.1:6379/` would otherwise sail straight past it. `Url::parse` normalizes the+/// octal, hex and integer IPv4 forms, so obfuscated literals arrive here as plain addresses.+///+/// Hostnames are passed through, to be vetted at connect time by whichever layer owns that:+/// `PublicIPv4Resolver` normally, or the egress proxy when one is configured.+fn ensure_fetchable_host(url: &Url, allow_internal_ips: bool) -> Result<(), JsResolveErr> {+ if allow_internal_ips {+ return Ok(());+ }++ let Some(host) = url.host_str() else {+ return Err(JsResolveErr::BlockedUrl(url.to_string()));+ };++ // IPv6 literals are bracketed in URLs, but `IpAddr` wants them bare.+ let bare = host+ .strip_prefix('[')+ .and_then(|h| h.strip_suffix(']'))+ .unwrap_or(host);++ let Ok(ip) = bare.parse::<IpAddr>() else {+ return Ok(());+ };++ if common_dns::is_global_ip(&ip) {+ return Ok(());+ }++ Err(JsResolveErr::BlockedUrl(url.to_string()))}#[derive(Clone)]@@ -123,24 +163,43 @@ impl SourcemapProvider {|| valid_proxy_url("https_proxy");if has_proxy {- // When an egress proxy (e.g. smokescreen) is configured, it handles SSRF- // protection. The PublicIPv4Resolver would block the connection to the proxy- // itself since it resolves to a cluster-internal IP.- info!(- "HTTP(S)_PROXY is set, skipping PublicIPv4Resolver (proxy handles SSRF protection)"- );+ // When an egress proxy (e.g. smokescreen) is configured, it owns vetting where a+ // *hostname* ends up resolving. We can't do that ourselves here: PublicIPv4Resolver+ // would block the connection to the proxy itself, since the proxy resolves to a+ // cluster-internal IP. `ensure_fetchable_host` below still applies either way - it+ // inspects the target url's host, not the proxy's, so it costs the proxy nothing.+ info!("HTTP(S)_PROXY is set, skipping PublicIPv4Resolver (proxy vets hostnames)");} else if !config.allow_internal_ips {client = client.dns_resolver(Arc::new(common_dns::PublicIPv4Resolver {}));} else {warn!("Internal IPs are allowed, this is a security risk");}+ // Redirect targets are as attacker-controlled as the original URL, so vet every hop the+ // same way. Whoever vets hostnames above covers those; this catches IP-literal hops,+ // which never reach a DNS resolver at all.+ let allow_internal_ips = config.allow_internal_ips;+ client = client.redirect(reqwest::redirect::Policy::custom(move |attempt| {+ // `previous` holds the urls already requested, so its length is the number of this+ // hop - refusing above the limit follows exactly MAX_REDIRECTS of them.+ if attempt.previous().len() > MAX_REDIRECTS {+ return attempt.error(JsResolveErr::RedirectError(format!(+ "exceeded {MAX_REDIRECTS} redirects"+ )));+ }+ match ensure_fetchable_host(attempt.url(), allow_internal_ips) {+ Ok(()) => attempt.follow(),+ Err(e) => attempt.error(e),+ }+ }));+let client = client.build().unwrap();Self {client,chunk_id_rescue: None,max_response_bytes: config.sourcemap_max_response_bytes,+ allow_internal_ips,}}@@ -178,7 +237,13 @@ impl Fetcher for SourcemapProvider {type Err = ResolveError;async fn fetch(&self, team_id: i32, r: Url) -> Result<Bytes, Self::Err> {let start = common_metrics::timing_guard(SOURCEMAP_FETCH, &[]);- let peek = find_sourcemap_url(&self.client, r, self.max_response_bytes).await?;+ let peek = find_sourcemap_url(+ &self.client,+ r,+ self.max_response_bytes,+ self.allow_internal_ips,+ )+ .await?;let start = start.label("found_url", "true");@@ -196,8 +261,13 @@ impl Fetcher for SourcemapProvider {let sourcemap = match peek.sourcemap_url {SourceMappingUrl::Url(sourcemap_url) => {- fetch_source_map(&self.client, sourcemap_url.clone(), self.max_response_bytes)- .await?+ fetch_source_map(+ &self.client,+ sourcemap_url.clone(),+ self.max_response_bytes,+ self.allow_internal_ips,+ )+ .await?}SourceMappingUrl::Data(data) => data,};@@ -311,7 +381,13 @@ async fn find_sourcemap_url(client: &reqwest::Client,start: Url,max_response_bytes: usize,+ allow_internal_ips: bool,) -> Result<JsSourcePeek, ResolveError> {+ // The frame's source url comes straight off an ingested event, so vet it before we connect.+ // Every other url in here is derived from the response, and so keeps this validated host,+ // except an absolute sourcemap url - `fetch_source_map` vets that one itself.+ ensure_fetchable_host(&start, allow_internal_ips)?;+debug!("Fetching script source from {}", start);// If this request fails, we cannot resolve the frame, and hand this error to the frames@@ -445,7 +521,12 @@ async fn fetch_source_map(client: &reqwest::Client,url: Url,max_response_bytes: usize,+ allow_internal_ips: bool,) -> Result<String, ResolveError> {+ // A `SourceMap` header or `//# sourceMappingURL=` comment can name an absolute url on any+ // host, so this needs vetting independently of the source url it came from.+ ensure_fetchable_host(&url, allow_internal_ips)?;+metrics::counter!(SOURCEMAP_BODY_FETCHES).increment(1);let res = client.get(url).send().await.map_err(JsResolveErr::from)?;res.error_for_status_ref().map_err(JsResolveErr::from)?;@@ -633,7 +714,7 @@ mod test {let client = reqwest::Client::new();let url = server.url("/static/chunk-PGUQKT6S.js").parse().unwrap();- let peek = find_sourcemap_url(&client, url, TEST_MAX_RESPONSE_BYTES)+ let peek = find_sourcemap_url(&client, url, TEST_MAX_RESPONSE_BYTES, true).await.unwrap();@@ -820,7 +901,7 @@ mod test {.url("/static/inline_sourcemap_example.js").parse().unwrap();- let peek = find_sourcemap_url(&client, url, TEST_MAX_RESPONSE_BYTES)+ let peek = find_sourcemap_url(&client, url, TEST_MAX_RESPONSE_BYTES, true).await.unwrap();@@ -853,6 +934,105 @@ mod test {));}+ #[test]+ fn ensure_fetchable_host_blocks_internal_ip_literals() {+ // Literal IPs never reach PublicIPv4Resolver, so this guard is the only thing+ // standing between an ingested frame url and an internal host.+ let blocked = [+ "http://127.0.0.1/app.js",+ "http://127.0.0.1:6379/app.js",+ "http://169.254.169.254/latest/meta-data/",+ "http://10.0.0.5/app.js",+ "http://192.168.1.1/app.js",+ "http://172.16.0.1/app.js",+ "http://100.64.0.1/app.js",+ "http://[::1]/app.js",+ // Userinfo can dress a literal up as a hostname, but the host is still an IP.+ "http://[email protected]/app.js",+ ];++ for raw in blocked {+ let url: Url = raw.parse().unwrap();+ assert!(+ matches!(+ ensure_fetchable_host(&url, false),+ Err(JsResolveErr::BlockedUrl(_))+ ),+ "expected {raw} to be blocked"+ );+ // The local-development escape hatch still lets these through.+ assert!(+ ensure_fetchable_host(&url, true).is_ok(),+ "expected {raw} to be allowed when internal IPs are permitted"+ );+ }++ // Obfuscated literals: `Url::parse` normalizes these to plain addresses per the URL+ // spec. If a form fails to parse instead, that's equally fine - we never fetch it.+ for raw in ["http://2130706433/app.js", "http://0177.0.0.1/app.js"] {+ let Ok(url) = raw.parse::<Url>() else {+ continue;+ };+ assert_eq!(+ url.host_str(),+ Some("127.0.0.1"),+ "expected {raw} to normalize to a plain address"+ );+ assert!(+ matches!(+ ensure_fetchable_host(&url, false),+ Err(JsResolveErr::BlockedUrl(_))+ ),+ "expected {raw} to be blocked, normalized to {url}"+ );+ }++ let allowed = [+ "http://8.8.8.8/app.js",+ "https://example.com/static/app.js",+ // Hostnames are the DNS resolver's job, so the guard waves them through and+ // PublicIPv4Resolver rejects them at connect time.+ "http://localhost/app.js",+ ];++ for raw in allowed {+ let url: Url = raw.parse().unwrap();+ assert!(+ ensure_fetchable_host(&url, false).is_ok(),+ "expected {raw} to pass the guard"+ );+ }+ }++ #[tokio::test]+ async fn fetch_refuses_ip_literal_that_bypasses_the_dns_resolver() {+ let server = MockServer::start();+ let mock = server.mock(|when, then| {+ when.method("GET").path("/static/chunk-PGUQKT6S.js");+ then.status(200).body(MINIFIED);+ });++ // httpmock listens on a 127.0.0.1 literal, which hyper connects to without ever+ // consulting the DNS resolver, so only the host guard can stop this fetch.+ let mut config = ResolverConfig::init_with_defaults().unwrap();+ config.allow_internal_ips = false;+ let provider = SourcemapProvider::new(&config);+ let url: Url = server.url("/static/chunk-PGUQKT6S.js").parse().unwrap();++ let error = provider.fetch(1, url).await.unwrap_err();++ assert!(+ matches!(+ error,+ ResolveError::ResolutionError(FrameError::JavaScript(JsResolveErr::BlockedUrl(+ ref blocked+ ))) if blocked.contains("127.0.0.1")+ ),+ "unexpected error: {error:?}"+ );+ mock.assert_hits(0);+ }+#[test]fn extract_chunk_id_from_body_handles_known_prefixes() {let canonical =