garage44.eu/jeroen/pinnacle

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

.. /tls/src/client.rs

raw

//! The TLS 1.3 client (RFC 8446), as a state machine with no I/O of its
//! own: what came from the server goes in ([`Client::receive`]), what is to
//! go to it comes out ([`Client::take_output`]), and the application's data
//! goes in and out in the clear ([`Client::write`], [`Client::read`]).
//!
//! It offers X25519 for the key exchange and three cipher suites:
//! AES-128-GCM and AES-256-GCM (on the core's AES instructions where it has
//! them) and ChaCha20-Poly1305. It checks the server's certificates
//! ([`crate::x509`]) and its signature over the handshake (ECDSA on P-256
//! or P-384, Ed25519, RSA-PSS), and exports keys from the connection
//! ([`Client::export`]). It does not resume sessions, send early data or
//! answer a HelloRetryRequest: X25519 is what servers take.

use crate::x509::{self, Certificate, Key};
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use pinnacle_crypto::aes::Gcm;
use pinnacle_crypto::rsa::{self, Hash};
use pinnacle_crypto::sha2::{self, Sha256, Sha384};
use pinnacle_crypto::{aead, ecdsa, ed25519, x25519};

pub(crate) const HANDSHAKE: u8 = 22;
pub(crate) const APPLICATION_DATA: u8 = 23;
pub(crate) const ALERT: u8 = 21;
pub(crate) const CHANGE_CIPHER_SPEC: u8 = 20;

pub(crate) const CLIENT_HELLO: u8 = 1;
pub(crate) const SERVER_HELLO: u8 = 2;
const NEW_SESSION_TICKET: u8 = 4;
pub(crate) const ENCRYPTED_EXTENSIONS: u8 = 8;
pub(crate) const CERTIFICATE: u8 = 11;
pub(crate) const CERTIFICATE_VERIFY: u8 = 15;
pub(crate) const FINISHED: u8 = 20;
const KEY_UPDATE: u8 = 24;

/// The most a record carries in the clear.
pub(crate) const MAX_FRAGMENT: usize = 1 << 14;

/// What a ServerHello's random is when it is a HelloRetryRequest.
pub(crate) const RETRY: [u8; 32] = [
    0xcf, 0x21, 0xad, 0x74, 0xe5, 0x9a, 0x61, 0x11, 0xbe, 0x1d, 0x8c, 0x02, 0x1e, 0x65, 0xb8, 0x91, 0xc2,
    0xa2, 0x11, 0x16, 0x7a, 0xbb, 0x8c, 0x5e, 0x07, 0x9e, 0x09, 0xe2, 0xc8, 0xa8, 0x33, 0x9c,
];

/// The signature schemes offered, in the order preferred.
const SCHEMES: [u16; 9] = [
    0x0403, 0x0503, 0x0807, 0x0804, 0x0805, 0x0806, 0x0401, 0x0501, 0x0601,
];

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum Suite {
    Aes128Gcm,
    Aes256Gcm,
    ChaCha20Poly1305,
}

impl Suite {
    pub(crate) fn from_id(id: u16) -> Option<Suite> {
        match id {
            0x1301 => Some(Suite::Aes128Gcm),
            0x1302 => Some(Suite::Aes256Gcm),
            0x1303 => Some(Suite::ChaCha20Poly1305),
            _ => None,
        }
    }

    pub(crate) fn hash_len(self) -> usize {
        match self {
            Suite::Aes256Gcm => 48,
            _ => 32,
        }
    }

    pub(crate) fn key_len(self) -> usize {
        match self {
            Suite::Aes128Gcm => 16,
            _ => 32,
        }
    }

    pub(crate) fn hash(self, data: &[u8]) -> Vec<u8> {
        if self.hash_len() == 48 {
            Sha384::digest(data).to_vec()
        } else {
            Sha256::digest(data).to_vec()
        }
    }

    pub(crate) fn hmac(self, key: &[u8], data: &[u8]) -> Vec<u8> {
        if self.hash_len() == 48 {
            sha2::hmac384(key, &[data]).to_vec()
        } else {
            sha2::hmac(key, &[data]).to_vec()
        }
    }

    pub(crate) fn extract(self, salt: &[u8], ikm: &[u8]) -> Vec<u8> {
        if self.hash_len() == 48 {
            sha2::hkdf384_extract(salt, ikm).to_vec()
        } else {
            sha2::hkdf_extract(salt, ikm).to_vec()
        }
    }

    /// HKDF-Expand-Label (RFC 8446 7.1).
    pub(crate) fn expand_label(self, secret: &[u8], label: &str, context: &[u8], len: usize) -> Vec<u8> {
        let mut info = Vec::new();
        info.extend_from_slice(&(len as u16).to_be_bytes());
        info.push((6 + label.len()) as u8);
        info.extend_from_slice(b"tls13 ");
        info.extend_from_slice(label.as_bytes());
        info.push(context.len() as u8);
        info.extend_from_slice(context);
        let mut out = vec![0u8; len];
        if self.hash_len() == 48 {
            sha2::hkdf384_expand(secret, &info, &mut out);
        } else {
            sha2::hkdf_expand(secret, &info, &mut out);
        }
        out
    }

    /// The key schedule (RFC 8446 7.1) from the X25519 secret and the hash
    /// of ClientHello and ServerHello: the client's and the server's
    /// handshake traffic secrets, and the master secret.
    pub(crate) fn handshake_secrets(self, shared: &[u8], hash: &[u8]) -> [Vec<u8>; 3] {
        let len = self.hash_len();
        let zeros = vec![0u8; len];
        let empty = self.hash(&[]);
        let early = self.extract(&zeros, &zeros);
        let derived = self.expand_label(&early, "derived", &empty, len);
        let handshake = self.extract(&derived, shared);
        let client = self.expand_label(&handshake, "c hs traffic", hash, len);
        let server = self.expand_label(&handshake, "s hs traffic", hash, len);
        let derived = self.expand_label(&handshake, "derived", &empty, len);
        [client, server, self.extract(&derived, &zeros)]
    }

    /// The exporter (RFC 8446 7.5): `len` bytes for `label` and `context`
    /// from the exporter master secret.
    pub(crate) fn export(self, exporter: &[u8], label: &str, context: &[u8], len: usize) -> Vec<u8> {
        let secret = self.expand_label(exporter, label, &self.hash(&[]), self.hash_len());
        self.expand_label(&secret, "exporter", &self.hash(context), len)
    }
}

/// The handshake's running hash.
#[derive(Clone)]
pub(crate) enum Transcript {
    Sha256(Sha256),
    Sha384(Sha384),
}

impl Transcript {
    pub(crate) fn new(suite: Suite) -> Transcript {
        if suite.hash_len() == 48 {
            Transcript::Sha384(Sha384::new())
        } else {
            Transcript::Sha256(Sha256::new())
        }
    }

    pub(crate) fn update(&mut self, data: &[u8]) {
        match self {
            Transcript::Sha256(h) => h.update(data),
            Transcript::Sha384(h) => h.update(data),
        }
    }

    pub(crate) fn hash(&self) -> Vec<u8> {
        match self.clone() {
            Transcript::Sha256(h) => h.finish().to_vec(),
            Transcript::Sha384(h) => h.finish().to_vec(),
        }
    }
}

enum Cipher {
    Gcm(alloc::boxed::Box<Gcm>),
    ChaCha([u8; 32]),
}

/// One direction's record protection: its key, IV and sequence number.
pub(crate) struct Direction {
    suite: Suite,
    secret: Vec<u8>,
    cipher: Cipher,
    iv: [u8; 12],
    seq: u64,
}

impl Direction {
    pub(crate) fn new(suite: Suite, secret: &[u8]) -> Direction {
        let key = suite.expand_label(secret, "key", &[], suite.key_len());
        let iv = suite.expand_label(secret, "iv", &[], 12);
        let cipher = match suite {
            Suite::ChaCha20Poly1305 => Cipher::ChaCha(key[..32].try_into().unwrap()),
            _ => Cipher::Gcm(alloc::boxed::Box::new(
                Gcm::new(&key).expect("a GCM key of 16 or 32 bytes"),
            )),
        };
        Direction {
            suite,
            secret: secret.to_vec(),
            cipher,
            iv: iv.try_into().unwrap(),
            seq: 0,
        }
    }

    fn nonce(&self) -> [u8; 12] {
        let mut nonce = self.iv;
        for (n, s) in nonce[4..].iter_mut().zip(self.seq.to_be_bytes()) {
            *n ^= s;
        }
        nonce
    }

    /// A record carrying `data` of `kind`, encrypted.
    pub(crate) fn seal(&mut self, kind: u8, data: &[u8]) -> Vec<u8> {
        let mut inner = data.to_vec();
        inner.push(kind);
        let len = inner.len() + 16;
        let header = [APPLICATION_DATA, 3, 3, (len >> 8) as u8, len as u8];
        let nonce = self.nonce();
        let tag = match &self.cipher {
            Cipher::Gcm(gcm) => gcm.seal(&nonce, &header, &mut inner),
            Cipher::ChaCha(key) => aead::seal(key, &nonce, &header, &mut inner),
        };
        self.seq += 1;
        let mut record = header.to_vec();
        record.extend_from_slice(&inner);
        record.extend_from_slice(&tag);
        record
    }

    /// An encrypted record's kind and content.
    pub(crate) fn open(&mut self, header: &[u8], body: &[u8]) -> Result<(u8, Vec<u8>), Error> {
        if body.len() < 17 {
            return Err(Error::Protocol("a record too short to be encrypted"));
        }
        let (data, tag) = body.split_at(body.len() - 16);
        let mut data = data.to_vec();
        let tag: [u8; 16] = tag.try_into().unwrap();
        let nonce = self.nonce();
        let opened = match &self.cipher {
            Cipher::Gcm(gcm) => gcm.open(&nonce, header, &mut data, &tag),
            Cipher::ChaCha(key) => aead::open(key, &nonce, header, &mut data, &tag),
        };
        if !opened {
            return Err(Error::Protocol("a record that does not open"));
        }
        self.seq += 1;
        // The content, then its kind, then zeros.
        let end = data
            .iter()
            .rposition(|&b| b != 0)
            .ok_or(Error::Protocol("a record of padding only"))?;
        let kind = data[end];
        data.truncate(end);
        Ok((kind, data))
    }

    /// The next generation of this direction's keys (a KeyUpdate).
    pub(crate) fn updated(&self) -> Direction {
        let len = self.suite.hash_len();
        Direction::new(
            self.suite,
            &self.suite.expand_label(&self.secret, "traffic upd", &[], len),
        )
    }
}

/// Whom the server must prove to be.
pub enum Verify {
    /// A chain to one of these roots (DER), for the host, valid `now`
    /// (seconds since 1970).
    Roots { roots: Vec<Vec<u8>>, now: i64 },
    /// A chain to one of these roots for the host, at no time in
    /// particular: for a device whose clock is not set yet, which then
    /// believes a time the server gives only within [`Client::window`].
    Untimed { roots: Vec<Vec<u8>> },
    /// Exactly this certificate (DER), whatever signed it: a server known
    /// beforehand, such as one's own package source.
    Pinned(Vec<u8>),
}

pub struct Config {
    /// The name the server is reached by, sent to it and checked against
    /// its certificate.
    pub host: String,
    pub verify: Verify,
    /// The shortest RSA key accepted: 2048 bits; less only to replay old
    /// traces in tests.
    pub min_rsa_bits: usize,
    /// The application protocols offered, the preferred first (ALPN,
    /// RFC 7301: "h2", "http/1.1"); none, and none is chosen.
    pub alpn: Vec<String>,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Error {
    /// The server broke the protocol (what it did).
    Protocol(&'static str),
    /// The server's certificates were not accepted.
    Certificate(x509::Error),
    /// Its signature over the handshake, or its Finished, did not check.
    Forged,
    /// It sent an alert (its description).
    Alert(u8),
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum State {
    ServerHello,
    EncryptedExtensions,
    Certificate,
    CertificateVerify,
    Finished,
    Connected,
    Closed,
}

pub struct Client {
    config: Config,
    state: State,
    /// Our X25519 secret, until the key exchange.
    secret: [u8; 32],
    session_id: Vec<u8>,
    /// The ClientHello, kept until the suite says which hash it goes into.
    hello: Vec<u8>,
    suite: Option<Suite>,
    transcript: Option<Transcript>,
    /// The exporter master secret, once connected (RFC 8446 7.5).
    exporter: Vec<u8>,
    client_handshake: Vec<u8>,
    server_handshake: Vec<u8>,
    master: Vec<u8>,
    read: Option<Direction>,
    write: Option<Direction>,
    /// Bytes received and not yet a whole record; handshake bytes not yet
    /// a whole message.
    records: Vec<u8>,
    messages: Vec<u8>,
    /// The server's certificates, its own first.
    chain: Vec<Vec<u8>>,
    /// When all of them are valid, as [`Verify::Untimed`] found it.
    window: Option<(i64, i64)>,
    output: Vec<u8>,
    received: Vec<u8>,
    /// The application protocol the server chose.
    protocol: Option<String>,
}

/// `data` behind its length, in `bytes` big-endian bytes.
pub(crate) fn with_len(bytes: usize, data: &[u8]) -> Vec<u8> {
    let mut out = data.len().to_be_bytes()[8 - bytes..].to_vec();
    out.extend_from_slice(data);
    out
}

/// Takes `n` bytes off the front.
pub(crate) fn take<'a>(data: &mut &'a [u8], n: usize) -> Result<&'a [u8], Error> {
    if data.len() < n {
        return Err(Error::Protocol("a message cut short"));
    }
    let (head, rest) = data.split_at(n);
    *data = rest;
    Ok(head)
}

pub(crate) fn take_u16(data: &mut &[u8]) -> Result<u16, Error> {
    let b = take(data, 2)?;
    Ok(u16::from_be_bytes([b[0], b[1]]))
}

/// Takes a length (of `bytes` bytes) and that many bytes.
pub(crate) fn take_vec<'a>(data: &mut &'a [u8], bytes: usize) -> Result<&'a [u8], Error> {
    let len = take(data, bytes)?
        .iter()
        .fold(0usize, |l, &b| (l << 8) | usize::from(b));
    take(data, len)
}

impl Client {
    /// Starts a handshake with `config.host`: `random` and `secret` (the
    /// X25519 secret) are fresh random bytes, as is `session_id` (sent for
    /// middleboxes that expect TLS 1.2's look).
    pub fn new(config: Config, random: [u8; 32], secret: [u8; 32], session_id: [u8; 32]) -> Client {
        let public = x25519::public(&secret);
        let mut extensions = Vec::new();
        let mut extension = |kind: u16, data: Vec<u8>| {
            extensions.extend_from_slice(&kind.to_be_bytes());
            extensions.extend_from_slice(&with_len(2, &data));
        };
        // server_name: one host_name.
        let mut name = vec![0];
        name.extend_from_slice(&with_len(2, config.host.as_bytes()));
        extension(0x0000, with_len(2, &name));
        // supported_groups: X25519.
        extension(0x000a, with_len(2, &[0x00, 0x1d]));
        let schemes: Vec<u8> = SCHEMES.iter().flat_map(|s| s.to_be_bytes()).collect();
        extension(0x000d, with_len(2, &schemes));
        // supported_versions: TLS 1.3.
        extension(0x002b, with_len(1, &[0x03, 0x04]));
        // key_share: X25519.
        let mut share = vec![0x00, 0x1d];
        share.extend_from_slice(&with_len(2, &public));
        extension(0x0033, with_len(2, &share));
        // application_layer_protocol_negotiation: the protocols offered.
        if !config.alpn.is_empty() {
            let names: Vec<u8> = config
                .alpn
                .iter()
                .flat_map(|p| with_len(1, p.as_bytes()))
                .collect();
            extension(0x0010, with_len(2, &names));
        }
        let mut body = vec![0x03, 0x03];
        body.extend_from_slice(&random);
        body.extend_from_slice(&with_len(1, &session_id));
        body.extend_from_slice(&with_len(2, &[0x13, 0x01, 0x13, 0x02, 0x13, 0x03]));
        body.extend_from_slice(&[1, 0]);
        body.extend_from_slice(&with_len(2, &extensions));
        let mut hello = vec![CLIENT_HELLO];
        hello.extend_from_slice(&with_len(3, &body));
        Client::with_hello(config, hello, secret)
    }

    /// Starts with a ClientHello made elsewhere (a trace's, in a test),
    /// its X25519 key share the one of `secret`.
    pub fn with_hello(config: Config, hello: Vec<u8>, secret: [u8; 32]) -> Client {
        // The session id: after the type, length, version and random.
        let session_id = hello
            .get(38)
            .and_then(|&len| hello.get(39..39 + usize::from(len)))
            .unwrap_or_default()
            .to_vec();
        let mut output = vec![HANDSHAKE, 3, 1];
        output.extend_from_slice(&with_len(2, &hello));
        Client {
            config,
            state: State::ServerHello,
            secret,
            session_id,
            hello,
            suite: None,
            transcript: None,
            exporter: Vec::new(),
            client_handshake: Vec::new(),
            server_handshake: Vec::new(),
            master: Vec::new(),
            read: None,
            write: None,
            records: Vec::new(),
            messages: Vec::new(),
            chain: Vec::new(),
            window: None,
            output,
            received: Vec::new(),
            protocol: None,
        }
    }

    /// What is to be sent to the server.
    pub fn take_output(&mut self) -> Vec<u8> {
        core::mem::take(&mut self.output)
    }

    /// The application's data the server sent, in the clear.
    pub fn read(&mut self) -> Vec<u8> {
        core::mem::take(&mut self.received)
    }

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

    /// With [`Verify::Untimed`], once the server's certificates are
    /// checked: when every one of them is valid, seconds since 1970 (from,
    /// until).
    pub fn window(&self) -> Option<(i64, i64)> {
        self.window
    }

    /// The application protocol the server chose of those offered
    /// ([`Config::alpn`]), once it has said.
    pub fn protocol(&self) -> Option<&str> {
        self.protocol.as_deref()
    }

    /// Keying material both ends derive from the connection (RFC 5705 as
    /// RFC 8446 7.5 has it), once connected: what Network Time Security
    /// takes its keys from.
    pub fn export(&self, label: &str, context: &[u8], len: usize) -> Option<Vec<u8>> {
        self.connected()
            .then(|| self.suite().export(&self.exporter, label, context, len))
    }

    /// The protocol EncryptedExtensions names, which must be one offered.
    fn chosen_protocol(&self, mut body: &[u8]) -> Result<Option<String>, Error> {
        let mut extensions = take_vec(&mut body, 2)?;
        while !extensions.is_empty() {
            let kind = take_u16(&mut extensions)?;
            let mut data = take_vec(&mut extensions, 2)?;
            if kind == 0x0010 {
                let mut list = take_vec(&mut data, 2)?;
                let name = take_vec(&mut list, 1)?;
                return match self.config.alpn.iter().find(|p| p.as_bytes() == name) {
                    Some(p) if list.is_empty() => Ok(Some(p.clone())),
                    _ => Err(Error::Protocol("an application protocol not offered")),
                };
            }
        }
        Ok(None)
    }

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

    /// Sends the application's `data` (once connected).
    pub fn write(&mut self, data: &[u8]) {
        if self.state != State::Connected {
            return;
        }
        let write = self.write.as_mut().expect("keys once connected");
        for chunk in data.chunks(MAX_FRAGMENT) {
            let record = write.seal(APPLICATION_DATA, chunk);
            self.output.extend_from_slice(&record);
        }
    }

    /// Says it is done (close_notify).
    pub fn close(&mut self) {
        if let Some(write) = self.write.as_mut() {
            let record = write.seal(ALERT, &[1, 0]);
            self.output.extend_from_slice(&record);
        }
    }

    /// Takes in what came from the server.
    pub fn receive(&mut self, data: &[u8]) -> Result<(), Error> {
        self.records.extend_from_slice(data);
        while self.records.len() >= 5 {
            let len = usize::from(u16::from_be_bytes([self.records[3], self.records[4]]));
            if len > MAX_FRAGMENT + 256 {
                return Err(Error::Protocol("a record too long"));
            }
            if self.records.len() < 5 + len {
                break;
            }
            let record: Vec<u8> = self.records.drain(..5 + len).collect();
            self.record(&record[..5], &record[5..])?;
        }
        Ok(())
    }

    fn record(&mut self, header: &[u8], body: &[u8]) -> Result<(), Error> {
        let (kind, content) = match header[0] {
            // Sent for middleboxes; means nothing in TLS 1.3.
            CHANGE_CIPHER_SPEC if body == [1] && self.state != State::Connected => return Ok(()),
            APPLICATION_DATA => {
                let read = self
                    .read
                    .as_mut()
                    .ok_or(Error::Protocol("encrypted data before the keys"))?;
                read.open(header, body)?
            }
            HANDSHAKE if self.state == State::ServerHello => (HANDSHAKE, body.to_vec()),
            ALERT if body.len() == 2 => return Err(Error::Alert(body[1])),
            _ => return Err(Error::Protocol("a record of an unexpected kind")),
        };
        match kind {
            HANDSHAKE => {
                self.messages.extend_from_slice(&content);
                while self.messages.len() >= 4 {
                    let len = (usize::from(self.messages[1]) << 16)
                        | (usize::from(self.messages[2]) << 8)
                        | usize::from(self.messages[3]);
                    if self.messages.len() < 4 + len {
                        break;
                    }
                    let message: Vec<u8> = self.messages.drain(..4 + len).collect();
                    self.message(&message)?;
                }
                Ok(())
            }
            APPLICATION_DATA if self.state == State::Connected => {
                self.received.extend_from_slice(&content);
                Ok(())
            }
            ALERT if content == [1, 0] => {
                self.state = State::Closed;
                Ok(())
            }
            ALERT if content.len() == 2 => Err(Error::Alert(content[1])),
            _ => Err(Error::Protocol("content of an unexpected kind")),
        }
    }

    fn transcript(&mut self) -> &mut Transcript {
        self.transcript
            .as_mut()
            .expect("a transcript once the suite is known")
    }

    fn suite(&self) -> Suite {
        self.suite.expect("the suite is known")
    }

    fn message(&mut self, message: &[u8]) -> Result<(), Error> {
        let body = &message[4..];
        match (self.state, message[0]) {
            (State::ServerHello, SERVER_HELLO) => self.server_hello(message),
            (State::EncryptedExtensions, ENCRYPTED_EXTENSIONS) => {
                self.protocol = self.chosen_protocol(body)?;
                self.transcript().update(message);
                self.state = State::Certificate;
                Ok(())
            }
            (State::Certificate, CERTIFICATE) => self.certificate(message),
            (State::CertificateVerify, CERTIFICATE_VERIFY) => self.certificate_verify(message),
            (State::Finished, FINISHED) => self.finished(message),
            // Tickets for resuming, which this client does not.
            (State::Connected, NEW_SESSION_TICKET) => Ok(()),
            (State::Connected, KEY_UPDATE) if body.len() == 1 => {
                let read = self.read.as_ref().unwrap().updated();
                self.read = Some(read);
                if body[0] == 1 {
                    let write = self.write.as_mut().unwrap();
                    let record = write.seal(HANDSHAKE, &[KEY_UPDATE, 0, 0, 1, 0]);
                    self.output.extend_from_slice(&record);
                    let write = write.updated();
                    self.write = Some(write);
                }
                Ok(())
            }
            _ => Err(Error::Protocol("a handshake message out of turn")),
        }
    }

    fn server_hello(&mut self, message: &[u8]) -> Result<(), Error> {
        let mut b = &message[4..];
        if take(&mut b, 2)? != [3, 3] {
            return Err(Error::Protocol("a ServerHello of another version"));
        }
        if take(&mut b, 32)? == RETRY {
            return Err(Error::Protocol(
                "a HelloRetryRequest, which this client does not answer",
            ));
        }
        if take_vec(&mut b, 1)? != &self.session_id[..] {
            return Err(Error::Protocol("a ServerHello for another session"));
        }
        let suite = Suite::from_id(take_u16(&mut b)?).ok_or(Error::Protocol("a cipher suite not offered"))?;
        if take(&mut b, 1)? != [0] {
            return Err(Error::Protocol("compression"));
        }
        let mut extensions = take_vec(&mut b, 2)?;
        let (mut version, mut share) = (false, None);
        while !extensions.is_empty() {
            let kind = take_u16(&mut extensions)?;
            let mut data = take_vec(&mut extensions, 2)?;
            match kind {
                0x002b => version = data == [3, 4],
                0x0033 => {
                    if take_u16(&mut data)? != 0x001d {
                        return Err(Error::Protocol("a key share of a group not offered"));
                    }
                    let key: [u8; 32] = take_vec(&mut data, 2)?
                        .try_into()
                        .map_err(|_| Error::Protocol("an X25519 share not 32 bytes"))?;
                    share = Some(key);
                }
                _ => {}
            }
        }
        if !version {
            return Err(Error::Protocol("a server not speaking TLS 1.3"));
        }
        let share = share.ok_or(Error::Protocol("no key share"))?;
        let shared = x25519::x25519(&self.secret, &share);
        self.secret = [0; 32];
        if shared == [0; 32] {
            return Err(Error::Protocol("a key share of a small order"));
        }
        self.suite = Some(suite);
        let mut transcript = Transcript::new(suite);
        transcript.update(&core::mem::take(&mut self.hello));
        transcript.update(message);
        [self.client_handshake, self.server_handshake, self.master] =
            suite.handshake_secrets(&shared, &transcript.hash());
        self.read = Some(Direction::new(suite, &self.server_handshake));
        self.write = Some(Direction::new(suite, &self.client_handshake));
        self.transcript = Some(transcript);
        self.state = State::EncryptedExtensions;
        Ok(())
    }

    fn certificate(&mut self, message: &[u8]) -> Result<(), Error> {
        let mut b = &message[4..];
        if !take_vec(&mut b, 1)?.is_empty() {
            return Err(Error::Protocol("a certificate request context"));
        }
        let mut list = take_vec(&mut b, 3)?;
        while !list.is_empty() {
            self.chain.push(take_vec(&mut list, 3)?.to_vec());
            take_vec(&mut list, 2)?; // each certificate's extensions
        }
        let chain: Vec<&[u8]> = self.chain.iter().map(|c| &c[..]).collect();
        match &self.config.verify {
            Verify::Roots { roots, now } => {
                let roots: Vec<&[u8]> = roots.iter().map(|r| &r[..]).collect();
                x509::verify_chain(&chain, &roots, &self.config.host, *now).map_err(Error::Certificate)?;
            }
            Verify::Untimed { roots } => {
                let roots: Vec<&[u8]> = roots.iter().map(|r| &r[..]).collect();
                let window = x509::chain_window(&chain, &roots, &self.config.host);
                self.window = Some(window.map_err(Error::Certificate)?);
            }
            Verify::Pinned(expected) => {
                if chain.first() != Some(&&expected[..]) {
                    return Err(Error::Certificate(x509::Error::Untrusted));
                }
            }
        }
        self.transcript().update(message);
        self.state = State::CertificateVerify;
        Ok(())
    }

    fn certificate_verify(&mut self, message: &[u8]) -> Result<(), Error> {
        let mut b = &message[4..];
        let scheme = take_u16(&mut b)?;
        let signature = take_vec(&mut b, 2)?;
        let mut content = vec![0x20u8; 64];
        content.extend_from_slice(b"TLS 1.3, server CertificateVerify\0");
        content.extend_from_slice(&self.transcript().hash());
        let leaf = Certificate::parse(&self.chain[0]).ok_or(Error::Certificate(x509::Error::Unreadable))?;
        let good = match (scheme, leaf.key) {
            (0x0403, Key::P256(point)) => {
                ecdsa::verify(&ecdsa::P256, point, &Sha256::digest(&content), signature)
            }
            (0x0503, Key::P384(point)) => {
                ecdsa::verify(&ecdsa::P384, point, &Sha384::digest(&content), signature)
            }
            (0x0807, Key::Ed25519(public)) => signature
                .try_into()
                .is_ok_and(|signature| ed25519::verify(public, &content, signature)),
            (0x0804..=0x0806, Key::Rsa { n, e }) => {
                let hash = [Hash::Sha256, Hash::Sha384, Hash::Sha512][usize::from(scheme - 0x0804)];
                rsa::PublicKey::with_minimum(n, e, self.config.min_rsa_bits)
                    .is_some_and(|key| key.verify_pss(hash, &content, signature))
            }
            _ => false,
        };
        if !good {
            return Err(Error::Forged);
        }
        self.transcript().update(message);
        self.state = State::Finished;
        Ok(())
    }

    fn finished(&mut self, message: &[u8]) -> Result<(), Error> {
        let suite = self.suite();
        let len = suite.hash_len();
        let key = suite.expand_label(&self.server_handshake, "finished", &[], len);
        let expected = suite.hmac(&key, &self.transcript().hash());
        if !pinnacle_crypto::equal(&expected, &message[4..]) {
            return Err(Error::Forged);
        }
        self.transcript().update(message);
        let hash = self.transcript().hash();
        let client_traffic = suite.expand_label(&self.master, "c ap traffic", &hash, len);
        let server_traffic = suite.expand_label(&self.master, "s ap traffic", &hash, len);
        self.exporter = suite.expand_label(&self.master, "exp master", &hash, len);
        // Ours: after a ChangeCipherSpec when a session id said to look
        // like TLS 1.2.
        if !self.session_id.is_empty() {
            self.output
                .extend_from_slice(&[CHANGE_CIPHER_SPEC, 3, 3, 0, 1, 1]);
        }
        let key = suite.expand_label(&self.client_handshake, "finished", &[], len);
        let verify = suite.hmac(&key, &hash);
        let mut finished = vec![FINISHED];
        finished.extend_from_slice(&with_len(3, &verify));
        let record = self.write.as_mut().unwrap().seal(HANDSHAKE, &finished);
        self.output.extend_from_slice(&record);
        self.read = Some(Direction::new(suite, &server_traffic));
        self.write = Some(Direction::new(suite, &client_traffic));
        self.state = State::Connected;
        Ok(())
    }
}