garage44.eu/jeroen/pinnacle

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

.. /net/src/nts.rs

raw

//! Network Time Security for NTP (RFC 8915): the time asked of a server
//! with every answer authenticated, so nobody on the path can move the
//! clock.
//!
//! First a key exchange over TLS 1.3 (port 4460, ALPN `ntske/1`): the
//! client sends [`ke_request`], reads the server's records with
//! [`ke_response`], and exports two keys from the TLS connection
//! ([`EXPORTER`], [`C2S`], [`S2C`]). The server gives cookies, each good
//! for one NTP request. Then NTP over UDP as before, each request carrying
//! a random identifier, a cookie and an authenticator ([`request`]); the
//! answer counts only when it echoes the identifier and its authenticator
//! checks with the server's key ([`answer`]), which also opens the fresh
//! cookie it brings. Packets are sealed with AES-SIV-CMAC-256.
//!
//! The server's half ([`ke_answer`], [`asked`], [`reply`], [`seal_cookie`])
//! is here too, for tests and for the stand-in server of
//! `cargo xtask time-demo`.

use crate::ntp;
use alloc::string::String;
use alloc::vec::Vec;
use pinnacle_crypto::aes::Siv;

/// The port NTS key exchange servers listen on.
pub const KE_PORT: u16 = 4460;
/// The key exchange's application protocol (ALPN).
pub const ALPN: &str = "ntske/1";
/// The label the two keys are exported from the TLS connection with.
pub const EXPORTER: &str = "EXPORTER-network-time-security";
/// The exporter's context for the client-to-server key, and for the
/// server-to-client one: NTPv4 (0), AEAD_AES_SIV_CMAC_256 (15), which.
pub const C2S: [u8; 5] = [0, 0, 0, 15, 0];
pub const S2C: [u8; 5] = [0, 0, 0, 15, 1];

const AES_SIV_CMAC_256: u16 = 15;
const CRITICAL: u16 = 0x8000;

// Key exchange record types.
const END: u16 = 0;
const NEXT_PROTOCOL: u16 = 1;
const ERROR: u16 = 2;
const WARNING: u16 = 3;
const AEAD: u16 = 4;
const NEW_COOKIE: u16 = 5;
const SERVER: u16 = 6;
const PORT: u16 = 7;

// NTP extension field types.
const UNIQUE_IDENTIFIER: u16 = 0x0104;
const COOKIE: u16 = 0x0204;
const COOKIE_PLACEHOLDER: u16 = 0x0304;
const AUTHENTICATOR: u16 = 0x0404;

/// The two keys of one key exchange.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Keys {
    /// What the client's requests are sealed with.
    pub c2s: [u8; 32],
    /// What the server's answers are sealed with.
    pub s2c: [u8; 32],
}

/// What the key exchange agreed.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Agreed {
    pub cookies: Vec<Vec<u8>>,
    /// The NTP server to ask, when not the key exchange's own.
    pub server: Option<String>,
    /// Its port, when not 123.
    pub port: Option<u16>,
}

/// Why a key exchange's answer is not used.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum KeRefused {
    /// The server said no (its error code: 0 an unknown critical record,
    /// 1 a bad request, 2 an internal error).
    Error(u16),
    /// It speaks no NTPv4, or seals with another algorithm than AES-SIV.
    Unsupported,
    /// It gave no cookie.
    NoCookies,
    /// Records that cannot be read, or one it must not send.
    Malformed,
}

/// One key exchange record.
fn record(out: &mut Vec<u8>, kind: u16, body: &[u8]) {
    out.extend_from_slice(&kind.to_be_bytes());
    out.extend_from_slice(&(body.len() as u16).to_be_bytes());
    out.extend_from_slice(body);
}

/// A key exchange record: its type, whether critical, its body.
type Record<'a> = (u16, bool, &'a [u8]);

/// The key exchange records `bytes` holds; `None` until the
/// end-of-message record has arrived.
fn records(mut bytes: &[u8]) -> Result<Option<Vec<Record<'_>>>, KeRefused> {
    let mut out = Vec::new();
    loop {
        if bytes.len() < 4 {
            return Ok(None);
        }
        let kind = u16::from_be_bytes([bytes[0], bytes[1]]);
        let len = usize::from(u16::from_be_bytes([bytes[2], bytes[3]]));
        let Some(body) = bytes.get(4..4 + len) else {
            return Ok(None);
        };
        bytes = &bytes[4 + len..];
        if kind & !CRITICAL == END {
            return if bytes.is_empty() {
                Ok(Some(out))
            } else {
                Err(KeRefused::Malformed)
            };
        }
        out.push((kind & !CRITICAL, kind & CRITICAL != 0, body));
    }
}

/// The client's key exchange request: NTPv4, sealed with AES-SIV.
pub fn ke_request() -> Vec<u8> {
    let mut out = Vec::new();
    record(&mut out, CRITICAL | NEXT_PROTOCOL, &[0, 0]);
    record(&mut out, CRITICAL | AEAD, &AES_SIV_CMAC_256.to_be_bytes());
    record(&mut out, CRITICAL | END, &[]);
    out
}

/// Reads the server's key exchange answer: `None` until all of it has
/// arrived.
pub fn ke_response(bytes: &[u8]) -> Result<Option<Agreed>, KeRefused> {
    let Some(records) = records(bytes)? else {
        return Ok(None);
    };
    let (mut ntp, mut siv) = (false, false);
    let mut agreed = Agreed {
        cookies: Vec::new(),
        server: None,
        port: None,
    };
    for (kind, critical, body) in records {
        match kind {
            ERROR => {
                let code = body.try_into().map_err(|_| KeRefused::Malformed)?;
                return Err(KeRefused::Error(u16::from_be_bytes(code)));
            }
            NEXT_PROTOCOL => ntp = body == [0, 0],
            AEAD => siv = body == AES_SIV_CMAC_256.to_be_bytes(),
            NEW_COOKIE if !body.is_empty() => agreed.cookies.push(body.to_vec()),
            SERVER => {
                let name = core::str::from_utf8(body).map_err(|_| KeRefused::Malformed)?;
                agreed.server = Some(name.into());
            }
            PORT => {
                let port = body.try_into().map_err(|_| KeRefused::Malformed)?;
                agreed.port = Some(u16::from_be_bytes(port));
            }
            WARNING => {}
            _ if critical => return Err(KeRefused::Malformed),
            _ => {}
        }
    }
    if !ntp || !siv {
        return Err(KeRefused::Unsupported);
    }
    if agreed.cookies.is_empty() {
        return Err(KeRefused::NoCookies);
    }
    Ok(Some(agreed))
}

/// One NTP extension field (RFC 7822): its body padded to whole words,
/// and to the 16 bytes a field is at least.
fn field(out: &mut Vec<u8>, kind: u16, body: &[u8]) {
    let len = (4 + body.len()).next_multiple_of(4).max(16);
    out.extend_from_slice(&kind.to_be_bytes());
    out.extend_from_slice(&(len as u16).to_be_bytes());
    out.extend_from_slice(body);
    out.resize(out.len() + len - 4 - body.len(), 0);
}

/// The extension fields of `bytes`, as (type, body, where it starts);
/// `None` when they do not fit.
fn fields(bytes: &[u8], from: usize) -> Option<Vec<(u16, &[u8], usize)>> {
    let mut out = Vec::new();
    let mut at = from;
    while at < bytes.len() {
        let header = bytes.get(at..at + 4)?;
        let kind = u16::from_be_bytes([header[0], header[1]]);
        let len = usize::from(u16::from_be_bytes([header[2], header[3]]));
        if len < 16 || len % 4 != 0 {
            return None;
        }
        out.push((kind, bytes.get(at + 4..at + len)?, at));
        at += len;
    }
    Some(out)
}

/// An authenticator's nonce and ciphertext.
fn authenticator(body: &[u8]) -> Option<(&[u8], &[u8])> {
    let nonce = usize::from(u16::from_be_bytes(body.get(..2)?.try_into().ok()?));
    let sealed = usize::from(u16::from_be_bytes(body.get(2..4)?.try_into().ok()?));
    let at = 4 + nonce.next_multiple_of(4);
    Some((body.get(4..4 + nonce)?, body.get(at..at + sealed)?))
}

/// The authenticator field over `packet` so far, sealing `plaintext`
/// (the encrypted extension fields) with `key`.
fn seal(packet: &mut Vec<u8>, key: &[u8; 32], nonce: &[u8; 16], mut plaintext: Vec<u8>) {
    let iv = Siv::new(key).seal(&[packet, nonce], &mut plaintext);
    let mut body = Vec::new();
    body.extend_from_slice(&16u16.to_be_bytes());
    body.extend_from_slice(&((16 + plaintext.len()) as u16).to_be_bytes());
    body.extend_from_slice(nonce);
    body.extend_from_slice(&iv);
    body.extend_from_slice(&plaintext);
    field(packet, AUTHENTICATOR, &body);
}

/// The plaintext of the authenticator at `at`, when it checks with `key`
/// over the packet before it.
fn open(packet: &[u8], at: usize, body: &[u8], key: &[u8; 32]) -> Option<Vec<u8>> {
    let (nonce, sealed) = authenticator(body)?;
    let iv: &[u8; 16] = sealed.get(..16)?.try_into().ok()?;
    let mut plaintext = sealed[16..].to_vec();
    Siv::new(key)
        .open(&[&packet[..at], nonce], &mut plaintext, iv)
        .then_some(plaintext)
}

/// An NTP request with NTS: as [`ntp::request`] with `cookie` as its
/// transmit time, then the random identifier `uid` the answer must echo,
/// an NTS cookie from the key exchange, `placeholders` asking for that many
/// more cookies, and the authenticator sealed with the client's key under
/// the random `nonce`.
pub fn request(
    cookie: u64,
    uid: &[u8; 32],
    nts_cookie: &[u8],
    placeholders: usize,
    keys: &Keys,
    nonce: &[u8; 16],
) -> Vec<u8> {
    let mut packet = ntp::request(cookie).to_vec();
    field(&mut packet, UNIQUE_IDENTIFIER, uid);
    field(&mut packet, COOKIE, nts_cookie);
    for _ in 0..placeholders {
        field(&mut packet, COOKIE_PLACEHOLDER, &alloc::vec![0; nts_cookie.len()]);
    }
    seal(&mut packet, &keys.c2s, nonce, Vec::new());
    packet
}

/// Why an answer is not used.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Refused {
    /// As plain NTP refuses it; `NotOurs` also when it does not echo the
    /// request's identifier.
    Ntp(ntp::Refused),
    /// It is not sealed with the server's key: forged, or changed on the
    /// way.
    Forged,
}

/// The time an answer gives, as [`ntp::answer`] has it, and the cookies
/// it brings, once it echoes `uid` and is sealed with the server's key.
/// Nothing of the answer is believed before that.
pub fn answer(
    packet: &[u8],
    cookie: u64,
    uid: &[u8; 32],
    keys: &Keys,
    elapsed_ms: u64,
) -> Result<(u64, Vec<Vec<u8>>), Refused> {
    let time = ntp::answer(packet, cookie, elapsed_ms);
    if let Err(e @ (ntp::Refused::NotAnAnswer | ntp::Refused::NotOurs)) = time {
        return Err(Refused::Ntp(e));
    }
    let found = fields(packet, ntp::SIZE).ok_or(Refused::Forged)?;
    // No identifier at all is an answer forged to the transmit time seen
    // on the path; another's, an answer to another request.
    match found.iter().find(|&&(kind, ..)| kind == UNIQUE_IDENTIFIER) {
        None => return Err(Refused::Forged),
        Some(&(_, body, _)) if body != uid => return Err(Refused::Ntp(ntp::Refused::NotOurs)),
        Some(_) => {}
    }
    // The first authenticator; what follows it is not covered, and unused.
    let &(_, body, at) = found
        .iter()
        .find(|&&(kind, ..)| kind == AUTHENTICATOR)
        .ok_or(Refused::Forged)?;
    let plaintext = open(packet, at, body, &keys.s2c).ok_or(Refused::Forged)?;
    let cookies = fields(&plaintext, 0)
        .ok_or(Refused::Forged)?
        .into_iter()
        .filter(|&(kind, ..)| kind == COOKIE)
        .map(|(_, body, _)| body.to_vec())
        .collect();
    Ok((time.map_err(Refused::Ntp)?, cookies))
}

/// A server's key exchange answer: NTPv4 and AES-SIV agreed, `cookies`,
/// and the NTP server and port to ask when they are not its own.
pub fn ke_answer(cookies: &[Vec<u8>], server: Option<&str>, port: Option<u16>) -> Vec<u8> {
    let mut out = Vec::new();
    record(&mut out, CRITICAL | NEXT_PROTOCOL, &[0, 0]);
    record(&mut out, AEAD, &AES_SIV_CMAC_256.to_be_bytes());
    for cookie in cookies {
        record(&mut out, NEW_COOKIE, cookie);
    }
    if let Some(server) = server {
        record(&mut out, SERVER, server.as_bytes());
    }
    if let Some(port) = port {
        record(&mut out, PORT, &port.to_be_bytes());
    }
    record(&mut out, CRITICAL | END, &[]);
    out
}

/// What a server reads from a request, once its authenticator checked.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Asked {
    pub uid: Vec<u8>,
    /// The keys its cookie held.
    pub keys: Keys,
    /// How many cookies to send back: one for the one used, one for each
    /// placeholder.
    pub cookies: usize,
}

/// Reads an NTS request, the keys found from its cookie by `keys_of`; `None`
/// for one that is not, or whose authenticator does not check.
pub fn asked(packet: &[u8], keys_of: impl Fn(&[u8]) -> Option<Keys>) -> Option<Asked> {
    let fields = fields(packet, ntp::SIZE)?;
    let find = |kind| fields.iter().find(|f| f.0 == kind);
    let uid = find(UNIQUE_IDENTIFIER)?.1;
    let keys = keys_of(find(COOKIE)?.1)?;
    let &(_, body, at) = find(AUTHENTICATOR)?;
    open(packet, at, body, &keys.c2s)?;
    Some(Asked {
        uid: uid.to_vec(),
        keys,
        cookies: 1 + fields.iter().filter(|f| f.0 == COOKIE_PLACEHOLDER).count(),
    })
}

/// A server's answer: its NTP `header`, the request's identifier, and
/// `cookies` encrypted, all sealed with the server's key under `nonce`.
pub fn reply(
    header: &[u8; ntp::SIZE],
    uid: &[u8],
    keys: &Keys,
    cookies: &[Vec<u8>],
    nonce: &[u8; 16],
) -> Vec<u8> {
    let mut packet = header.to_vec();
    field(&mut packet, UNIQUE_IDENTIFIER, uid);
    let mut plaintext = Vec::new();
    for cookie in cookies {
        field(&mut plaintext, COOKIE, cookie);
    }
    seal(&mut packet, &keys.s2c, nonce, plaintext);
    packet
}

/// A cookie as a stand-in server makes one: the two keys sealed with a
/// key of its own under `nonce`, so it keeps nothing per client.
pub fn seal_cookie(master: &[u8; 32], keys: &Keys, nonce: &[u8; 16]) -> Vec<u8> {
    let mut both = [0u8; 64];
    both[..32].copy_from_slice(&keys.c2s);
    both[32..].copy_from_slice(&keys.s2c);
    let iv = Siv::new(master).seal(&[nonce], &mut both);
    [&nonce[..], &iv, &both].concat()
}

/// The keys in a cookie [`seal_cookie`] made.
pub fn open_cookie(master: &[u8; 32], cookie: &[u8]) -> Option<Keys> {
    let (nonce, rest) = cookie.split_at_checked(16)?;
    let (iv, sealed) = rest.split_at_checked(16)?;
    let mut both: [u8; 64] = sealed.try_into().ok()?;
    if !Siv::new(master).open(&[nonce], &mut both, iv.try_into().ok()?) {
        return None;
    }
    Some(Keys {
        c2s: both[..32].try_into().unwrap(),
        s2c: both[32..].try_into().unwrap(),
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::vec;

    const MASTER: [u8; 32] = [9; 32];
    const KEYS: Keys = Keys {
        c2s: [1; 32],
        s2c: [2; 32],
    };
    const UID: [u8; 32] = [3; 32];
    // 29 November 2026 12:00:00 UTC, as NTP counts.
    const NOON: u64 = 1_795_953_600 + 2_208_988_800;

    fn cookie(n: u8) -> Vec<u8> {
        seal_cookie(&MASTER, &KEYS, &[n; 16])
    }

    /// A server's NTP header answering `cookie`, sent at `seconds`.
    fn header(cookie: u64, seconds: u64) -> [u8; ntp::SIZE] {
        let mut h = [0u8; ntp::SIZE];
        h[0] = 4 << 3 | 4;
        h[1] = 1;
        h[24..32].copy_from_slice(&cookie.to_be_bytes());
        h[32..40].copy_from_slice(&(seconds << 32).to_be_bytes());
        h[40..48].copy_from_slice(&(seconds << 32).to_be_bytes());
        h
    }

    #[test]
    fn key_exchange() {
        assert_eq!(
            ke_request(),
            [0x80, 1, 0, 2, 0, 0, 0x80, 4, 0, 2, 0, 15, 0x80, 0, 0, 0]
        );
        let answer = ke_answer(&[cookie(1), cookie(2)], Some("ntp.pinnacle.test"), Some(1123));
        // Until the end of the message, nothing.
        assert_eq!(ke_response(&answer[..answer.len() - 1]), Ok(None));
        let agreed = ke_response(&answer).unwrap().unwrap();
        assert_eq!(agreed.cookies, [cookie(1), cookie(2)]);
        assert_eq!(agreed.server.as_deref(), Some("ntp.pinnacle.test"));
        assert_eq!(agreed.port, Some(1123));
        assert_eq!(open_cookie(&MASTER, &agreed.cookies[0]), Some(KEYS));
        assert_eq!(open_cookie(&[8; 32], &agreed.cookies[0]), None);

        let mut refused = Vec::new();
        record(&mut refused, CRITICAL | ERROR, &[0, 1]);
        record(&mut refused, CRITICAL | END, &[]);
        assert_eq!(ke_response(&refused), Err(KeRefused::Error(1)));
        assert_eq!(
            ke_response(&ke_answer(&[], None, None)),
            Err(KeRefused::NoCookies)
        );
        let mut other = Vec::new();
        record(&mut other, CRITICAL | NEXT_PROTOCOL, &[0, 0]);
        record(&mut other, AEAD, &30u16.to_be_bytes());
        record(&mut other, NEW_COOKIE, &cookie(1));
        record(&mut other, CRITICAL | END, &[]);
        assert_eq!(ke_response(&other), Err(KeRefused::Unsupported));
        let mut unknown = Vec::new();
        record(&mut unknown, CRITICAL | 0x4000, &[]);
        record(&mut unknown, CRITICAL | END, &[]);
        assert_eq!(ke_response(&unknown), Err(KeRefused::Malformed));
    }

    /// A request read and answered by the server's half, the answer's time
    /// and fresh cookies taken.
    #[test]
    fn an_authenticated_answer() {
        let sent = request(77, &UID, &cookie(1), 2, &KEYS, &[4; 16]);
        assert_eq!(sent.len() % 4, 0);
        let asked = asked(&sent, |c| open_cookie(&MASTER, c)).unwrap();
        assert_eq!(asked.uid, UID);
        assert_eq!(asked.keys, KEYS);
        assert_eq!(asked.cookies, 3);
        let fresh: Vec<Vec<u8>> = (5..8).map(cookie).collect();
        let packet = reply(&header(77, NOON), &asked.uid, &asked.keys, &fresh, &[5; 16]);
        let (ms, cookies) = answer(&packet, 77, &UID, &KEYS, 0).unwrap();
        assert_eq!(ms, 1_795_953_600_000);
        assert_eq!(cookies, fresh);
    }

    /// A request whose authenticator is not by the cookie's key, or that
    /// was changed on the way, is not answered.
    #[test]
    fn forged_requests() {
        let other = Keys {
            c2s: [6; 32],
            s2c: [2; 32],
        };
        let sent = request(77, &UID, &cookie(1), 0, &other, &[4; 16]);
        assert_eq!(asked(&sent, |c| open_cookie(&MASTER, c)), None);
        let mut sent = request(77, &UID, &cookie(1), 0, &KEYS, &[4; 16]);
        sent[45] ^= 1;
        assert_eq!(asked(&sent, |c| open_cookie(&MASTER, c)), None);
        assert_eq!(asked(&ntp::request(77), |c| open_cookie(&MASTER, c)), None);
    }

    /// What someone on the path could send: a plain NTP answer, one sealed
    /// with a key of their own, a true one with its time moved back a
    /// year. None moves the clock; an answer to another request is not
    /// ours.
    #[test]
    fn forged_answers() {
        let year_ago = NOON - 365 * 86_400;
        assert_eq!(
            answer(&header(77, year_ago), 77, &UID, &KEYS, 0),
            Err(Refused::Forged)
        );
        let theirs = Keys {
            c2s: [1; 32],
            s2c: [7; 32],
        };
        let forged = reply(&header(77, year_ago), &UID, &theirs, &[], &[5; 16]);
        assert_eq!(answer(&forged, 77, &UID, &KEYS, 0), Err(Refused::Forged));
        let mut moved = reply(&header(77, NOON), &UID, &KEYS, &[cookie(5)], &[5; 16]);
        moved[40..48].copy_from_slice(&(year_ago << 32).to_be_bytes());
        assert_eq!(answer(&moved, 77, &UID, &KEYS, 0), Err(Refused::Forged));
        let mut sealed_cookie = reply(&header(77, NOON), &UID, &KEYS, &[cookie(5)], &[5; 16]);
        let last = sealed_cookie.len() - 1;
        sealed_cookie[last] ^= 1;
        assert_eq!(answer(&sealed_cookie, 77, &UID, &KEYS, 0), Err(Refused::Forged));
        let elsewhere = reply(&header(77, NOON), &[8; 32], &KEYS, &[], &[5; 16]);
        assert_eq!(
            answer(&elsewhere, 77, &UID, &KEYS, 0),
            Err(Refused::Ntp(ntp::Refused::NotOurs))
        );
        let late = reply(&header(76, NOON), &UID, &KEYS, &[], &[5; 16]);
        assert_eq!(
            answer(&late, 77, &UID, &KEYS, 0),
            Err(Refused::Ntp(ntp::Refused::NotOurs))
        );
        // Fields after the authenticator are not covered, and not used.
        let mut trailing = reply(&header(77, NOON), &UID, &KEYS, &[], &[5; 16]);
        field(&mut trailing, COOKIE, &[1; 12]);
        assert_eq!(
            answer(&trailing, 77, &UID, &KEYS, 0),
            Ok((1_795_953_600_000, vec![]))
        );
    }
}