aboutsummaryrefslogtreecommitdiffhomepage
path: root/oxish-graviola/src/lib.rs
blob: 7cccdbf6ac7f1a1c775f8efacaeadd4de3f612cb (plain)
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
use std::sync::Arc;

use graviola::{
    aead::AesGcm,
    hashing::{Hash as GHash, HashContext as GHashContext, Sha256 as GSha256},
    key_agreement::{mlkem768, p256::StaticPrivateKey, x25519},
    random,
    signing::{
        ecdsa::{self, P256},
        eddsa::{Ed25519SigningKey, Ed25519VerifyingKey as GEd25519VerifyingKey},
    },
};
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 graviola [`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 =
                    Ed25519SigningKey::generate().map_err(|_| CryptoError::KeyGenerationFailed)?;

                // An Ed25519 PKCS#8 v2 document (with the embedded public key) is
                // well under 128 bytes.
                let mut buf = Zeroizing::new([0u8; 128]);
                let pkcs8 = key
                    .to_pkcs8_der(&mut *buf)
                    .map_err(|_| CryptoError::Unspecified)?
                    .to_vec();

                Ok((Box::new(Ed25519Key::new(key)), pkcs8))
            }
            PublicKeyAlgorithm::EcdsaSha2Nistp256 => {
                let private_key =
                    StaticPrivateKey::new_random().map_err(|_| CryptoError::KeyGenerationFailed)?;
                let key = ecdsa::SigningKey::<P256> { private_key };

                // A P-256 PKCS#8 v1 document (with the embedded public key) is
                // comfortably under 256 bytes.
                let mut buf = [0u8; 256];
                let pkcs8 = key
                    .to_pkcs8_der(&mut buf)
                    .map_err(|_| CryptoError::Unspecified)?
                    .to_vec();

                Ok((Box::new(EcdsaP256Key::new(key)), 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) = Ed25519SigningKey::from_pkcs8_der(pkcs8) {
            return Ok(Box::new(Ed25519Key::new(key)));
        }

        let key = ecdsa::SigningKey::<P256>::from_pkcs8_der(pkcs8)
            .map_err(|_| CryptoError::KeyRejected)?;
        Ok(Box::new(EcdsaP256Key::new(key)))
    }

    fn verifying_key(
        &self,
        key: &[u8],
        algorithm: &PublicKeyAlgorithm<'_>,
    ) -> Result<Arc<dyn VerifyingKey>, CryptoError> {
        match algorithm {
            PublicKeyAlgorithm::EcdsaSha2Nistp256 => Ok(Arc::new(EcdsaP256VerifyingKey(
                ecdsa::VerifyingKey::<P256>::from_x962_uncompressed(key)
                    .map_err(|_| CryptoError::KeyRejected)?,
            ))),
            PublicKeyAlgorithm::Ed25519 => Ok(Arc::new(Ed25519VerifyingKey(
                GEd25519VerifyingKey::from_bytes(key).map_err(|_| CryptoError::KeyRejected)?,
            ))),
            _ => 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 Some(tag) = tag.first_chunk_mut::<TAG_LEN>() else {
            return Err(CryptoError::InvalidLength);
        };

        // The cleartext packet length is authenticated as associated data.
        self.0.key.encrypt(&nonce, length, plaintext, tag);
        Ok(())
    }

    fn counter(&self) -> u64 {
        self.0.counter
    }

    fn block_len(&self) -> usize {
        16
    }

    fn tag_len(&self) -> usize {
        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
            .decrypt(&nonce, length, ciphertext, tag)
            .map_err(|_| CryptoError::DecryptionFailed)
    }

    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 {
        TAG_LEN
    }
}

const TAG_LEN: usize = 16;
const NONCE_LEN: usize = 12;

/// Shared AES-128-GCM state: the key and the current 12-byte nonce
struct GcmState {
    key: AesGcm,
    nonce: [u8; NONCE_LEN],
    counter: u64,
}

impl GcmState {
    fn new(counter: u64, source: &KeySourceSide) -> Result<Self, CryptoError> {
        let Ok(key) = <&[u8; 16]>::try_from(source.encryption_key.as_slice()) else {
            return Err(CryptoError::InvalidLength);
        };

        let Ok(nonce) = <&[u8; NONCE_LEN]>::try_from(source.initial_iv.as_slice()) else {
            return Err(CryptoError::InvalidLength);
        };

        let mut new = Self {
            key: AesGcm::new(key),
            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<[u8; NONCE_LEN], CryptoError> {
        let nonce = 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` PQ-hybrid key exchange
struct Mlkem768X25519Kx;

impl KeyExchange for Mlkem768X25519Kx {
    fn start(&self) -> Result<Box<dyn ActiveKeyExchange>, CryptoError> {
        Ok(Box::new(Mlkem768X25519KeyExchange))
    }
}

struct Mlkem768X25519KeyExchange;

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_first_chunk() else {
            return Err(CryptoError::InvalidLength);
        };

        let encaps_key = mlkem768::EncapKey::from_bytes(encaps_key)
            .map_err(|_| CryptoError::KeyAgreementFailed)?;
        let (pq_secret, ciphertext) = encaps_key
            .encaps()
            .map_err(|_| CryptoError::KeyAgreementFailed)?;

        let x25519_private =
            x25519::PrivateKey::new_random().map_err(|_| CryptoError::NoRandomness)?;
        let x25519_public = x25519_private.public_key().as_bytes();
        let peer =
            x25519::PublicKey::try_from_slice(peer_x25519).map_err(|_| CryptoError::KeyRejected)?;
        let shared = x25519_private
            .diffie_hellman(&peer)
            .map_err(|_| CryptoError::KeyAgreementFailed)?;

        // K = SHA256(K_PQ || K_CL)
        let mut context = GSha256::new();
        context.update(pq_secret.as_ref());
        context.update(&shared.as_bytes());
        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() + x25519_public.len());
        public_key.extend_from_slice(ciphertext.as_ref());
        public_key.extend_from_slice(&x25519_public);

        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 private_key =
            x25519::PrivateKey::new_random().map_err(|_| CryptoError::NoRandomness)?;
        let public_key = private_key.public_key().as_bytes().to_vec();

        let peer = x25519::PublicKey::try_from_slice(peer_public_key)
            .map_err(|_| CryptoError::KeyRejected)?;
        let shared = private_key
            .diffie_hellman(&peer)
            .map_err(|_| CryptoError::KeyAgreementFailed)?;

        Ok(AgreedKey {
            public_key,
            shared_secret: SharedSecret::from(shared.as_bytes().to_vec()),
        })
    }
}

struct Ed25519Key {
    key: Ed25519SigningKey,
    public_key: Vec<u8>,
}

impl Ed25519Key {
    fn new(key: Ed25519SigningKey) -> Self {
        let public_key = key.public_key().as_bytes().to_vec();
        Self { key, public_key }
    }
}

impl SigningKey for Ed25519Key {
    fn public_key(&self) -> &[u8] {
        &self.public_key
    }

    fn sign(&self, message: &[u8]) -> Vec<u8> {
        self.key.sign(message).to_vec()
    }

    fn algorithm(&self) -> PublicKeyAlgorithm<'static> {
        PublicKeyAlgorithm::Ed25519
    }
}

struct EcdsaP256Key {
    key: ecdsa::SigningKey<P256>,
    public_key: Vec<u8>,
}

impl EcdsaP256Key {
    fn new(key: ecdsa::SigningKey<P256>) -> Self {
        let public_key = key.private_key.public_key_uncompressed().to_vec();
        Self { key, public_key }
    }
}

impl SigningKey for EcdsaP256Key {
    fn sign(&self, message: &[u8]) -> Vec<u8> {
        // ECDSA over P-256 with SHA-256 produces a fixed-length `r || s`
        // signature (32 bytes each); the SSH mpint framing is applied by the
        // protocol layer.
        let mut signature = [0u8; 64];
        match self.key.sign::<GSha256>(&[message], &mut signature) {
            Ok(signature) => signature.to_vec(),
            Err(_) => Vec::new(),
        }
    }

    fn public_key(&self) -> &[u8] {
        &self.public_key
    }

    fn algorithm(&self) -> PublicKeyAlgorithm<'static> {
        PublicKeyAlgorithm::EcdsaSha2Nistp256
    }
}

struct EcdsaP256VerifyingKey(ecdsa::VerifyingKey<P256>);

impl VerifyingKey for EcdsaP256VerifyingKey {
    fn verify(&self, message: &[u8], signature: &[u8]) -> Result<(), CryptoError> {
        // The SSH ecdsa-sha2-nistp256 signature has already been converted to the
        // fixed-length r||s encoding graviola expects.
        self.0
            .verify::<GSha256>(&[message], signature)
            .map_err(|_| CryptoError::VerificationFailed)
    }
}

struct Ed25519VerifyingKey(GEd25519VerifyingKey);

impl VerifyingKey for Ed25519VerifyingKey {
    fn verify(&self, message: &[u8], signature: &[u8]) -> Result<(), CryptoError> {
        self.0
            .verify(signature, message)
            .map_err(|_| CryptoError::VerificationFailed)
    }
}

struct Sha256;

impl Hash for Sha256 {
    fn start(&self) -> Box<dyn HashContext> {
        Box::new(Sha256Context(GSha256::new()))
    }

    fn output_len(&self) -> usize {
        32
    }
}

struct Sha256Context(<GSha256 as GHash>::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> {
        random::fill(buf).map_err(|_| CryptoError::NoRandomness)
    }
}