iroh/tls/
misc.rs

1use ctutils::CtEq;
2use noq_proto::crypto;
3use rand::RngExt;
4use rustls::crypto::cipher::{
5    AeadKey, InboundOpaqueMessage, Iv, NONCE_LEN, OutboundPlainMessage, Tls13AeadAlgorithm,
6};
7
8/// Implements [`crypto::HandshakeTokenKey`] using a [`Tls13AeadAlgorithm`].
9///
10/// This can be obtained from looking through available ciphers from a
11/// [`rustls::crypto::CryptoProvider`].
12pub(crate) struct RustlsTokenKey {
13    key: [u8; 32],
14    aead: &'static dyn Tls13AeadAlgorithm,
15}
16
17impl RustlsTokenKey {
18    /// Constructs [`crypto::HandshakeTokenKey`] from a [`rustls::crypto::CryptoProvider`].
19    ///
20    /// Tries to find a suitable TLS 1.3 cipher suite from the provided crypto provider,
21    /// then uses it to extract an AEAD to use as the token key encryption method.
22    ///
23    /// Then generates a random master key to use.
24    ///
25    /// Returns `None` when this can't find a suitable TLS cipher suite in the given crypto
26    /// provider.
27    pub(crate) fn new(
28        rng: &mut impl rand::CryptoRng,
29        crypto_provider: &rustls::crypto::CryptoProvider,
30    ) -> Option<Self> {
31        let suite = crypto_provider
32            .cipher_suites
33            .iter()
34            .filter_map(|suite| suite.tls13())
35            .next()?;
36        let aead = suite.aead_alg;
37        Some(Self {
38            key: rng.random(),
39            aead,
40        })
41    }
42}
43
44impl crypto::HandshakeTokenKey for RustlsTokenKey {
45    fn seal(&self, token_nonce: u128, data: &mut Vec<u8>) -> Result<(), crypto::CryptoError> {
46        let key = AeadKey::from(self.key);
47        let nonce: [u8; NONCE_LEN] = *token_nonce
48            .to_le_bytes()
49            .first_chunk()
50            .expect("expected u128 > 96 bit");
51        let iv = Iv::from(nonce);
52        let msg = OutboundPlainMessage {
53            typ: rustls::ContentType::ApplicationData,
54            version: rustls::ProtocolVersion::TLSv1_3,
55            payload: rustls::crypto::cipher::OutboundChunks::Single(&*data),
56        };
57        let out = self
58            .aead
59            .encrypter(key, iv)
60            .encrypt(msg, 0)
61            .map_err(|_| crypto::CryptoError)?;
62
63        data.clear();
64        data.extend(out.payload.as_ref());
65
66        Ok(())
67    }
68
69    fn open<'a>(
70        &self,
71        token_nonce: u128,
72        data: &'a mut [u8],
73    ) -> Result<&'a [u8], crypto::CryptoError> {
74        let key = AeadKey::from(self.key);
75        let nonce: [u8; NONCE_LEN] = *token_nonce
76            .to_le_bytes()
77            .first_chunk()
78            .expect("expected u128 > 96 bit");
79        let iv = Iv::from(nonce);
80
81        let msg = InboundOpaqueMessage::new(
82            rustls::ContentType::ApplicationData,
83            rustls::ProtocolVersion::TLSv1_3,
84            data,
85        );
86        let plain = self
87            .aead
88            .decrypter(key, iv)
89            .decrypt(msg, 0)
90            .map_err(|_| crypto::CryptoError)?;
91
92        Ok(plain.payload)
93    }
94}
95
96pub(crate) struct Blake3HmacKey([u8; 32]);
97
98impl Blake3HmacKey {
99    pub(crate) fn new(rng: &mut impl rand::CryptoRng) -> Self {
100        let mut key = [0u8; 32];
101        rng.fill_bytes(&mut key);
102        Self(key)
103    }
104}
105
106impl crypto::HmacKey for Blake3HmacKey {
107    fn sign(&self, data: &[u8], signature_out: &mut [u8]) {
108        signature_out.copy_from_slice(blake3::keyed_hash(&self.0, data).as_slice());
109    }
110
111    fn signature_len(&self) -> usize {
112        blake3::OUT_LEN // 32 bytes
113    }
114
115    fn verify(&self, data: &[u8], signature: &[u8]) -> Result<(), crypto::CryptoError> {
116        let reference = blake3::keyed_hash(&self.0, data);
117        // to_bool is fine here, because it's the last thing we do to
118        // distinguish success or failure (see to_bool documentation)
119        if signature.ct_eq(reference.as_slice()).to_bool() {
120            Ok(())
121        } else {
122            Err(crypto::CryptoError)
123        }
124    }
125}