bd91a1007e
Paused at Mark's request.
152 lines
5.3 KiB
Rust
152 lines
5.3 KiB
Rust
//! The AES-128-GCM frame around every control message (`docs/PROTOCOL.md` 3.2).
|
||
//!
|
||
//! ```text
|
||
//! 0 2 4 8 24
|
||
//! | 0x0001 | len | seq (LE) | GCM tag (16) | ciphertext … | len = 4 + 16 + ciphertext
|
||
//! nonce = seq (LE, 4) ‖ 0 × 6 ‖ direction ('C' client→host, 'H' host→client) ‖ 'C'
|
||
//! ```
|
||
|
||
use core::fmt;
|
||
|
||
use aes_gcm::Aes128Gcm;
|
||
use aes_gcm::aead::{AeadInOut, KeyInit};
|
||
|
||
use crate::util::{array, cap, malformed, u16_le, u32_le};
|
||
use crate::{Error, Result};
|
||
|
||
/// Type field of an encrypted frame.
|
||
pub const ENCRYPTED_FRAME_TYPE: u16 = 0x0001;
|
||
/// GCM tag length.
|
||
pub const GCM_TAG_LEN: usize = 16;
|
||
/// Bytes before the ciphertext (type, length, sequence, tag).
|
||
pub const FRAME_HEADER_LEN: usize = 2 + 2 + 4 + GCM_TAG_LEN;
|
||
/// Smallest valid frame: header plus a 4-byte message header inside.
|
||
pub const MIN_FRAME_BYTES: usize = FRAME_HEADER_LEN + 4;
|
||
/// Maximum frame size accepted or produced, in bytes.
|
||
pub const MAX_FRAME_BYTES: usize = 4096;
|
||
/// GCM nonce length.
|
||
pub const NONCE_LEN: usize = 12;
|
||
|
||
/// Which way a frame travels; selects byte 10 of the nonce.
|
||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||
pub enum Direction {
|
||
/// Client to host (`'C'`).
|
||
ClientToHost,
|
||
/// Host to client (`'H'`).
|
||
HostToClient,
|
||
}
|
||
|
||
/// The nonce for sequence number `sequence` in `direction`.
|
||
///
|
||
/// # Errors
|
||
/// None today.
|
||
pub fn nonce(sequence: u32, direction: Direction) -> Result<[u8; NONCE_LEN]> {
|
||
let mut n = [0u8; NONCE_LEN];
|
||
let [a, b, c, d] = sequence.to_le_bytes();
|
||
n[0] = a;
|
||
n[1] = b;
|
||
n[2] = c;
|
||
n[3] = d;
|
||
n[10] = match direction {
|
||
Direction::ClientToHost => b'C',
|
||
Direction::HostToClient => b'H',
|
||
};
|
||
n[11] = b'C';
|
||
Ok(n)
|
||
}
|
||
|
||
/// A frame split into its fields, not yet decrypted.
|
||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||
pub struct EncryptedFrame<'a> {
|
||
/// Sequence number.
|
||
pub sequence: u32,
|
||
/// GCM tag.
|
||
pub tag: [u8; GCM_TAG_LEN],
|
||
/// Ciphertext.
|
||
pub ciphertext: &'a [u8],
|
||
}
|
||
|
||
/// Splits a frame (one ENet packet) into its fields. The length field must match the bytes present exactly.
|
||
///
|
||
/// # Errors
|
||
/// [`Error::TooLarge`] over [`MAX_FRAME_BYTES`], [`Error::Truncated`] under [`MIN_FRAME_BYTES`],
|
||
/// [`Error::UnexpectedValue`] for a type other than [`ENCRYPTED_FRAME_TYPE`], [`Error::Malformed`] for a length
|
||
/// that does not match.
|
||
pub fn parse_encrypted_frame(frame: &[u8]) -> Result<EncryptedFrame<'_>> {
|
||
const W: &str = "control frame";
|
||
cap(W, MAX_FRAME_BYTES, frame.len())?;
|
||
crate::util::need(W, MIN_FRAME_BYTES, frame.len())?;
|
||
let kind = u16_le(W, frame, 0)?;
|
||
if kind != ENCRYPTED_FRAME_TYPE {
|
||
return Err(Error::UnexpectedValue { what: "control frame type", value: kind.into() });
|
||
}
|
||
if usize::from(u16_le(W, frame, 2)?) != frame.len() - 4 {
|
||
return Err(malformed("control frame length"));
|
||
}
|
||
Ok(EncryptedFrame {
|
||
sequence: u32_le(W, frame, 4)?,
|
||
tag: array::<GCM_TAG_LEN>(W, frame, 8)?,
|
||
ciphertext: frame.get(FRAME_HEADER_LEN..).unwrap_or(&[]),
|
||
})
|
||
}
|
||
|
||
/// AES-128-GCM with the session's `rikey`. `Debug` never prints the key.
|
||
#[derive(Clone)]
|
||
pub struct ControlCipher {
|
||
key: zeroize::Zeroizing<[u8; 16]>,
|
||
}
|
||
|
||
impl ControlCipher {
|
||
/// A cipher for `rikey`.
|
||
#[must_use]
|
||
pub fn new(rikey: [u8; 16]) -> Self {
|
||
Self { key: zeroize::Zeroizing::new(rikey) }
|
||
}
|
||
|
||
fn aead(&self) -> Aes128Gcm {
|
||
Aes128Gcm::new((&*self.key).into())
|
||
}
|
||
|
||
/// Encrypts one message (plaintext = type, length, body) into a whole frame.
|
||
///
|
||
/// # Errors
|
||
/// [`Error::TooLarge`] when the frame would exceed [`MAX_FRAME_BYTES`]; [`Error::Crypto`] if sealing fails.
|
||
pub fn seal(&self, sequence: u32, direction: Direction, plaintext: &[u8]) -> Result<Vec<u8>> {
|
||
cap("control frame", MAX_FRAME_BYTES, FRAME_HEADER_LEN.saturating_add(plaintext.len()))?;
|
||
let n = nonce(sequence, direction)?;
|
||
let mut body = plaintext.to_vec();
|
||
let tag = self
|
||
.aead()
|
||
.encrypt_inout_detached(&n.into(), b"", body.as_mut_slice().into())
|
||
.map_err(|_| Error::Crypto)?;
|
||
let len = u16::try_from(4 + GCM_TAG_LEN + body.len()).map_err(|_| malformed("control frame length"))?;
|
||
let mut out = Vec::with_capacity(FRAME_HEADER_LEN + body.len());
|
||
out.extend_from_slice(&ENCRYPTED_FRAME_TYPE.to_le_bytes());
|
||
out.extend_from_slice(&len.to_le_bytes());
|
||
out.extend_from_slice(&sequence.to_le_bytes());
|
||
out.extend_from_slice(tag.as_slice());
|
||
out.extend_from_slice(&body);
|
||
Ok(out)
|
||
}
|
||
|
||
/// Checks and decrypts one frame; returns its sequence number and the plaintext message.
|
||
///
|
||
/// # Errors
|
||
/// Parser errors as [`parse_encrypted_frame`]; [`Error::Crypto`] when the tag does not verify.
|
||
pub fn open(&self, direction: Direction, frame: &[u8]) -> Result<(u32, Vec<u8>)> {
|
||
let f = parse_encrypted_frame(frame)?;
|
||
let n = nonce(f.sequence, direction)?;
|
||
let mut body = f.ciphertext.to_vec();
|
||
self.aead()
|
||
.decrypt_inout_detached(&n.into(), b"", body.as_mut_slice().into(), &f.tag.into())
|
||
.map_err(|_| Error::Crypto)?;
|
||
Ok((f.sequence, body))
|
||
}
|
||
}
|
||
|
||
impl fmt::Debug for ControlCipher {
|
||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||
f.write_str("ControlCipher(<redacted>)")
|
||
}
|
||
}
|