//! Second security review of #404 (`dist/secreview2`): tests that confirm //! the transport findings on what changed since 4a7f75da (#411 to #417). //! Those that failed at 13fd8080 pass with their fixes (`dist/hardening2`); //! the measurement is `#[ignore]`d: run it with `--ignored --nocapture`. use std::collections::HashSet; use std::net::SocketAddr; use std::time::{Duration, Instant}; use super::*; /// An address where nothing listens: a dial there is refused at once. fn nowhere() -> SocketAddr { "127.0.0.1:1".parse().expect("an address") } /// SR2-1 (major). The discovery budget is global: `Thread::learn` takes a /// name while fewer than `max_peers` are discovered, from whichever peer /// lists it, and a name stays while that peer keeps listing it. One /// authenticated peer that lists `max_peers` names nobody answers at /// holds every slot for as long as it stays up: no other node is ever /// discovered. ADR 0072's *Trust* bounds a lying list to delaying the /// discovery of a node until that node confirms its own address; this /// prevents the discovery of every node, with no lie to correct. /// /// C does not discover (so only A can make A and C meet); X seeds C, so /// X's lists name C at its own address. Without B, A meets C through X's /// list. With B's four names first, it did not: now X's list takes the /// place of one of B's names, B holding more than its share /// (`Thread::room`). #[test] fn secreview2_one_peers_list_cannot_hold_every_discovery_slot() { let (c, _ec) = start(config("c", "node-c")); let mut cx = config("x", "node-impostor"); cx.mesh = true; cx.seeds = vec![(name("c"), c.local_addr())]; let (x, ex) = start(cx); ups(&ex, "X sees C", &["c"]); for junk in [false, true] { let mut ca = mesh("a"); ca.max_peers = 4; // The fake B sends no heartbeat: it must stay up meanwhile. ca.node_down_after_ms = 60_000; let (a, ea) = start(ca); let _b = junk.then(|| { let mut b = fake_up_with(&a, &ea, "b", 1, frame::FLAG_PEERS); let junk = ["j0", "j1", "j2", "j3"]; let listed: Vec<(&str, SocketAddr)> = junk.iter().map(|n| (*n, nowhere())).collect(); put(&mut b, frame::SIGNAL, &list(&listed)); let mut left: HashSet = junk.iter().map(|n| name(n)).collect(); while !left.is_empty() { if let Ev::Closed(peer, _) = ea.next("A dials B's names") { left.remove(&peer); } } b }); a.connect(&name("x"), x.local_addr()); let seen = ea.during(Duration::from_secs(3)); let met = seen .iter() .any(|e| matches!(e, Ev::Up(n) if n.name == name("c"))); assert!(met, "B's four names listed first: {junk}: A never met C"); a.stop(); down(&ex, "X loses A", "a"); } } /// SR2-2 (minor). A list of peers replaces the one before it (`first`). /// Each node that came up or went down queued a whole new list for every /// peer that discovers, behind what that peer had not read, however many /// waited there already: a peer that sends heartbeats and reads nothing /// held one list per up or down for as long as it stayed up. A peer's /// list now waits in one place, which a newer one takes ([`Conn::list`]). /// /// B fills its connection (it reads nothing), then C comes and goes ten /// times; then B reads everything: one list comes after the messages, /// the latest, not twenty. #[test] fn secreview2_unread_lists_of_peers_do_not_pile_up() { let mut ca = mesh("a"); ca.max_queue = 1 << 20; ca.node_down_after_ms = 60_000; let (a, ea) = start(ca); let mut b = fake_up_with(&a, &ea, "b", 1, frame::FLAG_PEERS); let to_b = Node { name: name("b"), incarnation: 1, }; // Messages until the socket, TLS and the queue hold all they take. let payload = vec![0u8; 256 << 10]; let mut serial = 0; let mut full_since: Option = None; loop { let frame = Outbound::Message(message(&to_b, serial, &payload)); match a.queue(&to_b, frame, None) { Ok(()) => { serial += 1; full_since = None; } Err((SendError::Full, _)) => { let since = *full_since.get_or_insert_with(Instant::now); if since.elapsed() > Duration::from_millis(500) { break; } std::thread::sleep(Duration::from_millis(10)); } Err((e, _)) => panic!("{e:?}"), } } for i in 0..10 { let c = fake_up_with(&a, &ea, "c", 100 + i, 0); // Past a heartbeat: each up and each down is a list of its own. std::thread::sleep(Duration::from_millis(150)); drop(c); down(&ea, "A loses C", "c"); std::thread::sleep(Duration::from_millis(150)); } let queued = a.outbox.routes().get(&name("b")).map_or(0, |r| { r.queue .iter() .filter(|e| e.kind() == frame::SIGNAL && e.body.first() == Some(&frame::PEERS)) .count() }); assert_eq!(queued, 0, "lists of peers in B's queue"); // B reads it all: the messages, and the lists among and after them. b.sock .set_read_timeout(Some(Duration::from_millis(1_000))) .expect("a timeout"); let (mut messages, mut lists) = (0u64, 0); // A's heartbeats keep coming: read for a while past the last message. let mut until = None; while until.is_none_or(|t| Instant::now() < t) && let Some((kind, body)) = get(&mut b) { if messages == serial { until.get_or_insert_with(|| Instant::now() + Duration::from_millis(500)); } match kind { frame::MESSAGE => messages += 1, frame::SIGNAL if messages > 0 && body.first() == Some(&frame::PEERS) => lists += 1, _ => {} } } eprintln!("secreview2: B read {messages} messages, then {lists} lists of peers"); assert_eq!(messages, serial, "every message"); assert!(lists <= 1, "{lists} lists of peers waited for B"); } /// SR2-3 (minor). A peer's list makes A dial each name it does not know, /// and each failed dial (refused, a TLS name that does not match, a /// timeout) is a non-routine `closed` labelled by that name. `node.rs` /// throttled only labels that are not node names (`State::closed`), so /// every one was a stderr line, and an entry in `failures` (256 at most, /// then cleared): the peer chooses the names, and with them the lines. /// The transport now marks such a dial *hearsay* (an address only lists /// gave), which `node.rs` logs through a throttle and keeps out of /// `failures` (`node::tests`). #[test] fn secreview2_each_listed_name_is_a_logged_failure() { let mut ca = mesh("a"); ca.max_peers = 64; ca.node_down_after_ms = 60_000; let (a, ea) = start(ca); let mut b = fake_up_with(&a, &ea, "b", 1, frame::FLAG_PEERS); let names: Vec = (0..64).map(|i| format!("j{i}")).collect(); let listed: Vec<(&str, SocketAddr)> = names.iter().map(|n| (n.as_str(), nowhere())).collect(); put(&mut b, frame::SIGNAL, &list(&listed)); let seen = ea.during(Duration::from_secs(2)); let failures: Vec<&String> = seen .iter() .filter_map(|e| match e { Ev::Closed(peer, r) if peer.starts_with("node-j") && !r.routine() => Some(peer), _ => None, }) .collect(); let hearsay = seen .iter() .filter(|e| matches!(e, Ev::Hearsay(peer) if peer.starts_with("node-j"))) .count(); let distinct: HashSet<&String> = failures.iter().copied().collect(); eprintln!( "secreview2: one list of 64 names: {} failed dials in 2 s (reconnect_ms 50), {hearsay} of them hearsay", failures.len() ); assert_eq!(distinct.len(), 64); assert!(failures.len() >= 64); assert_eq!( hearsay, failures.len(), "every failed dial to a listed name" ); drop(a); } /// SR2-4 (major). After a node comes up or goes down, `Thread::tell` sent /// every peer that discovers the whole list, built and encoded for each /// (it left out the receiver): with `n` such peers, `n` lists of about `n` /// entries, on the `louise-dist` thread that also sends heartbeats, at /// most once per heartbeat. Now a round encodes the list once for each /// frame limit, each peer ignoring its own entry, and shares it; and a /// round comes at most once per heartbeat for each 256 peers up. B, which /// gave its own address, so that A lists it, gets the very list C gets. #[test] fn secreview2_a_round_of_lists_is_encoded_once() { let (a, ea) = start(mesh("a")); let mut b = fake_up_with(&a, &ea, "b", 1, frame::FLAG_PEERS); let welcome = next_list(&mut b); assert_eq!(welcome.nodes, [(name("a"), a.local_addr())]); put(&mut b, frame::SIGNAL, &list(&[("b", nowhere())])); let mut c = fake_up_with(&a, &ea, "c", 1, frame::FLAG_PEERS); let to_c = next_list(&mut c); assert_eq!( to_c.nodes, [(name("a"), a.local_addr()), (name("b"), nowhere())] ); // C came up: B's next list, the same, its own entry included. assert_eq!(next_list(&mut b), to_c); } /// SR2-4, measured: one round of lists for `n` peers, as `Thread::tell` /// makes it now (one encoding, shared), against the earlier one (a list /// built and encoded for each peer). Each peer still gets the whole list /// written: those bytes are the price of whole lists (deltas would cut /// them, a change of the wire format), paid at most once per heartbeat /// for each 256 peers. #[test] #[ignore = "SR2-4: a measurement: run with --ignored --nocapture, best with --release"] fn secreview2_a_round_of_lists_costs_n_squared() { for n in [256usize, 1024, 4096] { let list: Vec<(String, SocketAddr)> = (0..n) .map(|i| (format!("node-{i}.cluster.example"), nowhere())) .collect(); let started = Instant::now(); let mut bytes = 0; for receiver in &list { let theirs: Vec<(String, SocketAddr)> = list .iter() .filter(|(m, _)| *m != receiver.0) .cloned() .collect(); let frames = frame::Peers::frames(&theirs, 8 << 20); bytes += frames.iter().map(Vec::len).sum::(); } let before = started.elapsed(); let started = Instant::now(); let shared: std::sync::Arc<[Vec]> = frame::Peers::frames(&list, 8 << 20).into(); let each: Vec]>> = list.iter().map(|_| shared.clone()).collect(); let now = started.elapsed(); eprintln!( "secreview2: one round of lists for {n} peers: {before:?} before, {now:?} now \ ({} KiB held for all; {} MiB to write, as before)", shared.iter().map(Vec::len).sum::() >> 10, bytes >> 20 ); drop(each); } } /// SR2-8 (minor). `Peers::decode` refused a frame whose count was past the /// receiver's `max_peers`, and `listed` a frame that took the list past /// it: a node keeping more peers than another's `max_peers` (seeds and /// connected nodes are exempt from the cap, and nodes may be configured /// differently) had every list dropped there, and discovery through it /// stopped. The receiver now reads the first `max_peers` names. #[test] fn secreview2_a_list_past_max_peers_is_cut_not_dropped() { let mut ca = mesh("a"); ca.max_peers = 2; ca.node_down_after_ms = 60_000; let (a, ea) = start(ca); let mut b = fake_up_with(&a, &ea, "b", 1, frame::FLAG_PEERS); put( &mut b, frame::SIGNAL, &list(&[("j0", nowhere()), ("j1", nowhere()), ("j2", nowhere())]), ); let seen = ea.during(Duration::from_secs(1)); assert!(dialed(&seen, "j0") && dialed(&seen, "j1"), "{seen:?}"); assert!(!dialed(&seen, "j2"), "{seen:?}"); assert_eq!(report(&a, "b").dropped, 0); } /// SR2-6 (major). "A third party's list replaces only an unconfirmed /// address", and the latest list wins: an honest peer sends its list when /// a node comes up or goes down, a lying one as often as it likes. A node /// that never dials this one (its discovery is `seeds`, or it does not /// know this node) can only be confirmed by a dial that comes up, which /// the liar prevents by listing a wrong address again before each dial. /// ADR 0072's *Trust* calls this a delay "before that node confirms its /// own"; for such a node it lasts as long as the liar stays up. /// /// C does not discover; X seeds C, so X's lists name C where it is. B /// lists C at a dead address first: told once, A meets C once X's list /// comes (the documented delay); told again every 5 ms, it never did. Now /// A's dials try each lister's address in turn (`Thread::dial`). #[test] fn secreview2_a_repeated_lie_does_not_keep_a_node_out() { let (c, _ec) = start(config("c", "node-c")); let mut cx = config("x", "node-impostor"); cx.mesh = true; cx.seeds = vec![(name("c"), c.local_addr())]; let (x, ex) = start(cx); ups(&ex, "X sees C", &["c"]); for repeated in [false, true] { let mut ca = mesh("a"); ca.node_down_after_ms = 60_000; let (a, ea) = start(ca); let mut b = fake_up_with(&a, &ea, "b", 1, frame::FLAG_PEERS); let lie = list(&[("c", nowhere())]); put(&mut b, frame::SIGNAL, &lie); a.connect(&name("x"), x.local_addr()); let until = Instant::now() + Duration::from_secs(5); let mut met = false; while !met && Instant::now() < until { if repeated { put(&mut b, frame::SIGNAL, &lie); } met = ea .during(Duration::from_millis(5)) .iter() .any(|e| matches!(e, Ev::Up(n) if n.name == name("c"))); } assert!(met, "B lied every 5 ms: {repeated}: A never met C in 5 s"); drop(b); a.stop(); down(&ex, "X loses A", "a"); } } /// SR2-1's fix, against a lister that hands its names to others' lists: /// B lists Z, and so does C; B then drops Z for names of its own. Z goes /// to C's share, not to nobody's, where B's next name would take its /// place: B, over its share, gets no more, and Z, which C still lists, is /// still dialed. #[test] fn a_dropped_name_another_peer_lists_stays() { let mut ca = mesh("a"); ca.max_peers = 3; ca.node_down_after_ms = 60_000; let (a, ea) = start(ca); let mut b = fake_up_with(&a, &ea, "b", 1, frame::FLAG_PEERS); let mut c = fake_up_with(&a, &ea, "c", 1, frame::FLAG_PEERS); put(&mut b, frame::SIGNAL, &list(&[("z", nowhere())])); ea.closed("A dials Z", |_| true); put(&mut c, frame::SIGNAL, &list(&[("z", nowhere())])); std::thread::sleep(Duration::from_millis(200)); put( &mut b, frame::SIGNAL, &list(&[("j0", nowhere()), ("j1", nowhere())]), ); std::thread::sleep(Duration::from_millis(200)); let more = [("j0", nowhere()), ("j1", nowhere()), ("j2", nowhere())]; put(&mut b, frame::SIGNAL, &list(&more)); let seen = ea.during(Duration::from_secs(4)); assert!(dialed(&seen, "z"), "Z forgotten: {seen:?}"); assert!(!dialed(&seen, "j2"), "B got past its share: {seen:?}"); drop(a); } /// SR2-6's fix, against a liar that moves its lie around the honest /// address: dials took the addresses in their sorted order, the next one /// each time, so a liar that sees each dial (at an address of its own) /// could list, before the next one, an address that sorts below the honest /// one, then one above it (any IPv6 address sorts after every IPv4 one), /// so that the next in turn was always its own. Now the turn goes by /// lister, not by address: the liar holds its place in it. /// /// As in [`secreview2_a_repeated_lie_does_not_keep_a_node_out`], C does /// not discover and X seeds C. B lists C at 127.0.0.1:1 or at [::1]:1, /// each time A's dial to C fails, whichever is the next in turn. #[test] fn a_lie_moved_around_the_honest_address_does_not_keep_a_node_out() { let (c, _ec) = start(config("c", "node-c")); let mut cx = config("x", "node-impostor"); cx.mesh = true; cx.seeds = vec![(name("c"), c.local_addr())]; let (x, ex) = start(cx); ups(&ex, "X sees C", &["c"]); let below: SocketAddr = "127.0.0.1:1".parse().expect("an address"); let above: SocketAddr = "[::1]:1".parse().expect("an address"); assert!(below < c.local_addr() && c.local_addr() < above); let mut ca = mesh("a"); ca.node_down_after_ms = 60_000; let (a, ea) = start(ca); let mut b = fake_up_with(&a, &ea, "b", 1, frame::FLAG_PEERS); put(&mut b, frame::SIGNAL, &list(&[("c", below)])); a.connect(&name("x"), x.local_addr()); let until = Instant::now() + Duration::from_secs(5); let (mut dials, mut met) = (0usize, false); while !met && Instant::now() < until { for e in ea.during(Duration::from_millis(5)) { match e { Ev::Up(n) if n.name == name("c") => met = true, Ev::Closed(peer, _) if peer == name("c") => { dials += 1; // The next dial takes index `dials % 2` of the sorted // two: be there. let lie = if dials % 2 == 0 { below } else { above }; put(&mut b, frame::SIGNAL, &list(&[("c", lie)])); } _ => {} } } } assert!( met, "B moved its lie after each of {dials} dials: A never met C in 5 s" ); drop(b); a.stop(); drop(x); }