git clone https://garage44.eu/jeroen/pinnacle.git.. /tls/src/server.rs
//! A TLS 1.3 server (RFC 8446), as small as a stand-in needs to be: for
//! the client's tests, and for servers a demo runs on the host (an NTS key
//! exchange for `cargo xtask time-demo`). Like the client it is a state
//! machine with no I/O of its own.
//!
//! It takes X25519, AES-128-GCM and an Ed25519 certificate, and chooses an
//! application protocol (ALPN) the client offers. It asks for no client
//! certificate and sends no tickets. [`certificate`] makes the certificates
//! it presents, and the root a client is to trust them by.
use crate::client::{
self, APPLICATION_DATA, CERTIFICATE, CERTIFICATE_VERIFY, CHANGE_CIPHER_SPEC, CLIENT_HELLO, Direction,
ENCRYPTED_EXTENSIONS, Error, FINISHED, HANDSHAKE, MAX_FRAGMENT, SERVER_HELLO, Suite, Transcript, take,
take_u16, take_vec, with_len,
};
use crate::der;
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use pinnacle_crypto::{ed25519, x25519};
pub struct Config {
/// Its certificates, its own first (DER).
pub chain: Vec<Vec<u8>>,
/// The Ed25519 secret key of its own certificate.
pub key: [u8; 32],
/// The application protocols it speaks: the first of them the client
/// offers is chosen; none, and none is.
pub alpn: Vec<String>,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum State {
ClientHello,
Finished,
Connected,
Closed,
}
pub struct Server {
config: Config,
state: State,
random: [u8; 32],
/// Our X25519 secret, until the key exchange.
secret: [u8; 32],
read: Option<Direction>,
write: Option<Direction>,
/// The client's application traffic secret, taken once its Finished
/// checks, and what that Finished must be.
client_traffic: Vec<u8>,
client_finished: Vec<u8>,
exporter: Vec<u8>,
records: Vec<u8>,
messages: Vec<u8>,
output: Vec<u8>,
received: Vec<u8>,
protocol: Option<String>,
}
const SUITE: Suite = Suite::Aes128Gcm;
impl Server {
/// Waits for a ClientHello: `random` and `secret` (the X25519 secret)
/// are fresh random bytes.
pub fn new(config: Config, random: [u8; 32], secret: [u8; 32]) -> Server {
Server {
config,
state: State::ClientHello,
random,
secret,
read: None,
write: None,
client_traffic: Vec::new(),
client_finished: Vec::new(),
exporter: Vec::new(),
records: Vec::new(),
messages: Vec::new(),
output: Vec::new(),
received: Vec::new(),
protocol: None,
}
}
/// What is to be sent to the client.
pub fn take_output(&mut self) -> Vec<u8> {
core::mem::take(&mut self.output)
}
/// The application's data the client 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
}
pub fn closed(&self) -> bool {
self.state == State::Closed
}
/// The application protocol chosen, once the ClientHello is read.
pub fn protocol(&self) -> Option<&str> {
self.protocol.as_deref()
}
/// As [`client::Client::export`]: the same bytes the client derives.
pub fn export(&self, label: &str, context: &[u8], len: usize) -> Option<Vec<u8>> {
self.connected()
.then(|| SUITE.export(&self.exporter, label, context, len))
}
/// Sends the application's `data` (once its keys are there, after the
/// ClientHello).
pub fn write(&mut self, data: &[u8]) {
let Some(write) = self.write.as_mut().filter(|_| self.state != State::ClientHello) else {
return;
};
for chunk in data.chunks(MAX_FRAGMENT) {
let record = write.seal(APPLICATION_DATA, chunk);
self.output.extend_from_slice(&record);
}
}
/// Takes in what came from the client.
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();
let (header, body) = record.split_at(5);
let (kind, content) = match header[0] {
CHANGE_CIPHER_SPEC if body == [1] && self.state != State::Connected => continue,
HANDSHAKE if self.state == State::ClientHello => (HANDSHAKE, body.to_vec()),
APPLICATION_DATA => self
.read
.as_mut()
.ok_or(Error::Protocol("encrypted data before the keys"))?
.open(header, body)?,
client::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();
match (self.state, message[0]) {
(State::ClientHello, CLIENT_HELLO) => self.client_hello(&message)?,
(State::Finished, FINISHED) => {
if !pinnacle_crypto::equal(&message[4..], &self.client_finished) {
return Err(Error::Forged);
}
self.read = Some(Direction::new(SUITE, &self.client_traffic));
self.state = State::Connected;
}
_ => return Err(Error::Protocol("a handshake message out of turn")),
}
}
}
APPLICATION_DATA if self.state == State::Connected => {
self.received.extend_from_slice(&content)
}
client::ALERT if content == [1, 0] => self.state = State::Closed,
client::ALERT if content.len() == 2 => return Err(Error::Alert(content[1])),
_ => return Err(Error::Protocol("content of an unexpected kind")),
}
}
Ok(())
}
/// Reads the ClientHello and answers with the whole of its flight:
/// ServerHello, then encrypted its extensions, certificates, signature
/// and Finished.
fn client_hello(&mut self, message: &[u8]) -> Result<(), Error> {
let mut b = &message[4..];
take(&mut b, 2 + 32)?; // the legacy version, the random
let session_id = take_vec(&mut b, 1)?.to_vec();
if !take_vec(&mut b, 2)?.chunks(2).any(|s| s == [0x13, 0x01]) {
return Err(Error::Protocol("no cipher suite this server has"));
}
take_vec(&mut b, 1)?; // compression
let mut extensions = take_vec(&mut b, 2)?;
let (mut version, mut ed25519, mut share, mut offered) = (false, false, None, Vec::new());
while !extensions.is_empty() {
let kind = take_u16(&mut extensions)?;
let mut data = take_vec(&mut extensions, 2)?;
match kind {
0x002b => version = take_vec(&mut data, 1)?.chunks(2).any(|v| v == [3, 4]),
0x000d => ed25519 = take_vec(&mut data, 2)?.chunks(2).any(|s| s == [8, 7]),
0x0033 => {
let mut shares = take_vec(&mut data, 2)?;
while !shares.is_empty() {
let group = take_u16(&mut shares)?;
let key = take_vec(&mut shares, 2)?;
if group == 0x001d {
share = <[u8; 32]>::try_from(key).ok();
}
}
}
0x0010 => {
let mut list = take_vec(&mut data, 2)?;
while !list.is_empty() {
offered.push(take_vec(&mut list, 1)?);
}
}
_ => {}
}
}
if !version {
return Err(Error::Protocol("a client not speaking TLS 1.3"));
}
if !ed25519 {
return Err(Error::Protocol("a client that takes no Ed25519 signature"));
}
let share = share.ok_or(Error::Protocol("no X25519 key share"))?;
let shared = x25519::x25519(&self.secret, &share);
let public = x25519::public(&self.secret);
self.secret = [0; 32];
if shared == [0; 32] {
return Err(Error::Protocol("a key share of a small order"));
}
self.protocol = self
.config
.alpn
.iter()
.find(|p| offered.contains(&p.as_bytes()))
.cloned();
let mut transcript = Transcript::new(SUITE);
transcript.update(message);
let mut extensions = Vec::new();
extensions.extend_from_slice(&[0x00, 0x2b, 0, 2, 3, 4]);
let mut key_share = vec![0x00, 0x1d];
key_share.extend_from_slice(&with_len(2, &public));
extensions.extend_from_slice(&[0x00, 0x33]);
extensions.extend_from_slice(&with_len(2, &key_share));
let mut body = vec![3, 3];
body.extend_from_slice(&self.random);
body.extend_from_slice(&with_len(1, &session_id));
body.extend_from_slice(&[0x13, 0x01, 0]);
body.extend_from_slice(&with_len(2, &extensions));
let hello = handshake(SERVER_HELLO, &body);
transcript.update(&hello);
self.output.extend_from_slice(&[HANDSHAKE, 3, 3]);
self.output.extend_from_slice(&with_len(2, &hello));
// For middleboxes, as the client's session id asks.
if !session_id.is_empty() {
self.output
.extend_from_slice(&[CHANGE_CIPHER_SPEC, 3, 3, 0, 1, 1]);
}
let [client_handshake, server_handshake, master] =
SUITE.handshake_secrets(&shared, &transcript.hash());
let mut write = Direction::new(SUITE, &server_handshake);
let mut flight = Vec::new();
let mut alpn = Vec::new();
if let Some(p) = &self.protocol {
alpn.extend_from_slice(&[0x00, 0x10]);
alpn.extend_from_slice(&with_len(2, &with_len(2, &with_len(1, p.as_bytes()))));
}
flight.push(handshake(ENCRYPTED_EXTENSIONS, &with_len(2, &alpn)));
let mut list = Vec::new();
for der in &self.config.chain {
list.extend_from_slice(&with_len(3, der));
list.extend_from_slice(&[0, 0]);
}
let mut certificate = vec![0];
certificate.extend_from_slice(&with_len(3, &list));
flight.push(handshake(CERTIFICATE, &certificate));
for message in &flight {
transcript.update(message);
}
let mut content = vec![0x20u8; 64];
content.extend_from_slice(b"TLS 1.3, server CertificateVerify\0");
content.extend_from_slice(&transcript.hash());
let mut verify = vec![0x08, 0x07];
verify.extend_from_slice(&with_len(2, &ed25519::sign(&self.config.key, &content)));
let verify = handshake(CERTIFICATE_VERIFY, &verify);
transcript.update(&verify);
let len = SUITE.hash_len();
let key = SUITE.expand_label(&server_handshake, "finished", &[], len);
let finished = handshake(FINISHED, &SUITE.hmac(&key, &transcript.hash()));
transcript.update(&finished);
flight.push(verify);
flight.push(finished);
for message in &flight {
let record = write.seal(HANDSHAKE, message);
self.output.extend_from_slice(&record);
}
let hash = transcript.hash();
let key = SUITE.expand_label(&client_handshake, "finished", &[], len);
self.client_finished = SUITE.hmac(&key, &hash);
self.client_traffic = SUITE.expand_label(&master, "c ap traffic", &hash, len);
self.exporter = SUITE.expand_label(&master, "exp master", &hash, len);
let server_traffic = SUITE.expand_label(&master, "s ap traffic", &hash, len);
self.read = Some(Direction::new(SUITE, &client_handshake));
self.write = Some(Direction::new(SUITE, &server_traffic));
self.state = State::Finished;
Ok(())
}
}
/// A handshake message: its type, its body behind a 3-byte length.
fn handshake(kind: u8, body: &[u8]) -> Vec<u8> {
let mut message = vec![kind];
message.extend_from_slice(&with_len(3, body));
message
}
/// What [`certificate`] puts in a certificate.
pub struct Issue<'a> {
/// The subject's common name.
pub name: &'a str,
/// The subject's Ed25519 public key.
pub key: [u8; 32],
/// Who signs it: their common name and Ed25519 secret key (the
/// subject's own, for a root).
pub issuer: &'a str,
pub issuer_key: &'a [u8; 32],
/// May sign others (a root): else it is a server's, for `hosts`.
pub ca: bool,
pub hosts: &'a [&'a str],
/// Valid from, until: seconds since 1970.
pub from: i64,
pub until: i64,
}
/// An X.509 certificate (DER) for an Ed25519 key, signed with Ed25519.
pub fn certificate(issue: &Issue) -> Vec<u8> {
let algorithm = tlv(der::SEQUENCE, &tlv(der::OID, crate::x509::ED25519));
let mut extensions = Vec::new();
let mut extension = |oid: &[u8], value: Vec<u8>| {
let mut e = tlv(der::OID, oid);
e.extend_from_slice(&tlv(der::BOOLEAN, &[0xff]));
e.extend_from_slice(&tlv(der::OCTET_STRING, &value));
extensions.extend_from_slice(&tlv(der::SEQUENCE, &e));
};
let ca = if issue.ca {
tlv(der::BOOLEAN, &[0xff])
} else {
Vec::new()
};
extension(&[0x55, 0x1d, 0x13], tlv(der::SEQUENCE, &ca));
if issue.ca {
// keyCertSign and cRLSign.
extension(&[0x55, 0x1d, 0x0f], tlv(der::BIT_STRING, &[1, 0x06]));
} else {
let names: Vec<u8> = issue.hosts.iter().flat_map(|h| tlv(0x82, h.as_bytes())).collect();
extension(&[0x55, 0x1d, 0x11], tlv(der::SEQUENCE, &names));
let server = tlv(der::OID, &[0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x01]);
extension(&[0x55, 0x1d, 0x25], tlv(der::SEQUENCE, &server));
}
let mut validity = generalized_time(issue.from);
validity.extend_from_slice(&generalized_time(issue.until));
let mut key = vec![0];
key.extend_from_slice(&issue.key);
let mut spki = algorithm.clone();
spki.extend_from_slice(&tlv(der::BIT_STRING, &key));
let mut tbs = tlv(0xa0, &tlv(der::INTEGER, &[2]));
tbs.extend_from_slice(&tlv(der::INTEGER, &[1]));
tbs.extend_from_slice(&algorithm);
tbs.extend_from_slice(&name(issue.issuer));
tbs.extend_from_slice(&tlv(der::SEQUENCE, &validity));
tbs.extend_from_slice(&name(issue.name));
tbs.extend_from_slice(&tlv(der::SEQUENCE, &spki));
tbs.extend_from_slice(&tlv(0xa3, &tlv(der::SEQUENCE, &extensions)));
let tbs = tlv(der::SEQUENCE, &tbs);
let mut signature = vec![0];
signature.extend_from_slice(&ed25519::sign(issue.issuer_key, &tbs));
let mut cert = tbs;
cert.extend_from_slice(&algorithm);
cert.extend_from_slice(&tlv(der::BIT_STRING, &signature));
tlv(der::SEQUENCE, &cert)
}
/// A DER element: tag, length, value.
fn tlv(tag: u8, value: &[u8]) -> Vec<u8> {
let mut out = vec![tag];
match value.len() {
n if n < 0x80 => out.push(n as u8),
n if n < 0x100 => out.extend_from_slice(&[0x81, n as u8]),
n => out.extend_from_slice(&[0x82, (n >> 8) as u8, n as u8]),
}
out.extend_from_slice(value);
out
}
/// A name of one common name.
fn name(common: &str) -> Vec<u8> {
let mut attribute = tlv(der::OID, &[0x55, 0x04, 0x03]);
attribute.extend_from_slice(&tlv(0x0c, common.as_bytes()));
tlv(der::SEQUENCE, &tlv(0x31, &tlv(der::SEQUENCE, &attribute)))
}
/// Seconds since 1970 as a GeneralizedTime (YYYYMMDDHHMMSSZ).
fn generalized_time(seconds: i64) -> Vec<u8> {
// Howard Hinnant's civil-from-days.
let z = seconds.div_euclid(86_400) + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = doy - (153 * mp + 2) / 5 + 1;
let month = if mp < 10 { mp + 3 } else { mp - 9 };
let year = yoe + era * 400 + i64::from(month <= 2);
let s = seconds.rem_euclid(86_400);
let text = alloc::format!(
"{year:04}{month:02}{day:02}{:02}{:02}{:02}Z",
s / 3600,
s / 60 % 60,
s % 60
);
tlv(der::GENERALIZED_TIME, text.as_bytes())
}