Skip to main content

eclipse_core/
netguard.rs

1//! SSRF protection for the `fetch` tool.
2//!
3//! The classification functions are pure (they take an already-resolved IP), so they are
4//! unit-testable without DNS. [`resolve_public`] does the real lookup and returns the
5//! vetted addresses, which the caller pins for the connection so a second DNS answer
6//! (rebinding) cannot swap in an internal address.
7
8use reqwest::Url;
9use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
10use std::time::Duration;
11
12fn v4_block_reason(ip: Ipv4Addr) -> Option<&'static str> {
13    let [a, b, c, _] = ip.octets();
14    Some(match (a, b, c) {
15        (0, ..) if ip.is_unspecified() => "unspecified address",
16        (0, ..) => "\"this network\" address (0.0.0.0/8)",
17        (127, ..) => "loopback address",
18        (10, ..) => "private address (10.0.0.0/8)",
19        (172, 16..=31, _) => "private address (172.16.0.0/12)",
20        (192, 168, _) => "private address (192.168.0.0/16)",
21        (169, 254, _) => "link-local address",
22        (100, 64..=127, _) => "carrier-grade NAT address (100.64.0.0/10)",
23        (192, 0, 0) => "IETF protocol assignment (192.0.0.0/24)",
24        (192, 0, 2) | (198, 51, 100) | (203, 0, 113) => "documentation address",
25        (198, 18..=19, _) => "benchmarking address (198.18.0.0/15)",
26        (224..=239, ..) => "multicast address",
27        (240..=255, ..) => "reserved or broadcast address",
28        _ => return None,
29    })
30}
31
32fn v6_block_reason(ip: Ipv6Addr) -> Option<&'static str> {
33    if ip.is_unspecified() {
34        return Some("unspecified address");
35    }
36    if ip.is_loopback() {
37        return Some("loopback address");
38    }
39    let s = ip.segments();
40    // Anything that embeds an IPv4 address is refused outright: the embedded address
41    // may be internal, and gateways such as NAT64 can translate it into a real connection.
42    if let Some(v4) = ip.to_ipv4_mapped() {
43        return Some(v4_block_reason(v4).unwrap_or("IPv4-mapped IPv6 address"));
44    }
45    Some(match s {
46        [0, 0, 0, 0, 0, 0, ..] => "IPv4-compatible IPv6 address (::/96)",
47        [0x64, 0xff9b, 0, 0, 0, 0, ..] => "NAT64 address (64:ff9b::/96)",
48        [0x64, 0xff9b, 1, ..] => "local-use NAT64 address (64:ff9b:1::/48)",
49        [0x2002, ..] => "6to4 address (2002::/16)",
50        [0x2001, 0, ..] => "Teredo address (2001::/32)",
51        [0x2001, 0xdb8, ..] => "documentation address (2001:db8::/32)",
52        [0x3fff, hi, ..] if hi < 0x1000 => "documentation address (3fff::/20)",
53        [first, ..] if first & 0xfe00 == 0xfc00 => "unique local address (fc00::/7)",
54        [first, ..] if first & 0xffc0 == 0xfe80 => "link-local address (fe80::/10)",
55        [first, ..] if first & 0xffc0 == 0xfec0 => "site-local address (fec0::/10)",
56        [first, ..] if first & 0xff00 == 0xff00 => "multicast address",
57        _ => return None,
58    })
59}
60
61/// Why `ip` must not be fetched, or `None` if it is a normal public address.
62pub fn blocked_reason(ip: IpAddr) -> Option<&'static str> {
63    match ip {
64        IpAddr::V4(v4) => v4_block_reason(v4),
65        IpAddr::V6(v6) => v6_block_reason(v6),
66    }
67}
68
69/// Check every address a host name resolved to; one internal answer blocks the lot.
70pub fn check_resolved(host: &str, addrs: &[IpAddr]) -> Result<(), String> {
71    if addrs.is_empty() {
72        return Err(format!("`{host}` did not resolve to any address"));
73    }
74    for ip in addrs {
75        if let Some(why) = blocked_reason(*ip) {
76            return Err(format!(
77                "blocked: `{host}` resolves to {ip}, a {why}; fetch only reaches public hosts"
78            ));
79        }
80    }
81    Ok(())
82}
83
84/// Host-name part of the policy that needs no DNS: IP literals (including
85/// IPv4-mapped IPv6 and the numeric forms the URL parser normalises) and `localhost`
86/// names are refused. Returns the domain name to resolve.
87pub fn check_url_host(url: &Url) -> Result<String, String> {
88    use url::Host;
89    match url.host() {
90        None => Err("blocked: URL has no host".into()),
91        Some(Host::Ipv4(ip)) => Err(format!(
92            "blocked: IP literal {ip} is not allowed; use a public host name"
93        )),
94        Some(Host::Ipv6(ip)) => Err(format!(
95            "blocked: IP literal {ip} is not allowed; use a public host name"
96        )),
97        Some(Host::Domain(d)) => {
98            let name = d.trim_end_matches('.').to_ascii_lowercase();
99            if name == "localhost" || name.ends_with(".localhost") {
100                Err(format!("blocked: `{d}` is a localhost name"))
101            } else {
102                Ok(name)
103            }
104        }
105    }
106}
107
108/// Resolve `host` and return its addresses only if all of them are public.
109pub async fn resolve_public(
110    host: &str,
111    port: u16,
112    timeout: Duration,
113) -> Result<Vec<SocketAddr>, String> {
114    let lookup = tokio::net::lookup_host((host, port));
115    let addrs: Vec<SocketAddr> = tokio::time::timeout(timeout, lookup)
116        .await
117        .map_err(|_| format!("DNS lookup for `{host}` timed out"))?
118        .map_err(|e| format!("DNS lookup for `{host}` failed: {e}"))?
119        .collect();
120    let ips: Vec<IpAddr> = addrs.iter().map(SocketAddr::ip).collect();
121    check_resolved(host, &ips)?;
122    Ok(addrs)
123}
124
125#[cfg(test)]
126mod tests {
127    use super::*;
128
129    fn ip(s: &str) -> IpAddr {
130        s.parse().unwrap()
131    }
132
133    #[test]
134    fn loopback_private_linklocal_and_unspecified_are_blocked() {
135        for s in [
136            "127.0.0.1",
137            "127.255.255.254",
138            "::1",
139            "10.0.0.1",
140            "10.255.255.255",
141            "172.16.0.1",
142            "172.31.255.255",
143            "192.168.1.1",
144            "169.254.169.254",
145            "fe80::1",
146            "febf::1",
147            "0.0.0.0",
148            "::",
149            "fc00::1",
150            "fd12:3456::1",
151        ] {
152            assert!(blocked_reason(ip(s)).is_some(), "{s} should be blocked");
153        }
154    }
155
156    #[test]
157    fn cgnat_documentation_and_translation_ranges_are_blocked() {
158        for s in [
159            "100.64.0.1",
160            "100.127.255.255",
161            "192.0.2.1",
162            "198.51.100.7",
163            "203.0.113.9",
164            "2001:db8::1",
165            "64:ff9b::7f00:1",
166            "64:ff9b::808:808",
167            "64:ff9b:1::1",
168            "::ffff:127.0.0.1",
169            "::ffff:8.8.8.8",
170            "2002:7f00:1::1",
171            "ff02::1",
172            "224.0.0.1",
173            "255.255.255.255",
174        ] {
175            assert!(blocked_reason(ip(s)).is_some(), "{s} should be blocked");
176        }
177    }
178
179    #[test]
180    fn public_addresses_and_range_edges_pass() {
181        for s in [
182            "8.8.8.8",
183            "1.1.1.1",
184            "172.15.255.255",
185            "172.32.0.1",
186            "100.63.255.255",
187            "100.128.0.1",
188            "192.169.0.1",
189            "198.17.0.1",
190            "198.20.0.1",
191            "203.0.114.1",
192            "2606:4700:4700::1111",
193            "2a00:1450:4001:81b::200e",
194            "fe00::1",
195        ] {
196            assert_eq!(blocked_reason(ip(s)), None, "{s} should be allowed");
197        }
198    }
199
200    #[test]
201    fn resolved_set_is_blocked_if_any_answer_is_internal() {
202        assert!(check_resolved("a.example", &[ip("8.8.8.8"), ip("2606:4700::1")]).is_ok());
203        let err = check_resolved("a.example", &[ip("8.8.8.8"), ip("10.0.0.5")]).unwrap_err();
204        assert!(err.contains("10.0.0.5") && err.contains("private"), "{err}");
205        assert!(check_resolved("a.example", &[]).is_err());
206    }
207
208    #[test]
209    fn url_hosts_literals_and_localhost_names_are_rejected() {
210        let host = |u: &str| check_url_host(&Url::parse(u).unwrap());
211        assert_eq!(host("https://Example.COM./x").unwrap(), "example.com");
212        for u in [
213            "http://127.0.0.1/",
214            "http://8.8.8.8/",
215            "http://[::1]:8080/",
216            "http://[::ffff:8.8.8.8]/",
217            "http://[::ffff:7f00:1]/",
218            "http://2130706433/",
219            "http://0x7f.1/",
220            "http://localhost/",
221            "http://LOCALHOST:3000/",
222            "http://localhost./",
223            "http://foo.localhost/",
224            "http://a.b.LOCALHOST./",
225        ] {
226            assert!(host(u).is_err(), "{u} should be rejected");
227        }
228        assert!(host("http://notlocalhost.example/").is_ok());
229        assert!(host("http://localhost.example/").is_ok());
230    }
231}