garage44.eu/jeroen/pinnacle

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

.. /tls/src/tests.rs

raw

extern crate std;

use crate::x509::{self, Certificate, Error, Key, verify_chain};

// A chain OpenSSL 3.0 made for these tests (2026-11-23): an RSA-2048 root,
// a P-384 intermediate it signed with SHA-256, and a P-256 certificate for
// pinnacle.test and *.apps.pinnacle.test the intermediate signed with
// SHA-384, valid from 2026-11-23 21:00:13 UTC.
const ROOT: &[u8] = include_bytes!("../testdata/root.der");
const INTERMEDIATE: &[u8] = include_bytes!("../testdata/int.der");
const LEAF: &[u8] = include_bytes!("../testdata/leaf.der");
/// 2026-12-01 00:00 UTC, when all three are valid.
const NOW: i64 = 1_796_083_200;

#[test]
fn certificates_read() {
    let root = Certificate::parse(ROOT).unwrap();
    let int = Certificate::parse(INTERMEDIATE).unwrap();
    let leaf = Certificate::parse(LEAF).unwrap();
    assert!(matches!(root.key, Key::Rsa { .. }) && root.ca);
    assert!(matches!(int.key, Key::P384(_)) && int.ca && int.signs_certificates == Some(true));
    assert!(matches!(leaf.key, Key::P256(_)) && !leaf.ca && leaf.server_auth == Some(true));
    assert_eq!(leaf.names, ["pinnacle.test", "*.apps.pinnacle.test"]);
    assert_eq!(int.subject, leaf.issuer);
    assert_eq!(root.subject, int.issuer);
    // 2026-11-23 21:00:13 UTC.
    assert_eq!(leaf.not_before, 1_795_467_613);
    assert!(root.signed(&int) && int.signed(&leaf) && root.signed(&root));
    assert!(!root.signed(&leaf) && !leaf.signed(&leaf));
}

#[test]
fn chains_checked() {
    let chain = [LEAF, INTERMEDIATE];
    assert_eq!(verify_chain(&chain, &[ROOT], "pinnacle.test", NOW), Ok(()));
    assert_eq!(
        verify_chain(&chain, &[ROOT], "Mail.Apps.Pinnacle.Test", NOW),
        Ok(())
    );
    assert_eq!(
        verify_chain(&chain, &[ROOT], "a.b.apps.pinnacle.test", NOW),
        Err(Error::WrongName)
    );
    assert_eq!(
        verify_chain(&chain, &[ROOT], "example.org", NOW),
        Err(Error::WrongName)
    );
    // Without the intermediate, or without the root, it reaches nothing.
    assert_eq!(
        verify_chain(&[LEAF], &[ROOT], "pinnacle.test", NOW),
        Err(Error::Untrusted)
    );
    assert_eq!(
        verify_chain(&chain, &[], "pinnacle.test", NOW),
        Err(Error::Untrusted)
    );
    // Before it was made, and after the leaf ran out (on 2027-12-28; 2030).
    assert_eq!(
        verify_chain(&chain, &[ROOT], "pinnacle.test", NOW - 30 * 86_400),
        Err(Error::Expired)
    );
    assert_eq!(
        verify_chain(&chain, &[ROOT], "pinnacle.test", 1_900_000_000),
        Err(Error::Expired)
    );
    // The leaf may not sign: a chain claiming it does is refused.
    assert_eq!(
        verify_chain(&[INTERMEDIATE, LEAF], &[ROOT], "pinnacle.test", NOW),
        Err(Error::WrongName)
    );
}

#[test]
fn a_chain_with_no_time_to_check_by() {
    // The span all three are valid in: within the leaf's, around NOW.
    let leaf = Certificate::parse(LEAF).unwrap();
    let chain = [LEAF, INTERMEDIATE];
    let (from, until) = x509::chain_window(&chain, &[ROOT], "pinnacle.test").unwrap();
    assert!(from >= leaf.not_before && until <= leaf.not_after);
    assert!((from..=until).contains(&NOW));
    // Still a chain to a root, for the host.
    assert_eq!(
        x509::chain_window(&[LEAF], &[ROOT], "pinnacle.test"),
        Err(Error::Untrusted)
    );
    assert_eq!(
        x509::chain_window(&chain, &[ROOT], "example.org"),
        Err(Error::WrongName)
    );
}

#[test]
fn a_changed_certificate_is_refused() {
    // One byte of the leaf's signed part changed: still readable, no
    // longer what the intermediate signed.
    let mut changed = LEAF.to_vec();
    let at = LEAF.windows(13).position(|w| w == b"pinnacle.test").unwrap();
    changed[at] = b'P';
    let chain = [&changed[..], INTERMEDIATE];
    assert_eq!(
        verify_chain(&chain, &[ROOT], "Pinnacle.test", NOW),
        Err(Error::Untrusted)
    );
    let _ = x509::verify;
}

/// A field of RFC 8448's simple 1-RTT handshake (section 3), as
/// `testdata/rfc8448-simple.txt` holds them: a name and its hex a line,
/// taken from the RFC's text.
fn trace(name: &str) -> std::vec::Vec<u8> {
    let text = include_str!("../testdata/rfc8448-simple.txt");
    let hex = text
        .lines()
        .find_map(|l| l.strip_prefix(name)?.strip_prefix(' '))
        .unwrap_or_else(|| panic!("no {name} in the trace"));
    (0..hex.len())
        .step_by(2)
        .map(|i| u8::from_str_radix(&hex[i..i + 2], 16).unwrap())
        .collect()
}

/// RFC 8448's trace replayed: the client given the trace's ClientHello and
/// X25519 key takes the server's records, checks its CertificateVerify and
/// Finished, and sends exactly the trace's Finished, application data and
/// close_notify records, byte for byte; it reads the server's data. The
/// trace's server key is RSA-1024, which only a test accepts.
#[test]
fn rfc8448_simple_handshake() {
    use crate::client::{Client, Config, Verify};
    let message = trace("certificate");
    // Certificate: type, length, empty context, list length, entry length.
    let certificate = message[11..11 + 0x1b0].to_vec();
    let config = Config {
        host: "server".into(),
        verify: Verify::Pinned(certificate),
        min_rsa_bits: 1024,
        alpn: std::vec::Vec::new(),
    };
    let hello = trace("client_hello");
    let secret: [u8; 32] = trace("client_private").try_into().unwrap();
    let mut client = Client::with_hello(config, hello.clone(), secret);
    let mut record = std::vec![0x16, 3, 1, 0, 0xc4];
    record.extend_from_slice(&hello);
    assert_eq!(client.take_output(), record);
    client.receive(&trace("server_hello_record")).unwrap();
    client.receive(&trace("server_flight_record")).unwrap();
    assert!(client.connected());
    assert_eq!(client.take_output(), trace("client_finished_record"));
    client.receive(&trace("ticket_record")).unwrap();
    client.write(&trace("client_data"));
    assert_eq!(client.take_output(), trace("client_data_record"));
    client.receive(&trace("server_data_record")).unwrap();
    assert_eq!(client.read(), trace("client_data"));
    client.close();
    assert_eq!(client.take_output(), trace("client_alert_record"));
    client.receive(&trace("server_alert_record")).unwrap();
    assert!(client.closed());
}

/// The trace's server flight with one byte changed is refused, and so is
/// another certificate than the pinned one.
#[test]
fn rfc8448_tampering_refused() {
    use crate::client::{Client, Config, Error, Verify};
    let message = trace("certificate");
    let certificate = message[11..11 + 0x1b0].to_vec();
    let start = |verify| {
        let config = Config {
            host: "server".into(),
            verify,
            min_rsa_bits: 1024,
            alpn: std::vec::Vec::new(),
        };
        let secret: [u8; 32] = trace("client_private").try_into().unwrap();
        let mut client = Client::with_hello(config, trace("client_hello"), secret);
        client.receive(&trace("server_hello_record")).unwrap();
        client
    };
    let mut flight = trace("server_flight_record");
    flight[300] ^= 1;
    assert!(
        start(Verify::Pinned(certificate.clone()))
            .receive(&flight)
            .is_err()
    );
    let mut other = certificate.clone();
    other[200] ^= 1;
    assert_eq!(
        start(Verify::Pinned(other)).receive(&trace("server_flight_record")),
        Err(Error::Certificate(crate::x509::Error::Untrusted))
    );
    // Without the test's allowance, its RSA-1024 key is refused.
    let config = Config {
        host: "server".into(),
        verify: Verify::Pinned(certificate),
        min_rsa_bits: 2048,
        alpn: std::vec::Vec::new(),
    };
    let secret: [u8; 32] = trace("client_private").try_into().unwrap();
    let mut client = Client::with_hello(config, trace("client_hello"), secret);
    client.receive(&trace("server_hello_record")).unwrap();
    assert_eq!(client.receive(&trace("server_flight_record")), Err(Error::Forged));
}

/// Mozilla's roots, as Pinnacle ships them: every one decodes, and nearly
/// all read (the few that do not use a curve or algorithm not offered).
#[test]
fn mozilla_roots_read() {
    let roots = crate::pem::certificates(include_str!("../../certificates/mozilla-roots.pem"));
    assert!(roots.len() >= 100, "{} roots", roots.len());
    let read = roots.iter().filter(|r| Certificate::parse(r).is_some()).count();
    std::println!("{read} of {} roots read", roots.len());
    assert!(
        read * 10 >= roots.len() * 9,
        "only {read} of {} roots read",
        roots.len()
    );
}

/// TLS 1.3 to real servers over this host's network, their chains checked
/// against Mozilla's roots: `cargo test -p pinnacle-tls -- --ignored
/// --nocapture`. Not in the gate, which must not need the internet.
#[test]
#[ignore]
fn real_servers() {
    use crate::client::{Client, Config, Verify};
    use std::io::{Read, Write};
    let roots = crate::pem::certificates(include_str!("../../certificates/mozilla-roots.pem"));
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs() as i64;
    let mut failures = 0;
    for host in [
        "example.com",
        "www.cloudflare.com",
        "www.google.com",
        "github.com",
        "letsencrypt.org",
        "www.wikipedia.org",
        "www.rust-lang.org",
    ] {
        let mut random = [0u8; 96];
        std::fs::File::open("/dev/urandom")
            .unwrap()
            .read_exact(&mut random)
            .unwrap();
        let config = Config {
            host: host.into(),
            verify: Verify::Roots {
                roots: roots.clone(),
                now,
            },
            min_rsa_bits: 2048,
            alpn: std::vec::Vec::new(),
        };
        let mut client = Client::new(
            config,
            random[..32].try_into().unwrap(),
            random[32..64].try_into().unwrap(),
            random[64..].try_into().unwrap(),
        );
        let mut tcp = std::net::TcpStream::connect((host, 443)).unwrap();
        tcp.set_read_timeout(Some(std::time::Duration::from_secs(10)))
            .unwrap();
        let mut sent_request = false;
        let mut response = std::vec::Vec::new();
        let mut buffer = [0u8; 16384];
        let outcome = loop {
            let out = client.take_output();
            if !out.is_empty() {
                tcp.write_all(&out).unwrap();
            }
            if client.connected() && !sent_request {
                let request = std::format!("HEAD / HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n");
                client.write(request.as_bytes());
                sent_request = true;
                continue;
            }
            let n = match tcp.read(&mut buffer) {
                Ok(0) | Err(_) => break Ok(()),
                Ok(n) => n,
            };
            if let Err(e) = client.receive(&buffer[..n]) {
                break Err(e);
            }
            response.extend_from_slice(&client.read());
            if client.closed() {
                break Ok(());
            }
        };
        let text = std::string::String::from_utf8_lossy(&response);
        let status = text.lines().next().unwrap_or("");
        std::println!("{host}: {outcome:?}, {status}");
        if outcome.is_err() || !status.starts_with("HTTP/1.1") {
            failures += 1;
        }
    }
    assert_eq!(failures, 0);
}

/// A root and a server certificate for `time.pinnacle.test` it signs,
/// valid through 2026 and 2027: the root's DER, the server's chain and
/// Ed25519 secret key.
fn ed25519_chain() -> (std::vec::Vec<u8>, std::vec::Vec<std::vec::Vec<u8>>, [u8; 32]) {
    use crate::server::{Issue, certificate};
    use pinnacle_crypto::ed25519;
    let (root_key, key) = ([1u8; 32], [2u8; 32]);
    let (from, until) = (1_767_225_600, 1_830_297_600);
    let root = certificate(&Issue {
        name: "Pinnacle test root",
        key: ed25519::public(&root_key),
        issuer: "Pinnacle test root",
        issuer_key: &root_key,
        ca: true,
        hosts: &[],
        from,
        until,
    });
    let leaf = certificate(&Issue {
        name: "time.pinnacle.test",
        key: ed25519::public(&key),
        issuer: "Pinnacle test root",
        issuer_key: &root_key,
        ca: false,
        hosts: &["time.pinnacle.test"],
        from,
        until,
    });
    (root, std::vec![leaf], key)
}

/// Hands each side's output to the other until neither has more.
fn pump(client: &mut crate::client::Client, server: &mut crate::server::Server) -> Result<(), Error> {
    loop {
        let to_server = client.take_output();
        let to_client = server.take_output();
        if to_server.is_empty() && to_client.is_empty() {
            return Ok(());
        }
        server
            .receive(&to_server)
            .map_err(|e| std::panic!("the server refused: {e:?}"))?;
        client.receive(&to_client).map_err(|e| match e {
            crate::client::Error::Certificate(e) => e,
            e => std::panic!("the client refused: {e:?}"),
        })?;
    }
}

/// The client and the stand-in server: an Ed25519 chain checked with no
/// clock (its window read) and at a time, ALPN chosen, data both ways, and
/// the same keys exported at both ends.
#[test]
fn a_server_of_our_own() {
    use crate::client::{Client, Config, Verify};
    use crate::server::{self, Server};
    let (root, chain, key) = ed25519_chain();
    // As PEM, as a roots file holds it, and back.
    for (der, line) in [(&b"a"[..], "\nYQ==\n"), (b"ab", "\nYWI=\n"), (b"abc", "\nYWJj\n")] {
        assert!(crate::pem::certificate(der).contains(line));
    }
    for der in [&root, &chain[0]] {
        assert_eq!(
            crate::pem::certificates(&crate::pem::certificate(der)),
            [der.clone()]
        );
    }
    let parsed = Certificate::parse(&chain[0]).unwrap();
    assert!(matches!(parsed.key, Key::Ed25519(_)) && parsed.names == ["time.pinnacle.test"]);
    assert!(Certificate::parse(&root).unwrap().signed(&parsed));
    assert_eq!(parsed.not_before, 1_767_225_600);
    let start = |verify| {
        let config = Config {
            host: "time.pinnacle.test".into(),
            verify,
            min_rsa_bits: 2048,
            alpn: std::vec!["ntske/1".into()],
        };
        let client = Client::new(config, [3; 32], [4; 32], [5; 32]);
        let config = server::Config {
            chain: chain.clone(),
            key,
            alpn: std::vec!["ntske/1".into()],
        };
        (client, Server::new(config, [6; 32], [7; 32]))
    };
    let (mut client, mut server) = start(Verify::Untimed {
        roots: std::vec![root.clone()],
    });
    pump(&mut client, &mut server).unwrap();
    assert!(client.connected() && server.connected());
    assert_eq!(client.protocol(), Some("ntske/1"));
    assert_eq!(client.window(), Some((1_767_225_600, 1_830_297_600)));
    let label = "EXPORTER-network-time-security";
    let ours = client.export(label, &[0, 0, 0, 15, 0], 32).unwrap();
    assert_eq!(server.export(label, &[0, 0, 0, 15, 0], 32), Some(ours.clone()));
    assert_ne!(client.export(label, &[0, 0, 0, 15, 1], 32), Some(ours));
    client.write(b"hello");
    pump(&mut client, &mut server).unwrap();
    assert_eq!(server.read(), b"hello");
    server.write(b"hello back");
    pump(&mut client, &mut server).unwrap();
    assert_eq!(client.read(), b"hello back");

    // At a time: in 2027 it holds, in 2025 it has not begun.
    let roots = std::vec![root.clone()];
    let (mut client, mut server) = start(Verify::Roots {
        roots,
        now: NOW + 365 * 86_400,
    });
    pump(&mut client, &mut server).unwrap();
    assert!(client.connected());
    let roots = std::vec![root];
    let (mut client, mut server) = start(Verify::Roots {
        roots,
        now: NOW - 365 * 86_400,
    });
    assert_eq!(pump(&mut client, &mut server), Err(Error::Expired));
    // A root this device does not have.
    let (mut client, mut server) = start(Verify::Untimed {
        roots: std::vec![ROOT.to_vec()],
    });
    assert_eq!(pump(&mut client, &mut server), Err(Error::Untrusted));
}

/// A server that signs with another key than its certificate's is caught
/// at its CertificateVerify.
#[test]
fn a_server_with_the_wrong_key() {
    use crate::client::{Client, Config, Verify};
    use crate::server::{self, Server};
    let (root, chain, _) = ed25519_chain();
    let config = Config {
        host: "time.pinnacle.test".into(),
        verify: Verify::Untimed {
            roots: std::vec![root],
        },
        min_rsa_bits: 2048,
        alpn: std::vec::Vec::new(),
    };
    let mut client = Client::new(config, [3; 32], [4; 32], [5; 32]);
    let config = server::Config {
        chain,
        key: [9; 32],
        alpn: std::vec::Vec::new(),
    };
    let mut server = Server::new(config, [6; 32], [7; 32]);
    server.receive(&client.take_output()).unwrap();
    assert_eq!(
        client.receive(&server.take_output()),
        Err(crate::client::Error::Forged)
    );
}