rustls/crypto/
tls12.rs

1use alloc::boxed::Box;
2
3use super::hmac;
4use super::kx::ActiveKeyExchange;
5use crate::enums::ProtocolVersion;
6use crate::error::Error;
7
8/// Implements [`Prf`] using a [`hmac::Hmac`].
9#[expect(clippy::exhaustive_structs)]
10pub struct PrfUsingHmac<'a>(pub &'a dyn hmac::Hmac);
11
12impl Prf for PrfUsingHmac<'_> {
13    fn for_key_exchange(
14        &self,
15        output: &mut [u8; 48],
16        kx: Box<dyn ActiveKeyExchange>,
17        peer_pub_key: &[u8],
18        label: &[u8],
19        seed: &[u8],
20    ) -> Result<(), Error> {
21        prf(
22            output,
23            self.0
24                .with_key(
25                    kx.complete_for_tls_version(peer_pub_key, ProtocolVersion::TLSv1_2)?
26                        .secret_bytes(),
27                )
28                .as_ref(),
29            label,
30            seed,
31        );
32        Ok(())
33    }
34
35    fn new_secret(&self, secret: &[u8; 48]) -> Box<dyn PrfSecret> {
36        Box::new(PrfSecretUsingHmac(self.0.with_key(secret)))
37    }
38}
39
40struct PrfSecretUsingHmac(Box<dyn hmac::Key>);
41
42impl PrfSecret for PrfSecretUsingHmac {
43    fn prf(&self, output: &mut [u8], label: &[u8], seed: &[u8]) {
44        prf(output, &*self.0, label, seed)
45    }
46}
47
48/// An instantiation of the TLS1.2 PRF with a specific, implicit hash function.
49///
50/// See the definition in [RFC5246 section 5](https://www.rfc-editor.org/rfc/rfc5246#section-5).
51///
52/// See [`PrfUsingHmac`] as a route to implementing this trait with just
53/// an implementation of [`hmac::Hmac`].
54pub trait Prf: Send + Sync {
55    /// Computes `PRF(secret, label, seed)` using the secret from a completed key exchange.
56    ///
57    /// Completes the given key exchange, and then uses the resulting shared secret
58    /// to compute the PRF, writing the result into `output`.
59    ///
60    /// The caller guarantees that `label`, `seed` are non-empty. The caller makes no
61    /// guarantees about the contents of `peer_pub_key`. It must be validated by
62    /// [`ActiveKeyExchange::complete`].
63    fn for_key_exchange(
64        &self,
65        output: &mut [u8; 48],
66        kx: Box<dyn ActiveKeyExchange>,
67        peer_pub_key: &[u8],
68        label: &[u8],
69        seed: &[u8],
70    ) -> Result<(), Error>;
71
72    /// Returns an object that can compute `PRF(secret, label, seed)` with
73    /// the same `master_secret`.
74    ///
75    /// This object can amortize any preprocessing needed on `master_secret` over
76    /// several `PRF(...)` calls.
77    fn new_secret(&self, master_secret: &[u8; 48]) -> Box<dyn PrfSecret>;
78
79    /// Return `true` if this is backed by a FIPS-approved implementation.
80    fn fips(&self) -> bool {
81        false
82    }
83}
84
85/// An instantiation of the TLS1.2 PRF with a fixed hash function and master secret.
86pub trait PrfSecret: Send + Sync {
87    /// Computes `PRF(secret, label, seed)`, writing the result into `output`.
88    ///
89    /// `secret` is implicit in this object; see [`Prf::new_secret`].
90    ///
91    /// The caller guarantees that `label` and `seed` are non-empty.
92    fn prf(&self, output: &mut [u8], label: &[u8], seed: &[u8]);
93}
94
95#[doc(hidden)]
96pub fn prf(out: &mut [u8], hmac_key: &dyn hmac::Key, label: &[u8], seed: &[u8]) {
97    let mut previous_a: Option<hmac::Tag> = None;
98
99    let chunk_size = hmac_key.tag_len();
100    for chunk in out.chunks_mut(chunk_size) {
101        let a_i = match previous_a {
102            // A(0) = HMAC_hash(secret, label + seed)
103            None => hmac_key.sign(&[label, seed]),
104            // A(i) = HMAC_hash(secret, A(i - 1))
105            Some(previous_a) => hmac_key.sign(&[previous_a.as_ref()]),
106        };
107
108        // P_hash[i] = HMAC_hash(secret, A(i) + label + seed)
109        let p_term = hmac_key.sign(&[a_i.as_ref(), label, seed]);
110        chunk.copy_from_slice(&p_term.as_ref()[..chunk.len()]);
111
112        previous_a = Some(a_i);
113    }
114}
115
116#[cfg(all(test, feature = "aws-lc-rs"))]
117pub(crate) struct FakePrf;
118
119#[cfg(all(test, feature = "aws-lc-rs"))]
120impl Prf for FakePrf {
121    fn for_key_exchange(
122        &self,
123        _: &mut [u8; 48],
124        _: Box<dyn ActiveKeyExchange>,
125        _: &[u8],
126        _: &[u8],
127        _: &[u8],
128    ) -> Result<(), Error> {
129        todo!()
130    }
131
132    fn new_secret(&self, _: &[u8; 48]) -> Box<dyn PrfSecret> {
133        todo!()
134    }
135
136    fn fips(&self) -> bool {
137        false
138    }
139}