fix(nat): randomize port offsets within bounded search strata
A rotated bit-reversed prefix stays in one residue class modulo 32 and systematically misses regular mapped-port pools. Independent uniform draws within evenly visited strata remove that blind spot without changing the target, socket or time budgets. Verified the sampling bounds, four owned-loopback mapping controls with original RTC adoption and cleanup, and Windows capture-enabled compilation.
This commit is contained in:
1 parent
c0b1792bf5
commit
dc94bda30b
2 files changed
+81
-25
No files matched your search
@@ -210,16 +210,31 @@ adding sockets. A survey that has already consumed three seconds can leave room
|
||||
for only about 745 checks, so the target budget is a ceiling, not a promise to
|
||||
send all of them. Parallel survey remains a separate comparison.
|
||||
|
||||
The search now uses a random start and bit-reversed port order. A 2026-11-27
|
||||
Windows control paired both orders against four fixed continuous 256-port pools
|
||||
with the same 1,024-target budget and five-second lifetime. All eight runs
|
||||
completed mutual authentication, adopted the winning sockets into the original
|
||||
RTC and exchanged DataChannel messages in both directions. The new order first
|
||||
hit at targets 178–249, versus 192–978 for the original draws. This control
|
||||
simulates mappings and destination filtering on loopback; it does not measure
|
||||
public reachability. The static coverage guarantee applies to a contiguous
|
||||
256-port pool, not arbitrary pool sizes or moving mappings. Sequential
|
||||
preparation retains its existing eight-socket path.
|
||||
The search divides ports 1,024–65,535 into 1,024 strata of 63 ports. It visits
|
||||
strata in bit-reversed order with a random rotation and draws an independent,
|
||||
uniform port within each stratum. Rejection sampling avoids modulo bias. This
|
||||
combines early range coverage with independent offsets, following
|
||||
[stratified sampling](https://artowen.su.domains/mc/Ch-var-basic.pdf). A single
|
||||
rotation of bit-reversed ports instead leaves the first 1,024 targets in one
|
||||
residue class modulo 32: fixed pools at strides 2, 4 and 8 are then missed for
|
||||
half, three quarters and seven eighths of rotations. Contiguous-pool tests alone
|
||||
do not reveal that blind spot.
|
||||
|
||||
The first 512 stratified targets leave at most 187 consecutive ports untested,
|
||||
so they reach any fixed contiguous 256-port pool. For any fixed pool of 256
|
||||
ports, the full-budget miss probability is at most `(62/63)^256`, about 1.664%,
|
||||
under independent uniform draws. Uniform distinct targets miss about 1.650%.
|
||||
These are static pool bounds, not unconditional dominance or field success rates.
|
||||
|
||||
A 2026-11-27 Windows loopback control used four fixed 256-port pools at strides
|
||||
1, 2, 4 and 8. First hits occurred at targets 215, 384, 38 and 35. All four
|
||||
completed mutual authentication, adopted the winner into the original RTC and
|
||||
exchanged SCTP messages in both directions; losing sockets and preparation
|
||||
permits were released. The fixture counted all attempted targets at the existing
|
||||
2 ms cadence, dropping unmapped attempts before sending. Actual packets stayed
|
||||
on owned loopback sockets. The 1,024-target, 256-socket and five-second limits
|
||||
and the separate eight-socket sequential path remain unchanged. Physical NAT
|
||||
allocation, filtering and competing traffic require independent-network trials.
|
||||
|
||||
Default observations use three documented services on different destination
|
||||
ports: [Cloudflare](https://developers.cloudflare.com/realtime/turn/faq/),
|
||||
|
||||
@@ -410,16 +410,42 @@ impl ProbePlan {
|
||||
}
|
||||
|
||||
fn search_targets(address: Ipv4Addr) -> Result<Vec<SocketAddrV4>> {
|
||||
let mut bytes = [0; 2];
|
||||
getrandom::fill(&mut bytes).map_err(|error| anyhow::anyhow!("preparation ports: {error}"))?;
|
||||
let start = u16::from_ne_bytes(bytes);
|
||||
// Bit reversal spreads early targets across the port range.
|
||||
Ok((0..=u16::MAX)
|
||||
.map(|index| index.reverse_bits().wrapping_add(start))
|
||||
.filter(|&port| port >= 1024)
|
||||
.take(RANDOM_TARGETS)
|
||||
.map(|port| SocketAddrV4::new(address, port))
|
||||
.collect())
|
||||
let fill = |bytes: &mut [u8]| {
|
||||
getrandom::fill(bytes).map_err(|error| anyhow::anyhow!("preparation ports: {error}"))
|
||||
};
|
||||
let mut bytes = [0; (RANDOM_TARGETS + 1) * 2];
|
||||
fill(&mut bytes)?;
|
||||
let mut draws = bytes.chunks_exact(2).map(|pair| u16::from_le_bytes([pair[0], pair[1]]));
|
||||
let start = draws.next().unwrap();
|
||||
stratified_targets(address, start, || {
|
||||
if let Some(value) = draws.next() { return Ok(value); }
|
||||
let mut extra = [0; 2];
|
||||
fill(&mut extra)?;
|
||||
Ok(u16::from_le_bytes(extra))
|
||||
})
|
||||
}
|
||||
|
||||
fn stratified_targets(
|
||||
address: Ipv4Addr,
|
||||
start: u16,
|
||||
mut draw: impl FnMut() -> Result<u16>,
|
||||
) -> Result<Vec<SocketAddrV4>> {
|
||||
const FIRST_PORT: usize = 1024;
|
||||
const PORT_COUNT: usize = u16::MAX as usize + 1 - FIRST_PORT;
|
||||
const _: () = assert!(RANDOM_TARGETS.is_power_of_two() && RANDOM_TARGETS <= PORT_COUNT);
|
||||
let shift = usize::BITS - RANDOM_TARGETS.ilog2();
|
||||
(0..RANDOM_TARGETS).map(|index| {
|
||||
// Spread strata first; independent offsets avoid locking guesses to a port residue.
|
||||
let stratum = ((index.reverse_bits() >> shift) + usize::from(start)) % RANDOM_TARGETS;
|
||||
let lower = FIRST_PORT + PORT_COUNT * stratum / RANDOM_TARGETS;
|
||||
let width = PORT_COUNT * (stratum + 1) / RANDOM_TARGETS - (lower - FIRST_PORT);
|
||||
let limit = (usize::from(u16::MAX) + 1) / width * width;
|
||||
let offset = loop {
|
||||
let value = usize::from(draw()?);
|
||||
if value < limit { break value % width; }
|
||||
};
|
||||
Ok(SocketAddrV4::new(address, (lower + offset) as u16))
|
||||
}).collect()
|
||||
}
|
||||
|
||||
impl Survey {
|
||||
@@ -1365,6 +1391,22 @@ mod tests {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_reaches_regular_mapping_pools_without_a_fixed_residue() -> Result<()> {
|
||||
use sha2::Digest;
|
||||
let mut counter = 0u64;
|
||||
let targets = stratified_targets(Ipv4Addr::LOCALHOST, 1, || {
|
||||
let digest = sha2::Sha256::digest(counter.to_le_bytes());
|
||||
counter += 1;
|
||||
Ok(u16::from_le_bytes([digest[0], digest[1]]))
|
||||
})?;
|
||||
for stride in [2, 4, 8, 16, 32, 63, 64] {
|
||||
let pool: HashSet<_> = (0..RANDOM_PORTS).map(|index| 30000 + stride * index).collect();
|
||||
assert!(targets.iter().any(|target| pool.contains(&usize::from(target.port()))), "stride {stride}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn random_pool_shares_capacity_adopts_one_socket_and_retires_on_peer_refusal(
|
||||
) -> Result<()> {
|
||||
@@ -1386,18 +1428,17 @@ mod tests {
|
||||
.targets
|
||||
.iter()
|
||||
.all(|target| *target.ip() == irregular.address() && target.port() >= 1024));
|
||||
// The first 252 targets cover any contiguous 256-port pool, including
|
||||
// one wrapping around the allowed port range.
|
||||
let mut prefix: Vec<_> = generated.targets[..252]
|
||||
// A half-budget prefix cannot leave a contiguous pool-sized gap.
|
||||
let mut prefix: Vec<_> = generated.targets[..RANDOM_TARGETS / 2]
|
||||
.iter()
|
||||
.map(|target| usize::from(target.port()))
|
||||
.collect();
|
||||
prefix.sort_unstable();
|
||||
let wrap_gap = usize::from(u16::MAX) + 1 - prefix.last().unwrap() + prefix[0] - 1024;
|
||||
assert_eq!(wrap_gap, RANDOM_PORTS);
|
||||
assert!(wrap_gap < RANDOM_PORTS);
|
||||
assert!(prefix
|
||||
.windows(2)
|
||||
.all(|ports| ports[1] - ports[0] == RANDOM_PORTS));
|
||||
.all(|ports| ports[1] - ports[0] < RANDOM_PORTS));
|
||||
assert!(
|
||||
ProbePlan::new(irregular, irregular).is_err(),
|
||||
"two irregular mappings cannot select birthday search"
|
||||
|
||||
Reference in new issue
Block a user