garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /bt/src/smp.rs

raw

//! The security manager: LE Secure Connections pairing (Core spec, Vol 3
//! Part H), as a pure state machine. Two devices agree a key by P-256
//! Diffie-Hellman, prove to each other that they hold it, and derive the
//! long-term key the controllers encrypt the link with; with a display on
//! both sides each shows a six-digit number and its person says whether
//! they match (numeric comparison), which a device in the middle cannot
//! fake; where one side has a keyboard and the other a display (a keyboard
//! pairing with a phone), one shows a six-digit passkey and its person types
//! it on the other (passkey entry), proved a bit a round over twenty rounds
//! so a device in the middle cannot fake that either; with nothing to show
//! or type on one side the pairing is "just works", private from listeners
//! but not proof against a device in the middle.
//!
//! Once the link is encrypted the two hand each other their identity
//! (Vol 3 Part H 3.6.4): an identity resolving key (IRK) and the address
//! that does not change. A phone or a watch moves to a new resolvable
//! private address every few minutes, made from its IRK ([`ah`]), so a
//! listener cannot follow it; whoever holds the IRK knows it still
//! ([`resolves`]).
//!
//! What is not here: legacy pairing (before Bluetooth 4.2: its key is
//! found from a recorded pairing, so it is refused), out-of-band data, and
//! signing keys.
//!
//! Bytes are as they go over the air, least significant first, the
//! functions too (Linux's convention): `cmac` turns them round for AES.

use alloc::vec::Vec;
use pinnacle_crypto::{aes, p256};

// PDUs.
pub const PAIRING_REQUEST: u8 = 0x01;
pub const PAIRING_RESPONSE: u8 = 0x02;
pub const PAIRING_CONFIRM: u8 = 0x03;
pub const PAIRING_RANDOM: u8 = 0x04;
pub const PAIRING_FAILED: u8 = 0x05;
pub const SECURITY_REQUEST: u8 = 0x0b;
pub const PAIRING_PUBLIC_KEY: u8 = 0x0c;
pub const PAIRING_DHKEY_CHECK: u8 = 0x0d;
pub const IDENTITY_INFORMATION: u8 = 0x08;
pub const IDENTITY_ADDRESS_INFORMATION: u8 = 0x09;

// Why a pairing failed.
pub const PASSKEY_ENTRY_FAILED: u8 = 0x01;
pub const AUTHENTICATION_REQUIREMENTS: u8 = 0x03;
pub const CONFIRM_VALUE_FAILED: u8 = 0x04;
pub const NOT_SUPPORTED: u8 = 0x05;
pub const UNSPECIFIED: u8 = 0x08;
pub const INVALID_PARAMETERS: u8 = 0x0a;
pub const DHKEY_CHECK_FAILED: u8 = 0x0b;
pub const NUMERIC_COMPARISON_FAILED: u8 = 0x0c;
/// Not a reason on the air: the 30 s the spec allows went by.
pub const TIMED_OUT: u8 = 0xff;

// What a device can show and take.
pub const DISPLAY_ONLY: u8 = 0x00;
pub const DISPLAY_YES_NO: u8 = 0x01;
pub const KEYBOARD_ONLY: u8 = 0x02;
pub const NO_INPUT_NO_OUTPUT: u8 = 0x03;
pub const KEYBOARD_DISPLAY: u8 = 0x04;

// Authentication requirements.
const BONDING: u8 = 0x01;
const MITM: u8 = 0x04;
const SECURE_CONNECTIONS: u8 = 0x08;

// The keys handed over after pairing: only the identity is asked for or
// given (Secure Connections agrees the link's key, so none is sent).
const ID_KEY: u8 = 0x02;

/// How long a pairing may wait for the other side, or for its person.
pub const TIMEOUT_MS: u64 = 30_000;

/// A reason, in words a person reads.
pub fn reason_text(reason: u8) -> &'static str {
    match reason {
        AUTHENTICATION_REQUIREMENTS => "it only pairs the old, unsafe way",
        PASSKEY_ENTRY_FAILED => "the code was not typed",
        CONFIRM_VALUE_FAILED => "the code typed was not the one shown, or the keys did not match",
        DHKEY_CHECK_FAILED => "the keys did not match",
        NOT_SUPPORTED => "it cannot pair",
        NUMERIC_COMPARISON_FAILED => "the numbers were not confirmed",
        TIMED_OUT => "no answer in time",
        _ => "it refused",
    }
}

/// AES-CMAC on over-the-air bytes.
fn cmac(key: &[u8; 16], message: &[u8]) -> [u8; 16] {
    let mut k = *key;
    k.reverse();
    let mut m: Vec<u8> = message.to_vec();
    m.reverse();
    let mut mac = aes::cmac(&k, &m);
    mac.reverse();
    mac
}

/// The confirm value: f4(U, V, X, Z), U and V x coordinates.
pub fn f4(u: &[u8; 32], v: &[u8; 32], x: &[u8; 16], z: u8) -> [u8; 16] {
    let mut m = Vec::with_capacity(65);
    m.push(z);
    m.extend_from_slice(v);
    m.extend_from_slice(u);
    cmac(x, &m)
}

/// The MAC key and the long-term key: f5(W, N1, N2, A1, A2), the
/// addresses each six bytes and a type.
pub fn f5(w: &[u8; 32], n1: &[u8; 16], n2: &[u8; 16], a1: &[u8; 7], a2: &[u8; 7]) -> ([u8; 16], [u8; 16]) {
    const SALT: [u8; 16] = [
        0xbe, 0x83, 0x60, 0x5a, 0xdb, 0x0b, 0x37, 0x60, 0x38, 0xa5, 0xf5, 0xaa, 0x91, 0x83, 0x88, 0x6c,
    ];
    let t = cmac(&SALT, w);
    let mut m = Vec::with_capacity(53);
    m.extend_from_slice(&[0x00, 0x01]);
    m.extend_from_slice(a2);
    m.extend_from_slice(a1);
    m.extend_from_slice(n2);
    m.extend_from_slice(n1);
    m.extend_from_slice(b"eltb");
    m.push(0);
    let mac_key = cmac(&t, &m);
    m[52] = 1;
    (mac_key, cmac(&t, &m))
}

/// The DHKey check: f6(W, N1, N2, R, IOcap, A1, A2).
pub fn f6(
    w: &[u8; 16],
    n1: &[u8; 16],
    n2: &[u8; 16],
    r: &[u8; 16],
    io: &[u8; 3],
    a1: &[u8; 7],
    a2: &[u8; 7],
) -> [u8; 16] {
    let mut m = Vec::with_capacity(65);
    m.extend_from_slice(a2);
    m.extend_from_slice(a1);
    m.extend_from_slice(io);
    m.extend_from_slice(r);
    m.extend_from_slice(n2);
    m.extend_from_slice(n1);
    cmac(w, &m)
}

/// The six-digit number both sides show: g2(U, V, X, Y) mod 10⁶.
pub fn g2(u: &[u8; 32], v: &[u8; 32], x: &[u8; 16], y: &[u8; 16]) -> u32 {
    let mut m = Vec::with_capacity(80);
    m.extend_from_slice(y);
    m.extend_from_slice(v);
    m.extend_from_slice(u);
    let t = cmac(x, &m);
    u32::from_le_bytes(t[..4].try_into().unwrap()) % 1_000_000
}

/// The random address hash: ah(k, r) = e(k, 0¹⁰⁴ ‖ r) mod 2²⁴, the IRK
/// and the three bytes as over the air.
pub fn ah(irk: &[u8; 16], prand: &[u8; 3]) -> [u8; 3] {
    let mut key = *irk;
    key.reverse();
    let mut block = [0u8; 16];
    block[13] = prand[2];
    block[14] = prand[1];
    block[15] = prand[0];
    aes::Aes::new(&key).unwrap().encrypt_blocks(&mut block);
    [block[15], block[14], block[13]]
}

/// A resolvable private address from an IRK and 22 random bits: the hash
/// in the low three bytes, `prand` in the high ones, its top bits 0b01.
pub fn private_address(irk: &[u8; 16], prand: [u8; 3]) -> [u8; 6] {
    let mut prand = prand;
    prand[2] = (prand[2] & 0x3f) | 0x40;
    let hash = ah(irk, &prand);
    [hash[0], hash[1], hash[2], prand[0], prand[1], prand[2]]
}

/// Whether `address` is a resolvable private address made from `irk`.
pub fn resolves(irk: &[u8; 16], address: &[u8; 6]) -> bool {
    address[5] & 0xc0 == 0x40 && ah(irk, &[address[3], address[4], address[5]]) == address[..3]
}

/// What the machine wants done.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Output {
    /// A PDU for the peer, on the security manager's channel.
    Send(Vec<u8>),
    /// Ask this device's person: does the other device show this number
    /// (numeric comparison), or, with `None`, may it pair at all (just
    /// works, the peer asking). [`Pairing::confirm`] answers.
    Ask(Option<u32>),
    /// Passkey entry: show this passkey to this device's person, to be
    /// typed on the other device. [`Pairing::confirm`] with no cancels.
    Show(u32),
    /// Passkey entry: this device's person is to type the passkey the
    /// other device shows. [`Pairing::enter`] answers.
    Type,
    /// Agreed: the link's long-term key, and whether the person compared
    /// numbers or typed a passkey (proof against a device in the middle,
    /// which would have shown another number). The link is to be
    /// encrypted with it, then [`Pairing::encrypted`] called.
    Done {
        key: [u8; 16],
        compared: bool,
    },
    /// The keys are handed over and the pairing over: the peer's identity,
    /// if it gave one.
    Keys(Option<Identity>),
    Failed(u8),
}

/// A device's identity: what it is known by whatever address it uses.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Identity {
    /// Its identity resolving key, as over the air.
    pub irk: [u8; 16],
    /// The address that does not change, and its type (0 public, 1 static
    /// random).
    pub address: [u8; 6],
    pub kind: u8,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum State {
    Response,
    PublicKey,
    Confirm,
    Random,
    /// The person is asked; the peer's check may arrive meanwhile.
    Person,
    Check,
    /// The key agreed; the link not yet encrypted with it.
    Encrypting,
    /// Encrypted: the keys handed over.
    Keys,
    Over,
}

/// One pairing, from the request to the long-term key.
pub struct Pairing {
    initiator: bool,
    state: State,
    /// The request and the response as sent (seven bytes, the code first).
    request: [u8; 7],
    response: [u8; 7],
    private: [u8; 32],
    /// Public keys as they go over the air: x then y, each LSB first.
    own: [u8; 64],
    peer: [u8; 64],
    dhkey: [u8; 32],
    nonce: [u8; 16],
    peer_nonce: [u8; 16],
    peer_confirm: [u8; 16],
    method: Method,
    /// Passkey entry: the passkey, once shown or typed; the round (of
    /// twenty, a bit of it each); the key each round's fresh nonce is
    /// drawn with; a passkey drawn for showing; and the peer's confirm for
    /// this round, held by a responder until its person has typed.
    passkey: Option<u32>,
    round: u8,
    nonce_key: [u8; 16],
    drawn: u32,
    held: bool,
    /// The initiator's address and the responder's: six bytes and a type.
    a: [u8; 7],
    b: [u8; 7],
    mac_key: [u8; 16],
    key: [u8; 16],
    asked: bool,
    peer_check: Option<[u8; 16]>,
    /// This device's IRK, its identity handed over with its own address.
    irk: Option<[u8; 16]>,
    /// The keys agreed: those this device sends, those the peer does.
    send_keys: u8,
    take_keys: u8,
    keys_sent: bool,
    peer_irk: Option<[u8; 16]>,
    peer_identity: Option<Identity>,
    /// The last time something happened.
    pub at: u64,
}

fn x(key: &[u8; 64]) -> &[u8; 32] {
    key[..32].try_into().unwrap()
}

/// A device's address for the functions: as over the air, then its type.
pub fn address_bytes(address: [u8; 6], kind: u8) -> [u8; 7] {
    let mut a = [0u8; 7];
    a[..6].copy_from_slice(&address);
    a[6] = kind;
    a
}

impl Pairing {
    /// `random` gives fresh secret bytes; `own` and `peer` are this
    /// device's and the peer's address bytes ([`address_bytes`]); `irk`
    /// this device's identity resolving key, handed over with `own` as its
    /// identity address (so `own` must be one: public or static).
    fn new(
        initiator: bool,
        own: [u8; 7],
        peer: [u8; 7],
        irk: Option<[u8; 16]>,
        random: &mut dyn FnMut(&mut [u8]),
        now: u64,
    ) -> Pairing {
        let (private, public) = loop {
            let mut private = [0u8; 32];
            random(&mut private);
            if let Some(public) = p256::public_key(&private) {
                break (private, public);
            }
        };
        // Over the air each coordinate goes least significant byte first.
        let mut wire = [0u8; 64];
        for (i, b) in public[..32].iter().rev().enumerate() {
            wire[i] = *b;
        }
        for (i, b) in public[32..].iter().rev().enumerate() {
            wire[32 + i] = *b;
        }
        let mut nonce = [0u8; 16];
        random(&mut nonce);
        let mut nonce_key = [0u8; 16];
        random(&mut nonce_key);
        let mut drawn = [0u8; 4];
        random(&mut drawn);
        let (a, b) = if initiator { (own, peer) } else { (peer, own) };
        Pairing {
            initiator,
            state: State::Response,
            request: [0; 7],
            response: [0; 7],
            private,
            own: wire,
            peer: [0; 64],
            dhkey: [0; 32],
            nonce,
            peer_nonce: [0; 16],
            peer_confirm: [0; 16],
            method: Method::JustWorks,
            passkey: None,
            round: 0,
            nonce_key,
            drawn: u32::from_le_bytes(drawn),
            held: false,
            a,
            b,
            mac_key: [0; 16],
            key: [0; 16],
            asked: false,
            peer_check: None,
            irk,
            send_keys: 0,
            take_keys: 0,
            keys_sent: false,
            peer_irk: None,
            peer_identity: None,
            at: now,
        }
    }

    /// The request or response this device sends: its IO, no OOB, bonding,
    /// MITM where it can compare, Secure Connections, 16-byte keys, and the
    /// keys to hand over afterwards: the initiator's, then the responder's.
    fn features(code: u8, io: u8, initiator_keys: u8, responder_keys: u8) -> [u8; 7] {
        let mitm = if io == NO_INPUT_NO_OUTPUT { 0 } else { MITM };
        [
            code,
            io,
            0,
            BONDING | mitm | SECURE_CONNECTIONS,
            16,
            initiator_keys,
            responder_keys,
        ]
    }

    /// The identity key bit, where this device has one to give.
    fn own_keys(&self) -> u8 {
        if self.irk.is_some() { ID_KEY } else { 0 }
    }

    /// Starts pairing as the central: the request to send.
    pub fn start(
        io: u8,
        own: [u8; 7],
        peer: [u8; 7],
        irk: Option<[u8; 16]>,
        random: &mut dyn FnMut(&mut [u8]),
        now: u64,
    ) -> (Pairing, Vec<Output>) {
        let mut p = Pairing::new(true, own, peer, irk, random, now);
        // Ours if we have one; the peer's always asked for.
        p.request = Self::features(PAIRING_REQUEST, io, p.own_keys(), ID_KEY);
        let out = alloc::vec![Output::Send(p.request.to_vec())];
        (p, out)
    }

    /// A peer's pairing request, as the peripheral.
    pub fn answer(
        io: u8,
        own: [u8; 7],
        peer: [u8; 7],
        irk: Option<[u8; 16]>,
        request: &[u8],
        random: &mut dyn FnMut(&mut [u8]),
        now: u64,
    ) -> (Pairing, Vec<Output>) {
        let mut p = Pairing::new(false, own, peer, irk, random, now);
        let Ok(request) = <[u8; 7]>::try_from(request) else {
            let out = p.failed(INVALID_PARAMETERS);
            return (p, out);
        };
        p.request = request;
        if request[3] & SECURE_CONNECTIONS == 0 {
            let out = p.failed(AUTHENTICATION_REQUIREMENTS);
            return (p, out);
        }
        if request[4] < 16 {
            let out = p.failed(INVALID_PARAMETERS);
            return (p, out);
        }
        // Of the keys asked for, only identities: theirs taken, ours given.
        p.take_keys = request[5] & ID_KEY;
        p.send_keys = request[6] & p.own_keys();
        p.response = Self::features(PAIRING_RESPONSE, io, p.take_keys, p.send_keys);
        p.method = method(&p.request, &p.response);
        p.state = State::PublicKey;
        let out = alloc::vec![Output::Send(p.response.to_vec())];
        (p, out)
    }

    pub fn over(&self) -> bool {
        self.state == State::Over
    }

    /// Whether it waits on this device's person.
    pub fn asking(&self) -> bool {
        self.state == State::Person && self.asked || self.typing()
    }

    /// Whether this device's person is to type the passkey, and has not.
    fn typing(&self) -> bool {
        self.passkey.is_none()
            && self.state != State::Over
            && matches!(self.method, Method::Passkey { .. })
            && !self.shows()
    }

    /// Passkey entry: whether this side shows the passkey (else its
    /// person types it).
    fn shows(&self) -> bool {
        match self.method {
            Method::Passkey {
                initiator_shows,
                responder_shows,
            } => {
                if self.initiator {
                    initiator_shows
                } else {
                    responder_shows
                }
            }
            _ => false,
        }
    }

    /// Passkey entry, once the public keys are across: the passkey shown,
    /// or the person asked to type it; the initiator then sends its first
    /// round's confirm as soon as it has the passkey.
    fn start_passkey(&mut self) -> Vec<Output> {
        let mut out = Vec::new();
        if self.shows() {
            let passkey = self.drawn % 1_000_000;
            self.passkey = Some(passkey);
            out.push(Output::Show(passkey));
        } else {
            out.push(Output::Type);
        }
        self.state = State::Confirm;
        if self.initiator && self.passkey.is_some() {
            out.push(Output::Send(self.round_confirm()));
        }
        out
    }

    /// This side's confirm for the round: a fresh nonce, committed to with
    /// the round's bit of the passkey (Cai = f4(PKax, PKbx, Nai, 0x80|rai),
    /// Cbi likewise from the responder's side).
    fn round_confirm(&mut self) -> Vec<u8> {
        self.nonce = cmac(&self.nonce_key, &[self.round]);
        let confirm = f4(x(&self.own), x(&self.peer), &self.nonce, self.round_bit());
        let mut c = alloc::vec![PAIRING_CONFIRM];
        c.extend_from_slice(&confirm);
        c
    }

    /// The round's z for f4: 0x80 and the passkey's bit, the lowest first.
    fn round_bit(&self) -> u8 {
        0x80 | (self.passkey.unwrap_or(0) >> self.round & 1) as u8
    }

    /// Passkey entry: whether the peer's nonce opens its confirm for this
    /// round, which it can only with the same bit of the passkey.
    fn round_checks(&self) -> bool {
        f4(x(&self.peer), x(&self.own), &self.peer_nonce, self.round_bit()) == self.peer_confirm
    }

    /// The person typed the passkey the other device shows
    /// ([`Output::Type`]).
    pub fn enter(&mut self, passkey: u32, now: u64) -> Vec<Output> {
        if !self.typing() || passkey >= 1_000_000 {
            return Vec::new();
        }
        self.at = now;
        self.passkey = Some(passkey);
        if self.state != State::Confirm {
            return Vec::new();
        }
        if self.initiator {
            alloc::vec![Output::Send(self.round_confirm())]
        } else if self.held {
            // The initiator's first confirm came while the person typed.
            self.held = false;
            self.state = State::Random;
            alloc::vec![Output::Send(self.round_confirm())]
        } else {
            Vec::new()
        }
    }

    fn failed(&mut self, reason: u8) -> Vec<Output> {
        self.state = State::Over;
        self.private = [0; 32];
        let mut out = alloc::vec![Output::Failed(reason)];
        if reason != TIMED_OUT {
            out.insert(0, Output::Send(alloc::vec![PAIRING_FAILED, reason]));
        }
        out
    }

    /// Time passed: a pairing waiting longer than the spec's 30 s fails.
    pub fn poll(&mut self, now: u64) -> Vec<Output> {
        if self.state != State::Over && now >= self.at + TIMEOUT_MS {
            return self.failed(TIMED_OUT);
        }
        Vec::new()
    }

    /// A PDU from the peer.
    pub fn receive(&mut self, pdu: &[u8], now: u64) -> Vec<Output> {
        if self.state == State::Over {
            return Vec::new();
        }
        self.at = now;
        let Some((&code, body)) = pdu.split_first() else {
            return Vec::new();
        };
        if code == PAIRING_FAILED {
            self.state = State::Over;
            return alloc::vec![Output::Failed(body.first().copied().unwrap_or(UNSPECIFIED))];
        }
        match (self.state, code, self.initiator) {
            (State::Response, PAIRING_RESPONSE, true) => {
                let Ok(response) = <[u8; 7]>::try_from(pdu) else {
                    return self.failed(INVALID_PARAMETERS);
                };
                self.response = response;
                if response[3] & SECURE_CONNECTIONS == 0 {
                    return self.failed(AUTHENTICATION_REQUIREMENTS);
                }
                // The keys to hand over: at most those asked for.
                if response[4] < 16
                    || response[5] & !self.request[5] != 0
                    || response[6] & !self.request[6] != 0
                {
                    return self.failed(INVALID_PARAMETERS);
                }
                self.send_keys = response[5];
                self.take_keys = response[6];
                self.method = method(&self.request, &self.response);
                self.state = State::PublicKey;
                alloc::vec![Output::Send(self.public_key_pdu())]
            }
            (State::PublicKey, PAIRING_PUBLIC_KEY, _) => {
                let Some(dhkey) = self.agree(body) else {
                    return self.failed(DHKEY_CHECK_FAILED);
                };
                self.dhkey = dhkey;
                let passkey = matches!(self.method, Method::Passkey { .. });
                if self.initiator {
                    if passkey {
                        return self.start_passkey();
                    }
                    self.state = State::Confirm;
                    Vec::new()
                } else if passkey {
                    let mut out = alloc::vec![Output::Send(self.public_key_pdu())];
                    out.extend(self.start_passkey());
                    out
                } else {
                    // Cb = f4(PKbx, PKax, Nb, 0).
                    let confirm = f4(x(&self.own), x(&self.peer), &self.nonce, 0);
                    let mut c = alloc::vec![PAIRING_CONFIRM];
                    c.extend_from_slice(&confirm);
                    self.state = State::Random;
                    alloc::vec![Output::Send(self.public_key_pdu()), Output::Send(c)]
                }
            }
            // The initiator's own confirm went first in passkey entry, so
            // not before its person typed.
            (State::Confirm, PAIRING_CONFIRM, true) if body.len() == 16 && !self.typing() => {
                self.peer_confirm.copy_from_slice(body);
                self.state = State::Random;
                alloc::vec![Output::Send(self.random_pdu())]
            }
            // Passkey entry: the initiator's confirm for a round, answered
            // with ours once the passkey is typed.
            (State::Confirm, PAIRING_CONFIRM, false) if body.len() == 16 && !self.held => {
                self.peer_confirm.copy_from_slice(body);
                if self.passkey.is_none() {
                    self.held = true;
                    return Vec::new();
                }
                self.state = State::Random;
                alloc::vec![Output::Send(self.round_confirm())]
            }
            (State::Random, PAIRING_RANDOM, _)
                if body.len() == 16 && matches!(self.method, Method::Passkey { .. }) =>
            {
                self.peer_nonce.copy_from_slice(body);
                if !self.round_checks() {
                    return self.failed(CONFIRM_VALUE_FAILED);
                }
                let mut out = Vec::new();
                if !self.initiator {
                    out.push(Output::Send(self.random_pdu()));
                }
                self.round += 1;
                if self.round < 20 {
                    self.state = State::Confirm;
                    if self.initiator {
                        out.push(Output::Send(self.round_confirm()));
                    }
                    return out;
                }
                // Twenty rounds: the last nonces are Na and Nb.
                let (na, nb) = self.nonces();
                (self.mac_key, self.key) = f5(&self.dhkey, &na, &nb, &self.a, &self.b);
                if self.initiator {
                    out.push(Output::Send(self.check_pdu()));
                }
                self.state = State::Check;
                out
            }
            (State::Random, PAIRING_RANDOM, _) if body.len() == 16 => {
                self.peer_nonce.copy_from_slice(body);
                let (na, nb) = self.nonces();
                let mut out = Vec::new();
                if self.initiator {
                    if f4(x(&self.peer), x(&self.own), &self.peer_nonce, 0) != self.peer_confirm {
                        return self.failed(CONFIRM_VALUE_FAILED);
                    }
                } else {
                    out.push(Output::Send(self.random_pdu()));
                }
                (self.mac_key, self.key) = f5(&self.dhkey, &na, &nb, &self.a, &self.b);
                let (pkax, pkbx) = if self.initiator {
                    (x(&self.own), x(&self.peer))
                } else {
                    (x(&self.peer), x(&self.own))
                };
                if self.method == Method::Numeric {
                    out.push(Output::Ask(Some(g2(pkax, pkbx, &na, &nb))));
                    self.asked = true;
                    self.state = State::Person;
                } else if !self.initiator {
                    // Just works, asked by the peer: may it?
                    out.push(Output::Ask(None));
                    self.asked = true;
                    self.state = State::Person;
                } else {
                    out.push(Output::Send(self.check_pdu()));
                    self.state = State::Check;
                }
                out
            }
            (State::Person, PAIRING_DHKEY_CHECK, false) if body.len() == 16 => {
                self.peer_check = Some(body.try_into().unwrap());
                Vec::new()
            }
            (State::Check, PAIRING_DHKEY_CHECK, _) if body.len() == 16 => {
                let check: [u8; 16] = body.try_into().unwrap();
                self.finish(check)
            }
            // The peer's identity: its IRK, then its address. It may come
            // before this side's controller says the link is encrypted.
            (State::Encrypting | State::Keys, IDENTITY_INFORMATION, _)
                if body.len() == 16 && self.take_keys & ID_KEY != 0 && self.peer_irk.is_none() =>
            {
                self.peer_irk = Some(body.try_into().unwrap());
                Vec::new()
            }
            (State::Encrypting | State::Keys, IDENTITY_ADDRESS_INFORMATION, _)
                if body.len() == 7 && self.peer_identity.is_none() =>
            {
                let Some(irk) = self.peer_irk else {
                    return self.failed(UNSPECIFIED);
                };
                self.peer_identity = Some(Identity {
                    irk,
                    address: body[1..].try_into().unwrap(),
                    kind: body[0],
                });
                self.hand_over()
            }
            _ => self.failed(UNSPECIFIED),
        }
    }

    /// This device's person answered [`Output::Ask`], or with no cancelled
    /// a passkey shown or asked for.
    pub fn confirm(&mut self, yes: bool, now: u64) -> Vec<Output> {
        if !yes && matches!(self.method, Method::Passkey { .. }) && self.state != State::Over {
            return self.failed(PASSKEY_ENTRY_FAILED);
        }
        if self.state != State::Person {
            return Vec::new();
        }
        self.at = now;
        if !yes {
            return self.failed(NUMERIC_COMPARISON_FAILED);
        }
        self.asked = false;
        if self.initiator {
            self.state = State::Check;
            alloc::vec![Output::Send(self.check_pdu())]
        } else {
            self.state = State::Check;
            match self.peer_check.take() {
                Some(check) => self.finish(check),
                None => Vec::new(),
            }
        }
    }

    /// Checks the peer's DHKey check; the responder then sends its own.
    fn finish(&mut self, check: [u8; 16]) -> Vec<Output> {
        let (na, nb) = self.nonces();
        let r = self.r();
        let expected = if self.initiator {
            // Eb = f6(MacKey, Nb, Na, 0, IOcapB, B, A).
            f6(
                &self.mac_key,
                &nb,
                &na,
                &r,
                &io_cap(&self.response),
                &self.b,
                &self.a,
            )
        } else {
            f6(
                &self.mac_key,
                &na,
                &nb,
                &r,
                &io_cap(&self.request),
                &self.a,
                &self.b,
            )
        };
        if !pinnacle_crypto::equal(&expected, &check) {
            return self.failed(DHKEY_CHECK_FAILED);
        }
        let mut out = Vec::new();
        if !self.initiator {
            out.push(Output::Send(self.check_pdu()));
        }
        self.state = State::Encrypting;
        self.private = [0; 32];
        out.push(Output::Done {
            key: self.key,
            compared: self.method != Method::JustWorks,
        });
        out
    }

    /// The link is encrypted with the key agreed: the keys are handed over,
    /// the responder's first, and [`Output::Keys`] ends the pairing.
    pub fn encrypted(&mut self, now: u64) -> Vec<Output> {
        if self.state != State::Encrypting {
            return Vec::new();
        }
        self.at = now;
        self.state = State::Keys;
        self.hand_over()
    }

    /// Sends this side's keys once it is its turn, and ends the pairing
    /// once both sides' are across.
    fn hand_over(&mut self) -> Vec<Output> {
        let mut out = Vec::new();
        if self.state != State::Keys {
            return out;
        }
        let peer_done = self.take_keys & ID_KEY == 0 || self.peer_identity.is_some();
        if !self.keys_sent && (!self.initiator || peer_done) {
            self.keys_sent = true;
            if self.send_keys & ID_KEY != 0
                && let Some(irk) = self.irk
            {
                let own = if self.initiator { self.a } else { self.b };
                let mut info = alloc::vec![IDENTITY_INFORMATION];
                info.extend_from_slice(&irk);
                let mut address = alloc::vec![IDENTITY_ADDRESS_INFORMATION, own[6]];
                address.extend_from_slice(&own[..6]);
                out.push(Output::Send(info));
                out.push(Output::Send(address));
            }
        }
        if self.keys_sent && peer_done {
            self.state = State::Over;
            out.push(Output::Keys(self.peer_identity));
        }
        out
    }

    /// R for the DHKey checks: the passkey in passkey entry, else zero.
    fn r(&self) -> [u8; 16] {
        let mut r = [0u8; 16];
        if matches!(self.method, Method::Passkey { .. }) {
            r[..4].copy_from_slice(&self.passkey.unwrap_or(0).to_le_bytes());
        }
        r
    }

    /// (Na, Nb): the initiator's nonce and the responder's.
    fn nonces(&self) -> ([u8; 16], [u8; 16]) {
        if self.initiator {
            (self.nonce, self.peer_nonce)
        } else {
            (self.peer_nonce, self.nonce)
        }
    }

    fn public_key_pdu(&self) -> Vec<u8> {
        let mut p = alloc::vec![PAIRING_PUBLIC_KEY];
        p.extend_from_slice(&self.own);
        p
    }

    fn random_pdu(&self) -> Vec<u8> {
        let mut p = alloc::vec![PAIRING_RANDOM];
        p.extend_from_slice(&self.nonce);
        p
    }

    /// This side's DHKey check: Ea as the initiator, Eb as the responder.
    fn check_pdu(&self) -> Vec<u8> {
        let (na, nb) = self.nonces();
        let r = self.r();
        let e = if self.initiator {
            f6(
                &self.mac_key,
                &na,
                &nb,
                &r,
                &io_cap(&self.request),
                &self.a,
                &self.b,
            )
        } else {
            f6(
                &self.mac_key,
                &nb,
                &na,
                &r,
                &io_cap(&self.response),
                &self.b,
                &self.a,
            )
        };
        let mut p = alloc::vec![PAIRING_DHKEY_CHECK];
        p.extend_from_slice(&e);
        p
    }

    /// The peer's public key taken and the DHKey agreed: `None` for a
    /// point off the curve, or our own key sent back to us.
    fn agree(&mut self, body: &[u8]) -> Option<[u8; 32]> {
        let peer: [u8; 64] = body.try_into().ok()?;
        if peer[..32] == self.own[..32] {
            return None;
        }
        self.peer = peer;
        let mut big = [0u8; 64];
        for i in 0..32 {
            big[i] = peer[31 - i];
            big[32 + i] = peer[63 - i];
        }
        let mut dhkey = p256::shared(&self.private, &big)?;
        dhkey.reverse();
        Some(dhkey)
    }
}

/// IOcap for f6: a request's or response's AuthReq, OOB flag and IO, as
/// over the air (IO first).
fn io_cap(features: &[u8; 7]) -> [u8; 3] {
    [features[1], features[2], features[3]]
}

/// How two devices pair.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Method {
    JustWorks,
    Numeric,
    /// Which sides show the passkey; a side that does not types it (with
    /// a keyboard on both, both people type one they chose).
    Passkey {
        initiator_shows: bool,
        responder_shows: bool,
    },
}

/// How two devices pair, from what each can show and take (Vol 3 Part H
/// 2.3.5.1, the table for Secure Connections).
fn method(request: &[u8; 7], response: &[u8; 7]) -> Method {
    if (request[3] | response[3]) & MITM == 0 {
        return Method::JustWorks;
    }
    let (i, r) = (request[1], response[1]);
    let display = |io: u8| io == DISPLAY_YES_NO || io == KEYBOARD_DISPLAY;
    if i == NO_INPUT_NO_OUTPUT || r == NO_INPUT_NO_OUTPUT {
        return Method::JustWorks;
    }
    if display(i) && display(r) {
        return Method::Numeric;
    }
    // A keyboard types; one with a display too types only beside a display
    // without buttons, and otherwise shows.
    let initiator_types = i == KEYBOARD_ONLY || i == KEYBOARD_DISPLAY && r == DISPLAY_ONLY;
    let responder_types = r == KEYBOARD_ONLY || r == KEYBOARD_DISPLAY && i == DISPLAY_ONLY;
    if !initiator_types && !responder_types {
        // Displays only, nothing to type on.
        return Method::JustWorks;
    }
    Method::Passkey {
        initiator_shows: !initiator_types,
        responder_shows: !responder_types,
    }
}