| @@ -1,13 +1,16 @@ |
| 1 | 1 | //! Cryptographic kernels over `ring` (already linked for TLS, ADR 0038): |
| 2 | 2 | //! SHA-256, HMAC-SHA-256 and PBKDF2-HMAC-SHA-256 — what PostgreSQL's |
| 3 | | −//! SCRAM-SHA-256 authentication (RFC 5802, RFC 7677) needs — and Ed25519 |
| 4 | | −//! signatures (RFC 8032, ADR 0067). |
| 3 | +//! SCRAM-SHA-256 authentication (RFC 5802, RFC 7677) needs — Ed25519 |
| 4 | +//! signatures (RFC 8032, ADR 0067), and ChaCha20-Poly1305 with HKDF for |
| 5 | +//! encryption at rest (RFC 8439, RFC 5869, ADR 0071). |
| 5 | 6 | //! |
| 6 | 7 | //! Both back ends call these, so a hash can never drift between them; the |
| 7 | | −//! FIPS 180-4, RFC 2202 and RFC 8032 vectors below pin them down anyway. |
| 8 | +//! FIPS 180-4, RFC 2202, RFC 8032, RFC 8439 and RFC 5869 vectors below pin |
| 9 | +//! them down anyway. |
| 8 | 10 | |
| 11 | +use ring::aead::{Aad, CHACHA20_POLY1305, LessSafeKey, Nonce, UnboundKey}; |
| 9 | 12 | use ring::signature::{ED25519, Ed25519KeyPair, KeyPair, UnparsedPublicKey}; |
| 10 | | −use ring::{digest, hmac, pbkdf2}; |
| 13 | +use ring::{digest, hkdf, hmac, pbkdf2}; |
| 11 | 14 | use std::num::NonZeroU32; |
| 12 | 15 | |
| 13 | 16 | /// SHA-256 of `data`. |
| @@ -73,6 +76,99 @@ fn key_pair(seed: &[u8]) -> Result<Ed25519KeyPair, String> { |
| 73 | 76 | .map_err(|_| format!("crypto: an Ed25519 seed is 32 bytes, not {}", seed.len())) |
| 74 | 77 | } |
| 75 | 78 | |
| 79 | +/// The ChaCha20-Poly1305 sealing of `plaintext` under a 32-byte `key` and a |
| 80 | +/// 12-byte `nonce`, authenticating `aad` too (RFC 8439): the ciphertext |
| 81 | +/// followed by the 16-byte tag. A key or nonce of another length is |
| 82 | +/// refused, with the message both back ends panic with. |
| 83 | +pub fn chacha20_poly1305_seal( |
| 84 | + key: &[u8], |
| 85 | + nonce: &[u8], |
| 86 | + plaintext: &[u8], |
| 87 | + aad: &[u8], |
| 88 | +) -> Result<Vec<u8>, String> { |
| 89 | + let (key, nonce) = (aead_key(key)?, aead_nonce(nonce)?); |
| 90 | + let mut sealed = plaintext.to_vec(); |
| 91 | + key.seal_in_place_append_tag(nonce, Aad::from(aad), &mut sealed) |
| 92 | + .map_err(|_| "crypto: a ChaCha20-Poly1305 message is at most 256 GiB".to_string())?; |
| 93 | + Ok(sealed) |
| 94 | +} |
| 95 | + |
| 96 | +/// What `open` answers when a message does not authenticate. |
| 97 | +pub const NOT_AUTHENTIC: &str = |
| 98 | + "crypto: the sealed message does not authenticate under this key, nonce and associated data"; |
| 99 | + |
| 100 | +/// The plaintext of `sealed`, if it authenticates under `key`, `nonce` and |
| 101 | +/// `aad`; `None` if it does not (a changed byte, a wrong key, nonce or |
| 102 | +/// `aad`, or fewer than 16 bytes). A key or nonce of another length is |
| 103 | +/// refused like [`chacha20_poly1305_seal`]'s. |
| 104 | +pub fn chacha20_poly1305_open( |
| 105 | + key: &[u8], |
| 106 | + nonce: &[u8], |
| 107 | + sealed: &[u8], |
| 108 | + aad: &[u8], |
| 109 | +) -> Result<Option<Vec<u8>>, String> { |
| 110 | + let (key, nonce) = (aead_key(key)?, aead_nonce(nonce)?); |
| 111 | + let mut buffer = sealed.to_vec(); |
| 112 | + Ok(key |
| 113 | + .open_in_place(nonce, Aad::from(aad), &mut buffer) |
| 114 | + .ok() |
| 115 | + .map(|plaintext| plaintext.to_vec())) |
| 116 | +} |
| 117 | + |
| 118 | +fn aead_key(key: &[u8]) -> Result<LessSafeKey, String> { |
| 119 | + UnboundKey::new(&CHACHA20_POLY1305, key) |
| 120 | + .map(LessSafeKey::new) |
| 121 | + .map_err(|_| { |
| 122 | + format!( |
| 123 | + "crypto: a ChaCha20-Poly1305 key is 32 bytes, not {}", |
| 124 | + key.len() |
| 125 | + ) |
| 126 | + }) |
| 127 | +} |
| 128 | + |
| 129 | +fn aead_nonce(nonce: &[u8]) -> Result<Nonce, String> { |
| 130 | + Nonce::try_assume_unique_for_key(nonce).map_err(|_| { |
| 131 | + format!( |
| 132 | + "crypto: a ChaCha20-Poly1305 nonce is 12 bytes, not {}", |
| 133 | + nonce.len() |
| 134 | + ) |
| 135 | + }) |
| 136 | +} |
| 137 | + |
| 138 | +/// The most HKDF-SHA-256 can derive: 255 blocks of 32 bytes (RFC 5869). |
| 139 | +pub const HKDF_SHA256_MAX: usize = 255 * 32; |
| 140 | + |
| 141 | +/// HKDF-SHA-256 (RFC 5869), extract then expand: `length` bytes derived |
| 142 | +/// from `secret` with `salt` (empty means a zero salt) and `info`. A length |
| 143 | +/// outside `0..=8160` is refused, with the message both back ends panic |
| 144 | +/// with. |
| 145 | +pub fn hkdf_sha256( |
| 146 | + secret: &[u8], |
| 147 | + salt: &[u8], |
| 148 | + info: &[u8], |
| 149 | + length: i64, |
| 150 | +) -> Result<Vec<u8>, String> { |
| 151 | + let length = usize::try_from(length) |
| 152 | + .ok() |
| 153 | + .filter(|n| *n <= HKDF_SHA256_MAX) |
| 154 | + .ok_or_else(|| format!("crypto: HKDF-SHA-256 derives 0 to 8160 bytes, not {length}"))?; |
| 155 | + let mut out = vec![0u8; length]; |
| 156 | + hkdf::Salt::new(hkdf::HKDF_SHA256, salt) |
| 157 | + .extract(secret) |
| 158 | + .expand(&[info], Length(length)) |
| 159 | + .and_then(|okm| okm.fill(&mut out)) |
| 160 | + .expect("the length is checked above"); |
| 161 | + Ok(out) |
| 162 | +} |
| 163 | + |
| 164 | +struct Length(usize); |
| 165 | + |
| 166 | +impl hkdf::KeyType for Length { |
| 167 | + fn len(&self) -> usize { |
| 168 | + self.0 |
| 169 | + } |
| 170 | +} |
| 171 | + |
| 76 | 172 | #[cfg(test)] |
| 77 | 173 | mod tests { |
| 78 | 174 | use super::*; |
| @@ -153,4 +249,90 @@ mod tests { |
| 153 | 249 | ); |
| 154 | 250 | assert!(ed25519_sign(&[], b"m").is_err()); |
| 155 | 251 | } |
| 252 | + |
| 253 | + const SUNSCREEN: &[u8] = b"Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the future, sunscreen would be it."; |
| 254 | + |
| 255 | + #[test] |
| 256 | + fn chacha20_poly1305_vectors() { |
| 257 | + // RFC 8439 §2.8.2. |
| 258 | + let key: Vec<u8> = (0x80..=0x9f).collect(); |
| 259 | + let nonce = unhex("070000004041424344454647"); |
| 260 | + let aad = unhex("50515253c0c1c2c3c4c5c6c7"); |
| 261 | + let sealed = chacha20_poly1305_seal(&key, &nonce, SUNSCREEN, &aad).unwrap(); |
| 262 | + assert_eq!( |
| 263 | + hex(&sealed), |
| 264 | + "d31a8d34648e60db7b86afbc53ef7ec2a4aded51296e08fea9e2b5a736ee62d6\ |
| 265 | + 3dbea45e8ca9671282fafb69da92728b1a71de0a9e060b2905d6a5b67ecd3b36\ |
| 266 | + 92ddbd7f2d778b8c9803aee328091b58fab324e4fad675945585808b4831d7bc\ |
| 267 | + 3ff4def08e4b7a9de576d26586cec64b6116\ |
| 268 | + 1ae10b594f09e26a7e902ecbd0600691" |
| 269 | + ); |
| 270 | + assert_eq!( |
| 271 | + chacha20_poly1305_open(&key, &nonce, &sealed, &aad).unwrap(), |
| 272 | + Some(SUNSCREEN.to_vec()) |
| 273 | + ); |
| 274 | + } |
| 275 | + |
| 276 | + #[test] |
| 277 | + fn chacha20_poly1305_refuses_what_does_not_authenticate() { |
| 278 | + let (key, nonce) = ([7u8; 32], [9u8; 12]); |
| 279 | + let sealed = chacha20_poly1305_seal(&key, &nonce, b"secret", b"stream-1").unwrap(); |
| 280 | + assert_eq!(sealed.len(), 6 + 16); |
| 281 | + let open = |key: &[u8], nonce: &[u8], sealed: &[u8], aad: &[u8]| { |
| 282 | + chacha20_poly1305_open(key, nonce, sealed, aad).unwrap() |
| 283 | + }; |
| 284 | + assert_eq!( |
| 285 | + open(&key, &nonce, &sealed, b"stream-1"), |
| 286 | + Some(b"secret".to_vec()) |
| 287 | + ); |
| 288 | + assert_eq!(open(&key, &nonce, &sealed, b"stream-2"), None); |
| 289 | + assert_eq!(open(&[8u8; 32], &nonce, &sealed, b"stream-1"), None); |
| 290 | + assert_eq!(open(&key, &[0u8; 12], &sealed, b"stream-1"), None); |
| 291 | + let mut flipped = sealed.clone(); |
| 292 | + flipped[0] ^= 1; |
| 293 | + assert_eq!(open(&key, &nonce, &flipped, b"stream-1"), None); |
| 294 | + assert_eq!(open(&key, &nonce, &sealed[..15], b"stream-1"), None); |
| 295 | + assert_eq!(open(&key, &nonce, &[], b""), None); |
| 296 | + let empty = chacha20_poly1305_seal(&key, &nonce, b"", b"").unwrap(); |
| 297 | + assert_eq!(open(&key, &nonce, &empty, b""), Some(Vec::new())); |
| 298 | + } |
| 299 | + |
| 300 | + #[test] |
| 301 | + fn chacha20_poly1305_refuses_wrong_lengths() { |
| 302 | + assert_eq!( |
| 303 | + chacha20_poly1305_seal(&[0u8; 31], &[0u8; 12], b"m", b""), |
| 304 | + Err("crypto: a ChaCha20-Poly1305 key is 32 bytes, not 31".to_string()) |
| 305 | + ); |
| 306 | + assert_eq!( |
| 307 | + chacha20_poly1305_open(&[0u8; 32], &[0u8; 24], b"m", b""), |
| 308 | + Err("crypto: a ChaCha20-Poly1305 nonce is 12 bytes, not 24".to_string()) |
| 309 | + ); |
| 310 | + } |
| 311 | + |
| 312 | + #[test] |
| 313 | + fn hkdf_sha256_vectors() { |
| 314 | + // RFC 5869, test cases 1 and 3 (no salt, no info). |
| 315 | + let secret = [0x0b; 22]; |
| 316 | + assert_eq!( |
| 317 | + hex(&hkdf_sha256( |
| 318 | + &secret, |
| 319 | + &unhex("000102030405060708090a0b0c"), |
| 320 | + &unhex("f0f1f2f3f4f5f6f7f8f9"), |
| 321 | + 42 |
| 322 | + ) |
| 323 | + .unwrap()), |
| 324 | + "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865" |
| 325 | + ); |
| 326 | + assert_eq!( |
| 327 | + hex(&hkdf_sha256(&secret, &[], &[], 42).unwrap()), |
| 328 | + "8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d9d201395faa4b61a96c8" |
| 329 | + ); |
| 330 | + assert_eq!(hkdf_sha256(b"k", b"", b"", 0).unwrap(), Vec::<u8>::new()); |
| 331 | + assert_eq!(hkdf_sha256(b"k", b"", b"", 8160).unwrap().len(), 8160); |
| 332 | + assert_eq!( |
| 333 | + hkdf_sha256(b"k", b"", b"", 8161), |
| 334 | + Err("crypto: HKDF-SHA-256 derives 0 to 8160 bytes, not 8161".to_string()) |
| 335 | + ); |
| 336 | + assert!(hkdf_sha256(b"k", b"", b"", -1).is_err()); |
| 337 | + } |
| 156 | 338 | } |