libp2p_core/transport/
global_only.rs

1// Copyright 2023 Protocol Labs
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the "Software"),
5// to deal in the Software without restriction, including without limitation
6// the rights to use, copy, modify, merge, publish, distribute, sublicense,
7// and/or sell copies of the Software, and to permit persons to whom the
8// Software is furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19// DEALINGS IN THE SOFTWARE.
20
21use crate::{
22    multiaddr::{Multiaddr, Protocol},
23    transport::{DialOpts, ListenerId, TransportError, TransportEvent},
24};
25use std::{
26    pin::Pin,
27    task::{Context, Poll},
28};
29
30/// Dropping all dial requests to non-global IP addresses.
31#[derive(Debug, Clone, Default)]
32pub struct Transport<T> {
33    inner: T,
34}
35
36/// This module contains an implementation of the `is_global` IPv4 address space.
37///
38/// Credit for this implementation goes to the Rust standard library team.
39///
40/// Unstable tracking issue: [#27709](https://github.com/rust-lang/rust/issues/27709)
41mod ipv4_global {
42    use std::net::Ipv4Addr;
43
44    /// Returns [`true`] if this address is reserved by IANA for future use. [IETF RFC 1112]
45    /// defines the block of reserved addresses as `240.0.0.0/4`. This range normally includes the
46    /// broadcast address `255.255.255.255`, but this implementation explicitly excludes it, since
47    /// it is obviously not reserved for future use.
48    ///
49    /// [IETF RFC 1112]: https://tools.ietf.org/html/rfc1112
50    ///
51    /// # Warning
52    ///
53    /// As IANA assigns new addresses, this method will be
54    /// updated. This may result in non-reserved addresses being
55    /// treated as reserved in code that relies on an outdated version
56    /// of this method.
57    #[must_use]
58    #[inline]
59    const fn is_reserved(a: Ipv4Addr) -> bool {
60        a.octets()[0] & 240 == 240 && !a.is_broadcast()
61    }
62
63    /// Returns [`true`] if this address part of the `198.18.0.0/15` range, which is reserved for
64    /// network devices benchmarking. This range is defined in [IETF RFC 2544] as `192.18.0.0`
65    /// through `198.19.255.255` but [errata 423] corrects it to `198.18.0.0/15`.
66    ///
67    /// [IETF RFC 2544]: https://tools.ietf.org/html/rfc2544
68    /// [errata 423]: https://www.rfc-editor.org/errata/eid423
69    #[must_use]
70    #[inline]
71    const fn is_benchmarking(a: Ipv4Addr) -> bool {
72        a.octets()[0] == 198 && (a.octets()[1] & 0xfe) == 18
73    }
74
75    /// Returns [`true`] if this address is part of the Shared Address Space defined in
76    /// [IETF RFC 6598] (`100.64.0.0/10`).
77    ///
78    /// [IETF RFC 6598]: https://tools.ietf.org/html/rfc6598
79    #[must_use]
80    #[inline]
81    const fn is_shared(a: Ipv4Addr) -> bool {
82        a.octets()[0] == 100 && (a.octets()[1] & 0b1100_0000 == 0b0100_0000)
83    }
84
85    /// Returns [`true`] if this is a private address.
86    ///
87    /// The private address ranges are defined in [IETF RFC 1918] and include:
88    ///
89    ///  - `10.0.0.0/8`
90    ///  - `172.16.0.0/12`
91    ///  - `192.168.0.0/16`
92    ///
93    /// [IETF RFC 1918]: https://tools.ietf.org/html/rfc1918
94    #[must_use]
95    #[inline]
96    const fn is_private(a: Ipv4Addr) -> bool {
97        match a.octets() {
98            [10, ..] => true,
99            [172, b, ..] if b >= 16 && b <= 31 => true,
100            [192, 168, ..] => true,
101            _ => false,
102        }
103    }
104
105    /// Returns [`true`] if the address appears to be globally reachable
106    /// as specified by the [IANA IPv4 Special-Purpose Address Registry].
107    /// Whether or not an address is practically reachable will depend on your network configuration.
108    ///
109    /// Most IPv4 addresses are globally reachable;
110    /// unless they are specifically defined as *not* globally reachable.
111    ///
112    /// Non-exhaustive list of notable addresses that are not globally reachable:
113    ///
114    /// - The [unspecified address] ([`is_unspecified`](Ipv4Addr::is_unspecified))
115    /// - Addresses reserved for private use ([`is_private`](Ipv4Addr::is_private))
116    /// - Addresses in the shared address space ([`is_shared`](Ipv4Addr::is_shared))
117    /// - Loopback addresses ([`is_loopback`](Ipv4Addr::is_loopback))
118    /// - Link-local addresses ([`is_link_local`](Ipv4Addr::is_link_local))
119    /// - Addresses reserved for documentation ([`is_documentation`](Ipv4Addr::is_documentation))
120    /// - Addresses reserved for benchmarking ([`is_benchmarking`](Ipv4Addr::is_benchmarking))
121    /// - Reserved addresses ([`is_reserved`](Ipv4Addr::is_reserved))
122    /// - The [broadcast address] ([`is_broadcast`](Ipv4Addr::is_broadcast))
123    ///
124    /// For the complete overview of which addresses are globally reachable, see the table at the [IANA IPv4 Special-Purpose Address Registry].
125    ///
126    /// [IANA IPv4 Special-Purpose Address Registry]: https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml
127    /// [unspecified address]: Ipv4Addr::UNSPECIFIED
128    /// [broadcast address]: Ipv4Addr::BROADCAST
129    #[must_use]
130    #[inline]
131    pub(crate) const fn is_global(a: Ipv4Addr) -> bool {
132        !(a.octets()[0] == 0 // "This network"
133            || is_private(a)
134            || is_shared(a)
135            || a.is_loopback()
136            || a.is_link_local()
137            // addresses reserved for future protocols (`192.0.0.0/24`)
138            ||(a.octets()[0] == 192 && a.octets()[1] == 0 && a.octets()[2] == 0)
139            || a.is_documentation()
140            || is_benchmarking(a)
141            || is_reserved(a)
142            || a.is_broadcast())
143    }
144}
145
146/// This module contains an implementation of the `is_global` IPv6 address space.
147///
148/// Credit for this implementation goes to the Rust standard library team.
149///
150/// Unstable tracking issue: [#27709](https://github.com/rust-lang/rust/issues/27709)
151mod ipv6_global {
152    use std::net::Ipv6Addr;
153
154    /// Returns `true` if the address is a unicast address with link-local scope,
155    /// as defined in [RFC 4291].
156    ///
157    /// A unicast address has link-local scope if it has the prefix `fe80::/10`, as per [RFC 4291 section 2.4].
158    /// Note that this encompasses more addresses than those defined in [RFC 4291 section 2.5.6],
159    /// which describes "Link-Local IPv6 Unicast Addresses" as having the following stricter format:
160    ///
161    /// ```text
162    /// | 10 bits  |         54 bits         |          64 bits           |
163    /// +----------+-------------------------+----------------------------+
164    /// |1111111010|           0             |       interface ID         |
165    /// +----------+-------------------------+----------------------------+
166    /// ```
167    /// So while currently the only addresses with link-local scope an application will encounter are all in `fe80::/64`,
168    /// this might change in the future with the publication of new standards. More addresses in `fe80::/10` could be allocated,
169    /// and those addresses will have link-local scope.
170    ///
171    /// Also note that while [RFC 4291 section 2.5.3] mentions about the [loopback address] (`::1`) that "it is treated as having Link-Local scope",
172    /// this does not mean that the loopback address actually has link-local scope and this method will return `false` on it.
173    ///
174    /// [RFC 4291]: https://tools.ietf.org/html/rfc4291
175    /// [RFC 4291 section 2.4]: https://tools.ietf.org/html/rfc4291#section-2.4
176    /// [RFC 4291 section 2.5.3]: https://tools.ietf.org/html/rfc4291#section-2.5.3
177    /// [RFC 4291 section 2.5.6]: https://tools.ietf.org/html/rfc4291#section-2.5.6
178    /// [loopback address]: Ipv6Addr::LOCALHOST
179    #[must_use]
180    #[inline]
181    const fn is_unicast_link_local(a: Ipv6Addr) -> bool {
182        (a.segments()[0] & 0xffc0) == 0xfe80
183    }
184
185    /// Returns [`true`] if this is a unique local address (`fc00::/7`).
186    ///
187    /// This property is defined in [IETF RFC 4193].
188    ///
189    /// [IETF RFC 4193]: https://tools.ietf.org/html/rfc4193
190    #[must_use]
191    #[inline]
192    const fn is_unique_local(a: Ipv6Addr) -> bool {
193        (a.segments()[0] & 0xfe00) == 0xfc00
194    }
195
196    /// Returns [`true`] if this is an address reserved for documentation
197    /// (`2001:db8::/32`).
198    ///
199    /// This property is defined in [IETF RFC 3849].
200    ///
201    /// [IETF RFC 3849]: https://tools.ietf.org/html/rfc3849
202    #[must_use]
203    #[inline]
204    const fn is_documentation(a: Ipv6Addr) -> bool {
205        (a.segments()[0] == 0x2001) && (a.segments()[1] == 0xdb8)
206    }
207
208    /// Returns [`true`] if the address appears to be globally reachable
209    /// as specified by the [IANA IPv6 Special-Purpose Address Registry].
210    /// Whether or not an address is practically reachable will depend on your network configuration.
211    ///
212    /// Most IPv6 addresses are globally reachable;
213    /// unless they are specifically defined as *not* globally reachable.
214    ///
215    /// Non-exhaustive list of notable addresses that are not globally reachable:
216    /// - The [unspecified address] ([`is_unspecified`](Ipv6Addr::is_unspecified))
217    /// - The [loopback address] ([`is_loopback`](Ipv6Addr::is_loopback))
218    /// - IPv4-mapped addresses
219    /// - Addresses reserved for benchmarking
220    /// - Addresses reserved for documentation ([`is_documentation`](Ipv6Addr::is_documentation))
221    /// - Unique local addresses ([`is_unique_local`](Ipv6Addr::is_unique_local))
222    /// - Unicast addresses with link-local scope ([`is_unicast_link_local`](Ipv6Addr::is_unicast_link_local))
223    ///
224    /// For the complete overview of which addresses are globally reachable, see the table at the [IANA IPv6 Special-Purpose Address Registry].
225    ///
226    /// Note that an address having global scope is not the same as being globally reachable,
227    /// and there is no direct relation between the two concepts: There exist addresses with global scope
228    /// that are not globally reachable (for example unique local addresses),
229    /// and addresses that are globally reachable without having global scope
230    /// (multicast addresses with non-global scope).
231    ///
232    /// [IANA IPv6 Special-Purpose Address Registry]: https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml
233    /// [unspecified address]: Ipv6Addr::UNSPECIFIED
234    /// [loopback address]: Ipv6Addr::LOCALHOST
235    #[must_use]
236    #[inline]
237    pub(crate) const fn is_global(a: Ipv6Addr) -> bool {
238        !(a.is_unspecified()
239            || a.is_loopback()
240            // IPv4-mapped Address (`::ffff:0:0/96`)
241            || matches!(a.segments(), [0, 0, 0, 0, 0, 0xffff, _, _])
242            // IPv4-IPv6 Translat. (`64:ff9b:1::/48`)
243            || matches!(a.segments(), [0x64, 0xff9b, 1, _, _, _, _, _])
244            // Discard-Only Address Block (`100::/64`)
245            || matches!(a.segments(), [0x100, 0, 0, 0, _, _, _, _])
246            // IETF Protocol Assignments (`2001::/23`)
247            || (matches!(a.segments(), [0x2001, b, _, _, _, _, _, _] if b < 0x200)
248                && !(
249                    // Port Control Protocol Anycast (`2001:1::1`)
250                    u128::from_be_bytes(a.octets()) == 0x2001_0001_0000_0000_0000_0000_0000_0001
251                    // Traversal Using Relays around NAT Anycast (`2001:1::2`)
252                    || u128::from_be_bytes(a.octets()) == 0x2001_0001_0000_0000_0000_0000_0000_0002
253                    // AMT (`2001:3::/32`)
254                    || matches!(a.segments(), [0x2001, 3, _, _, _, _, _, _])
255                    // AS112-v6 (`2001:4:112::/48`)
256                    || matches!(a.segments(), [0x2001, 4, 0x112, _, _, _, _, _])
257                    // ORCHIDv2 (`2001:20::/28`)
258                    || matches!(a.segments(), [0x2001, b, _, _, _, _, _, _] if b >= 0x20 && b <= 0x2F)
259                ))
260            || is_documentation(a)
261            || is_unique_local(a)
262            || is_unicast_link_local(a))
263    }
264}
265
266impl<T> Transport<T> {
267    pub fn new(transport: T) -> Self {
268        Transport { inner: transport }
269    }
270}
271
272impl<T: crate::Transport + Unpin> crate::Transport for Transport<T> {
273    type Output = <T as crate::Transport>::Output;
274    type Error = <T as crate::Transport>::Error;
275    type ListenerUpgrade = <T as crate::Transport>::ListenerUpgrade;
276    type Dial = <T as crate::Transport>::Dial;
277
278    fn listen_on(
279        &mut self,
280        id: ListenerId,
281        addr: Multiaddr,
282    ) -> Result<(), TransportError<Self::Error>> {
283        self.inner.listen_on(id, addr)
284    }
285
286    fn remove_listener(&mut self, id: ListenerId) -> bool {
287        self.inner.remove_listener(id)
288    }
289
290    fn dial(
291        &mut self,
292        addr: Multiaddr,
293        opts: DialOpts,
294    ) -> Result<Self::Dial, TransportError<Self::Error>> {
295        match addr.iter().next() {
296            Some(Protocol::Ip4(a)) => {
297                if !ipv4_global::is_global(a) {
298                    tracing::debug!(ip=%a, "Not dialing non global IP address");
299                    return Err(TransportError::MultiaddrNotSupported(addr));
300                }
301                self.inner.dial(addr, opts)
302            }
303            Some(Protocol::Ip6(a)) => {
304                if !ipv6_global::is_global(a) {
305                    tracing::debug!(ip=%a, "Not dialing non global IP address");
306                    return Err(TransportError::MultiaddrNotSupported(addr));
307                }
308                self.inner.dial(addr, opts)
309            }
310            _ => {
311                tracing::debug!(address=%addr, "Not dialing unsupported Multiaddress");
312                Err(TransportError::MultiaddrNotSupported(addr))
313            }
314        }
315    }
316
317    fn poll(
318        mut self: Pin<&mut Self>,
319        cx: &mut Context<'_>,
320    ) -> Poll<TransportEvent<Self::ListenerUpgrade, Self::Error>> {
321        Pin::new(&mut self.inner).poll(cx)
322    }
323}