1#![cfg(not(target_arch = "wasm32"))]
7
8use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket};
9use std::time::Duration;
10
11pub const MAGIC: u32 = 0x2112_A442;
13const BINDING_REQUEST: u16 = 0x0001;
14const BINDING_SUCCESS: u16 = 0x0101;
15const ATTR_XOR_MAPPED: u16 = 0x0020;
16const FAMILY_IPV4: u8 = 0x01;
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum MappingClass {
21 EndpointIndependent,
24 AddressDependent,
28}
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum ProbeRole {
33 ConnectOnly,
35}
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub struct ObserveReport {
40 pub local: SocketAddr,
41 pub sample_a: SocketAddr,
42 pub sample_b: SocketAddr,
43 pub class: MappingClass,
44}
45
46pub const fn internet_two_host_handshake_executed() -> bool {
48 false
49}
50
51pub const fn labelled_wireguard_transition() -> bool {
53 true
54}
55
56pub fn recommend_role(class: MappingClass) -> ProbeRole {
58 match class {
59 MappingClass::EndpointIndependent | MappingClass::AddressDependent => {
60 ProbeRole::ConnectOnly
61 }
62 }
63}
64
65pub fn parse_xor_mapped_v4(msg: &[u8], expected_tid: &[u8; 12]) -> Result<SocketAddr, String> {
67 if msg.len() < 20 {
68 return Err("stun truncated".into());
69 }
70 let typ = u16::from_be_bytes([msg[0], msg[1]]);
71 if typ != BINDING_SUCCESS {
72 return Err(format!("stun type {typ:#06x}, want success"));
73 }
74 let magic = u32::from_be_bytes([msg[4], msg[5], msg[6], msg[7]]);
75 if magic != MAGIC {
76 return Err("stun bad magic".into());
77 }
78 if &msg[8..20] != expected_tid {
79 return Err("stun tid mismatch".into());
80 }
81 let attr_len = u16::from_be_bytes([msg[2], msg[3]]) as usize;
82 let end = 20usize.saturating_add(attr_len).min(msg.len());
83 let mut i = 20usize;
84 while i + 4 <= end {
85 let atype = u16::from_be_bytes([msg[i], msg[i + 1]]);
86 let alen = u16::from_be_bytes([msg[i + 2], msg[i + 3]]) as usize;
87 let val_at = i + 4;
88 if val_at.saturating_add(alen) > msg.len() {
89 return Err("stun attr truncated".into());
90 }
91 if atype == ATTR_XOR_MAPPED {
92 return decode_xor_mapped(&msg[val_at..val_at + alen]);
93 }
94 let pad = (4 - (alen % 4)) % 4;
95 i = val_at + alen + pad;
96 }
97 Err("stun no XOR-MAPPED-ADDRESS".into())
98}
99
100fn decode_xor_mapped(val: &[u8]) -> Result<SocketAddr, String> {
101 if val.len() < 8 {
102 return Err("xor-mapped short".into());
103 }
104 let family = val[1];
105 if family != FAMILY_IPV4 {
106 return Err("xor-mapped not IPv4".into());
107 }
108 let xport = u16::from_be_bytes([val[2], val[3]]);
109 let port = xport ^ ((MAGIC >> 16) as u16);
110 let mut ip = [0u8; 4];
111 ip.copy_from_slice(&val[4..8]);
112 let cookie = MAGIC.to_be_bytes();
113 for i in 0..4 {
114 ip[i] ^= cookie[i];
115 }
116 Ok(SocketAddr::V4(SocketAddrV4::new(
117 Ipv4Addr::new(ip[0], ip[1], ip[2], ip[3]),
118 port,
119 )))
120}
121
122pub fn encode_binding_success_v4(tid: &[u8; 12], mapped: SocketAddr) -> Result<[u8; 32], String> {
124 let SocketAddr::V4(v4) = mapped else {
125 return Err("fixture IPv4 only".into());
126 };
127 let mut out = [0u8; 32];
128 out[0..2].copy_from_slice(&BINDING_SUCCESS.to_be_bytes());
129 out[2..4].copy_from_slice(&12u16.to_be_bytes());
130 out[4..8].copy_from_slice(&MAGIC.to_be_bytes());
131 out[8..20].copy_from_slice(tid);
132 out[20..22].copy_from_slice(&ATTR_XOR_MAPPED.to_be_bytes());
133 out[22..24].copy_from_slice(&8u16.to_be_bytes());
134 out[25] = FAMILY_IPV4;
135 let xport = v4.port() ^ ((MAGIC >> 16) as u16);
136 out[26..28].copy_from_slice(&xport.to_be_bytes());
137 let oct = v4.ip().octets();
138 let cookie = MAGIC.to_be_bytes();
139 for i in 0..4 {
140 out[28 + i] = oct[i] ^ cookie[i];
141 }
142 Ok(out)
143}
144
145pub fn stun_bind(
147 sock: &UdpSocket,
148 server: SocketAddr,
149 timeout: Duration,
150) -> Result<SocketAddr, String> {
151 sock.set_read_timeout(Some(timeout))
152 .map_err(|e| e.to_string())?;
153 let mut tid = [0u8; 12];
154 fill_tid(&mut tid)?;
155 let mut req = [0u8; 20];
156 req[0..2].copy_from_slice(&BINDING_REQUEST.to_be_bytes());
157 req[4..8].copy_from_slice(&MAGIC.to_be_bytes());
158 req[8..20].copy_from_slice(&tid);
159 sock.send_to(&req, server).map_err(|e| e.to_string())?;
160 let mut buf = [0u8; 512];
161 let (n, _) = sock.recv_from(&mut buf).map_err(|e| e.to_string())?;
162 parse_xor_mapped_v4(&buf[..n], &tid)
163}
164
165fn fill_tid(tid: &mut [u8; 12]) -> Result<(), String> {
166 getrandom::fill(tid).map_err(|e| e.to_string())
167}
168
169pub fn observe_mapping(
171 sock: &UdpSocket,
172 stun_a: SocketAddr,
173 stun_b: SocketAddr,
174 timeout: Duration,
175) -> Result<ObserveReport, String> {
176 let local = sock.local_addr().map_err(|e| e.to_string())?;
177 let sample_a = stun_bind(sock, stun_a, timeout)?;
178 let sample_b = stun_bind(sock, stun_b, timeout)?;
179 let class = if sample_a == sample_b {
180 MappingClass::EndpointIndependent
181 } else {
182 MappingClass::AddressDependent
183 };
184 Ok(ObserveReport {
185 local,
186 sample_a,
187 sample_b,
188 class,
189 })
190}
191
192pub fn classify_samples(a: SocketAddr, b: SocketAddr) -> MappingClass {
194 if a == b {
195 MappingClass::EndpointIndependent
196 } else {
197 MappingClass::AddressDependent
198 }
199}
200
201#[cfg(test)]
202mod tests {
203 use super::*;
204
205 #[test]
206 fn xor_mapped_v4_round_trips() {
207 let tid = [7u8; 12];
208 let mapped: SocketAddr = "203.0.113.5:51820".parse().unwrap();
209 let pkt = encode_binding_success_v4(&tid, mapped).unwrap();
210 assert_eq!(parse_xor_mapped_v4(&pkt, &tid).unwrap(), mapped);
211 }
212
213 #[test]
214 fn rejects_tid_mismatch() {
215 let tid = [1u8; 12];
216 let mapped: SocketAddr = "192.0.2.1:9".parse().unwrap();
217 let pkt = encode_binding_success_v4(&tid, mapped).unwrap();
218 let other = [2u8; 12];
219 assert!(parse_xor_mapped_v4(&pkt, &other)
220 .unwrap_err()
221 .contains("tid"));
222 }
223
224 #[test]
225 fn address_dependent_when_samples_differ() {
226 let a: SocketAddr = "198.51.100.1:1000".parse().unwrap();
227 let b: SocketAddr = "198.51.100.2:2000".parse().unwrap();
228 assert_eq!(classify_samples(a, b), MappingClass::AddressDependent);
229 assert_eq!(
230 recommend_role(MappingClass::AddressDependent),
231 ProbeRole::ConnectOnly
232 );
233 assert_eq!(classify_samples(a, a), MappingClass::EndpointIndependent);
234 assert_eq!(
235 recommend_role(MappingClass::EndpointIndependent),
236 ProbeRole::ConnectOnly
237 );
238 }
239
240 #[test]
241 fn live_two_server_observe_does_not_claim_handshake() {
242 use std::net::ToSocketAddrs;
243 let Ok(sock) = UdpSocket::bind("0.0.0.0:0") else {
244 return;
245 };
246 let Ok(mut a_it) = ("stun.l.google.com", 3478u16).to_socket_addrs() else {
247 return;
248 };
249 let Ok(mut b_it) = ("stun.cloudflare.com", 3478u16).to_socket_addrs() else {
250 return;
251 };
252 let Some(a) = a_it.find(|s| s.is_ipv4()) else {
253 return;
254 };
255 let Some(b) = b_it.find(|s| s.is_ipv4()) else {
256 return;
257 };
258 if let Ok(report) = observe_mapping(&sock, a, b, Duration::from_secs(3)) {
259 println!(
260 "live observe local={} a={} b={} class={:?}",
261 report.local, report.sample_a, report.sample_b, report.class
262 );
263 assert_eq!(recommend_role(report.class), ProbeRole::ConnectOnly);
264 assert_ne!(report.sample_a.ip(), std::net::IpAddr::from([0, 0, 0, 0]));
265 } else {
266 println!("live observe: STUN did not complete (offline CI is fine)");
267 }
268 assert!(!internet_two_host_handshake_executed());
269 }
270}