Files
CustosPublic/crates/custos-seal/src/lib.rs
T

181 lines
7.2 KiB
Rust

//! Sealed boxes (docs/SEAL.md). A device that wants a secret makes a one-time X25519 key pair and sends
//! only its public key; whoever releases the secret seals it to that key, so the mailbox in between (the
//! factor service on the home server) carries ciphertext it cannot open. Also the factor service's
//! at-rest sealing of the TOTP shares it keeps.
//!
//! ```text
//! sealed = "CSL1" ‖ ephemeral public (32) ‖ nonce (24) ‖ XChaCha20-Poly1305(key, nonce, plaintext, aad)
//! key = HKDF-SHA256(X25519(ephemeral, recipient), salt = ephemeral pub ‖ recipient pub,
//! info = "custos seal v1" ‖ context)
//! aad = "CSL1" ‖ ephemeral public ‖ context
//!
//! at rest = "CSR1" ‖ nonce (24) ‖ XChaCha20-Poly1305(HKDF(key, "", "custos rest v1" ‖ context), nonce,
//! plaintext, "CSR1" ‖ context)
//! ```
//!
//! `context` binds a box to its purpose (e.g. `approval:<factor id>:<request id>`): a box sealed for one
//! request does not open as another.
use chacha20poly1305::aead::{Aead, KeyInit, Payload};
use chacha20poly1305::{XChaCha20Poly1305, XNonce};
use rand::Rng;
use rand::rand_core::UnwrapErr;
use rand::rngs::SysRng;
use sha2::{Digest, Sha256};
use x25519_dalek::{PublicKey, StaticSecret};
use zeroize::Zeroizing;
const MAGIC: &[u8; 4] = b"CSL1";
const REST: &[u8; 4] = b"CSR1";
const NONCE: usize = 24;
const TAG: usize = 16;
/// The largest plaintext a box carries (a key pair's private key fits many times over).
pub const MAX_PLAINTEXT: usize = 32 * 1024;
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
pub enum SealError {
#[error("not a sealed box, or it was changed")]
Malformed,
#[error("this box was not sealed for this key and purpose")]
Rejected,
#[error("not a valid public key")]
BadKey,
#[error("the secret is too large to seal")]
TooLarge,
}
fn random<const N: usize>() -> Zeroizing<[u8; N]> {
let mut b = Zeroizing::new([0u8; N]);
UnwrapErr(SysRng).fill_bytes(b.as_mut());
b
}
fn derive(ikm: &[u8], salt: &[u8], info: &[&[u8]]) -> Zeroizing<[u8; 32]> {
let mut k = Zeroizing::new([0u8; 32]);
hkdf::Hkdf::<Sha256>::new(Some(salt), ikm).expand(&info.concat(), k.as_mut()).expect("32 bytes is a valid HKDF length");
k
}
fn cipher(key: &[u8; 32]) -> XChaCha20Poly1305 {
XChaCha20Poly1305::new_from_slice(key).expect("32-byte key")
}
fn xnonce(n: &[u8]) -> XNonce {
XNonce::try_from(n).expect("24-byte nonce")
}
/// The one-time key pair of a device waiting for a secret. Its secret half never leaves memory and is
/// wiped on drop.
pub struct Recipient {
secret: StaticSecret,
public: [u8; 32],
}
impl Recipient {
pub fn generate() -> Recipient {
let secret = StaticSecret::from(*random::<32>());
let public = PublicKey::from(&secret).to_bytes();
Recipient { secret, public }
}
/// What the device sends: 32 bytes.
pub fn public(&self) -> [u8; 32] {
self.public
}
/// The six digits both screens show, so the person approving sees it is this request.
pub fn match_code(&self) -> String {
match_code(&self.public)
}
/// Opens a box sealed to this key for `context`.
pub fn open(&self, sealed: &[u8], context: &[u8]) -> Result<Zeroizing<Vec<u8>>, SealError> {
if sealed.len() < 4 + 32 + NONCE + TAG || &sealed[..4] != MAGIC {
return Err(SealError::Malformed);
}
let eph: [u8; 32] = sealed[4..36].try_into().expect("32 bytes");
let shared = self.secret.diffie_hellman(&PublicKey::from(eph));
if !shared.was_contributory() {
return Err(SealError::Rejected);
}
let key = derive(shared.as_bytes(), &[eph.as_slice(), &self.public].concat(), &[b"custos seal v1", context]);
let aad = [MAGIC.as_slice(), &eph, context].concat();
cipher(&key)
.decrypt(&xnonce(&sealed[36..36 + NONCE]), Payload { msg: &sealed[36 + NONCE..], aad: &aad })
.map(Zeroizing::new)
.map_err(|_| SealError::Rejected)
}
}
impl std::fmt::Debug for Recipient {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Recipient {{ match_code: {} }}", self.match_code())
}
}
/// Seals `plaintext` to a recipient's public key for `context`. Only that recipient opens it.
pub fn seal(recipient: &[u8], context: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, SealError> {
let recipient: [u8; 32] = recipient.try_into().map_err(|_| SealError::BadKey)?;
if plaintext.len() > MAX_PLAINTEXT {
return Err(SealError::TooLarge);
}
let eph = StaticSecret::from(*random::<32>());
let eph_pub = PublicKey::from(&eph).to_bytes();
let shared = eph.diffie_hellman(&PublicKey::from(recipient));
// A low-order "public key" would give a shared secret anyone knows.
if !shared.was_contributory() {
return Err(SealError::BadKey);
}
let key = derive(shared.as_bytes(), &[eph_pub.as_slice(), &recipient].concat(), &[b"custos seal v1", context]);
let nonce = random::<NONCE>();
let aad = [MAGIC.as_slice(), &eph_pub, context].concat();
let ct = cipher(&key)
.encrypt(&xnonce(nonce.as_ref()), Payload { msg: plaintext, aad: &aad })
.expect("encryption cannot fail for in-memory buffers");
Ok([MAGIC.as_slice(), &eph_pub, nonce.as_ref(), &ct].concat())
}
/// Six digits from a public key: what the requesting screen and the approving screen both show.
pub fn match_code(public: &[u8]) -> String {
let h = Sha256::new().chain_update(b"custos match v1").chain_update(public).finalize();
let n = u32::from_be_bytes([h[0], h[1], h[2], h[3]]) % 1_000_000;
format!("{n:06}")
}
/// The match code of the one-time key a box was sealed with. When the receiver must know who sealed a
/// box (pairing a phone), the sealing screen shows this code and the receiving screen checks it.
pub fn sender_code(sealed: &[u8]) -> Result<String, SealError> {
if sealed.len() < 4 + 32 + NONCE + TAG || &sealed[..4] != MAGIC {
return Err(SealError::Malformed);
}
Ok(match_code(&sealed[4..36]))
}
/// Seals data the factor service keeps on disk, with its own key (from a systemd credential).
pub fn seal_at_rest(key: &[u8; 32], context: &[u8], plaintext: &[u8]) -> Vec<u8> {
let k = derive(key, b"", &[b"custos rest v1", context]);
let nonce = random::<NONCE>();
let aad = [REST.as_slice(), context].concat();
let ct = cipher(&k)
.encrypt(&xnonce(nonce.as_ref()), Payload { msg: plaintext, aad: &aad })
.expect("encryption cannot fail for in-memory buffers");
[REST.as_slice(), nonce.as_ref(), &ct].concat()
}
pub fn open_at_rest(key: &[u8; 32], context: &[u8], sealed: &[u8]) -> Result<Zeroizing<Vec<u8>>, SealError> {
if sealed.len() < 4 + NONCE + TAG || &sealed[..4] != REST {
return Err(SealError::Malformed);
}
let k = derive(key, b"", &[b"custos rest v1", context]);
let aad = [REST.as_slice(), context].concat();
cipher(&k)
.decrypt(&xnonce(&sealed[4..4 + NONCE]), Payload { msg: &sealed[4 + NONCE..], aad: &aad })
.map(Zeroizing::new)
.map_err(|_| SealError::Rejected)
}
/// 32 random bytes from the OS (factor material, tokens).
pub fn random_bytes() -> Zeroizing<[u8; 32]> {
random()
}