Skip to main content

rustls/crypto/
tls13.rs

1use alloc::boxed::Box;
2use alloc::vec::Vec;
3
4use pki_types::FipsStatus;
5use zeroize::Zeroize;
6
7use super::hmac;
8use super::kx::ActiveKeyExchange;
9use crate::enums::ProtocolVersion;
10use crate::error::Error;
11
12/// Implementation of `HkdfExpander` via `hmac::Key`.
13pub struct HkdfExpanderUsingHmac(Box<dyn hmac::Key>);
14
15impl HkdfExpanderUsingHmac {
16    fn expand_unchecked(&self, info: &[&[u8]], output: &mut [u8]) {
17        let mut term = hmac::Tag::new(b"");
18
19        for (n, chunk) in output
20            .chunks_mut(self.0.tag_len())
21            .enumerate()
22        {
23            term = self
24                .0
25                .sign_concat(term.as_ref(), info, &[(n + 1) as u8]);
26            chunk.copy_from_slice(&term.as_ref()[..chunk.len()]);
27        }
28    }
29}
30
31impl HkdfExpander for HkdfExpanderUsingHmac {
32    fn expand_slice(&self, info: &[&[u8]], output: &mut [u8]) -> Result<(), OutputLengthError> {
33        if output.len() > 255 * self.0.tag_len() {
34            return Err(OutputLengthError);
35        }
36
37        self.expand_unchecked(info, output);
38        Ok(())
39    }
40
41    fn expand_block(&self, info: &[&[u8]]) -> OkmBlock {
42        let mut tag = [0u8; hmac::Tag::MAX_LEN];
43        let reduced_tag = &mut tag[..self.0.tag_len()];
44        self.expand_unchecked(info, reduced_tag);
45        OkmBlock::new(reduced_tag)
46    }
47
48    fn hash_len(&self) -> usize {
49        self.0.tag_len()
50    }
51}
52
53/// Implementation of `Hkdf` (and thence `HkdfExpander`) via `hmac::Hmac`.
54#[expect(clippy::exhaustive_structs)]
55pub struct HkdfUsingHmac<'a>(pub &'a dyn hmac::Hmac);
56
57impl Hkdf for HkdfUsingHmac<'_> {
58    fn extract_from_zero_ikm(&self, salt: Option<&[u8]>) -> Box<dyn HkdfExpander> {
59        let zeroes = [0u8; hmac::Tag::MAX_LEN];
60        Box::new(HkdfExpanderUsingHmac(self.0.with_key(
61            &self.extract_prk_from_secret(salt, &zeroes[..self.0.hash_output_len()]),
62        )))
63    }
64
65    fn extract_from_secret(&self, salt: Option<&[u8]>, secret: &[u8]) -> Box<dyn HkdfExpander> {
66        Box::new(HkdfExpanderUsingHmac(
67            self.0
68                .with_key(&self.extract_prk_from_secret(salt, secret)),
69        ))
70    }
71
72    fn expander_for_okm(&self, okm: &OkmBlock) -> Box<dyn HkdfExpander> {
73        Box::new(HkdfExpanderUsingHmac(self.0.with_key(okm.as_ref())))
74    }
75
76    fn hmac_sign(&self, key: &OkmBlock, message: &[u8]) -> hmac::Tag {
77        self.0
78            .with_key(key.as_ref())
79            .sign(&[message])
80    }
81}
82
83impl HkdfPrkExtract for HkdfUsingHmac<'_> {
84    fn extract_prk_from_secret(&self, salt: Option<&[u8]>, secret: &[u8]) -> Vec<u8> {
85        let zeroes = [0u8; hmac::Tag::MAX_LEN];
86        let salt = match salt {
87            Some(salt) => salt,
88            None => &zeroes[..self.0.hash_output_len()],
89        };
90        self.0
91            .with_key(salt)
92            .sign(&[secret])
93            .as_ref()
94            .to_vec()
95    }
96}
97
98/// Implementation of `HKDF-Expand` with an implicitly stored and immutable `PRK`.
99pub trait HkdfExpander: Send + Sync {
100    /// `HKDF-Expand(PRK, info, L)` into a slice.
101    ///
102    /// Where:
103    ///
104    /// - `PRK` is the implicit key material represented by this instance.
105    /// - `L` is `output.len()`.
106    /// - `info` is a slice of byte slices, which should be processed sequentially
107    ///   (or concatenated if that is not possible).
108    ///
109    /// Returns `Err(OutputLengthError)` if `L` is larger than `255 * HashLen`.
110    /// Otherwise, writes to `output`.
111    fn expand_slice(&self, info: &[&[u8]], output: &mut [u8]) -> Result<(), OutputLengthError>;
112
113    /// `HKDF-Expand(PRK, info, L=HashLen)` returned as a value.
114    ///
115    /// - `PRK` is the implicit key material represented by this instance.
116    /// - `L := HashLen`.
117    /// - `info` is a slice of byte slices, which should be processed sequentially
118    ///   (or concatenated if that is not possible).
119    ///
120    /// This is infallible, because by definition `OkmBlock` is always exactly
121    /// `HashLen` bytes long.
122    fn expand_block(&self, info: &[&[u8]]) -> OkmBlock;
123
124    /// Return what `HashLen` is for this instance.
125    ///
126    /// This must be no larger than [`OkmBlock::MAX_LEN`].
127    fn hash_len(&self) -> usize;
128}
129
130/// The `HkdfLabel` structure used as the `info` input to [HKDF-Expand-Label].
131///
132/// [HKDF-Expand-Label]: <https://www.rfc-editor.org/rfc/rfc9846#section-7.1>
133pub(crate) struct HkdfLabel<'a> {
134    output_len: [u8; 2],
135    label_len: [u8; 1],
136    label: &'a [u8],
137    context_len: [u8; 1],
138    context: &'a [u8],
139}
140
141impl<'a> HkdfLabel<'a> {
142    pub(crate) fn new(label: &'a [u8], context: &'a [u8], n: usize) -> Self {
143        Self {
144            output_len: u16::to_be_bytes(n as u16),
145            label_len: u8::to_be_bytes((Self::LABEL_PREFIX.len() + label.len()) as u8),
146            label,
147            context_len: u8::to_be_bytes(context.len() as u8),
148            context,
149        }
150    }
151
152    pub(crate) fn info(&self) -> [&[u8]; 6] {
153        let Self {
154            output_len,
155            label_len,
156            label,
157            context_len,
158            context,
159        } = self;
160
161        [
162            output_len,
163            label_len,
164            Self::LABEL_PREFIX,
165            label,
166            context_len,
167            context,
168        ]
169    }
170
171    const LABEL_PREFIX: &'static [u8] = b"tls13 ";
172}
173
174/// A HKDF implementation oriented to the needs of TLS1.3.
175///
176/// See [RFC 5869](https://datatracker.ietf.org/doc/html/rfc5869) for the terminology
177/// used in this definition.
178///
179/// You can use [`HkdfUsingHmac`] which implements this trait on top of an implementation
180/// of [`hmac::Hmac`].
181pub trait Hkdf: Send + Sync {
182    /// `HKDF-Extract(salt, 0_HashLen)`
183    ///
184    /// `0_HashLen` is a string of `HashLen` zero bytes.
185    ///
186    /// A `salt` of `None` should be treated as a sequence of `HashLen` zero bytes.
187    fn extract_from_zero_ikm(&self, salt: Option<&[u8]>) -> Box<dyn HkdfExpander>;
188
189    /// `HKDF-Extract(salt, secret)`
190    ///
191    /// A `salt` of `None` should be treated as a sequence of `HashLen` zero bytes.
192    fn extract_from_secret(&self, salt: Option<&[u8]>, secret: &[u8]) -> Box<dyn HkdfExpander>;
193
194    /// `HKDF-Extract(salt, shared_secret)` where `shared_secret` is the result of a key exchange.
195    ///
196    /// Custom implementations should complete the key exchange by calling
197    /// `kx.complete(peer_pub_key)` and then using this as the input keying material to
198    /// `HKDF-Extract`.
199    ///
200    /// A `salt` of `None` should be treated as a sequence of `HashLen` zero bytes.
201    fn extract_from_kx_shared_secret(
202        &self,
203        salt: Option<&[u8]>,
204        kx: Box<dyn ActiveKeyExchange>,
205        peer_pub_key: &[u8],
206    ) -> Result<Box<dyn HkdfExpander>, Error> {
207        Ok(self.extract_from_secret(
208            salt,
209            kx.complete_for_tls_version(peer_pub_key, ProtocolVersion::TLSv1_3)?
210                .secret_bytes(),
211        ))
212    }
213
214    /// Build a `HkdfExpander` using `okm` as the secret PRK.
215    fn expander_for_okm(&self, okm: &OkmBlock) -> Box<dyn HkdfExpander>;
216
217    /// Signs `message` using `key` viewed as a HMAC key.
218    ///
219    /// This should use the same hash function as the HKDF functions in this
220    /// trait.
221    ///
222    /// See [RFC 2104](https://datatracker.ietf.org/doc/html/rfc2104) for the
223    /// definition of HMAC.
224    fn hmac_sign(&self, key: &OkmBlock, message: &[u8]) -> hmac::Tag;
225
226    /// Return the FIPS validation status of this implementation.
227    fn fips(&self) -> FipsStatus {
228        FipsStatus::Unvalidated
229    }
230}
231
232/// An extended HKDF implementation that supports directly extracting a pseudo-random key (PRK).
233///
234/// The base [`Hkdf`] trait is tailored to the needs of TLS 1.3, where all extracted PRKs
235/// are expanded as-is, and so can be safely encapsulated without exposing the caller
236/// to the key material.
237///
238/// In other contexts (for example, hybrid public key encryption (HPKE)) it may be necessary
239/// to use the extracted PRK directly for purposes other than an immediate expansion.
240/// This trait can be implemented to offer this functionality when it is required.
241pub trait HkdfPrkExtract: Hkdf {
242    /// `HKDF-Extract(salt, secret)`
243    ///
244    /// A `salt` of `None` should be treated as a sequence of `HashLen` zero bytes.
245    ///
246    /// In most cases you should prefer [`Hkdf::extract_from_secret`] and using the
247    /// returned [HkdfExpander] instead of handling the PRK directly.
248    fn extract_prk_from_secret(&self, salt: Option<&[u8]>, secret: &[u8]) -> Vec<u8>;
249}
250
251/// `HKDF-Expand(PRK, info, L)` to construct any type from a byte array.
252///
253/// - `PRK` is the implicit key material represented by this instance.
254/// - `L := N`; N is the size of the byte array.
255/// - `info` is a slice of byte slices, which should be processed sequentially
256///   (or concatenated if that is not possible).
257///
258/// This is infallible, because the set of types (and therefore their length) is known
259/// at compile time.
260pub fn expand<T, const N: usize>(expander: &dyn HkdfExpander, info: &[&[u8]]) -> T
261where
262    T: From<[u8; N]>,
263{
264    let mut output = [0u8; N];
265    expander
266        .expand_slice(info, &mut output)
267        .expect("expand type parameter T is too large");
268    T::from(output)
269}
270
271/// Output key material from HKDF, as a value type.
272#[derive(Clone)]
273pub struct OkmBlock {
274    buf: [u8; Self::MAX_LEN],
275    used: usize,
276}
277
278impl OkmBlock {
279    /// Build a single OKM block by copying a byte slice.
280    ///
281    /// The slice can be up to [`OkmBlock::MAX_LEN`] bytes in length.
282    pub fn new(bytes: &[u8]) -> Self {
283        let mut tag = Self {
284            buf: [0u8; Self::MAX_LEN],
285            used: 0,
286        };
287        tag.buf[..bytes.len()].copy_from_slice(bytes);
288        tag.used = bytes.len();
289        tag
290    }
291
292    /// Maximum supported OKM block size: supports up to SHA512.
293    pub const MAX_LEN: usize = 64;
294}
295
296impl Drop for OkmBlock {
297    #[inline(never)]
298    fn drop(&mut self) {
299        self.buf[..self.used].zeroize();
300    }
301}
302
303impl AsRef<[u8]> for OkmBlock {
304    fn as_ref(&self) -> &[u8] {
305        &self.buf[..self.used]
306    }
307}
308
309/// An error type used for `HkdfExpander::expand_slice` when
310/// the slice exceeds the maximum HKDF output length.
311#[expect(clippy::exhaustive_structs)]
312#[derive(Debug)]
313pub struct OutputLengthError;