Skip to main content

rtci_shared/stream/
nat64.rs

1//! NAT64 for the Happy Eyeballs engine on an IPv6-only network (RFC 8305 section 7, RFC 8445
2//! section 5.1.1.2): the prefix the network's NAT64 uses is discovered with RFC 7050 (the
3//! AAAA records of [`IPV4ONLY_ARPA`], which a DNS64 resolver synthesizes from its well-known
4//! IPv4 addresses), and IPv4 addresses are written into IPv6 ones with that prefix as RFC 6052
5//! section 2.2 has it.
6
7use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
8
9/// RFC 7050 section 2: the well-known name whose AAAA records a DNS64 resolver synthesizes.
10pub const IPV4ONLY_ARPA: &str = "ipv4only.arpa";
11
12/// RFC 7050 section 2.2: the well-known IPv4 addresses of [`IPV4ONLY_ARPA`].
13pub const WELL_KNOWN_IPV4: [Ipv4Addr; 2] =
14    [Ipv4Addr::new(192, 0, 0, 170), Ipv4Addr::new(192, 0, 0, 171)];
15
16/// RFC 6052 section 2.2: the prefix lengths an IPv4-embedded IPv6 address may have.
17pub const PREFIX_LENGTHS: [u8; 6] = [96, 64, 56, 48, 40, 32];
18
19/// A NAT64 prefix (RFC 6052 section 2.2): its first `len` bits are the network's.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub struct Nat64Prefix {
22    /// The prefix, the bits past `len` zero.
23    pub prefix: Ipv6Addr,
24    /// 32, 40, 48, 56, 64 or 96.
25    pub len: u8,
26}
27
28/// The byte positions of the 32 IPv4 bits in an IPv4-embedded IPv6 address of a prefix of
29/// `len` bits (RFC 6052 section 2.2, figure 1): bits 64 to 71 (byte 8, "u") are skipped and
30/// left zero.
31fn ipv4_positions(len: u8) -> Option<[usize; 4]> {
32    Some(match len {
33        32 => [4, 5, 6, 7],
34        40 => [5, 6, 7, 9],
35        48 => [6, 7, 9, 10],
36        56 => [7, 9, 10, 11],
37        64 => [9, 10, 11, 12],
38        96 => [12, 13, 14, 15],
39        _ => return None,
40    })
41}
42
43impl Nat64Prefix {
44    /// The prefix of length `len` of `addr` (bits past it cleared); `None` for a length
45    /// RFC 6052 does not allow.
46    pub fn new(addr: Ipv6Addr, len: u8) -> Option<Self> {
47        ipv4_positions(len)?;
48        let bits = u128::from(addr);
49        let mask = if len == 0 {
50            0
51        } else {
52            u128::MAX << (128 - u32::from(len))
53        };
54        Some(Self {
55            prefix: Ipv6Addr::from(bits & mask),
56            len,
57        })
58    }
59
60    /// RFC 6052 section 2.2: `v4` embedded under this prefix, the "u" octet (bits 64 to 71)
61    /// and the suffix zero.
62    pub fn synthesize(&self, v4: Ipv4Addr) -> Ipv6Addr {
63        let mut octets = self.prefix.octets();
64        // Bits from the prefix length on are the IPv4 address's, the u octet's and the
65        // suffix's: start them from zero.
66        for (i, o) in octets.iter_mut().enumerate() {
67            if i * 8 >= usize::from(self.len) {
68                *o = 0;
69            }
70        }
71        let positions = ipv4_positions(self.len).unwrap_or([12, 13, 14, 15]);
72        for (p, b) in positions.iter().zip(v4.octets()) {
73            octets[*p] = b;
74        }
75        Ipv6Addr::from(octets)
76    }
77
78    /// The IPv4 address `addr` embeds under this prefix, if `addr` has the prefix.
79    pub fn extract(&self, addr: Ipv6Addr) -> Option<Ipv4Addr> {
80        if Self::new(addr, self.len)? != *self {
81            return None;
82        }
83        let o = addr.octets();
84        let p = ipv4_positions(self.len)?;
85        Some(Ipv4Addr::new(o[p[0]], o[p[1]], o[p[2]], o[p[3]]))
86    }
87}
88
89/// RFC 7050 section 3: the NAT64 prefixes the AAAA answers for [`IPV4ONLY_ARPA`] show. Each
90/// IPv6 address is searched for one of the [`WELL_KNOWN_IPV4`] addresses at each prefix
91/// length (longest first); an address that holds none is not a synthesized one and is
92/// ignored. Duplicates are dropped; the order of the answers is kept.
93pub fn discover_prefixes(answers: &[IpAddr]) -> Vec<Nat64Prefix> {
94    let mut out: Vec<Nat64Prefix> = vec![];
95    for answer in answers {
96        let IpAddr::V6(v6) = answer else {
97            continue;
98        };
99        let found = PREFIX_LENGTHS.iter().find_map(|&len| {
100            let prefix = Nat64Prefix::new(*v6, len)?;
101            let embedded = prefix.extract(*v6)?;
102            (WELL_KNOWN_IPV4.contains(&embedded) && prefix.synthesize(embedded) == *v6)
103                .then_some(prefix)
104        });
105        if let Some(prefix) = found
106            && !out.contains(&prefix)
107        {
108            out.push(prefix);
109        }
110    }
111    out
112}
113
114/// RFC 8305 section 7.1: the IPv6 addresses synthesized for the IPv4 ones among `addresses`
115/// with each of `prefixes`, with their ports. "The synthesized addresses are then inserted
116/// into the list of addresses as if they were results from DNS queries".
117pub fn synthesize_all(addresses: &[SocketAddr], prefixes: &[Nat64Prefix]) -> Vec<SocketAddr> {
118    let mut out = vec![];
119    for a in addresses {
120        let IpAddr::V4(v4) = a.ip() else {
121            continue;
122        };
123        for p in prefixes {
124            let s = SocketAddr::new(IpAddr::V6(p.synthesize(v4)), a.port());
125            if !out.contains(&s) {
126                out.push(s);
127            }
128        }
129    }
130    out
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136
137    fn v6(s: &str) -> Ipv6Addr {
138        s.parse().unwrap()
139    }
140
141    /// RFC 6052 section 2.4, table 1: 192.0.2.33 under 2001:db8:100::/40 and the other
142    /// lengths of the table's example prefixes, and under the well-known prefix 64:ff9b::/96.
143    #[test]
144    fn synthesis_follows_rfc_6052_table_1() {
145        let v4 = Ipv4Addr::new(192, 0, 2, 33);
146        let cases = [
147            ("2001:db8::", 32, "2001:db8:c000:221::"),
148            ("2001:db8:100::", 40, "2001:db8:1c0:2:21::"),
149            ("2001:db8:122::", 48, "2001:db8:122:c000:2:2100::"),
150            ("2001:db8:122:300::", 56, "2001:db8:122:3c0:0:221::"),
151            ("2001:db8:122:344::", 64, "2001:db8:122:344:c0:2:2100:0"),
152            ("2001:db8:122:344::", 96, "2001:db8:122:344::c000:221"),
153            ("64:ff9b::", 96, "64:ff9b::c000:221"),
154        ];
155        for (prefix, len, want) in cases {
156            let p = Nat64Prefix::new(v6(prefix), len).unwrap();
157            assert_eq!(p.synthesize(v4), v6(want), "/{len}");
158            assert_eq!(p.extract(v6(want)), Some(v4), "/{len}");
159        }
160        assert!(Nat64Prefix::new(v6("64:ff9b::"), 80).is_none());
161        assert_eq!(
162            Nat64Prefix::new(v6("64:ff9b::"), 96)
163                .unwrap()
164                .extract(v6("2001:db8::c000:221")),
165            None,
166            "another prefix"
167        );
168    }
169
170    /// RFC 7050 section 3: the prefix is found from the synthesized AAAA records of
171    /// ipv4only.arpa, at whichever length holds a well-known address; an answer that holds
172    /// none is ignored.
173    #[test]
174    fn prefixes_are_discovered_from_the_well_known_addresses() {
175        let answers: Vec<IpAddr> = vec![
176            "64:ff9b::c000:aa".parse().unwrap(),
177            "64:ff9b::c000:ab".parse().unwrap(),
178            "2001:db8:122:3c0:0:aa::".parse().unwrap(),
179            "2001:db8::1".parse().unwrap(),
180            "192.0.0.170".parse().unwrap(),
181        ];
182        let found = discover_prefixes(&answers);
183        assert_eq!(
184            found,
185            vec![
186                Nat64Prefix::new(v6("64:ff9b::"), 96).unwrap(),
187                Nat64Prefix::new(v6("2001:db8:122:300::"), 56).unwrap(),
188            ]
189        );
190        assert!(discover_prefixes(&["2001:db8::1".parse().unwrap()]).is_empty());
191        let synthesized = synthesize_all(
192            &[
193                "192.0.2.10:3478".parse().unwrap(),
194                "[2001:db8::9]:3478".parse().unwrap(),
195            ],
196            &found[..1],
197        );
198        assert_eq!(
199            synthesized,
200            vec!["[64:ff9b::c000:20a]:3478".parse().unwrap()]
201        );
202    }
203}