Debian Codegraph @

crt/s2n/bindings/rust/aws-kms-tls-auth/src/psk_derivation.rs

raw symbols SCIP
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // SPDX-License-Identifier: Apache-2.0
3
4 //! There are three components to the HMAC PSK Design
5 //!
6 //! ## Epoch Secret
7 //!
8 //! The epoch secret is generated using the KMS GenerateMac API. The "message"
9 //! being signed is the number of days elapsed since the unix epoch, represented
10 //! as a `u64` in big-endian format.
11 //!
12 //! The KMS key must use an HMAC-SHA384 keyspec. This is not currently library
13 //! configurable.
14 //!
15 //! ## PSK Secret
16 //!
17 //! First the client generates a random `session_name` to be used as a nonce. This
18 //! is then used with the epoch_secret in an HKDF to derive a connection-specific
19 //! secret.
20 //!
21 //! ```text
22 //! connection_secret = HKDF(
23 //! secret: epoch_secret
24 //! info: session_name
25 //! salt: null
26 //! )
27 //! ```
28 //!
29 //! ## PSK Identity
30 //!
31 //! The PSK identity is sent in plaintext in the client hello. Note that a server
32 //! ([`crate::PskReceiver`]) supports trusting multiple KMS keys, which allows for
33 //! rotation/transitioning the underlying KMS key.
34 //!
35 //! If a server trusts both keyA and keyB, then the client will need to
36 //! communicate which key it used to derive its PSK. The naive solution would be
37 //! to just include keyA or keyB in plaintext in the PSK Identity. However, this
38 //! would leak information about “fleet membership”, because it is sent in the
39 //! clear. Ideally, the PSK identity would not leak this information.
40 //!
41 //! To do this we calculate a `kms_key_binder` to include in the PSK Identity. This
42 //! incorporates
43 //! - kms key arn: the key that was used to generate the daily secret
44 //! - session name: this makes the kms key binder unique per connection, preventing
45 //! information from being correlated across multiple connections from a single
46 //! client.
47 //! - epoch_secret: without incorporating this secret, an attacker would be able
48 //! to check if the kms_key_binder was valid for some specific KMS key.
49
50 use crate::{
51 codec::{DecodeByteSource, DecodeValue, EncodeBytesSink, EncodeValue},
52 prefixed_list::PrefixedBlob,
53 KeyArn,
54 };
55 use aws_lc_rs::{
56 digest::{self},
57 hkdf,
58 rand::SecureRandom,
59 };
60 use aws_sdk_kms::{primitives::Blob, types::MacAlgorithmSpec, Client};
61 use s2n_tls::error::Error as S2NError;
62 use std::{fmt::Debug, hash::Hash, io::ErrorKind};
63
64 const SHA384_DIGEST_SIZE: usize = 48;
65 const SESSION_NAME_LENGTH: usize = 16;
66
67 // V1 was used for an earlier KMS data-key based solution and is no longer supported
68 #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
69 #[repr(u8)]
70 pub enum PskVersion {
71 V2 = 2,
72 }
73
74 impl EncodeValue for PskVersion {
75 fn encode_to(&self, buffer: &mut Vec<u8>) -> std::io::Result<()> {
76 let byte = *self as u8;
77 buffer.encode_value(&byte)?;
78 Ok(())
79 }
80 }
81
82 impl DecodeValue for PskVersion {
83 fn decode_from(buffer: &[u8]) -> std::io::Result<(Self, &[u8])> {
84 let (value, buffer) = u8::decode_from(buffer)?;
85 match value {
86 2 => Ok((Self::V2, buffer)),
87 _ => Err(std::io::Error::new(
88 ErrorKind::InvalidData,
89 format!("{value} is not a valid KmsPskFormat"),
90 )),
91 }
92 }
93 }
94
95 #[derive(Clone, PartialEq, Eq)]
96 pub(crate) struct EpochSecret {
97 /// the ARN of the KMS HMAC key
98 pub key_arn: KeyArn,
99 /// the key epoch, which is the number of days elapsed since the unix epoch
100 pub key_epoch: u64,
101 /// the secret material from the generateMAC API
102 pub secret: Vec<u8>,
103 }
104
105 impl Debug for EpochSecret {
106 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107 f.debug_struct("EpochSecret")
108 .field("key_arn", &self.key_arn)
109 .field("key_epoch", &self.key_epoch)
110 .field("secret", &"<REDACTED>")
111 .finish()
112 }
113 }
114
115 impl EpochSecret {
116 /// This label ties the output of generateMAC to its use in this library.
117 pub const PURPOSE_LABEL: &'static [u8] = b"aws-kms-tls-auth-epoch-secret";
118
119 /// Construct the message to be used by KMS for `epoch`
120 ///
121 /// key_epoch || PURPOSE_LABEL
122 pub fn construct_message(epoch: u64) -> Vec<u8> {
123 let mut msg = Vec::with_capacity(8 + Self::PURPOSE_LABEL.len());
124 msg.extend_from_slice(&epoch.to_be_bytes());
125 msg.extend_from_slice(Self::PURPOSE_LABEL);
126 msg
127 }
128
129 /// Fetch the secret for `epoch` from KMS.
130 pub async fn fetch_epoch_secret(
131 kms_client: &Client,
132 key_arn: &KeyArn,
133 epoch: u64,
134 ) -> anyhow::Result<Self> {
135 let mac_output = kms_client
136 .generate_mac()
137 .key_id(key_arn.clone())
138 .mac_algorithm(MacAlgorithmSpec::HmacSha384)
139 .message(Blob::new(Self::construct_message(epoch)))
140 .send()
141 .await?;
142
143 let secret = match mac_output.mac {
144 Some(mac) => mac.into_inner(),
145 // the KMS documentation implies that the ciphertext and plaintext
146 // fields are required, although the SDK does not model them as such
147 // https://docs.aws.amazon.com/kms/latest/APIReference/API_GenerateMac.html#API_GenerateMac_ResponseSyntax
148 None => anyhow::bail!("failed to retrieve the Mac from the GenerateMac operation"),
149 };
150
151 Ok(Self {
152 key_arn: key_arn.clone(),
153 key_epoch: epoch,
154 secret,
155 })
156 }
157
158 #[cfg(test)]
159 pub fn test_constructor(key_arn: KeyArn, key_epoch: u64, secret: Vec<u8>) -> Self {
160 Self {
161 key_arn,
162 key_epoch,
163 secret,
164 }
165 }
166
167 pub fn new_connection_psk(&self) -> Result<s2n_tls::psk::Psk, S2NError> {
168 let session_name = {
169 let rng = aws_lc_rs::rand::SystemRandom::new();
170 let mut session_name = [0; SESSION_NAME_LENGTH];
171 rng.fill(&mut session_name)
172 .map_err(|_| S2NError::application("failed to create session name".into()))?;
173 session_name
174 };
175
176 let identity =
177 PskIdentity::new(&session_name, self).map_err(|e| S2NError::application(e.into()))?;
178 let secret = self.new_psk_secret(&session_name)?;
179 Self::psk_from_parts(identity, secret)
180 }
181
182 pub fn new_psk_secret(&self, session_name: &[u8]) -> Result<Vec<u8>, S2NError> {
183 let null_salt = hkdf::Salt::new(hkdf::HKDF_SHA384, &[]);
184 let pseudo_random_key = null_salt.extract(&self.secret);
185 let binding = [session_name];
186 let session_secret = pseudo_random_key
187 .expand(&binding, hkdf::HKDF_SHA384.hmac_algorithm())
188 .map_err(|_| S2NError::application("PSK secret HKDF failed".into()))?;
189 let mut session_secret_bytes = vec![0; SHA384_DIGEST_SIZE];
190 session_secret
191 .fill(&mut session_secret_bytes)
192 .map_err(|_| S2NError::application("failed to extract key material".into()))?;
193 Ok(session_secret_bytes)
194 }
195
196 pub fn psk_from_parts(
197 identity: PskIdentity,
198 secret: Vec<u8>,
199 ) -> Result<s2n_tls::psk::Psk, S2NError> {
200 let identity_bytes = identity.encode_to_vec().map_err(|e| {
201 S2NError::application(format!("unable to encode PSK identity: {e:?}").into())
202 })?;
203 let mut psk = s2n_tls::psk::Psk::builder()?;
204 psk.set_hmac(s2n_tls::enums::PskHmac::SHA384)?;
205 psk.set_identity(&identity_bytes)?;
206 psk.set_secret(&secret)?;
207 psk.build()
208 }
209 }
210
211 #[derive(Clone, Hash, PartialEq, Eq)]
212 pub(crate) struct PskIdentity {
213 version: PskVersion,
214 /// the key epoch that was used to derive the daily secret
215 pub key_epoch: u64,
216 /// the session name used to derive session specific keys
217 pub session_name: PrefixedBlob<u16>,
218 /// a value indicating the KMS key arn that was used
219 kms_key_binder: PrefixedBlob<u16>,
220 }
221
222 impl Debug for PskIdentity {
223 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
224 f.debug_struct("PskIdentity")
225 .field("version", &self.version)
226 .field("key_epoch", &self.key_epoch)
227 .field("session_name", &hex::encode(self.session_name.blob()))
228 .field("kms_key_binder", &hex::encode(self.kms_key_binder.blob()))
229 .finish()
230 }
231 }
232
233 impl EncodeValue for PskIdentity {
234 fn encode_to(&self, buffer: &mut Vec<u8>) -> std::io::Result<()> {
235 buffer.encode_value(&self.version)?;
236 buffer.encode_value(&self.key_epoch)?;
237 buffer.encode_value(&self.session_name)?;
238 buffer.encode_value(&self.kms_key_binder)?;
239 Ok(())
240 }
241 }
242
243 impl DecodeValue for PskIdentity {
244 fn decode_from(buffer: &[u8]) -> std::io::Result<(Self, &[u8])> {
245 let (version, buffer) = buffer.decode_value()?;
246 let (key_epoch, buffer) = buffer.decode_value()?;
247 let (session_name, buffer) = buffer.decode_value()?;
248 let (kms_key_binder, buffer) = buffer.decode_value()?;
249
250 let value = Self {
251 version,
252 key_epoch,
253 session_name,
254 kms_key_binder,
255 };
256
257 Ok((value, buffer))
258 }
259 }
260
261 impl PskIdentity {
262 pub fn new(session_name: &[u8], daily_secret: &EpochSecret) -> anyhow::Result<Self> {
263 let kms_key_binder = Self::kms_key_binder(session_name, daily_secret);
264 let kms_key_binder = PrefixedBlob::new(kms_key_binder)?;
265 let session_name = PrefixedBlob::new(session_name.to_vec())?;
266 Ok(Self {
267 version: PskVersion::V2,
268 key_epoch: daily_secret.key_epoch,
269 session_name,
270 kms_key_binder,
271 })
272 }
273
274 fn kms_key_binder(session_name: &[u8], daily_secret: &EpochSecret) -> Vec<u8> {
275 let mut ctx = digest::Context::new(&digest::SHA384);
276 ctx.update(&daily_secret.secret);
277 ctx.update(session_name);
278 ctx.update(daily_secret.key_arn.as_bytes());
279 let kms_key_binder = ctx.finish();
280 kms_key_binder.as_ref().to_vec()
281 }
282 }
283
284 #[cfg(test)]
285 mod tests {
286 use super::*;
287 use aws_lc_rs::digest::SHA384;
288 use std::{collections::HashSet, time::Instant};
289
290 fn test_epoch_secret() -> EpochSecret {
291 EpochSecret::test_constructor(
292 "arn:1234:abcd".to_owned(),
293 123_456,
294 b"secret material bytes".to_vec(),
295 )
296 }
297
298 /// serializing and deserializing a PSK Identity should result in the same struct
299 #[test]
300 fn round_trip() {
301 let identity = PskIdentity::new(b"a session name", &test_epoch_secret()).unwrap();
302 let serialized_identity = identity.encode_to_vec().unwrap();
303
304 let (deserialized_identity, remaining) =
305 PskIdentity::decode_from(&serialized_identity).unwrap();
306 assert!(remaining.is_empty());
307
308 assert_eq!(deserialized_identity, identity);
309 }
310
311 /// Check that the KMS key binder incorporates
312 /// - session name
313 /// - KMS arn
314 /// - epoch secret
315 ///
316 /// Changing any of these should change the KMS key binder
317 #[test]
318 fn kms_key_binder() {
319 let epoch_secret = test_epoch_secret();
320 let session_name = b"session name";
321
322 let kms_binder = PskIdentity::kms_key_binder(session_name, &epoch_secret);
323 let changed_session_name =
324 PskIdentity::kms_key_binder(b"other session name", &epoch_secret);
325 let changed_key_name = {
326 let mut changed_key = test_epoch_secret();
327 changed_key.key_arn = "different key name".to_owned();
328 PskIdentity::kms_key_binder(session_name, &changed_key)
329 };
330 let changed_epoch_secret = {
331 let mut changed_key = test_epoch_secret();
332 changed_key.secret = b"different secret material".to_vec();
333 PskIdentity::kms_key_binder(session_name, &changed_key)
334 };
335 let unique_binders = HashSet::from([
336 kms_binder,
337 changed_session_name,
338 changed_key_name,
339 changed_epoch_secret,
340 ]);
341 assert_eq!(unique_binders.len(), 4);
342
343 assert_eq!(unique_binders.len(), 4);
344 }
345
346 /// Check that the PSK connection secret incorporates
347 /// - epoch secret
348 /// - session name
349 ///
350 /// Changing any of these should change the connection secret
351 #[test]
352 fn psk_secret() -> anyhow::Result<()> {
353 let epoch_secret = test_epoch_secret();
354 let session_name = b"session name";
355
356 let psk_secret = epoch_secret.new_psk_secret(session_name)?;
357 let changed_session_name = epoch_secret.new_psk_secret(b"different session name")?;
358 let changed_epoch_secret = {
359 let mut epoch_secret = test_epoch_secret();
360 epoch_secret.secret = b"different secret material".to_vec();
361 epoch_secret.new_psk_secret(session_name)?
362 };
363
364 let unique_secrets =
365 HashSet::from([psk_secret, changed_session_name, changed_epoch_secret]);
366 assert_eq!(unique_secrets.len(), 3);
367
368 Ok(())
369 }
370
371 /// The encoded PSK Identity from the 0.0.2 version of the library was checked
372 /// in. If we ever fail to deserialize this STOP! You are about to make a
373 /// breaking change. You must find a way to make your change backwards
374 /// compatible.
375 #[test]
376 fn backwards_compatibility() {
377 const ENCODED_IDENTITY: &[u8] = include_bytes!("../resources/psk_identity.bin");
378 const SESSION_NAME: &[u8] = b"psk session name";
379
380 let identity = PskIdentity::new(SESSION_NAME, &test_epoch_secret()).unwrap();
381
382 let deserialized_identity = PskIdentity::decode_from_exact(ENCODED_IDENTITY).unwrap();
383 assert_eq!(deserialized_identity, identity);
384 }
385
386 /// This is a very simple benchmark checking the cost of PSK Identity derivation
387 /// We use this setup because it allows us to keep the EpochSecret struct private
388 ///
389 /// In release mode a PSK Derivation takes ~ 292 ns.
390 #[test]
391 fn psk_derivation_benchmark() {
392 const TRIALS: u32 = 1_000_000;
393 let start = Instant::now();
394 for i in 0..TRIALS {
395 let _identity = PskIdentity::new(&i.to_be_bytes(), &test_epoch_secret()).unwrap();
396 }
397 let elapsed = start.elapsed();
398 println!(
399 "total time: {:?}, per derivation: {:?}",
400 elapsed,
401 elapsed / TRIALS
402 );
403 }
404
405 /// We should avoid logging sensitive materials
406 #[test]
407 fn redacted_debug() {
408 let secret_a = test_epoch_secret();
409 let secret_b = {
410 let mut secret = test_epoch_secret();
411 secret.secret = b"different material".to_vec();
412 secret
413 };
414
415 // these can only be equal if the secret material isn't included in the
416 // debug representation
417 assert_eq!(format!("{secret_a:?}"), format!("{secret_b:?}"));
418 }
419
420 /// `output_len()` isn't a const function, so we define
421 /// our own constants to let us use those values in things like array sizes.
422 #[test]
423 fn constant_check() {
424 assert_eq!(SHA384_DIGEST_SIZE, SHA384.output_len());
425 }
426 }