garage44.eu/jeroen/pinnacle

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

.. /p2p/src/session.rs

raw

//! End-to-end encrypted sessions between two contacts, after the pattern of
//! Noise IK: the initiator knows the responder's static key-exchange key
//! (from its card); one message each way agrees on keys mixing four
//! Diffie–Hellman results, two of them with fresh ephemeral keys, so a
//! session's keys stay secret even if a device's long-term keys are stolen
//! later. Then each message is ChaCha20-Poly1305 with its own counter, and
//! a replayed or reordered-too-far counter is refused.
//!
//! HELLO:   e_i (32) ‖ seal(k1, s_i card (160)) ‖ seal(k2, session id (8) ‖ stamp (8))
//! WELCOME: session id (8) ‖ e_r (32) ‖ seal(k3, stamp (8))
//! DATA:    session id (8) ‖ counter (8) ‖ seal(direction key, payload)
//!
//! A stamp only ever grows on one device, across restarts too (`Node`'s
//! epoch): a responder refuses a HELLO not newer than the last it took
//! from that contact, so a recorded one replayed cannot replace a session
//! or move where the contact is answered, as WireGuard's TAI64N does.

use crate::identity::{Card, Identity, Key};
use alloc::vec::Vec;
use pinnacle_crypto::{aead, sha2, x25519};

const TAG: usize = 16;
pub const HELLO_SIZE: usize = 32 + Card::SIZE + TAG + 16 + TAG;
pub const WELCOME_SIZE: usize = 8 + 32 + 8 + TAG;

/// Chaining key and handshake hash, as Noise keeps them.
#[derive(Clone)]
struct Chain {
    ck: [u8; 32],
    h: [u8; 32],
}

impl Chain {
    fn new(responder_dh: &Key) -> Chain {
        let h = sha2::Sha256::digest(&[b"pinnacle ik v2".as_slice(), responder_dh].concat());
        Chain { ck: h, h }
    }

    fn mix_hash(&mut self, data: &[u8]) {
        let mut s = sha2::Sha256::new();
        s.update(&self.h);
        s.update(data);
        self.h = s.finish();
    }

    /// Mixes a DH result into the chain; returns a key for the next message.
    fn mix_key(&mut self, dh: &[u8]) -> [u8; 32] {
        let mut out = [0u8; 64];
        sha2::hkdf(&self.ck, dh, b"", &mut out);
        self.ck.copy_from_slice(&out[..32]);
        out[32..].try_into().unwrap()
    }

    fn seal(&mut self, key: &[u8; 32], plain: &[u8]) -> Vec<u8> {
        let mut data = plain.to_vec();
        let tag = aead::seal(key, &[0; 12], &self.h, &mut data);
        data.extend_from_slice(&tag);
        self.mix_hash(&data);
        data
    }

    fn open(&mut self, key: &[u8; 32], sealed: &[u8]) -> Option<Vec<u8>> {
        let (data, tag) = sealed.split_at(sealed.len().checked_sub(TAG)?);
        let mut plain = data.to_vec();
        if !aead::open(key, &[0; 12], &self.h, &mut plain, tag.try_into().ok()?) {
            return None;
        }
        self.mix_hash(sealed);
        Some(plain)
    }

    /// The two transport keys: initiator → responder, responder → initiator.
    fn split(&self) -> ([u8; 32], [u8; 32]) {
        let mut out = [0u8; 64];
        sha2::hkdf(&self.ck, b"", b"transport", &mut out);
        (out[..32].try_into().unwrap(), out[32..].try_into().unwrap())
    }
}

/// An initiator waiting for WELCOME.
pub struct Pending {
    pub id: u64,
    chain: Chain,
    ephemeral: [u8; 32],
    ephemeral_public: Key,
}

/// HELLO to `peer`, stamped `stamp`: returns the message and what to keep
/// for its answer.
pub fn hello(
    me: &Identity,
    my_card: &Card,
    peer_dh: &Key,
    ephemeral: [u8; 32],
    id: u64,
    stamp: u64,
) -> (Vec<u8>, Pending) {
    let mut chain = Chain::new(peer_dh);
    let e = x25519::public(&ephemeral);
    chain.mix_hash(&e);
    let k1 = chain.mix_key(&x25519::x25519(&ephemeral, peer_dh));
    let mut message = e.to_vec();
    message.extend(chain.seal(&k1, &my_card.to_bytes()));
    let k2 = chain.mix_key(&me.dh(peer_dh));
    message.extend(chain.seal(&k2, &[id.to_le_bytes(), stamp.to_le_bytes()].concat()));
    (
        message,
        Pending {
            id,
            chain,
            ephemeral,
            ephemeral_public: e,
        },
    )
}

/// What a responder makes of a HELLO.
pub struct Welcomed {
    /// The initiator's card, checked by the caller against its contacts.
    pub card: Card,
    /// The initiator's stamp, checked by the caller against the last.
    pub stamp: u64,
    /// The WELCOME to send.
    pub message: Vec<u8>,
    pub session: Session,
}

/// A responder's answer to HELLO, stamped `stamp`.
pub fn welcome(me: &Identity, hello: &[u8], ephemeral: [u8; 32], stamp: u64) -> Option<Welcomed> {
    if hello.len() != HELLO_SIZE {
        return None;
    }
    let mut chain = Chain::new(&me.dh_public);
    let e_i: Key = hello[..32].try_into().unwrap();
    chain.mix_hash(&e_i);
    let k1 = chain.mix_key(&me.dh(&e_i));
    let card = Card::from_bytes(&chain.open(&k1, &hello[32..32 + Card::SIZE + TAG])?)?;
    let k2 = chain.mix_key(&me.dh(&card.dh));
    let sealed = chain.open(&k2, &hello[32 + Card::SIZE + TAG..])?;
    let id = u64::from_le_bytes(sealed[..8].try_into().ok()?);
    let their_stamp = u64::from_le_bytes(sealed[8..16].try_into().ok()?);
    let e_r = x25519::public(&ephemeral);
    chain.mix_hash(&e_r);
    let ee = x25519::x25519(&ephemeral, &e_i);
    let se = x25519::x25519(&ephemeral, &card.dh);
    let k3 = chain.mix_key(&[ee, se].concat());
    let mut message = id.to_le_bytes().to_vec();
    message.extend_from_slice(&e_r);
    message.extend(chain.seal(&k3, &stamp.to_le_bytes()));
    let (to_responder, to_initiator) = chain.split();
    Some(Welcomed {
        card,
        stamp: their_stamp,
        message,
        session: Session::new(id, to_initiator, to_responder),
    })
}

impl Pending {
    /// The session WELCOME completes, if it is the answer to this HELLO,
    /// and the responder's stamp.
    pub fn complete(&self, me: &Identity, welcome: &[u8]) -> Option<(Session, u64)> {
        if welcome.len() != WELCOME_SIZE || welcome[..8] != self.id.to_le_bytes() {
            return None;
        }
        let e_r: Key = welcome[8..40].try_into().unwrap();
        let mut chain = self.chain.clone();
        chain.mix_hash(&e_r);
        let ee = x25519::x25519(&self.ephemeral, &e_r);
        let se = me.dh(&e_r);
        let k3 = chain.mix_key(&[ee, se].concat());
        let stamp = chain.open(&k3, &welcome[40..])?;
        let _ = self.ephemeral_public;
        let (to_responder, to_initiator) = chain.split();
        Some((
            Session::new(self.id, to_responder, to_initiator),
            u64::from_le_bytes(stamp.try_into().ok()?),
        ))
    }
}

/// An established session: a key each way and the counters.
pub struct Session {
    pub id: u64,
    send_key: [u8; 32],
    receive_key: [u8; 32],
    sent: u64,
    /// The highest counter received, and which of the 64 below it came.
    highest: u64,
    window: u64,
}

impl Session {
    fn new(id: u64, send_key: [u8; 32], receive_key: [u8; 32]) -> Session {
        Session {
            id,
            send_key,
            receive_key,
            sent: 0,
            highest: 0,
            window: 0,
        }
    }

    fn nonce(counter: u64) -> [u8; 12] {
        let mut n = [0u8; 12];
        n[4..].copy_from_slice(&counter.to_le_bytes());
        n
    }

    /// A DATA message carrying `payload`.
    pub fn seal(&mut self, payload: &[u8]) -> Vec<u8> {
        self.sent += 1;
        let header: Vec<u8> = [self.id.to_le_bytes(), self.sent.to_le_bytes()].concat();
        let mut data = payload.to_vec();
        let tag = aead::seal(&self.send_key, &Self::nonce(self.sent), &header, &mut data);
        let mut message = header;
        message.extend(data);
        message.extend_from_slice(&tag);
        message
    }

    /// The payload of a DATA message, if authentic and not seen before.
    pub fn open(&mut self, message: &[u8]) -> Option<Vec<u8>> {
        if message.len() < 16 + TAG || message[..8] != self.id.to_le_bytes() {
            return None;
        }
        let counter = u64::from_le_bytes(message[8..16].try_into().unwrap());
        if counter == 0 || counter + 64 <= self.highest {
            return None;
        }
        if counter <= self.highest && self.window & (1 << (self.highest - counter)) != 0 {
            return None;
        }
        let (body, tag) = message[16..].split_at(message.len() - 16 - TAG);
        let mut plain = body.to_vec();
        if !aead::open(
            &self.receive_key,
            &Self::nonce(counter),
            &message[..16],
            &mut plain,
            tag.try_into().ok()?,
        ) {
            return None;
        }
        if counter > self.highest {
            let shift = counter - self.highest;
            self.window = if shift >= 64 { 0 } else { self.window << shift };
            self.window |= 1;
            self.highest = counter;
        } else {
            self.window |= 1 << (self.highest - counter);
        }
        Some(plain)
    }
}