[domistream] Host pairing: tests first (client and host paired in memory, wrong PIN on both sides, order, timeouts, trusted clients)
This commit is contained in:
@@ -212,6 +212,7 @@ pub const CLIENT_CERT_PEM: &str = include_str!("../fixtures/test-only-client-cer
|
|||||||
pub const ROGUE_CERT_PEM: &str = include_str!("../fixtures/test-only-rogue-cert.pem");
|
pub const ROGUE_CERT_PEM: &str = include_str!("../fixtures/test-only-rogue-cert.pem");
|
||||||
pub const EC_CERT_PEM: &str = include_str!("../fixtures/test-only-ec-cert.pem");
|
pub const EC_CERT_PEM: &str = include_str!("../fixtures/test-only-ec-cert.pem");
|
||||||
pub const CLIENT_KEY_PEM: &str = include_str!("../fixtures/test-only-client-key.pem");
|
pub const CLIENT_KEY_PEM: &str = include_str!("../fixtures/test-only-client-key.pem");
|
||||||
|
pub const HOST_KEY_PEM: &str = include_str!("../fixtures/test-only-host-key.pem");
|
||||||
|
|
||||||
/// Base64 (RFC 4648, standard alphabet, padding allowed) to bytes; panics on anything else.
|
/// Base64 (RFC 4648, standard alphabet, padding allowed) to bytes; panics on anything else.
|
||||||
pub fn base64_decode(s: &str) -> Vec<u8> {
|
pub fn base64_decode(s: &str) -> Vec<u8> {
|
||||||
|
|||||||
@@ -0,0 +1,658 @@
|
|||||||
|
//! The host's pairing machine (`docs/PROTOCOL.md` 1.5) driven by this crate's own client, entirely in memory: every
|
||||||
|
//! client request goes through the host's HTTP parser, every host answer through the host's XML writer and the
|
||||||
|
//! client's parser. The keys are the test-only fixtures (`tests/fixtures`).
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
|
||||||
|
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
use core::time::Duration;
|
||||||
|
|
||||||
|
use common::{CLIENT_CERT_PEM, EC_CERT_PEM, HOST_KEY_PEM, SeqRng, Vectors, pem_blocks};
|
||||||
|
use domistream::host::http::{Route, pair_answer_xml, parse_request_head};
|
||||||
|
use domistream::host::pairing::{
|
||||||
|
DEFAULT_PHASE_TIMEOUT, DEFAULT_PIN_TIMEOUT, HostIdentity, HostPairingConfig, HostPairingFailure,
|
||||||
|
HostPairingSession, HostPairingState, HostPairingStep, PairAnswer, PairPhase, PairRequest, PairedClient, Transport,
|
||||||
|
};
|
||||||
|
use domistream::http::{HttpRequest, Scheme};
|
||||||
|
use domistream::pairing::identity::MAX_CERT_DER_BYTES;
|
||||||
|
use domistream::pairing::{
|
||||||
|
ClientIdentity, MAX_SIGNATURE_BYTES, PairedHost, PairingFailure, PairingSession, PairingState, PairingStep, Pin,
|
||||||
|
};
|
||||||
|
use domistream::{Error, Instant, RandomSource};
|
||||||
|
|
||||||
|
const UID: &str = "0123456789ABCDEF";
|
||||||
|
const DEVICE: &str = "Pixel Test Phone";
|
||||||
|
|
||||||
|
fn v() -> Vectors {
|
||||||
|
common::pairing_vectors()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn host_id() -> HostIdentity {
|
||||||
|
let key = pem_blocks(HOST_KEY_PEM, "PRIVATE KEY").pop().expect("host key PEM");
|
||||||
|
HostIdentity::from_der(&v().bytes("host_cert_der"), &key).expect("HostIdentity::from_der(test-only host)")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn client_id() -> ClientIdentity {
|
||||||
|
let v = v();
|
||||||
|
ClientIdentity::from_der(&v.bytes("client_cert_der"), &v.bytes("client_key_pkcs8_der")).expect("client identity")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rogue_id() -> ClientIdentity {
|
||||||
|
let v = v();
|
||||||
|
ClientIdentity::from_der(&v.bytes("rogue_cert_der"), &v.bytes("rogue_key_pkcs8_der")).expect("rogue identity")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pin(d: &str) -> Pin {
|
||||||
|
Pin::from_digits(d).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn secs(s: u64) -> Instant {
|
||||||
|
Instant::ZERO.saturating_add(Duration::from_secs(s))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The client's request as the host's HTTP layer sees it.
|
||||||
|
fn to_host(req: &HttpRequest) -> PairRequest {
|
||||||
|
let head = format!("GET {} HTTP/1.1\r\nHost: lumen.test\r\n\r\n", req.path_and_query);
|
||||||
|
let parsed = parse_request_head(head.as_bytes()).expect("the host parses the client's pair request");
|
||||||
|
assert_eq!(parsed.unique_id.as_deref(), Some(UID));
|
||||||
|
match parsed.route {
|
||||||
|
Route::Pair(p) => p,
|
||||||
|
other => panic!("expected a /pair route, got {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A random source that counts what it hands out.
|
||||||
|
struct Counting(SeqRng, usize);
|
||||||
|
|
||||||
|
impl RandomSource for Counting {
|
||||||
|
fn fill(&mut self, dest: &mut [u8]) {
|
||||||
|
self.1 += dest.len();
|
||||||
|
self.0.fill(dest);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One client and one host, wired together in memory.
|
||||||
|
struct Duo {
|
||||||
|
cid: ClientIdentity,
|
||||||
|
hid: HostIdentity,
|
||||||
|
client: PairingSession,
|
||||||
|
host: HostPairingSession,
|
||||||
|
next: Option<HttpRequest>,
|
||||||
|
crng: SeqRng,
|
||||||
|
hrng: Counting,
|
||||||
|
host_pin: Pin,
|
||||||
|
now: Instant,
|
||||||
|
paired_client: Option<PairedClient>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Duo {
|
||||||
|
fn new(client_pin: &str, host_pin: &str, seed: u64) -> Self {
|
||||||
|
let cid = client_id();
|
||||||
|
let hid = host_id();
|
||||||
|
let mut crng = SeqRng::new(seed);
|
||||||
|
let (client, req) = PairingSession::start(&cid, UID, DEVICE, pin(client_pin), &mut crng).unwrap();
|
||||||
|
let host = HostPairingSession::new(&hid, HostPairingConfig::default(), Instant::ZERO);
|
||||||
|
Self {
|
||||||
|
cid,
|
||||||
|
hid,
|
||||||
|
client,
|
||||||
|
host,
|
||||||
|
next: Some(req),
|
||||||
|
crng,
|
||||||
|
hrng: Counting(SeqRng::new(seed ^ 0xA5A5), 0),
|
||||||
|
host_pin: pin(host_pin),
|
||||||
|
now: Instant::ZERO,
|
||||||
|
paired_client: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The host handles `req` (supplying the PIN when it holds the request); its answer, or `Refused` on failure.
|
||||||
|
fn host_answers(&mut self, req: &PairRequest, scheme: Scheme) -> PairAnswer {
|
||||||
|
self.now = self.now.saturating_add(Duration::from_millis(250));
|
||||||
|
let transport = match scheme {
|
||||||
|
Scheme::Http => Transport::Http,
|
||||||
|
Scheme::Https => Transport::Https { client_cert_der: self.cid.cert_der() },
|
||||||
|
};
|
||||||
|
match self.host.handle(&self.hid, req, transport, self.now, &mut self.hrng) {
|
||||||
|
Ok(HostPairingStep::Answer(a)) => a,
|
||||||
|
Ok(HostPairingStep::HoldForPin) => {
|
||||||
|
assert_eq!(self.host.state(), HostPairingState::AwaitPin);
|
||||||
|
self.now = self.now.saturating_add(Duration::from_secs(5));
|
||||||
|
self.host.supply_pin(&self.hid, self.host_pin, self.now).unwrap_or(PairAnswer::Refused)
|
||||||
|
}
|
||||||
|
Ok(HostPairingStep::Paired(c)) => {
|
||||||
|
self.paired_client = Some(c);
|
||||||
|
PairAnswer::Paired
|
||||||
|
}
|
||||||
|
Err(_) => PairAnswer::Refused,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One round trip of the client's next request. `Ok(Some)` when the client is paired, `Err` when it failed.
|
||||||
|
fn round(&mut self) -> Result<Option<PairedHost>, Error> {
|
||||||
|
let req = self.next.take().expect("a request to send");
|
||||||
|
let answer = self.host_answers(&to_host(&req), req.scheme);
|
||||||
|
let body = pair_answer_xml(&answer).expect("pair_answer_xml");
|
||||||
|
match self.client.handle_response(&self.cid, 200, &body, &mut self.crng)? {
|
||||||
|
PairingStep::Send(r) => {
|
||||||
|
self.next = Some(r);
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
PairingStep::Paired(h) => Ok(Some(h)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs until the client is paired or fails.
|
||||||
|
fn run(&mut self) -> Result<PairedHost, Error> {
|
||||||
|
for _ in 0..5 {
|
||||||
|
if let Some(h) = self.round()? {
|
||||||
|
return Ok(h);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
panic!("pairing did not finish in five round trips")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The host after `rounds` full round trips (0..=4).
|
||||||
|
fn after(rounds: usize) -> Self {
|
||||||
|
let mut d = Self::new("4071", "4071", 7);
|
||||||
|
for _ in 0..rounds {
|
||||||
|
assert!(d.round().unwrap().is_none());
|
||||||
|
}
|
||||||
|
d
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle(&mut self, phase: PairPhase, transport_scheme: Scheme) -> Result<HostPairingStep, Error> {
|
||||||
|
let req = PairRequest { unique_id: UID.into(), device_name: None, phase };
|
||||||
|
self.now = self.now.saturating_add(Duration::from_millis(250));
|
||||||
|
let now = self.now;
|
||||||
|
let cert = self.cid.cert_der().to_vec();
|
||||||
|
let transport = match transport_scheme {
|
||||||
|
Scheme::Http => Transport::Http,
|
||||||
|
Scheme::Https => Transport::Https { client_cert_der: &cert },
|
||||||
|
};
|
||||||
|
self.host.handle(&self.hid, &req, transport, now, &mut self.hrng)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ both sides agree
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn client_and_host_pair_in_memory() {
|
||||||
|
let mut d = Duo::new("4071", "4071", 1);
|
||||||
|
let paired_host = d.run().expect("the client pairs with the host");
|
||||||
|
assert_eq!(d.client.state(), PairingState::Paired);
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::Paired);
|
||||||
|
|
||||||
|
// The client pins exactly the host's certificate; the host authorizes exactly the client's.
|
||||||
|
assert_eq!(paired_host.server_cert.der(), d.hid.cert_der());
|
||||||
|
assert_eq!(paired_host.server_cert.matches(d.hid.cert_der()), Ok(true));
|
||||||
|
let pc = d.paired_client.clone().expect("the host returned the paired client");
|
||||||
|
assert_eq!(d.host.paired_client(), Some(&pc));
|
||||||
|
assert_eq!(pc.cert_der, d.cid.cert_der());
|
||||||
|
assert_eq!(pc.unique_id.as_deref(), Some(UID));
|
||||||
|
assert_eq!(pc.device_name.as_deref(), Some(DEVICE));
|
||||||
|
assert_eq!(pc.matches(d.cid.cert_der()), Ok(true));
|
||||||
|
assert_eq!(pc.matches(rogue_id().cert_der()), Ok(false));
|
||||||
|
|
||||||
|
let pending = d.host.pending_client().expect("phase 1 described the client");
|
||||||
|
assert_eq!(pending.cert_der, d.cid.cert_der());
|
||||||
|
assert_eq!(pending.unique_id, UID);
|
||||||
|
assert_eq!(pending.device_name.as_deref(), Some(DEVICE));
|
||||||
|
|
||||||
|
// The host draws exactly S_c and secret_s (16 bytes each), nothing else.
|
||||||
|
assert_eq!(d.hrng.1, 32);
|
||||||
|
assert_eq!(d.host.poll_timeout(), None, "Paired is terminal");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn several_pins_and_seeds_pair() {
|
||||||
|
for (p, seed) in [("0000", 2u64), ("9999", 3), ("1234", 4)] {
|
||||||
|
let mut d = Duo::new(p, p, seed);
|
||||||
|
d.run().unwrap_or_else(|e| panic!("PIN {p}: {e:?}"));
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::Paired, "PIN {p}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_generated_host_identity_pairs() {
|
||||||
|
let hid = HostIdentity::generate(&mut SeqRng::new(0x1u64), "Lumen Test Host", 1_764_000_000).unwrap();
|
||||||
|
let parsed = domistream::pairing::ServerCert::from_der(hid.cert_der()).expect("an RSA X.509 certificate");
|
||||||
|
assert!(hid.cert_der().windows(15).any(|w| w == b"Lumen Test Host"));
|
||||||
|
assert!(hid.cert_pem().unwrap().starts_with("-----BEGIN CERTIFICATE-----\n"));
|
||||||
|
let again = HostIdentity::from_der(hid.cert_der(), hid.key_pkcs8_der()).unwrap();
|
||||||
|
assert_eq!(again.cert_der(), hid.cert_der());
|
||||||
|
|
||||||
|
let mut d = Duo::new("2468", "2468", 5);
|
||||||
|
d.host = HostPairingSession::new(&hid, HostPairingConfig::default(), Instant::ZERO);
|
||||||
|
d.hid = hid;
|
||||||
|
let paired = d.run().unwrap();
|
||||||
|
assert_eq!(paired.server_cert, parsed);
|
||||||
|
assert_err!(HostIdentity::generate(&mut SeqRng::new(1), "", 0), Error::Malformed { .. });
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn host_answers_are_fresh_per_session() {
|
||||||
|
// Same client randomness, different host randomness: the phase-2 answers differ (fresh S_c and secret_s).
|
||||||
|
let answer2 = |host_seed: u64| {
|
||||||
|
let mut d = Duo::new("4071", "4071", 9);
|
||||||
|
d.hrng = Counting(SeqRng::new(host_seed), 0);
|
||||||
|
d.round().unwrap();
|
||||||
|
let req = d.next.clone().unwrap();
|
||||||
|
d.host_answers(&to_host(&req), req.scheme)
|
||||||
|
};
|
||||||
|
let (a, b, a2) = (answer2(1), answer2(2), answer2(1));
|
||||||
|
assert!(matches!(a, PairAnswer::ChallengeResponse(ref v) if v.len() == 48), "{a:?}");
|
||||||
|
assert_ne!(a, b);
|
||||||
|
assert_eq!(a, a2, "the host's randomness comes only from the caller");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ wrong PIN
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn wrong_pin_fails_on_both_sides() {
|
||||||
|
let mut d = Duo::new("1234", "4321", 11);
|
||||||
|
let r = d.run();
|
||||||
|
assert_err!(r, Error::PairingRefused);
|
||||||
|
assert_eq!(d.client.state(), PairingState::Failed(PairingFailure::ProofMismatch), "the client sees it first");
|
||||||
|
// The client stops; the host waits for phase 4 until its deadline, then fails.
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::AwaitClientPairingSecret);
|
||||||
|
let deadline = d.host.poll_timeout().expect("a deadline while in progress");
|
||||||
|
assert!(!d.host.handle_timeout(deadline), "the deadline itself is still in time");
|
||||||
|
assert!(d.host.handle_timeout(deadline.saturating_add(Duration::from_micros(1))));
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::TimedOut));
|
||||||
|
assert!(!d.host.handle_timeout(deadline.saturating_add(Duration::from_secs(1))), "only once");
|
||||||
|
assert_eq!(d.host.paired_client(), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn wrong_pin_is_caught_by_the_host_when_the_client_carries_on() {
|
||||||
|
// A client that ignores its own failed check and sends phase 4 anyway (signed correctly): the host's proof
|
||||||
|
// check catches the PIN mismatch.
|
||||||
|
let mut d = Duo::new("1234", "4321", 12);
|
||||||
|
for _ in 0..2 {
|
||||||
|
d.round().unwrap();
|
||||||
|
}
|
||||||
|
assert!(d.round().is_err());
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::AwaitClientPairingSecret);
|
||||||
|
let secret = [0x5Au8; 16];
|
||||||
|
let sig = d.cid.sign(&secret).unwrap();
|
||||||
|
let r = d.handle(PairPhase::ClientPairingSecret([&secret[..], &sig].concat()), Scheme::Http);
|
||||||
|
assert_err!(r, Error::PairingRefused);
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::WrongPin));
|
||||||
|
assert_eq!(d.host.paired_client(), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_right_pin_but_a_forged_proof_is_a_wrong_pin() {
|
||||||
|
// Correct PIN on both sides, but the client's secret is not the one behind H_c.
|
||||||
|
let mut d = Duo::after(3);
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::AwaitClientPairingSecret);
|
||||||
|
let secret = [0x11u8; 16];
|
||||||
|
let sig = d.cid.sign(&secret).unwrap();
|
||||||
|
assert_err!(
|
||||||
|
d.handle(PairPhase::ClientPairingSecret([&secret[..], &sig].concat()), Scheme::Http),
|
||||||
|
Error::PairingRefused
|
||||||
|
);
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::WrongPin));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ signatures
|
||||||
|
|
||||||
|
/// The genuine phase-4 value the client would send now, split into secret and signature.
|
||||||
|
fn genuine_phase4(d: &mut Duo) -> (Vec<u8>, Vec<u8>) {
|
||||||
|
let req = d.next.clone().expect("phase 4 pending");
|
||||||
|
match to_host(&req).phase {
|
||||||
|
PairPhase::ClientPairingSecret(v) => (v[..16].to_vec(), v[16..].to_vec()),
|
||||||
|
other => panic!("expected phase 4, got {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bad_client_signatures() {
|
||||||
|
let rogue = rogue_id();
|
||||||
|
let cases: Vec<(&str, Box<dyn Fn(&[u8], &[u8]) -> Vec<u8>>)> = vec![
|
||||||
|
("signed by another key", Box::new(move |s, _| [s.to_vec(), rogue.sign(s).unwrap()].concat())),
|
||||||
|
(
|
||||||
|
"one bit flipped",
|
||||||
|
Box::new(|s, sig| {
|
||||||
|
let mut sig = sig.to_vec();
|
||||||
|
sig[100] ^= 0x08;
|
||||||
|
[s.to_vec(), sig].concat()
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
("cut short", Box::new(|s, sig| [s, &sig[..sig.len() - 1]].concat())),
|
||||||
|
("zeroed", Box::new(|s, sig| [s.to_vec(), vec![0; sig.len()]].concat())),
|
||||||
|
("one byte", Box::new(|s, _| [s, &[1u8][..]].concat())),
|
||||||
|
];
|
||||||
|
for (why, make) in cases {
|
||||||
|
let mut d = Duo::after(3);
|
||||||
|
let (secret, sig) = genuine_phase4(&mut d);
|
||||||
|
let r = d.handle(PairPhase::ClientPairingSecret(make(&secret, &sig)), Scheme::Http);
|
||||||
|
assert_err!(r, Error::PairingRefused, "{why}");
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::BadSignature), "{why}");
|
||||||
|
}
|
||||||
|
// The genuine value passes.
|
||||||
|
let mut d = Duo::after(3);
|
||||||
|
let (secret, sig) = genuine_phase4(&mut d);
|
||||||
|
let step = d.handle(PairPhase::ClientPairingSecret([secret, sig].concat()), Scheme::Http).unwrap();
|
||||||
|
assert_eq!(step, HostPairingStep::Answer(PairAnswer::Paired));
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::AwaitPairChallenge);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ order
|
||||||
|
|
||||||
|
fn phase(n: u8) -> PairPhase {
|
||||||
|
match n {
|
||||||
|
1 => PairPhase::GetServerCert { salt: [7; 16], client_cert_pem: CLIENT_CERT_PEM.as_bytes().to_vec() },
|
||||||
|
2 => PairPhase::ClientChallenge(vec![0; 16]),
|
||||||
|
3 => PairPhase::ServerChallengeResp(vec![0; 32]),
|
||||||
|
4 => PairPhase::ClientPairingSecret(vec![0; 16 + 256]),
|
||||||
|
_ => PairPhase::PairChallenge,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A host in in-progress state `i` (0..6), with the phase it expects (0 = it expects the PIN, no phase).
|
||||||
|
fn host_in_state(i: usize) -> (Duo, u8) {
|
||||||
|
match i {
|
||||||
|
0 => (Duo::after(0), 1),
|
||||||
|
1 => {
|
||||||
|
// AwaitPin: phase 1 delivered, PIN not supplied.
|
||||||
|
let mut d = Duo::after(0);
|
||||||
|
let req = to_host(d.next.as_ref().unwrap());
|
||||||
|
let now = d.now;
|
||||||
|
let step = d.host.handle(&d.hid, &req, Transport::Http, now, &mut d.hrng).unwrap();
|
||||||
|
assert_eq!(step, HostPairingStep::HoldForPin);
|
||||||
|
(d, 0)
|
||||||
|
}
|
||||||
|
_ => (Duo::after(i - 1), i as u8),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn out_of_order_phases_are_refused() {
|
||||||
|
let states = [
|
||||||
|
HostPairingState::AwaitGetServerCert,
|
||||||
|
HostPairingState::AwaitPin,
|
||||||
|
HostPairingState::AwaitClientChallenge,
|
||||||
|
HostPairingState::AwaitServerChallengeResp,
|
||||||
|
HostPairingState::AwaitClientPairingSecret,
|
||||||
|
HostPairingState::AwaitPairChallenge,
|
||||||
|
];
|
||||||
|
for (i, want) in states.iter().enumerate() {
|
||||||
|
for wrong in 1..=5u8 {
|
||||||
|
let (mut d, expected) = host_in_state(i);
|
||||||
|
assert_eq!(d.host.state(), *want);
|
||||||
|
if wrong == expected {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let r = d.handle(phase(wrong), if wrong == 5 { Scheme::Https } else { Scheme::Http });
|
||||||
|
assert_err!(r, Error::PairingRefused, "phase {wrong} in {want:?}");
|
||||||
|
assert_eq!(
|
||||||
|
d.host.state(),
|
||||||
|
HostPairingState::Failed(HostPairingFailure::WrongOrder),
|
||||||
|
"phase {wrong} in {want:?}"
|
||||||
|
);
|
||||||
|
// Failed is terminal, also for the phase that would have been right.
|
||||||
|
let right = if expected == 0 { 2 } else { expected };
|
||||||
|
assert_err!(d.handle(phase(right), Scheme::Http), Error::State { .. });
|
||||||
|
assert_err!(d.host.supply_pin(&d.hid, pin("4071"), d.now), Error::State { .. });
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::WrongOrder));
|
||||||
|
assert_eq!(d.host.poll_timeout(), None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_replayed_phase_is_refused() {
|
||||||
|
// Phase 2 accepted, then the same request again.
|
||||||
|
let mut d = Duo::after(1);
|
||||||
|
let req = to_host(d.next.as_ref().unwrap());
|
||||||
|
let now = d.now;
|
||||||
|
assert!(matches!(
|
||||||
|
d.host.handle(&d.hid, &req, Transport::Http, now, &mut d.hrng).unwrap(),
|
||||||
|
HostPairingStep::Answer(PairAnswer::ChallengeResponse(_))
|
||||||
|
));
|
||||||
|
assert_err!(d.host.handle(&d.hid, &req, Transport::Http, now, &mut d.hrng), Error::PairingRefused);
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::WrongOrder));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn paired_is_terminal() {
|
||||||
|
let mut d = Duo::new("4071", "4071", 21);
|
||||||
|
d.run().unwrap();
|
||||||
|
for n in 1..=5 {
|
||||||
|
assert_err!(d.handle(phase(n), Scheme::Https), Error::State { .. }, "phase {n}");
|
||||||
|
}
|
||||||
|
d.host.cancel();
|
||||||
|
assert!(!d.host.handle_timeout(secs(1_000_000)));
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::Paired);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ who is asking
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_phase_must_come_from_the_phase_1_client() {
|
||||||
|
let mut d = Duo::after(1);
|
||||||
|
let mut req = to_host(d.next.as_ref().unwrap());
|
||||||
|
req.unique_id = "FEDCBA9876543210".into();
|
||||||
|
let now = d.now;
|
||||||
|
assert_err!(d.host.handle(&d.hid, &req, Transport::Http, now, &mut d.hrng), Error::PairingRefused);
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::WrongClient));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn phase_5_needs_https_with_the_phase_1_certificate() {
|
||||||
|
let rogue = rogue_id();
|
||||||
|
for (why, cert) in
|
||||||
|
[("plain HTTP", None), ("another certificate", Some(rogue.cert_der().to_vec())), ("empty", Some(vec![]))]
|
||||||
|
{
|
||||||
|
let mut d = Duo::after(4);
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::AwaitPairChallenge);
|
||||||
|
let req = PairRequest { unique_id: UID.into(), device_name: None, phase: PairPhase::PairChallenge };
|
||||||
|
let transport = match &cert {
|
||||||
|
None => Transport::Http,
|
||||||
|
Some(c) => Transport::Https { client_cert_der: c },
|
||||||
|
};
|
||||||
|
let now = d.now;
|
||||||
|
assert_err!(d.host.handle(&d.hid, &req, transport, now, &mut d.hrng), Error::PairingRefused, "{why}");
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::WrongClient), "{why}");
|
||||||
|
assert_eq!(d.host.paired_client(), None);
|
||||||
|
}
|
||||||
|
let mut d = Duo::after(4);
|
||||||
|
match d.handle(PairPhase::PairChallenge, Scheme::Https).unwrap() {
|
||||||
|
HostPairingStep::Paired(c) => assert_eq!(c.cert_der, d.cid.cert_der()),
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn identity_must_stay_the_same() {
|
||||||
|
let mut d = Duo::after(1);
|
||||||
|
let other = HostIdentity::from_der(d.cid.cert_der(), d.cid.key_pkcs8_der()).unwrap();
|
||||||
|
let req = to_host(d.next.as_ref().unwrap());
|
||||||
|
let now = d.now;
|
||||||
|
assert_err!(d.host.handle(&other, &req, Transport::Http, now, &mut d.hrng), Error::Malformed { .. });
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::AwaitClientChallenge, "misuse does not end the session");
|
||||||
|
let mut d = Duo::after(0);
|
||||||
|
let req = to_host(d.next.as_ref().unwrap());
|
||||||
|
let hid = host_id();
|
||||||
|
let now = d.now;
|
||||||
|
d.host.handle(&hid, &req, Transport::Http, now, &mut d.hrng).unwrap();
|
||||||
|
assert_err!(d.host.supply_pin(&other, pin("4071"), now), Error::Malformed { .. });
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::AwaitPin);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ bad values
|
||||||
|
|
||||||
|
fn expect_malformed(mut d: Duo, ph: PairPhase, why: &str) {
|
||||||
|
let r = d.handle(ph, Scheme::Http);
|
||||||
|
assert!(matches!(r, Err(Error::Malformed { .. } | Error::TooLarge { .. })), "{why}: {r:?}");
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::Malformed), "{why}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bad_phase_values() {
|
||||||
|
let pem = |s: &str| PairPhase::GetServerCert { salt: [1; 16], client_cert_pem: s.as_bytes().to_vec() };
|
||||||
|
expect_malformed(Duo::after(0), pem(""), "empty certificate");
|
||||||
|
expect_malformed(Duo::after(0), pem("hello"), "not PEM");
|
||||||
|
expect_malformed(Duo::after(0), pem(EC_CERT_PEM), "not an RSA certificate");
|
||||||
|
expect_malformed(Duo::after(0), pem(&format!("{CLIENT_CERT_PEM}{CLIENT_CERT_PEM}")), "two certificates");
|
||||||
|
expect_malformed(Duo::after(0), pem(&"A".repeat(1 << 20)), "huge");
|
||||||
|
for len in [0usize, 15, 17, 32] {
|
||||||
|
expect_malformed(Duo::after(1), PairPhase::ClientChallenge(vec![0; len]), &format!("challenge {len}"));
|
||||||
|
}
|
||||||
|
for len in [0usize, 16, 31, 33, 48] {
|
||||||
|
expect_malformed(Duo::after(2), PairPhase::ServerChallengeResp(vec![0; len]), &format!("resp {len}"));
|
||||||
|
}
|
||||||
|
for len in [0usize, 15, 16, 16 + MAX_SIGNATURE_BYTES + 1] {
|
||||||
|
expect_malformed(Duo::after(3), PairPhase::ClientPairingSecret(vec![0; len]), &format!("secret {len}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bad_unique_ids_and_device_names_in_phase_1() {
|
||||||
|
for (uid, dev) in [
|
||||||
|
("", None),
|
||||||
|
("a&b", None),
|
||||||
|
("a b", None),
|
||||||
|
(&*"a".repeat(65), None),
|
||||||
|
(UID, Some("x".repeat(257))),
|
||||||
|
(UID, Some("tv\u{1}".to_string())),
|
||||||
|
] {
|
||||||
|
let mut d = Duo::after(0);
|
||||||
|
let req = PairRequest { unique_id: uid.to_string(), device_name: dev.clone(), phase: phase(1) };
|
||||||
|
let now = d.now;
|
||||||
|
let r = d.host.handle(&d.hid, &req, Transport::Http, now, &mut d.hrng);
|
||||||
|
assert!(matches!(r, Err(Error::Malformed { .. } | Error::TooLarge { .. })), "{uid:?} {dev:?}: {r:?}");
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::Malformed));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ the PIN slot
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn supply_pin_only_while_a_request_is_held() {
|
||||||
|
let hid = host_id();
|
||||||
|
let mut s = HostPairingSession::new(&hid, HostPairingConfig::default(), Instant::ZERO);
|
||||||
|
assert_err!(s.supply_pin(&hid, pin("4071"), Instant::ZERO), Error::State { .. });
|
||||||
|
assert_eq!(s.state(), HostPairingState::AwaitGetServerCert, "an early PIN does not end the session");
|
||||||
|
assert_eq!(s.pending_client(), None);
|
||||||
|
|
||||||
|
let mut d = Duo::after(1);
|
||||||
|
assert_err!(d.host.supply_pin(&d.hid, pin("4071"), d.now), Error::State { .. });
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::AwaitClientChallenge, "a second PIN is refused, nothing else");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn deadlines_follow_the_caller_clock() {
|
||||||
|
let hid = host_id();
|
||||||
|
let cfg = HostPairingConfig { pin_timeout: Duration::from_secs(60), phase_timeout: Duration::from_secs(10) };
|
||||||
|
assert_eq!(HostPairingConfig::default().pin_timeout, DEFAULT_PIN_TIMEOUT);
|
||||||
|
assert_eq!(HostPairingConfig::default().phase_timeout, DEFAULT_PHASE_TIMEOUT);
|
||||||
|
let mut s = HostPairingSession::new(&hid, cfg, secs(100));
|
||||||
|
assert_eq!(s.poll_timeout(), Some(secs(110)), "phase 1 within the phase timeout");
|
||||||
|
let req = PairRequest { unique_id: UID.into(), device_name: Some(DEVICE.into()), phase: phase(1) };
|
||||||
|
let mut rng = SeqRng::new(1);
|
||||||
|
assert_eq!(s.handle(&hid, &req, Transport::Http, secs(105), &mut rng).unwrap(), HostPairingStep::HoldForPin);
|
||||||
|
assert_eq!(s.poll_timeout(), Some(secs(165)), "the PIN within the PIN timeout");
|
||||||
|
assert!(!s.handle_timeout(secs(165)));
|
||||||
|
assert!(matches!(s.supply_pin(&hid, pin("4071"), secs(165)).unwrap(), PairAnswer::ServerCert { .. }));
|
||||||
|
assert_eq!(s.poll_timeout(), Some(secs(175)), "each phase within the phase timeout of the last answer");
|
||||||
|
let late = PairRequest { unique_id: UID.into(), device_name: None, phase: phase(2) };
|
||||||
|
assert_err!(s.handle(&hid, &late, Transport::Http, secs(176), &mut rng), Error::TimedOut);
|
||||||
|
assert_eq!(s.state(), HostPairingState::Failed(HostPairingFailure::TimedOut));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pin_not_typed_in_time() {
|
||||||
|
let mut d = Duo::after(0);
|
||||||
|
let req = to_host(d.next.as_ref().unwrap());
|
||||||
|
d.host.handle(&d.hid, &req, Transport::Http, secs(1), &mut d.hrng).unwrap();
|
||||||
|
let deadline = d.host.poll_timeout().unwrap();
|
||||||
|
assert_eq!(deadline, secs(1).saturating_add(DEFAULT_PIN_TIMEOUT));
|
||||||
|
// Typed one microsecond late, without a timer wake-up first.
|
||||||
|
let late = deadline.saturating_add(Duration::from_micros(1));
|
||||||
|
assert_err!(d.host.supply_pin(&d.hid, pin("4071"), late), Error::TimedOut);
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::TimedOut));
|
||||||
|
|
||||||
|
// The timer fires first.
|
||||||
|
let mut d = Duo::after(0);
|
||||||
|
let req = to_host(d.next.as_ref().unwrap());
|
||||||
|
d.host.handle(&d.hid, &req, Transport::Http, secs(1), &mut d.hrng).unwrap();
|
||||||
|
assert!(d.host.handle_timeout(secs(1000)));
|
||||||
|
assert_err!(d.host.supply_pin(&d.hid, pin("4071"), secs(1000)), Error::State { .. });
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_owner_cancels() {
|
||||||
|
let mut d = Duo::after(0);
|
||||||
|
let req = to_host(d.next.as_ref().unwrap());
|
||||||
|
let now = d.now;
|
||||||
|
d.host.handle(&d.hid, &req, Transport::Http, now, &mut d.hrng).unwrap();
|
||||||
|
d.host.cancel();
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::Cancelled));
|
||||||
|
assert_err!(d.host.supply_pin(&d.hid, pin("4071"), now), Error::State { .. });
|
||||||
|
d.host.cancel();
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::Cancelled));
|
||||||
|
// The client is answered paired=0 and stops.
|
||||||
|
let body = pair_answer_xml(&PairAnswer::Refused).unwrap();
|
||||||
|
assert_err!(d.client.handle_response(&d.cid, 200, &body, &mut d.crng), Error::PairingRefused);
|
||||||
|
assert_eq!(d.client.state(), PairingState::Failed(PairingFailure::HostRefused));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ trusted clients
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn trusted_clients_need_no_pin() {
|
||||||
|
let cid = client_id();
|
||||||
|
let c = PairedClient::trusted(cid.cert_der()).unwrap();
|
||||||
|
assert_eq!(c.cert_der, cid.cert_der());
|
||||||
|
assert_eq!(c.unique_id, None);
|
||||||
|
assert_eq!(c.matches(cid.cert_der()), Ok(true));
|
||||||
|
let mut flipped = cid.cert_der().to_vec();
|
||||||
|
let mid = flipped.len() / 2;
|
||||||
|
flipped[mid] ^= 1;
|
||||||
|
assert_eq!(c.matches(&flipped), Ok(false));
|
||||||
|
assert_eq!(c.matches(&[]), Ok(false));
|
||||||
|
assert_too_large!(c.matches(&vec![0; MAX_CERT_DER_BYTES + 1]), MAX_CERT_DER_BYTES, MAX_CERT_DER_BYTES + 1);
|
||||||
|
|
||||||
|
let ec = pem_blocks(EC_CERT_PEM, "CERTIFICATE").pop().unwrap();
|
||||||
|
for (bad, why) in [(vec![], "empty"), (vec![0x30], "one byte"), (ec, "EC key"), (flipped[..100].to_vec(), "cut")] {
|
||||||
|
assert_err!(PairedClient::trusted(&bad), Error::Malformed { .. }, "{why}");
|
||||||
|
}
|
||||||
|
assert_too_large!(
|
||||||
|
PairedClient::trusted(&vec![0x30; MAX_CERT_DER_BYTES + 1]),
|
||||||
|
MAX_CERT_DER_BYTES,
|
||||||
|
MAX_CERT_DER_BYTES + 1
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ hygiene
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn debug_never_prints_host_secrets() {
|
||||||
|
let key = pem_blocks(HOST_KEY_PEM, "PRIVATE KEY").pop().unwrap();
|
||||||
|
let hid = host_id();
|
||||||
|
let s = format!("{hid:?}");
|
||||||
|
assert!(s.contains("redacted"), "{s}");
|
||||||
|
assert!(!s.to_lowercase().contains(&common::to_hex(&key[key.len() - 32..])));
|
||||||
|
assert!(!s.contains(&format!("{:?}", &key[key.len() - 8..])));
|
||||||
|
|
||||||
|
let mut d = Duo::after(2);
|
||||||
|
let s = format!("{:?}", d.host);
|
||||||
|
assert!(s.len() < 200, "session Debug stays short: {s}");
|
||||||
|
let req = d.next.clone().unwrap();
|
||||||
|
let a = d.host_answers(&to_host(&req), req.scheme);
|
||||||
|
let s = format!("{a:?}");
|
||||||
|
assert!(s.starts_with("PairingSecret"), "{s}");
|
||||||
|
assert!(s.len() < 40, "answers print lengths, not bytes: {s}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn transport_scheme() {
|
||||||
|
assert_eq!(Transport::Http.scheme(), Scheme::Http);
|
||||||
|
assert_eq!(Transport::Https { client_cert_der: &[] }.scheme(), Scheme::Https);
|
||||||
|
assert_eq!(phase(1).number(), 1);
|
||||||
|
assert_eq!(phase(5).number(), 5);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user