1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
|
use std::sync::Arc;
use ::aws_lc_rs::{
aead::{AES_128_GCM, Aad, LessSafeKey, NONCE_LEN, Nonce, UnboundKey},
agreement::{self, EphemeralPrivateKey, X25519},
digest,
encoding::{AsBigEndian, Curve25519SeedBin, EcPrivateKeyBin},
kem::ML_KEM_768,
rand,
signature::{self, EcdsaKeyPair, Ed25519KeyPair, KeyPair, UnparsedPublicKey},
};
use aws_lc_rs::kem::EncapsulationKey;
use proto::{
crypto::{
ActiveKeyExchange, AgreedKey, CryptoError, CryptoProvider, Digest, Hash, HashContext,
KeyExchange, KeySourceSide, OpeningKey, SealingKey, SecureRandom, SharedSecret, SigningKey,
SupportedAlgorithms, VerifyingKey,
},
named::{EncryptionAlgorithm, KeyExchangeAlgorithm, MacAlgorithm, PublicKeyAlgorithm},
};
use zeroize::Zeroizing;
pub const DEFAULT_PROVIDER: &'static dyn CryptoProvider = &Provider;
/// The aws-lc-rs [`CryptoProvider`].
#[derive(Clone, Copy, Debug)]
struct Provider;
impl CryptoProvider for Provider {
fn generate_signing_key(
&self,
algorithm: &PublicKeyAlgorithm<'_>,
) -> Result<(Box<dyn SigningKey>, Vec<u8>), CryptoError> {
match algorithm {
PublicKeyAlgorithm::Ed25519 => {
let key_pair =
Ed25519KeyPair::generate().map_err(|_| CryptoError::KeyGenerationFailed)?;
let pkcs8 = key_pair
.to_pkcs8v1()
.map_err(|_| CryptoError::Unspecified)?
.as_ref()
.to_vec();
Ok((Box::new(Ed25519SigningKey::new(key_pair)), pkcs8))
}
PublicKeyAlgorithm::EcdsaSha2Nistp256 => {
let key_pair = EcdsaKeyPair::generate(&signature::ECDSA_P256_SHA256_FIXED_SIGNING)
.map_err(|_| CryptoError::KeyGenerationFailed)?;
let pkcs8 = key_pair
.to_pkcs8v1()
.map_err(|_| CryptoError::Unspecified)?
.as_ref()
.to_vec();
Ok((Box::new(EcdsaP256SigningKey::new(key_pair)), pkcs8))
}
_ => Err(CryptoError::UnknownAlgorithm),
}
}
fn signing_key_from_pkcs8(&self, pkcs8: &[u8]) -> Result<Box<dyn SigningKey>, CryptoError> {
// The PKCS#8 algorithm identifier distinguishes the key type; each loader
// validates it, so try Ed25519 first and fall back to ECDSA P-256.
if let Ok(key_pair) = Ed25519KeyPair::from_pkcs8(pkcs8) {
return Ok(Box::new(Ed25519SigningKey::new(key_pair)));
}
let key_pair = EcdsaKeyPair::from_pkcs8(&signature::ECDSA_P256_SHA256_FIXED_SIGNING, pkcs8)
.map_err(|_| CryptoError::KeyRejected)?;
Ok(Box::new(EcdsaP256SigningKey::new(key_pair)))
}
fn verifying_key(
&self,
key: &[u8],
algorithm: &PublicKeyAlgorithm<'_>,
) -> Result<Arc<dyn VerifyingKey>, CryptoError> {
match algorithm {
PublicKeyAlgorithm::EcdsaSha2Nistp256 => Ok(Arc::new(EcdsaP256VerifyingKey {
key: UnparsedPublicKey::new(&signature::ECDSA_P256_SHA256_FIXED, key.to_owned()),
})),
PublicKeyAlgorithm::Ed25519 => Ok(Arc::new(Ed25519VerifyingKey {
key: UnparsedPublicKey::new(&signature::ED25519, key.to_owned()),
})),
_ => Err(CryptoError::UnknownAlgorithm),
}
}
fn opening_key(
&self,
counter: u64,
source: &KeySourceSide,
) -> Result<Box<dyn OpeningKey>, CryptoError> {
match source.algorithm {
EncryptionAlgorithm::Aes128Gcm => {
Ok(Box::new(Aes128GcmOpener(GcmState::new(counter, source)?)))
}
_ => Err(CryptoError::UnknownAlgorithm),
}
}
fn sealing_key(
&self,
counter: u64,
source: &KeySourceSide,
) -> Result<Box<dyn SealingKey>, CryptoError> {
match source.algorithm {
EncryptionAlgorithm::Aes128Gcm => {
Ok(Box::new(Aes128GcmSealer(GcmState::new(counter, source)?)))
}
_ => Err(CryptoError::UnknownAlgorithm),
}
}
fn key_exchange(
&self,
algorithm: &KeyExchangeAlgorithm<'_>,
) -> Result<&'static dyn KeyExchange, CryptoError> {
match algorithm {
KeyExchangeAlgorithm::MlKem768X25519Sha256 => Ok(&Mlkem768X25519Kx),
KeyExchangeAlgorithm::Curve25519Sha256 => Ok(&X25519Kx),
_ => Err(CryptoError::UnknownAlgorithm),
}
}
fn hash(&self, algorithm: &KeyExchangeAlgorithm<'_>) -> Result<&'static dyn Hash, CryptoError> {
match algorithm {
KeyExchangeAlgorithm::MlKem768X25519Sha256 | KeyExchangeAlgorithm::Curve25519Sha256 => {
Ok(&Sha256)
}
_ => Err(CryptoError::UnknownAlgorithm),
}
}
fn supported_algorithms(&self) -> SupportedAlgorithms {
SupportedAlgorithms {
key_exchange: &[
KeyExchangeAlgorithm::MlKem768X25519Sha256,
KeyExchangeAlgorithm::Curve25519Sha256,
],
public_key: &[
PublicKeyAlgorithm::EcdsaSha2Nistp256,
PublicKeyAlgorithm::Ed25519,
],
encryption: &[EncryptionAlgorithm::Aes128Gcm],
mac: &[MacAlgorithm::None],
}
}
fn secure_random(&self) -> &'static dyn SecureRandom {
&SystemRandom
}
}
struct Aes128GcmSealer(GcmState);
impl SealingKey for Aes128GcmSealer {
fn seal_in_place(
&mut self,
_seq: u32,
data: &mut [u8],
tag: &mut [u8],
) -> Result<(), CryptoError> {
let nonce = self.0.nonce()?;
let Some((length, plaintext)) = data.split_at_mut_checked(4) else {
return Err(CryptoError::InvalidLength);
};
let computed = self
.0
.key
.seal_in_place_separate_tag(nonce, Aad::from(length), plaintext)
.map_err(|_| CryptoError::EncryptionFailed)?;
tag.copy_from_slice(computed.as_ref());
Ok(())
}
fn counter(&self) -> u64 {
self.0.counter
}
fn block_len(&self) -> usize {
16
}
fn tag_len(&self) -> usize {
self.0.key.algorithm().tag_len()
}
}
struct Aes128GcmOpener(GcmState);
impl OpeningKey for Aes128GcmOpener {
fn open_in_place(&mut self, _seq: u32, data: &mut [u8], tag: &[u8]) -> Result<(), CryptoError> {
let nonce = self.0.nonce()?;
let Some((length, ciphertext)) = data.split_at_mut_checked(4) else {
return Err(CryptoError::InvalidLength);
};
self.0
.key
.open_in_place_separate_tag(nonce, Aad::from(&length[..]), tag, ciphertext)
.map_err(|_| CryptoError::DecryptionFailed)?;
Ok(())
}
fn decrypt_packet_length(&mut self, _seq: u32, encrypted: [u8; 4]) -> [u8; 4] {
// The packet length is transmitted in cleartext (authenticated as AAD).
encrypted
}
fn counter(&self) -> u64 {
self.0.counter
}
fn tag_len(&self) -> usize {
self.0.key.algorithm().tag_len()
}
}
/// Shared AES-128-GCM state: the key and the current 12-byte nonce
struct GcmState {
key: LessSafeKey,
nonce: [u8; NONCE_LEN],
counter: u64,
}
impl GcmState {
fn new(counter: u64, source: &KeySourceSide) -> Result<Self, CryptoError> {
let Ok(nonce) = <&[u8; NONCE_LEN]>::try_from(source.initial_iv.as_slice()) else {
return Err(CryptoError::InvalidLength);
};
let mut new = Self {
key: LessSafeKey::new(
UnboundKey::new(&AES_128_GCM, &source.encryption_key)
.map_err(|_| CryptoError::InvalidLength)?,
),
nonce: *nonce,
counter: 0,
};
new.increment(counter)?;
Ok(new)
}
/// Return the nonce for the next packet and advance the invocation counter
///
/// <https://www.rfc-editor.org/rfc/rfc5647#section-7.1>: the low 8 bytes form a
/// big-endian invocation counter that is incremented after each packet.
fn nonce(&mut self) -> Result<Nonce, CryptoError> {
let nonce = Nonce::assume_unique_for_key(self.nonce);
self.increment(1)?;
Ok(nonce)
}
fn increment(&mut self, delta: u64) -> Result<(), CryptoError> {
let Some(counter_dst) = self.nonce.last_chunk_mut::<8>() else {
return Err(CryptoError::InvalidLength);
};
let Some(new) = u64::from_be_bytes(*counter_dst).checked_add(delta) else {
return Err(CryptoError::NonceOverflow);
};
*counter_dst = new.to_be_bytes();
self.counter += delta;
Ok(())
}
}
/// The `mlkem768x25519-sha256` key exchange
struct Mlkem768X25519Kx;
impl KeyExchange for Mlkem768X25519Kx {
fn start(&self) -> Result<Box<dyn ActiveKeyExchange>, CryptoError> {
Ok(Box::new(Mlkem768X25519KeyExchange))
}
}
struct Mlkem768X25519KeyExchange;
impl Mlkem768X25519KeyExchange {
/// Length of an ML-KEM-768 encapsulation key
const MLKEM768_ENCAPS_KEY_LEN: usize = 1184;
}
impl ActiveKeyExchange for Mlkem768X25519KeyExchange {
fn complete(self: Box<Self>, peer_public_key: &[u8]) -> Result<AgreedKey, CryptoError> {
// `C_INIT` = ML-KEM-768 encapsulation key || X25519 public key
let Some((encaps_key, peer_x25519)) =
peer_public_key.split_at_checked(Self::MLKEM768_ENCAPS_KEY_LEN)
else {
return Err(CryptoError::InvalidLength);
};
let encaps_key =
EncapsulationKey::new(&ML_KEM_768, encaps_key).map_err(|_| CryptoError::KeyRejected)?;
let (ciphertext, pq_secret) = encaps_key
.encapsulate()
.map_err(|_| CryptoError::KeyAgreementFailed)?;
let random = rand::SystemRandom::new();
let private_key = EphemeralPrivateKey::generate(&X25519, &random)
.map_err(|_| CryptoError::KeyGenerationFailed)?;
let classic_public_key = private_key
.compute_public_key()
.map_err(|_| CryptoError::Unspecified)?
.as_ref()
.to_vec();
let mut context = digest::Context::new(&digest::SHA256);
context.update(pq_secret.as_ref());
let peer = agreement::UnparsedPublicKey::new(&X25519, peer_x25519);
agreement::agree_ephemeral(
private_key,
peer,
CryptoError::KeyAgreementFailed,
|shared_secret| {
context.update(shared_secret);
Ok(())
},
)?;
let shared_secret = SharedSecret::from(context.finish().as_ref().to_vec());
// `S_REPLY` = ML-KEM-768 ciphertext || X25519 public key
let mut public_key =
Vec::with_capacity(ciphertext.as_ref().len() + classic_public_key.len());
public_key.extend_from_slice(ciphertext.as_ref());
public_key.extend_from_slice(&classic_public_key);
Ok(AgreedKey {
public_key,
shared_secret,
})
}
}
/// The `curve25519-sha256` key exchange
struct X25519Kx;
impl KeyExchange for X25519Kx {
fn start(&self) -> Result<Box<dyn ActiveKeyExchange>, CryptoError> {
Ok(Box::new(X25519KeyExchange))
}
}
struct X25519KeyExchange;
impl ActiveKeyExchange for X25519KeyExchange {
fn complete(self: Box<Self>, peer_public_key: &[u8]) -> Result<AgreedKey, CryptoError> {
let random = rand::SystemRandom::new();
let private_key = EphemeralPrivateKey::generate(&X25519, &random)
.map_err(|_| CryptoError::KeyGenerationFailed)?;
let public_key = private_key
.compute_public_key()
.map_err(|_| CryptoError::Unspecified)?
.as_ref()
.to_vec();
let peer = agreement::UnparsedPublicKey::new(&X25519, peer_public_key);
let shared_secret = agreement::agree_ephemeral(
private_key,
peer,
CryptoError::KeyAgreementFailed,
|shared_secret| Ok(SharedSecret::from(shared_secret.to_vec())),
)?;
Ok(AgreedKey {
public_key,
shared_secret,
})
}
}
struct Ed25519SigningKey {
key_pair: Ed25519KeyPair,
public_key: Vec<u8>,
}
impl Ed25519SigningKey {
fn new(key_pair: Ed25519KeyPair) -> Self {
let public_key = key_pair.public_key().as_ref().to_vec();
Self {
key_pair,
public_key,
}
}
}
impl SigningKey for Ed25519SigningKey {
fn public_key(&self) -> &[u8] {
&self.public_key
}
fn sign(&self, message: &[u8]) -> Vec<u8> {
self.key_pair.sign(message).as_ref().to_vec()
}
fn algorithm(&self) -> PublicKeyAlgorithm<'static> {
PublicKeyAlgorithm::Ed25519
}
fn private_key(&self) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
let seed = self.key_pair.seed().map_err(|_| CryptoError::Unspecified)?;
let bytes = AsBigEndian::<Curve25519SeedBin<'_>>::as_be_bytes(&seed)
.map_err(|_| CryptoError::Unspecified)?;
Ok(Zeroizing::new(bytes.as_ref().to_vec()))
}
}
struct EcdsaP256SigningKey {
key_pair: EcdsaKeyPair,
public_key: Vec<u8>,
}
impl EcdsaP256SigningKey {
fn new(key_pair: EcdsaKeyPair) -> Self {
// `public_key()` returns the point in X9.62 uncompressed form.
let public_key = key_pair.public_key().as_ref().to_vec();
Self {
key_pair,
public_key,
}
}
}
impl SigningKey for EcdsaP256SigningKey {
fn sign(&self, message: &[u8]) -> Vec<u8> {
// The fixed-format algorithm yields a 64-byte `r || s` signature; the SSH mpint framing
// is applied by the protocol layer. aws-lc-rs ignores the supplied RNG for ECDSA signing.
match self.key_pair.sign(&rand::SystemRandom::new(), message) {
Ok(signature) => signature.as_ref().to_vec(),
Err(_) => Vec::new(),
}
}
fn public_key(&self) -> &[u8] {
&self.public_key
}
fn algorithm(&self) -> PublicKeyAlgorithm<'static> {
PublicKeyAlgorithm::EcdsaSha2Nistp256
}
fn private_key(&self) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
let d = AsBigEndian::<EcPrivateKeyBin<'_>>::as_be_bytes(&self.key_pair.private_key())
.map_err(|_| CryptoError::Unspecified)?;
Ok(Zeroizing::new(d.as_ref().to_vec()))
}
}
struct EcdsaP256VerifyingKey {
key: UnparsedPublicKey<Vec<u8>>,
}
impl VerifyingKey for EcdsaP256VerifyingKey {
fn verify(&self, message: &[u8], signature: &[u8]) -> Result<(), CryptoError> {
self.key
.verify(message, signature)
.map_err(|_| CryptoError::VerificationFailed)
}
}
struct Ed25519VerifyingKey {
key: UnparsedPublicKey<Vec<u8>>,
}
impl VerifyingKey for Ed25519VerifyingKey {
fn verify(&self, message: &[u8], signature: &[u8]) -> Result<(), CryptoError> {
self.key
.verify(message, signature)
.map_err(|_| CryptoError::VerificationFailed)
}
}
struct Sha256;
impl Hash for Sha256 {
fn start(&self) -> Box<dyn HashContext> {
Box::new(Sha256Context(digest::Context::new(&digest::SHA256)))
}
fn output_len(&self) -> usize {
digest::SHA256.output_len()
}
}
struct Sha256Context(digest::Context);
impl HashContext for Sha256Context {
fn update(&mut self, data: &[u8]) {
self.0.update(data);
}
fn fork(&self) -> Box<dyn HashContext> {
Box::new(Self(self.0.clone()))
}
fn finish(self: Box<Self>) -> Digest {
Digest::new(self.0.finish().as_ref())
}
}
struct SystemRandom;
impl SecureRandom for SystemRandom {
fn fill(&self, buf: &mut [u8]) -> Result<(), CryptoError> {
rand::fill(buf).map_err(|_| CryptoError::NoRandomness)
}
}
|