Skip to main content

rings_node/onion/
target.rs

1//! Target authority parsing shared by onion policy and proxy adapters.
2
3#[cfg(any(test, rings_native))]
4use std::net::SocketAddr;
5
6#[cfg(rings_native)]
7use tokio::net::lookup_host;
8use url::Host;
9#[cfg(any(all(feature = "browser", target_family = "wasm"), test))]
10use url::Url;
11
12use crate::error::Error;
13use crate::error::Result;
14
15/// Closed parse failures for an onion proxy authority.
16#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
17pub enum OnionProxyTargetError {
18    /// Authority is empty after trimming.
19    #[error("onion proxy target authority must not be empty")]
20    EmptyAuthority,
21    /// A bracketed IPv6 host has no closing bracket.
22    #[error("invalid bracketed IPv6 onion proxy authority")]
23    MissingIpv6Bracket,
24    /// The authority has no explicit port separator or port value.
25    #[error("onion proxy authority must include a port")]
26    MissingPort,
27    /// Host is empty after canonicalization.
28    #[error("onion proxy target host must not be empty")]
29    EmptyHost,
30    /// Host contains whitespace.
31    #[error("onion proxy target host must not contain whitespace")]
32    HostWhitespace,
33    /// Host contains `*`: no authority has a wildcard host, so a `*` is never a literal (the
34    /// exit patterns `*`, `*:*` and `*:port` are recognised before any host is parsed).
35    #[error("onion proxy target host must not contain '*'")]
36    WildcardHost,
37    /// Host is not a syntactically valid domain or IP literal.
38    #[error("onion proxy target host is invalid")]
39    InvalidHost,
40    /// Port is not a valid `u16`.
41    #[error("onion proxy target has an invalid port")]
42    InvalidPort,
43    /// Port zero cannot identify a connect target.
44    #[error("onion proxy target port must be non-zero")]
45    ZeroPort,
46}
47
48/// Host/port target requested through an onion proxy.
49#[derive(Clone, Debug, Eq, PartialEq)]
50pub struct OnionProxyTarget {
51    host: String,
52    port: u16,
53}
54
55impl OnionProxyTarget {
56    /// Validate a host and port already separated by a URL or proxy parser.
57    pub fn new(host: &str, port: u16) -> Result<Self> {
58        let host = normalize_host(host)?;
59        if port == 0 {
60            return Err(OnionProxyTargetError::ZeroPort.into());
61        }
62        Ok(Self { host, port })
63    }
64
65    /// Parse an HTTP CONNECT authority (`host:port` or `[ipv6]:port`).
66    pub fn parse_authority(authority: &str) -> Result<Self> {
67        let authority = authority.trim();
68        if authority.is_empty() {
69            return Err(OnionProxyTargetError::EmptyAuthority.into());
70        }
71
72        let (host, port) = if let Some(rest) = authority.strip_prefix('[') {
73            let Some((host, rest)) = rest.split_once(']') else {
74                return Err(OnionProxyTargetError::MissingIpv6Bracket.into());
75            };
76            let Some(port) = rest.strip_prefix(':') else {
77                return Err(OnionProxyTargetError::MissingPort.into());
78            };
79            (host, port)
80        } else {
81            authority
82                .rsplit_once(':')
83                .ok_or(OnionProxyTargetError::MissingPort)?
84        };
85
86        let port = port
87            .parse::<u16>()
88            .map_err(|_| OnionProxyTargetError::InvalidPort)?;
89        Self::new(host, port)
90    }
91
92    /// Construct a target from an already canonicalized host literal and non-zero port.
93    pub(crate) fn from_canonical_literal(host: &'static str, port: u16) -> Self {
94        Self {
95            host: host.to_string(),
96            port,
97        }
98    }
99
100    /// Return the normalized host.
101    pub fn host(&self) -> &str {
102        &self.host
103    }
104
105    /// Return the target port.
106    pub const fn port(&self) -> u16 {
107        self.port
108    }
109
110    /// Return the canonical authority string used for exit policy/service lookup.
111    pub fn authority(&self) -> String {
112        if self.host.contains(':') {
113            format!("[{}]:{}", self.host, self.port)
114        } else {
115            format!("{}:{}", self.host, self.port)
116        }
117    }
118}
119
120/// Resolve an exit target exactly once and retain only publicly routable
121/// addresses. Callers must connect to one of the returned socket addresses,
122/// rather than resolving the hostname again, so a DNS rebinding cannot change
123/// the destination after this admission decision.
124#[cfg(rings_native)]
125pub(crate) async fn resolve_public_target(target: &OnionProxyTarget) -> Result<Vec<SocketAddr>> {
126    let addresses = resolve_target_addresses(target).await?;
127    match select_public_exit_addresses(addresses) {
128        PublicAddressSelection::Public(addresses) => Ok(addresses),
129        PublicAddressSelection::Denied => Err(Error::NoPermission),
130        PublicAddressSelection::Empty => Err(Error::OnionTargetResolvedEmpty {
131            authority: target.authority(),
132        }),
133    }
134}
135
136/// Resolve one target into a single DNS snapshot without assigning egress authority:
137/// [`resolve_public_target`] passes the complete snapshot through
138/// [`select_public_exit_addresses`] before any address is used.
139#[cfg(rings_native)]
140async fn resolve_target_addresses(target: &OnionProxyTarget) -> Result<Vec<SocketAddr>> {
141    Ok(lookup_host((target.host(), target.port()))
142        .await
143        .map_err(|error| Error::OnionTargetResolve {
144            authority: target.authority(),
145            source: error,
146        })?
147        .collect())
148}
149
150#[derive(Clone, Debug, Eq, PartialEq)]
151#[cfg(any(test, rings_native))]
152enum PublicAddressSelection {
153    Empty,
154    Denied,
155    Public(Vec<SocketAddr>),
156}
157
158/// Select a stable, de-duplicated public projection from one DNS result snapshot.
159#[cfg(any(test, rings_native))]
160fn select_public_exit_addresses(addresses: Vec<SocketAddr>) -> PublicAddressSelection {
161    if addresses.is_empty() {
162        return PublicAddressSelection::Empty;
163    }
164    let public = addresses
165        .into_iter()
166        .filter(|address| rings_network_policy::is_public_ip(address.ip()))
167        .fold(Vec::new(), |mut selected, address| {
168            if !selected.contains(&address) {
169                selected.push(address);
170            }
171            selected
172        });
173    if public.is_empty() {
174        PublicAddressSelection::Denied
175    } else {
176        PublicAddressSelection::Public(public)
177    }
178}
179
180/// Validate that `target`'s host is an explicit public IPv4 or IPv6 literal.
181///
182/// Browser `fetch()` cannot pin resolved DNS addresses before connecting, so browser HTTPS exits
183/// only admit public IP-literal destinations.
184pub(crate) fn validate_public_ip_literal(target: &OnionProxyTarget) -> Result<()> {
185    let ip = target
186        .host()
187        .parse::<std::net::IpAddr>()
188        .map_err(|_| Error::NoPermission)?;
189    if rings_network_policy::is_public_ip(ip) {
190        Ok(())
191    } else {
192        Err(Error::NoPermission)
193    }
194}
195
196/// Validate that an HTTPS exit request URL parses as an `https://` target without embedded
197/// credentials, targets an explicit public IP literal, and matches `target`'s canonical host and
198/// port.
199#[cfg(any(all(feature = "browser", target_family = "wasm"), test))]
200pub(crate) fn validate_public_https_url(url: &str, target: &OnionProxyTarget) -> Result<()> {
201    validate_public_ip_literal(target)?;
202    let parsed = Url::parse(url).map_err(|_| Error::NoPermission)?;
203    if parsed.scheme() != "https" || !parsed.username().is_empty() || parsed.password().is_some() {
204        return Err(Error::NoPermission);
205    }
206    if parsed.port_or_known_default() != Some(target.port()) {
207        return Err(Error::NoPermission);
208    }
209    let parsed_host = parsed.host_str().ok_or(Error::NoPermission)?;
210    let parsed_target =
211        OnionProxyTarget::new(parsed_host, target.port()).map_err(|_| Error::NoPermission)?;
212    validate_public_ip_literal(&parsed_target)?;
213    if parsed_target != *target {
214        return Err(Error::NoPermission);
215    }
216    Ok(())
217}
218
219/// The canonical host: trimmed, without trailing dots, canonicalized via `url::Host::parse`
220/// (IDNA Punycode lowercase ASCII for domains, canonical dotted-quad / compressed IPv6 for IP
221/// literals); empty, whitespace, `*`, and syntactically invalid hosts are refused.
222fn normalize_host(host: &str) -> Result<String> {
223    let host = host.trim().trim_end_matches('.');
224    if host.is_empty() {
225        return Err(OnionProxyTargetError::EmptyHost.into());
226    }
227    if host.chars().any(char::is_whitespace) {
228        return Err(OnionProxyTargetError::HostWhitespace.into());
229    }
230    if host.contains('*') {
231        return Err(OnionProxyTargetError::WildcardHost.into());
232    }
233    let parsed = if host.contains(':') && !host.starts_with('[') {
234        Host::parse(&format!("[{host}]"))
235    } else {
236        Host::parse(host)
237    }
238    .map_err(|_| OnionProxyTargetError::InvalidHost)?;
239    Ok(match parsed {
240        Host::Domain(domain) => domain,
241        Host::Ipv4(ipv4) => ipv4.to_string(),
242        Host::Ipv6(ipv6) => ipv6.to_string(),
243    })
244}
245
246#[cfg(test)]
247mod tests {
248    use std::net::IpAddr;
249    use std::net::SocketAddr;
250
251    #[cfg(rings_native)]
252    use super::resolve_public_target;
253    use super::select_public_exit_addresses;
254    #[cfg(rings_native)]
255    use super::OnionProxyTarget;
256    use super::PublicAddressSelection;
257    #[cfg(rings_native)]
258    use crate::error::Error;
259
260    #[test]
261    fn test_public_address_selection_distinguishes_empty_denied_and_deduplicated_public() {
262        let denied: SocketAddr = "127.0.0.1:443".parse().expect("denied address");
263        let public: SocketAddr = "8.8.8.8:443".parse().expect("public address");
264
265        assert_eq!(
266            select_public_exit_addresses(Vec::new()),
267            PublicAddressSelection::Empty
268        );
269        assert_eq!(
270            select_public_exit_addresses(vec![denied]),
271            PublicAddressSelection::Denied
272        );
273        assert_eq!(
274            select_public_exit_addresses(vec![denied, public, public]),
275            PublicAddressSelection::Public(vec![public])
276        );
277    }
278
279    #[test]
280    fn test_exit_address_predicate_rejects_internal_and_special_destinations() {
281        for address in [
282            "0.0.0.0",
283            "10.0.0.1",
284            "100.64.0.1",
285            "127.0.0.1",
286            "169.254.169.254",
287            "172.16.0.1",
288            "192.168.0.1",
289            "198.18.0.1",
290            "224.0.0.1",
291            "::",
292            "::1",
293            "::ffff:127.0.0.1",
294            "64:ff9b::7f00:1",
295            "2001:db8::1",
296            "2002:7f00:1::",
297            "3fff::1",
298            "4000::1",
299            "fc00::1",
300            "fe80::1",
301            "ff02::1",
302        ] {
303            let address = address.parse::<IpAddr>().expect("valid fixture address");
304            assert!(
305                !rings_network_policy::is_public_ip(address),
306                "accepted special address {address}"
307            );
308        }
309    }
310
311    #[test]
312    fn test_exit_address_predicate_accepts_public_destinations() {
313        for address in ["1.1.1.1", "8.8.8.8", "2606:4700:4700::1111"] {
314            let address = address.parse::<IpAddr>().expect("valid fixture address");
315            assert!(
316                rings_network_policy::is_public_ip(address),
317                "rejected public address {address}"
318            );
319        }
320    }
321
322    #[test]
323    fn test_idna_punycode_canonicalization_and_public_https_url_validation() {
324        let idna = super::OnionProxyTarget::parse_authority("Bücher.Example.:443")
325            .expect("valid IDNA authority");
326        assert_eq!(idna.host(), "xn--bcher-kva.example");
327        assert_eq!(idna.authority(), "xn--bcher-kva.example:443");
328
329        let public_ip = super::OnionProxyTarget::parse_authority("1.1.1.1:443").expect("public ip");
330        assert!(super::validate_public_https_url("https://1.1.1.1/dns-query", &public_ip).is_ok());
331        let public_ipv6 =
332            super::OnionProxyTarget::parse_authority("[2606:4700:4700::1111]:443").expect("ipv6");
333        assert!(super::validate_public_https_url(
334            "https://[2606:4700:4700::1111]:443/dns-query",
335            &public_ipv6,
336        )
337        .is_ok());
338
339        for denied_authority in [
340            "xn--bcher-kva.example:443",
341            "service.example.com:443",
342            "127.0.0.1:443",
343            "10.0.0.1:443",
344            "[::1]:443",
345            "localhost:443",
346            "service.local:443",
347            "metadata.google.internal:443",
348        ] {
349            let target =
350                super::OnionProxyTarget::parse_authority(denied_authority).expect("authority");
351            let url = format!("https://{}/", target.authority());
352            assert!(
353                matches!(
354                    super::validate_public_https_url(&url, &target),
355                    Err(crate::error::Error::NoPermission)
356                ),
357                "unexpectedly allowed {url}"
358            );
359        }
360    }
361
362    #[cfg(rings_native)]
363    #[tokio::test]
364    async fn test_resolver_rejects_loopback_before_any_exit_connection() {
365        let target =
366            OnionProxyTarget::parse_authority("127.0.0.1:443").expect("valid loopback authority");
367
368        assert!(matches!(
369            resolve_public_target(&target).await,
370            Err(Error::NoPermission)
371        ));
372    }
373}