first commit
This commit is contained in:
commit
6d3ea3e2a6
43 files changed
+8204
No files matched your search
@@ -0,0 +1,24 @@
|
||||
[package]
|
||||
name = "meow-crypto"
|
||||
description = "Meow v2 cryptographic primitives: keys, sealed boxes, Double Ratchet, at-rest encryption"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
ed25519-dalek = { version = "2.1", features = ["rand_core", "zeroize"] }
|
||||
x25519-dalek = { version = "2.0", features = ["static_secrets", "zeroize"] }
|
||||
chacha20poly1305 = "0.10"
|
||||
hkdf = "0.12"
|
||||
hmac = "0.12"
|
||||
sha2 = "0.10"
|
||||
argon2 = "0.5"
|
||||
rand_core = { version = "0.6", features = ["getrandom"] }
|
||||
zeroize = { version = "1", features = ["derive"] }
|
||||
subtle = "2"
|
||||
thiserror = "2"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
postcard = { version = "1", default-features = false, features = ["alloc"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,75 @@
|
||||
//! XChaCha20-Poly1305 with random nonces. Output format: `nonce (24) || ciphertext+tag`.
|
||||
|
||||
use chacha20poly1305::aead::{Aead, KeyInit, Payload};
|
||||
use chacha20poly1305::{XChaCha20Poly1305, XNonce};
|
||||
use zeroize::{Zeroize, ZeroizeOnDrop};
|
||||
|
||||
use crate::{CryptoError, Result};
|
||||
|
||||
pub const NONCE_LEN: usize = 24;
|
||||
pub const TAG_LEN: usize = 16;
|
||||
pub const OVERHEAD: usize = NONCE_LEN + TAG_LEN;
|
||||
|
||||
/// 256-bit symmetric key.
|
||||
#[derive(Clone, Zeroize, ZeroizeOnDrop, PartialEq, Eq)]
|
||||
pub struct Key(pub [u8; 32]);
|
||||
|
||||
impl Key {
|
||||
pub fn generate() -> Self {
|
||||
Key(crate::random_bytes())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Key {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("Key(..)")
|
||||
}
|
||||
}
|
||||
|
||||
pub fn encrypt(key: &Key, plaintext: &[u8], aad: &[u8]) -> Vec<u8> {
|
||||
let cipher = XChaCha20Poly1305::new((&key.0).into());
|
||||
let nonce: [u8; NONCE_LEN] = crate::random_bytes();
|
||||
// Encryption with a valid key and in-memory buffers cannot fail.
|
||||
let ct = cipher
|
||||
.encrypt(XNonce::from_slice(&nonce), Payload { msg: plaintext, aad })
|
||||
.unwrap_or_default();
|
||||
let mut out = Vec::with_capacity(NONCE_LEN + ct.len());
|
||||
out.extend_from_slice(&nonce);
|
||||
out.extend_from_slice(&ct);
|
||||
out
|
||||
}
|
||||
|
||||
pub fn decrypt(key: &Key, data: &[u8], aad: &[u8]) -> Result<Vec<u8>> {
|
||||
if data.len() < OVERHEAD {
|
||||
return Err(CryptoError::Decrypt);
|
||||
}
|
||||
let (nonce, ct) = data.split_at(NONCE_LEN);
|
||||
XChaCha20Poly1305::new((&key.0).into())
|
||||
.decrypt(XNonce::from_slice(nonce), Payload { msg: ct, aad })
|
||||
.map_err(|_| CryptoError::Decrypt)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn roundtrip_and_tamper() {
|
||||
let k = Key::generate();
|
||||
let ct = encrypt(&k, b"secret", b"ad");
|
||||
assert_eq!(decrypt(&k, &ct, b"ad").unwrap(), b"secret");
|
||||
assert!(decrypt(&k, &ct, b"AD").is_err());
|
||||
let mut bad = ct.clone();
|
||||
let last = bad.len() - 1;
|
||||
bad[last] ^= 1;
|
||||
assert!(decrypt(&k, &bad, b"ad").is_err());
|
||||
assert!(decrypt(&Key::generate(), &ct, b"ad").is_err());
|
||||
assert!(decrypt(&k, &ct[..10], b"ad").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonces_are_random() {
|
||||
let k = Key::generate();
|
||||
assert_ne!(encrypt(&k, b"x", b""), encrypt(&k, b"x", b""));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
//! HKDF-SHA256 with mandatory domain-separation labels.
|
||||
//!
|
||||
//! Every label is prefixed with `meow/v2/` so that keys derived for one purpose can
|
||||
//! never collide with keys derived for another one.
|
||||
|
||||
use hkdf::Hkdf;
|
||||
use hmac::{Hmac, Mac};
|
||||
use sha2::Sha256;
|
||||
|
||||
use crate::{CryptoError, Result};
|
||||
|
||||
pub const LABEL_PREFIX: &str = "meow/v2/";
|
||||
|
||||
/// Derive `N` bytes from `ikm` with an optional salt and a purpose label.
|
||||
pub fn derive<const N: usize>(ikm: &[u8], salt: &[u8], label: &str) -> Result<[u8; N]> {
|
||||
let hk = Hkdf::<Sha256>::new(Some(salt), ikm);
|
||||
let mut out = [0u8; N];
|
||||
let info = [LABEL_PREFIX.as_bytes(), label.as_bytes()].concat();
|
||||
hk.expand(&info, &mut out).map_err(|_| CryptoError::Kdf)?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// HMAC-SHA256.
|
||||
pub fn hmac(key: &[u8], data: &[u8]) -> [u8; 32] {
|
||||
// HMAC accepts keys of any length: `new_from_slice` cannot fail.
|
||||
let mut m = <Hmac<Sha256> as Mac>::new_from_slice(key).unwrap_or_else(|_| unreachable!());
|
||||
m.update(data);
|
||||
m.finalize().into_bytes().into()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn labels_separate_domains() {
|
||||
let a: [u8; 32] = derive(b"ikm", b"salt", "a").unwrap();
|
||||
let b: [u8; 32] = derive(b"ikm", b"salt", "b").unwrap();
|
||||
assert_ne!(a, b);
|
||||
let a2: [u8; 32] = derive(b"ikm", b"salt", "a").unwrap();
|
||||
assert_eq!(a, a2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
//! Strongly typed key material.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use ed25519_dalek::Signer;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use zeroize::{Zeroize, ZeroizeOnDrop};
|
||||
|
||||
use crate::{CryptoError, Result};
|
||||
|
||||
/// Ed25519 signature (64 bytes).
|
||||
pub type Signature = [u8; 64];
|
||||
|
||||
macro_rules! public_key_type {
|
||||
($name:ident, $doc:literal) => {
|
||||
#[doc = $doc]
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
pub struct $name(pub [u8; 32]);
|
||||
|
||||
impl $name {
|
||||
pub fn from_slice(b: &[u8]) -> Result<Self> {
|
||||
let arr: [u8; 32] = b.try_into().map_err(|_| CryptoError::BadKey)?;
|
||||
Ok(Self(arr))
|
||||
}
|
||||
pub fn as_bytes(&self) -> &[u8; 32] {
|
||||
&self.0
|
||||
}
|
||||
pub fn to_vec(&self) -> Vec<u8> {
|
||||
self.0.to_vec()
|
||||
}
|
||||
/// Lower-case hex, for logs/filenames (never for secrets).
|
||||
pub fn to_hex(&self) -> String {
|
||||
hex(&self.0)
|
||||
}
|
||||
/// Short fingerprint for UI display.
|
||||
pub fn fingerprint(&self) -> String {
|
||||
hex(&crate::sha256(&[&self.0])[..8])
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for $name {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, concat!(stringify!($name), "({})"), &self.to_hex()[..16])
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public_key_type!(SignPublic, "Ed25519 public key. Also used as a mailbox identifier.");
|
||||
public_key_type!(DhPublic, "X25519 public key.");
|
||||
|
||||
pub(crate) fn hex(b: &[u8]) -> String {
|
||||
b.iter().map(|x| format!("{x:02x}")).collect()
|
||||
}
|
||||
|
||||
impl SignPublic {
|
||||
pub fn verify(&self, msg: &[u8], sig: &[u8]) -> Result<()> {
|
||||
let vk = ed25519_dalek::VerifyingKey::from_bytes(&self.0).map_err(|_| CryptoError::BadKey)?;
|
||||
let sig: [u8; 64] = sig.try_into().map_err(|_| CryptoError::BadSignature)?;
|
||||
vk.verify_strict(msg, &ed25519_dalek::Signature::from_bytes(&sig))
|
||||
.map_err(|_| CryptoError::BadSignature)
|
||||
}
|
||||
}
|
||||
|
||||
/// Ed25519 key pair.
|
||||
#[derive(Clone, Zeroize, ZeroizeOnDrop, Serialize, Deserialize)]
|
||||
pub struct SigningKeyPair {
|
||||
secret: [u8; 32],
|
||||
}
|
||||
|
||||
impl SigningKeyPair {
|
||||
pub fn generate() -> Self {
|
||||
Self {
|
||||
secret: crate::random_bytes(),
|
||||
}
|
||||
}
|
||||
pub fn from_secret(secret: [u8; 32]) -> Self {
|
||||
Self { secret }
|
||||
}
|
||||
pub fn secret_bytes(&self) -> &[u8; 32] {
|
||||
&self.secret
|
||||
}
|
||||
fn inner(&self) -> ed25519_dalek::SigningKey {
|
||||
ed25519_dalek::SigningKey::from_bytes(&self.secret)
|
||||
}
|
||||
pub fn public(&self) -> SignPublic {
|
||||
SignPublic(self.inner().verifying_key().to_bytes())
|
||||
}
|
||||
pub fn sign(&self, msg: &[u8]) -> Signature {
|
||||
self.inner().sign(msg).to_bytes()
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for SigningKeyPair {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "SigningKeyPair({:?})", self.public())
|
||||
}
|
||||
}
|
||||
|
||||
/// X25519 key pair.
|
||||
#[derive(Clone, Zeroize, ZeroizeOnDrop, Serialize, Deserialize)]
|
||||
pub struct DhKeyPair {
|
||||
secret: [u8; 32],
|
||||
}
|
||||
|
||||
impl DhKeyPair {
|
||||
pub fn generate() -> Self {
|
||||
Self {
|
||||
secret: crate::random_bytes(),
|
||||
}
|
||||
}
|
||||
pub fn from_secret(secret: [u8; 32]) -> Self {
|
||||
Self { secret }
|
||||
}
|
||||
pub fn secret_bytes(&self) -> &[u8; 32] {
|
||||
&self.secret
|
||||
}
|
||||
fn inner(&self) -> x25519_dalek::StaticSecret {
|
||||
x25519_dalek::StaticSecret::from(self.secret)
|
||||
}
|
||||
pub fn public(&self) -> DhPublic {
|
||||
DhPublic(x25519_dalek::PublicKey::from(&self.inner()).to_bytes())
|
||||
}
|
||||
/// X25519. Rejects all-zero shared secrets (low-order peer keys).
|
||||
pub fn dh(&self, peer: &DhPublic) -> Result<SharedSecret> {
|
||||
let s = self.inner().diffie_hellman(&x25519_dalek::PublicKey::from(peer.0));
|
||||
if !s.was_contributory() {
|
||||
return Err(CryptoError::BadKey);
|
||||
}
|
||||
Ok(SharedSecret(s.to_bytes()))
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for DhKeyPair {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "DhKeyPair({:?})", self.public())
|
||||
}
|
||||
}
|
||||
|
||||
/// Raw X25519 output. Never use directly as a key: feed it to a KDF.
|
||||
#[derive(Zeroize, ZeroizeOnDrop)]
|
||||
pub struct SharedSecret(pub(crate) [u8; 32]);
|
||||
|
||||
impl SharedSecret {
|
||||
pub fn as_bytes(&self) -> &[u8; 32] {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn sign_verify() {
|
||||
let kp = SigningKeyPair::generate();
|
||||
let sig = kp.sign(b"hello");
|
||||
assert!(kp.public().verify(b"hello", &sig).is_ok());
|
||||
assert_eq!(kp.public().verify(b"hellO", &sig), Err(CryptoError::BadSignature));
|
||||
let other = SigningKeyPair::generate();
|
||||
assert!(other.public().verify(b"hello", &sig).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dh_agreement() {
|
||||
let a = DhKeyPair::generate();
|
||||
let b = DhKeyPair::generate();
|
||||
assert_eq!(
|
||||
a.dh(&b.public()).unwrap().as_bytes(),
|
||||
b.dh(&a.public()).unwrap().as_bytes()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dh_rejects_low_order() {
|
||||
let a = DhKeyPair::generate();
|
||||
assert!(a.dh(&DhPublic([0u8; 32])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roundtrip_secret() {
|
||||
let kp = SigningKeyPair::generate();
|
||||
let kp2 = SigningKeyPair::from_secret(*kp.secret_bytes());
|
||||
assert_eq!(kp.public(), kp2.public());
|
||||
let d = DhKeyPair::generate();
|
||||
assert_eq!(d.public(), DhKeyPair::from_secret(*d.secret_bytes()).public());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
//! Meow v2 cryptographic primitives.
|
||||
//!
|
||||
//! * [`keys`]: Ed25519 signing keys and X25519 Diffie-Hellman keys with strong types;
|
||||
//! * [`aead`]: XChaCha20-Poly1305 with random 24-byte nonces;
|
||||
//! * [`kdf`]: HKDF-SHA256 with domain-separation labels;
|
||||
//! * [`seal`]: ECIES-style sealed boxes with a derived response key;
|
||||
//! * [`password`]: Argon2id based at-rest encryption;
|
||||
//! * [`ratchet`]: Double Ratchet (Signal specification);
|
||||
//! * [`pad`]: length-hiding padding.
|
||||
//!
|
||||
//! Every secret type zeroizes its memory on drop.
|
||||
|
||||
#![forbid(unsafe_code)]
|
||||
#![cfg_attr(not(test), warn(clippy::unwrap_used, clippy::expect_used))]
|
||||
|
||||
pub mod aead;
|
||||
pub mod kdf;
|
||||
pub mod keys;
|
||||
pub mod pad;
|
||||
pub mod password;
|
||||
pub mod ratchet;
|
||||
pub mod seal;
|
||||
|
||||
pub use keys::{DhKeyPair, DhPublic, SignPublic, Signature, SigningKeyPair};
|
||||
|
||||
/// Errors raised by this crate. Messages are intentionally vague to avoid oracles.
|
||||
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
|
||||
pub enum CryptoError {
|
||||
#[error("decryption failed")]
|
||||
Decrypt,
|
||||
#[error("invalid signature")]
|
||||
BadSignature,
|
||||
#[error("invalid key material")]
|
||||
BadKey,
|
||||
#[error("malformed data")]
|
||||
Malformed,
|
||||
#[error("too many skipped messages")]
|
||||
TooManySkipped,
|
||||
#[error("ratchet session not ready to send")]
|
||||
NotReady,
|
||||
#[error("key derivation failed")]
|
||||
Kdf,
|
||||
}
|
||||
|
||||
pub type Result<T> = std::result::Result<T, CryptoError>;
|
||||
|
||||
/// Fill a fixed-size array with OS randomness.
|
||||
pub fn random_bytes<const N: usize>() -> [u8; N] {
|
||||
use rand_core::RngCore;
|
||||
let mut b = [0u8; N];
|
||||
rand_core::OsRng.fill_bytes(&mut b);
|
||||
b
|
||||
}
|
||||
|
||||
/// SHA-256 helper.
|
||||
pub fn sha256(parts: &[&[u8]]) -> [u8; 32] {
|
||||
use sha2::Digest;
|
||||
let mut h = sha2::Sha256::new();
|
||||
for p in parts {
|
||||
h.update((p.len() as u64).to_be_bytes());
|
||||
h.update(p);
|
||||
}
|
||||
h.finalize().into()
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
//! Length-hiding padding: `len (u32 BE) ‖ data ‖ zeros`, rounded up to a bucket size.
|
||||
//!
|
||||
//! Buckets: 256 B, 1 KiB, 4 KiB, 16 KiB, 64 KiB, then multiples of 64 KiB.
|
||||
|
||||
use crate::{CryptoError, Result};
|
||||
|
||||
const BUCKETS: [usize; 5] = [256, 1024, 4096, 16 * 1024, 64 * 1024];
|
||||
const STEP: usize = 64 * 1024;
|
||||
|
||||
fn bucket(n: usize) -> usize {
|
||||
BUCKETS
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|b| *b >= n)
|
||||
.unwrap_or_else(|| n.div_ceil(STEP) * STEP)
|
||||
}
|
||||
|
||||
pub fn pad(data: &[u8]) -> Vec<u8> {
|
||||
let total = bucket(data.len() + 4);
|
||||
let mut out = Vec::with_capacity(total);
|
||||
out.extend_from_slice(&(data.len() as u32).to_be_bytes());
|
||||
out.extend_from_slice(data);
|
||||
out.resize(total, 0);
|
||||
out
|
||||
}
|
||||
|
||||
pub fn unpad(padded: &[u8]) -> Result<&[u8]> {
|
||||
if padded.len() < 4 {
|
||||
return Err(CryptoError::Malformed);
|
||||
}
|
||||
let n = u32::from_be_bytes([padded[0], padded[1], padded[2], padded[3]]) as usize;
|
||||
padded.get(4..4 + n).ok_or(CryptoError::Malformed)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn buckets() {
|
||||
assert_eq!(pad(b"").len(), 256);
|
||||
assert_eq!(pad(&[1u8; 252]).len(), 256);
|
||||
assert_eq!(pad(&[1u8; 253]).len(), 1024);
|
||||
assert_eq!(pad(&[1u8; 70_000]).len(), 2 * STEP);
|
||||
for n in [0, 1, 252, 253, 5000, 70_000] {
|
||||
let d = vec![7u8; n];
|
||||
assert_eq!(unpad(&pad(&d)).unwrap(), &d[..]);
|
||||
}
|
||||
assert!(unpad(&[0, 0, 1, 0]).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
//! Password-based at-rest encryption (Argon2id + XChaCha20-Poly1305).
|
||||
//!
|
||||
//! Blob format:
|
||||
//! ```text
|
||||
//! "MEOWPW" (6) ‖ version (1) ‖ m_cost KiB (u32 BE) ‖ t_cost (u32 BE) ‖ p_cost (u32 BE)
|
||||
//! ‖ salt (16) ‖ nonce ‖ ciphertext+tag
|
||||
//! ```
|
||||
//! The header is authenticated as AEAD associated data.
|
||||
|
||||
use argon2::{Algorithm, Argon2, Params, Version};
|
||||
|
||||
use crate::aead::{self, Key};
|
||||
use crate::{CryptoError, Result};
|
||||
|
||||
const MAGIC: &[u8; 6] = b"MEOWPW";
|
||||
const VERSION: u8 = 1;
|
||||
const HEADER_LEN: usize = 6 + 1 + 12 + 16;
|
||||
|
||||
/// Argon2id cost parameters.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct KdfParams {
|
||||
pub m_cost_kib: u32,
|
||||
pub t_cost: u32,
|
||||
pub p_cost: u32,
|
||||
}
|
||||
|
||||
impl KdfParams {
|
||||
/// Interactive default: 64 MiB, 3 passes.
|
||||
pub const DEFAULT: Self = Self {
|
||||
m_cost_kib: 64 * 1024,
|
||||
t_cost: 3,
|
||||
p_cost: 1,
|
||||
};
|
||||
/// Very cheap parameters, for tests only.
|
||||
pub const INSECURE_TEST: Self = Self {
|
||||
m_cost_kib: 64,
|
||||
t_cost: 1,
|
||||
p_cost: 1,
|
||||
};
|
||||
}
|
||||
|
||||
/// Derive a key from a password with Argon2id.
|
||||
pub fn derive_key(password: &[u8], salt: &[u8; 16], p: KdfParams) -> Result<Key> {
|
||||
let params = Params::new(p.m_cost_kib, p.t_cost, p.p_cost, Some(32)).map_err(|_| CryptoError::Kdf)?;
|
||||
let mut out = [0u8; 32];
|
||||
Argon2::new(Algorithm::Argon2id, Version::V0x13, params)
|
||||
.hash_password_into(password, salt, &mut out)
|
||||
.map_err(|_| CryptoError::Kdf)?;
|
||||
Ok(Key(out))
|
||||
}
|
||||
|
||||
/// Encrypt `plaintext` under `password`.
|
||||
pub fn encrypt(password: &[u8], plaintext: &[u8], p: KdfParams) -> Result<Vec<u8>> {
|
||||
let salt: [u8; 16] = crate::random_bytes();
|
||||
let key = derive_key(password, &salt, p)?;
|
||||
let mut header = Vec::with_capacity(HEADER_LEN);
|
||||
header.extend_from_slice(MAGIC);
|
||||
header.push(VERSION);
|
||||
header.extend_from_slice(&p.m_cost_kib.to_be_bytes());
|
||||
header.extend_from_slice(&p.t_cost.to_be_bytes());
|
||||
header.extend_from_slice(&p.p_cost.to_be_bytes());
|
||||
header.extend_from_slice(&salt);
|
||||
let ct = aead::encrypt(&key, plaintext, &header);
|
||||
Ok([header, ct].concat())
|
||||
}
|
||||
|
||||
/// Decrypt a blob produced by [`encrypt`].
|
||||
pub fn decrypt(password: &[u8], blob: &[u8]) -> Result<Vec<u8>> {
|
||||
if blob.len() < HEADER_LEN || &blob[..6] != MAGIC || blob[6] != VERSION {
|
||||
return Err(CryptoError::Malformed);
|
||||
}
|
||||
let be = |i: usize| u32::from_be_bytes([blob[i], blob[i + 1], blob[i + 2], blob[i + 3]]);
|
||||
let p = KdfParams {
|
||||
m_cost_kib: be(7),
|
||||
t_cost: be(11),
|
||||
p_cost: be(15),
|
||||
};
|
||||
// Refuse absurd parameters coming from a tampered file (DoS).
|
||||
if p.m_cost_kib > 4 * 1024 * 1024 || p.t_cost > 64 || p.p_cost > 16 {
|
||||
return Err(CryptoError::Malformed);
|
||||
}
|
||||
let mut salt = [0u8; 16];
|
||||
salt.copy_from_slice(&blob[19..35]);
|
||||
let key = derive_key(password, &salt, p)?;
|
||||
aead::decrypt(&key, &blob[HEADER_LEN..], &blob[..HEADER_LEN])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn roundtrip() {
|
||||
let blob = encrypt(b"pw", b"data", KdfParams::INSECURE_TEST).unwrap();
|
||||
assert_eq!(decrypt(b"pw", &blob).unwrap(), b"data");
|
||||
assert_eq!(decrypt(b"bad", &blob), Err(CryptoError::Decrypt));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_is_authenticated() {
|
||||
let mut blob = encrypt(b"pw", b"data", KdfParams::INSECURE_TEST).unwrap();
|
||||
blob[20] ^= 1; // salt
|
||||
assert!(decrypt(b"pw", &blob).is_err());
|
||||
assert_eq!(decrypt(b"pw", b"junk"), Err(CryptoError::Malformed));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
//! Double Ratchet, following the Signal specification
|
||||
//! (<https://signal.org/docs/specifications/doubleratchet/>).
|
||||
//!
|
||||
//! * `KDF_RK(rk, dh)` = HKDF-SHA256(salt = rk, ikm = dh, "ratchet/rk") → (rk', ck)
|
||||
//! * `KDF_CK(ck)` = (HMAC(ck, 0x02), HMAC(ck, 0x01)) → (ck', mk)
|
||||
//! * `ENCRYPT(mk, pt, ad ‖ header)` = XChaCha20-Poly1305 (random nonce)
|
||||
//!
|
||||
//! Decryption is transactional: the state is only updated when authentication
|
||||
//! succeeds, so forged or replayed messages cannot desynchronise a session.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use zeroize::{Zeroize, ZeroizeOnDrop};
|
||||
|
||||
use crate::aead::{self, Key};
|
||||
use crate::keys::{DhKeyPair, DhPublic};
|
||||
use crate::{kdf, CryptoError, Result};
|
||||
|
||||
/// Maximum number of message keys skipped within one receiving chain.
|
||||
pub const MAX_SKIP: u32 = 1000;
|
||||
/// Maximum number of skipped message keys kept overall (oldest are dropped).
|
||||
pub const MAX_STORED_SKIPPED: usize = 2000;
|
||||
|
||||
/// Clear-text ratchet header.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Header {
|
||||
pub dh: DhPublic,
|
||||
/// Number of messages in the previous sending chain.
|
||||
pub pn: u32,
|
||||
/// Message number in the current sending chain.
|
||||
pub n: u32,
|
||||
}
|
||||
|
||||
impl Header {
|
||||
fn encode(&self) -> [u8; 40] {
|
||||
let mut out = [0u8; 40];
|
||||
out[..32].copy_from_slice(&self.dh.0);
|
||||
out[32..36].copy_from_slice(&self.pn.to_be_bytes());
|
||||
out[36..].copy_from_slice(&self.n.to_be_bytes());
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize, Zeroize, ZeroizeOnDrop)]
|
||||
struct SkippedKey {
|
||||
dh: [u8; 32],
|
||||
n: u32,
|
||||
order: u64,
|
||||
mk: [u8; 32],
|
||||
}
|
||||
|
||||
/// Double Ratchet session state. Serialisable with [`Session::to_bytes`].
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
pub struct Session {
|
||||
dhs: DhKeyPair,
|
||||
dhr: Option<DhPublic>,
|
||||
rk: [u8; 32],
|
||||
cks: Option<[u8; 32]>,
|
||||
ckr: Option<[u8; 32]>,
|
||||
ns: u32,
|
||||
nr: u32,
|
||||
pn: u32,
|
||||
skipped: BTreeMap<([u8; 32], u32), SkippedKey>,
|
||||
skip_counter: u64,
|
||||
}
|
||||
|
||||
impl Drop for Session {
|
||||
fn drop(&mut self) {
|
||||
self.rk.zeroize();
|
||||
if let Some(c) = self.cks.as_mut() {
|
||||
c.zeroize();
|
||||
}
|
||||
if let Some(c) = self.ckr.as_mut() {
|
||||
c.zeroize();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn kdf_rk(rk: &[u8; 32], dh: &[u8; 32]) -> Result<([u8; 32], [u8; 32])> {
|
||||
let okm: [u8; 64] = kdf::derive(dh, rk, "ratchet/rk")?;
|
||||
let mut new_rk = [0u8; 32];
|
||||
let mut ck = [0u8; 32];
|
||||
new_rk.copy_from_slice(&okm[..32]);
|
||||
ck.copy_from_slice(&okm[32..]);
|
||||
Ok((new_rk, ck))
|
||||
}
|
||||
|
||||
fn kdf_ck(ck: &[u8; 32]) -> ([u8; 32], [u8; 32]) {
|
||||
(kdf::hmac(ck, &[0x02]), kdf::hmac(ck, &[0x01]))
|
||||
}
|
||||
|
||||
fn full_ad(ad: &[u8], h: &Header) -> Vec<u8> {
|
||||
[ad, &h.encode()].concat()
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Initialise the party that sends first (the invitation initiator),
|
||||
/// knowing the peer's initial ratchet public key.
|
||||
pub fn init_sender(shared_key: [u8; 32], peer_ratchet: DhPublic) -> Result<Self> {
|
||||
let dhs = DhKeyPair::generate();
|
||||
let dh = dhs.dh(&peer_ratchet)?;
|
||||
let (rk, cks) = kdf_rk(&shared_key, dh.as_bytes())?;
|
||||
Ok(Self {
|
||||
dhs,
|
||||
dhr: Some(peer_ratchet),
|
||||
rk,
|
||||
cks: Some(cks),
|
||||
ckr: None,
|
||||
ns: 0,
|
||||
nr: 0,
|
||||
pn: 0,
|
||||
skipped: BTreeMap::new(),
|
||||
skip_counter: 0,
|
||||
})
|
||||
}
|
||||
|
||||
/// Initialise the party that receives first, owning the initial ratchet key pair.
|
||||
pub fn init_receiver(shared_key: [u8; 32], own_ratchet: DhKeyPair) -> Self {
|
||||
Self {
|
||||
dhs: own_ratchet,
|
||||
dhr: None,
|
||||
rk: shared_key,
|
||||
cks: None,
|
||||
ckr: None,
|
||||
ns: 0,
|
||||
nr: 0,
|
||||
pn: 0,
|
||||
skipped: BTreeMap::new(),
|
||||
skip_counter: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this side can already send (the receiver must first receive one message).
|
||||
pub fn can_send(&self) -> bool {
|
||||
self.cks.is_some()
|
||||
}
|
||||
|
||||
pub fn encrypt(&mut self, plaintext: &[u8], ad: &[u8]) -> Result<(Header, Vec<u8>)> {
|
||||
let ck = self.cks.ok_or(CryptoError::NotReady)?;
|
||||
let (next_ck, mk) = kdf_ck(&ck);
|
||||
self.cks = Some(next_ck);
|
||||
let header = Header {
|
||||
dh: self.dhs.public(),
|
||||
pn: self.pn,
|
||||
n: self.ns,
|
||||
};
|
||||
self.ns += 1;
|
||||
let ct = aead::encrypt(&Key(mk), plaintext, &full_ad(ad, &header));
|
||||
Ok((header, ct))
|
||||
}
|
||||
|
||||
pub fn decrypt(&mut self, header: &Header, ciphertext: &[u8], ad: &[u8]) -> Result<Vec<u8>> {
|
||||
// Skipped message?
|
||||
if let Some(sk) = self.skipped.get(&(header.dh.0, header.n)) {
|
||||
let pt = aead::decrypt(&Key(sk.mk), ciphertext, &full_ad(ad, header))?;
|
||||
self.skipped.remove(&(header.dh.0, header.n));
|
||||
return Ok(pt);
|
||||
}
|
||||
// Work on a copy: commit only on success.
|
||||
let mut next = self.clone();
|
||||
if Some(header.dh) != next.dhr {
|
||||
next.skip_until(header.pn)?;
|
||||
next.dh_ratchet(header)?;
|
||||
}
|
||||
next.skip_until(header.n)?;
|
||||
let ck = next.ckr.ok_or(CryptoError::Decrypt)?;
|
||||
let (next_ck, mk) = kdf_ck(&ck);
|
||||
next.ckr = Some(next_ck);
|
||||
next.nr += 1;
|
||||
let pt = aead::decrypt(&Key(mk), ciphertext, &full_ad(ad, header))?;
|
||||
*self = next;
|
||||
Ok(pt)
|
||||
}
|
||||
|
||||
fn skip_until(&mut self, until: u32) -> Result<()> {
|
||||
let Some(mut ck) = self.ckr else { return Ok(()) };
|
||||
if until < self.nr {
|
||||
return Ok(());
|
||||
}
|
||||
if until - self.nr > MAX_SKIP {
|
||||
return Err(CryptoError::TooManySkipped);
|
||||
}
|
||||
let dhr = self.dhr.ok_or(CryptoError::Decrypt)?;
|
||||
while self.nr < until {
|
||||
let (next_ck, mk) = kdf_ck(&ck);
|
||||
ck = next_ck;
|
||||
self.skip_counter += 1;
|
||||
self.skipped.insert(
|
||||
(dhr.0, self.nr),
|
||||
SkippedKey {
|
||||
dh: dhr.0,
|
||||
n: self.nr,
|
||||
order: self.skip_counter,
|
||||
mk,
|
||||
},
|
||||
);
|
||||
self.nr += 1;
|
||||
}
|
||||
self.ckr = Some(ck);
|
||||
while self.skipped.len() > MAX_STORED_SKIPPED {
|
||||
let oldest = self
|
||||
.skipped
|
||||
.iter()
|
||||
.min_by_key(|(_, v)| v.order)
|
||||
.map(|(k, _)| *k)
|
||||
.ok_or(CryptoError::Decrypt)?;
|
||||
self.skipped.remove(&oldest);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn dh_ratchet(&mut self, header: &Header) -> Result<()> {
|
||||
self.pn = self.ns;
|
||||
self.ns = 0;
|
||||
self.nr = 0;
|
||||
self.dhr = Some(header.dh);
|
||||
let dh = self.dhs.dh(&header.dh)?;
|
||||
let (rk, ckr) = kdf_rk(&self.rk, dh.as_bytes())?;
|
||||
self.rk = rk;
|
||||
self.ckr = Some(ckr);
|
||||
self.dhs = DhKeyPair::generate();
|
||||
let dh = self.dhs.dh(&header.dh)?;
|
||||
let (rk, cks) = kdf_rk(&self.rk, dh.as_bytes())?;
|
||||
self.rk = rk;
|
||||
self.cks = Some(cks);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Serialise the full state (contains secrets: encrypt before storing!).
|
||||
pub fn to_bytes(&self) -> Vec<u8> {
|
||||
postcard::to_allocvec(self).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn from_bytes(b: &[u8]) -> Result<Self> {
|
||||
postcard::from_bytes(b).map_err(|_| CryptoError::Malformed)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn pair() -> (Session, Session) {
|
||||
let sk: [u8; 32] = crate::random_bytes();
|
||||
let bob_ratchet = DhKeyPair::generate();
|
||||
let alice = Session::init_sender(sk, bob_ratchet.public()).unwrap();
|
||||
let bob = Session::init_receiver(sk, bob_ratchet);
|
||||
(alice, bob)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ping_pong() {
|
||||
let (mut a, mut b) = pair();
|
||||
assert!(!b.can_send());
|
||||
for i in 0..5 {
|
||||
let m = format!("a->b {i}");
|
||||
let (h, c) = a.encrypt(m.as_bytes(), b"ad").unwrap();
|
||||
assert_eq!(b.decrypt(&h, &c, b"ad").unwrap(), m.as_bytes());
|
||||
let m = format!("b->a {i}");
|
||||
let (h, c) = b.encrypt(m.as_bytes(), b"ad").unwrap();
|
||||
assert_eq!(a.decrypt(&h, &c, b"ad").unwrap(), m.as_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn out_of_order_and_replay() {
|
||||
let (mut a, mut b) = pair();
|
||||
let msgs: Vec<_> = (0..4).map(|i| a.encrypt(&[i], b"").unwrap()).collect();
|
||||
assert_eq!(b.decrypt(&msgs[3].0, &msgs[3].1, b"").unwrap(), [3]);
|
||||
assert_eq!(b.decrypt(&msgs[0].0, &msgs[0].1, b"").unwrap(), [0]);
|
||||
assert_eq!(b.decrypt(&msgs[2].0, &msgs[2].1, b"").unwrap(), [2]);
|
||||
// replay
|
||||
assert!(b.decrypt(&msgs[0].0, &msgs[0].1, b"").is_err());
|
||||
assert_eq!(b.decrypt(&msgs[1].0, &msgs[1].1, b"").unwrap(), [1]);
|
||||
// new chain after reply, old chain messages still decryptable
|
||||
let late = a.encrypt(b"late", b"").unwrap();
|
||||
let (h, c) = b.encrypt(b"reply", b"").unwrap();
|
||||
a.decrypt(&h, &c, b"").unwrap();
|
||||
let (h2, c2) = a.encrypt(b"new chain", b"").unwrap();
|
||||
assert_eq!(b.decrypt(&h2, &c2, b"").unwrap(), b"new chain");
|
||||
assert_eq!(b.decrypt(&late.0, &late.1, b"").unwrap(), b"late");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forgery_does_not_corrupt_state() {
|
||||
let (mut a, mut b) = pair();
|
||||
let (h, mut c) = a.encrypt(b"x", b"").unwrap();
|
||||
let good = c.clone();
|
||||
let last = c.len() - 1;
|
||||
c[last] ^= 1;
|
||||
assert!(b.decrypt(&h, &c, b"").is_err());
|
||||
// forged header with a random DH key
|
||||
let fake = Header {
|
||||
dh: DhKeyPair::generate().public(),
|
||||
pn: 0,
|
||||
n: 0,
|
||||
};
|
||||
assert!(b.decrypt(&fake, &good, b"").is_err());
|
||||
assert_eq!(b.decrypt(&h, &good, b"").unwrap(), b"x");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_ad_fails() {
|
||||
let (mut a, mut b) = pair();
|
||||
let (h, c) = a.encrypt(b"x", b"ad1").unwrap();
|
||||
assert!(b.decrypt(&h, &c, b"ad2").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_many_skipped() {
|
||||
let (mut a, mut b) = pair();
|
||||
let mut h = a.encrypt(b"", b"").unwrap().0;
|
||||
h.n = MAX_SKIP + 5;
|
||||
assert_eq!(
|
||||
b.decrypt(&h, b"whatever-ciphertext-long-enough-for-aead", b""),
|
||||
Err(CryptoError::TooManySkipped)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persist_and_restore() {
|
||||
let (mut a, mut b) = pair();
|
||||
let (h, c) = a.encrypt(b"1", b"").unwrap();
|
||||
b.decrypt(&h, &c, b"").unwrap();
|
||||
let mut a2 = Session::from_bytes(&a.to_bytes()).unwrap();
|
||||
let mut b2 = Session::from_bytes(&b.to_bytes()).unwrap();
|
||||
let (h, c) = b2.encrypt(b"2", b"").unwrap();
|
||||
assert_eq!(a2.decrypt(&h, &c, b"").unwrap(), b"2");
|
||||
let (h, c) = a2.encrypt(b"3", b"").unwrap();
|
||||
assert_eq!(b2.decrypt(&h, &c, b"").unwrap(), b"3");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
//! Sealed boxes (ECIES: X25519 + HKDF-SHA256 + XChaCha20-Poly1305).
|
||||
//!
|
||||
//! ```text
|
||||
//! eph ← fresh X25519
|
||||
//! shared = DH(eph, recipient)
|
||||
//! k_req ‖ k_resp = HKDF(shared, salt = eph_pk ‖ recipient_pk, "seal/" ‖ context)
|
||||
//! ciphertext = AEAD(k_req, plaintext, aad = context)
|
||||
//! ```
|
||||
//!
|
||||
//! `k_resp` lets the recipient answer the (anonymous) sender without knowing who it is.
|
||||
|
||||
use crate::aead::{self, Key};
|
||||
use crate::keys::{DhKeyPair, DhPublic};
|
||||
use crate::{kdf, Result};
|
||||
|
||||
/// A sealed message as transported.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct SealedBox {
|
||||
pub ephemeral: DhPublic,
|
||||
pub ciphertext: Vec<u8>,
|
||||
}
|
||||
|
||||
fn keys(shared: &[u8; 32], eph: &DhPublic, recipient: &DhPublic, context: &str) -> Result<(Key, Key)> {
|
||||
let salt = [eph.0.as_slice(), recipient.0.as_slice()].concat();
|
||||
let okm: [u8; 64] = kdf::derive(shared, &salt, &format!("seal/{context}"))?;
|
||||
let mut req = [0u8; 32];
|
||||
let mut resp = [0u8; 32];
|
||||
req.copy_from_slice(&okm[..32]);
|
||||
resp.copy_from_slice(&okm[32..]);
|
||||
Ok((Key(req), Key(resp)))
|
||||
}
|
||||
|
||||
/// Seal `plaintext` for `recipient`. Returns the box and the key that will protect the reply.
|
||||
pub fn seal(recipient: &DhPublic, context: &str, plaintext: &[u8]) -> Result<(SealedBox, Key)> {
|
||||
let eph = DhKeyPair::generate();
|
||||
let eph_pub = eph.public();
|
||||
let shared = eph.dh(recipient)?;
|
||||
let (k_req, k_resp) = keys(shared.as_bytes(), &eph_pub, recipient, context)?;
|
||||
let ciphertext = aead::encrypt(&k_req, plaintext, context.as_bytes());
|
||||
Ok((
|
||||
SealedBox {
|
||||
ephemeral: eph_pub,
|
||||
ciphertext,
|
||||
},
|
||||
k_resp,
|
||||
))
|
||||
}
|
||||
|
||||
/// Open a sealed box with the recipient key pair. Returns the plaintext and the reply key.
|
||||
pub fn open(recipient: &DhKeyPair, context: &str, sealed: &SealedBox) -> Result<(Vec<u8>, Key)> {
|
||||
let shared = recipient.dh(&sealed.ephemeral)?;
|
||||
let (k_req, k_resp) = keys(shared.as_bytes(), &sealed.ephemeral, &recipient.public(), context)?;
|
||||
let pt = aead::decrypt(&k_req, &sealed.ciphertext, context.as_bytes())?;
|
||||
Ok((pt, k_resp))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn seal_open_with_reply() {
|
||||
let server = DhKeyPair::generate();
|
||||
let (sealed, k_client) = seal(&server.public(), "rpc", b"request").unwrap();
|
||||
let (pt, k_server) = open(&server, "rpc", &sealed).unwrap();
|
||||
assert_eq!(pt, b"request");
|
||||
assert_eq!(k_client, k_server);
|
||||
let reply = aead::encrypt(&k_server, b"response", b"");
|
||||
assert_eq!(aead::decrypt(&k_client, &reply, b"").unwrap(), b"response");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_context_or_key_fails() {
|
||||
let server = DhKeyPair::generate();
|
||||
let (sealed, _) = seal(&server.public(), "rpc", b"x").unwrap();
|
||||
assert!(open(&server, "other", &sealed).is_err());
|
||||
assert!(open(&DhKeyPair::generate(), "rpc", &sealed).is_err());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user