tobogganSe connecter

louise

The Louise language: compiler, runtime, std, tooling

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

338 lignes · 12748 octetsBrut · Historique
1//! Cryptographic kernels over `ring` (already linked for TLS, ADR 0038):
2//! SHA-256, HMAC-SHA-256 and PBKDF2-HMAC-SHA-256 — what PostgreSQL's
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).
6//!
7//! Both back ends call these, so a hash can never drift between them; the
8//! FIPS 180-4, RFC 2202, RFC 8032, RFC 8439 and RFC 5869 vectors below pin
9//! them down anyway.
10
11use ring::aead::{Aad, CHACHA20_POLY1305, LessSafeKey, Nonce, UnboundKey};
12use ring::signature::{ED25519, Ed25519KeyPair, KeyPair, UnparsedPublicKey};
13use ring::{digest, hkdf, hmac, pbkdf2};
14use std::num::NonZeroU32;
15
16/// SHA-256 of `data`.
17pub fn sha256(data: &[u8]) -> [u8; 32] {
18 let mut out = [0u8; 32];
19 out.copy_from_slice(digest::digest(&digest::SHA256, data).as_ref());
20 out
21}
22
23/// HMAC-SHA-256 of `message` under `key` (RFC 2104).
24pub fn hmac_sha256(key: &[u8], message: &[u8]) -> [u8; 32] {
25 let mut out = [0u8; 32];
26 out.copy_from_slice(hmac::sign(&hmac::Key::new(hmac::HMAC_SHA256, key), message).as_ref());
27 out
28}
29
30/// PBKDF2-HMAC-SHA-256 of `password` with `salt` and `iterations`
31/// (saturated to at least 1), `length` output bytes.
32pub fn pbkdf2_hmac_sha256(password: &[u8], salt: &[u8], iterations: i64, length: usize) -> Vec<u8> {
33 let iterations = NonZeroU32::new(iterations.clamp(1, u32::MAX as i64) as u32)
34 .expect("clamped to at least 1");
35 let mut out = vec![0u8; length];
36 pbkdf2::derive(
37 pbkdf2::PBKDF2_HMAC_SHA256,
38 iterations,
39 salt,
40 password,
41 &mut out,
42 );
43 out
44}
45
46/// Whether `signature` is the Ed25519 signature of `message` under
47/// `public_key` (RFC 8032). A key that is not 32 bytes or a signature that
48/// is not 64 is no signature: `false`.
49pub fn ed25519_verify(public_key: &[u8], message: &[u8], signature: &[u8]) -> bool {
50 UnparsedPublicKey::new(&ED25519, public_key)
51 .verify(message, signature)
52 .is_ok()
53}
54
55/// The Ed25519 public key of a 32-byte `seed` (RFC 8032's private key).
56/// A seed of another length is refused, with the message both back ends
57/// panic with.
58pub fn ed25519_public_key(seed: &[u8]) -> Result<[u8; 32], String> {
59 let pair = key_pair(seed)?;
60 let mut out = [0u8; 32];
61 out.copy_from_slice(pair.public_key().as_ref());
62 Ok(out)
63}
64
65/// The Ed25519 signature of `message` under the key pair of a 32-byte
66/// `seed`, refused like [`ed25519_public_key`]'s.
67pub fn ed25519_sign(seed: &[u8], message: &[u8]) -> Result<[u8; 64], String> {
68 let pair = key_pair(seed)?;
69 let mut out = [0u8; 64];
70 out.copy_from_slice(pair.sign(message).as_ref());
71 Ok(out)
72}
73
74fn key_pair(seed: &[u8]) -> Result<Ed25519KeyPair, String> {
75 Ed25519KeyPair::from_seed_unchecked(seed)
76 .map_err(|_| format!("crypto: an Ed25519 seed is 32 bytes, not {}", seed.len()))
77}
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.
83pub 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.
97pub 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.
104pub 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
118fn 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
129fn 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).
139pub 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.
145pub 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
164struct Length(usize);
165
166impl hkdf::KeyType for Length {
167 fn len(&self) -> usize {
168 self.0
169 }
170}
171
172#[cfg(test)]
173mod tests {
174 use super::*;
175
176 fn hex(bytes: &[u8]) -> String {
177 bytes.iter().map(|b| format!("{b:02x}")).collect()
178 }
179
180 #[test]
181 fn sha256_vectors() {
182 // FIPS 180-4 examples.
183 assert_eq!(
184 hex(&sha256(b"abc")),
185 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
186 );
187 assert_eq!(
188 hex(&sha256(b"")),
189 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
190 );
191 }
192
193 #[test]
194 fn hmac_sha256_vectors() {
195 // RFC 2202, cases 1 and 2.
196 let key = [0x0b; 20];
197 assert_eq!(
198 hex(&hmac_sha256(&key, b"Hi There")),
199 "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"
200 );
201 assert_eq!(
202 hex(&hmac_sha256(b"Jefe", b"what do ya want for nothing?")),
203 "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"
204 );
205 }
206
207 #[test]
208 fn pbkdf2_vectors() {
209 // RFC 7914-style vectors for PBKDF2-HMAC-SHA256 (from RFC 7677's
210 // SCRAM example is covered end to end in the postgres package).
211 assert_eq!(
212 hex(&pbkdf2_hmac_sha256(b"password", b"salt", 1, 32)),
213 "120fb6cffcf8b32c43e7225256c4f837a86548c92ccc35480805987cb70be17b"
214 );
215 assert_eq!(
216 hex(&pbkdf2_hmac_sha256(b"password", b"salt", 2, 32)),
217 "ae4d0c95af6b46d32d0adff928f06dd02a303f8ef3c251dfd6e2d85a95474c43"
218 );
219 // A zero iteration count is clamped to 1, not a crash.
220 assert_eq!(pbkdf2_hmac_sha256(b"p", b"s", 0, 32).len(), 32);
221 }
222
223 fn unhex(text: &str) -> Vec<u8> {
224 (0..text.len())
225 .step_by(2)
226 .map(|i| u8::from_str_radix(&text[i..i + 2], 16).unwrap())
227 .collect()
228 }
229
230 #[test]
231 fn ed25519_vectors() {
232 // RFC 8032 §7.1, TEST 2: a one-byte message.
233 let seed = unhex("4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb");
234 let public = unhex("3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c");
235 let signature = unhex(
236 "92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da\
237 085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00",
238 );
239 assert_eq!(ed25519_public_key(&seed).unwrap().to_vec(), public);
240 assert_eq!(ed25519_sign(&seed, &[0x72]).unwrap().to_vec(), signature);
241 assert!(ed25519_verify(&public, &[0x72], &signature));
242 assert!(!ed25519_verify(&public, &[0x73], &signature));
243 // Wrong lengths are no signature, and no seed.
244 assert!(!ed25519_verify(&public[..31], &[0x72], &signature));
245 assert!(!ed25519_verify(&public, &[0x72], &signature[..63]));
246 assert_eq!(
247 ed25519_public_key(&seed[..31]),
248 Err("crypto: an Ed25519 seed is 32 bytes, not 31".to_string())
249 );
250 assert!(ed25519_sign(&[], b"m").is_err());
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 }
338}