Debian Codegraph @

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

raw symbols SCIP
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // SPDX-License-Identifier: Apache-2.0
3
4 use crate::{
5 codec::DecodeValue,
6 epoch_schedule,
7 psk_derivation::{EpochSecret, PskIdentity},
8 psk_parser::retrieve_psk_identities,
9 KeyArn, ONE_HOUR,
10 };
11 use aws_sdk_kms::Client;
12 use s2n_tls::{
13 callbacks::{ClientHelloCallback, ConnectionFuture},
14 error::Error as S2NError,
15 };
16 use std::{
17 collections::HashMap,
18 pin::Pin,
19 sync::{Arc, RwLock},
20 time::Duration,
21 };
22
23 #[derive(Debug)]
24 struct ReceiverSecrets {
25 smoothing_factor: Duration,
26 pub trusted_key_arns: Vec<KeyArn>,
27 pub epoch_secrets: RwLock<HashMap<u64, HashMap<KeyArn, EpochSecret>>>,
28 }
29
30 impl ReceiverSecrets {
31 fn new(trusted_key_arns: Vec<KeyArn>) -> Self {
32 Self {
33 smoothing_factor: epoch_schedule::smoothing_factor(),
34 trusted_key_arns,
35 epoch_secrets: Default::default(),
36 }
37 }
38
39 /// Given a decoded client_identity, try to find an EpochSecret that was used
40 /// to produce it. This requires generating the corresponding PskIdentity for
41 /// all of the trusted KMS keys.
42 fn find_match(&self, client_identity: PskIdentity) -> anyhow::Result<s2n_tls::psk::Psk> {
43 let read_lock = self.epoch_secrets.read().unwrap();
44 let key_map = match read_lock.get(&client_identity.key_epoch) {
45 Some(key_map) => key_map,
46 None => anyhow::bail!(
47 "no keys found for client epoch {}",
48 client_identity.key_epoch
49 ),
50 };
51
52 for epoch_secret in key_map.values() {
53 let psk_identity = PskIdentity::new(client_identity.session_name.blob(), epoch_secret)?;
54 if psk_identity == client_identity {
55 let psk_secret =
56 epoch_secret.new_psk_secret(client_identity.session_name.blob())?;
57 return EpochSecret::psk_from_parts(psk_identity, psk_secret)
58 .map_err(|e| anyhow::anyhow!("failed to construct psk {e}"));
59 }
60 }
61
62 anyhow::bail!(
63 "no matching kms binder found for session {}",
64 hex::encode(client_identity.session_name.blob())
65 );
66 }
67
68 fn insert_secret(&self, epoch_secret: EpochSecret) {
69 self.epoch_secrets
70 .write()
71 .unwrap()
72 .entry(epoch_secret.key_epoch)
73 .or_default()
74 .insert(epoch_secret.key_arn.clone(), epoch_secret);
75 }
76
77 /// Return a list of all the (epoch, key_arn) EpochSecrets that are available
78 fn available_secrets(&self) -> Vec<(u64, KeyArn)> {
79 self.epoch_secrets
80 .read()
81 .unwrap()
82 .iter()
83 .flat_map(|(epoch, arn_map)| arn_map.keys().map(|key_arn| (*epoch, key_arn.clone())))
84 .collect()
85 }
86
87 fn newest_available_epoch(&self) -> Option<u64> {
88 self.epoch_secrets.read().unwrap().keys().max().cloned()
89 }
90
91 async fn fetch_secrets(
92 &self,
93 kms_client: &Client,
94 current_epoch: u64,
95 failure_notification: &(dyn Fn(anyhow::Error) + Send + Sync + 'static),
96 ) -> Result<Duration, Duration> {
97 // fetch all keys that aren't already available
98 // This will almost always just fetch `this_epoch + 2`, unless key
99 // generation has failed for several days
100 let mut fetch_failed = false;
101 let mut to_fetch: Vec<(u64, KeyArn)> = {
102 // we need to fetch current_epoch - 1 to allow for clock skew in clients
103 // as well as provider::ROTATION_CUSHION
104 [
105 current_epoch - 1,
106 current_epoch,
107 current_epoch + 1,
108 current_epoch + 2,
109 ]
110 .iter()
111 .flat_map(|epoch| {
112 self.trusted_key_arns
113 .iter()
114 .cloned()
115 .map(|arn| (*epoch, arn))
116 })
117 .collect()
118 };
119
120 let available: Vec<(u64, KeyArn)> = self.available_secrets();
121 to_fetch.retain(|epoch| !available.contains(epoch));
122
123 for (epoch, key_arn) in to_fetch {
124 match EpochSecret::fetch_epoch_secret(kms_client, &key_arn, epoch).await {
125 Ok(epoch_secret) => {
126 tracing::debug!("fetched secret for epoch {epoch} from {key_arn} ");
127 self.insert_secret(epoch_secret);
128 }
129 Err(e) => {
130 fetch_failed = true;
131 tracing::error!(
132 "failed to fetch secret for epoch {epoch} from {key_arn}: {e:?}"
133 );
134 failure_notification(anyhow::anyhow!("failed to fetch {key_arn}").context(e));
135 }
136 }
137 }
138
139 if fetch_failed {
140 return Err(ONE_HOUR);
141 }
142
143 let sleep_duration = self.newest_available_epoch().and_then(|fetch_epoch| {
144 epoch_schedule::until_fetch(fetch_epoch + 1, self.smoothing_factor)
145 });
146 match sleep_duration {
147 Some(duration) => Ok(duration),
148 None => Err(ONE_HOUR),
149 }
150 }
151
152 /// Drop all of the unneeded secrets.
153 ///
154 /// If the current epoch is `n`, any key from epoch `n - 2` or earlier will
155 /// be dropped.
156 fn cleanup_old_secrets(&self, current_epoch: u64) {
157 self.epoch_secrets
158 .write()
159 .unwrap()
160 .retain(|epoch, _arn_map| *epoch >= current_epoch - 1);
161 }
162
163 /// The is the entry point for periodic updates of the secret state.
164 ///
165 /// This will fetch any new secrets that are needed, and clean up old secrets.
166 async fn poll_update(
167 &self,
168 kms_client: &Client,
169 current_epoch: u64,
170 failure_notification: &(dyn Fn(anyhow::Error) + Send + Sync + 'static),
171 ) -> Result<Duration, Duration> {
172 let sleep_duration = self
173 .fetch_secrets(kms_client, current_epoch, failure_notification)
174 .await;
175 self.cleanup_old_secrets(current_epoch);
176 sleep_duration
177 }
178 }
179
180 /// The `PskReceiver` is used along with the [`PskProvider`] to perform TLS
181 /// 1.3 out-of-band PSK authentication, using PSK's generated from KMS.
182 ///
183 /// This struct can be enabled on a config with [`s2n_tls::config::Builder::set_client_hello_callback`].
184 #[derive(Debug, Clone)]
185 pub struct PskReceiver {
186 secrets: Arc<ReceiverSecrets>,
187 }
188
189 impl PskReceiver {
190 /// Create a new PskReceiver.
191 ///
192 /// This will receive the ciphertext datakey identities from a TLS client hello,
193 /// then decrypt them using KMS. This establishes a mutually authenticated TLS
194 /// handshake between parties with IAM permissions to generate and decrypt data keys
195 ///
196 /// * `kms_client`: The KMS Client that will be used for the decrypt calls
197 ///
198 /// * `trusted_key_arns`: The list of KMS KeyArns that the PskReceiver will
199 /// accept PSKs from. Applications should avoid trusting large (1000+) numbers
200 /// of KMS keys, because the PskReceiver has to do brute force linear matching
201 /// to find the KMS key that was used for a client identity. This costs ~ 300ns
202 /// per trusted key, and thus is negligible for small amounts of trusted keys.
203 pub async fn initialize(
204 kms_client: Client,
205 trusted_key_arns: Vec<KeyArn>,
206 failure_notification: impl Fn(anyhow::Error) + Send + Sync + 'static,
207 ) -> anyhow::Result<Self> {
208 let secret_state = Arc::new(ReceiverSecrets::new(trusted_key_arns.clone()));
209 let current_epoch = epoch_schedule::current_epoch();
210
211 let update = secret_state
212 .fetch_secrets(&kms_client, current_epoch, &failure_notification)
213 .await;
214 if update.is_err() {
215 anyhow::bail!("failed to fetch keys during startup");
216 }
217
218 // spawn the fetcher
219 let secret_handle = Arc::clone(&secret_state);
220 tokio::spawn(async move {
221 loop {
222 let this_epoch = epoch_schedule::current_epoch();
223 let sleep_duration = secret_handle
224 .fetch_secrets(&kms_client, this_epoch, &failure_notification)
225 .await;
226 secret_handle.cleanup_old_secrets(this_epoch);
227
228 let sleep_duration = match sleep_duration {
229 Ok(d) => d,
230 Err(d) => d,
231 };
232 tracing::debug!("sleeping for {sleep_duration:?}");
233 tokio::time::sleep(sleep_duration).await;
234 }
235 });
236
237 Ok(Self {
238 secrets: secret_state,
239 })
240 }
241 }
242
243 impl ClientHelloCallback for PskReceiver {
244 fn on_client_hello(
245 &self,
246 connection: &mut s2n_tls::connection::Connection,
247 ) -> Result<Option<Pin<Box<dyn ConnectionFuture>>>, s2n_tls::error::Error> {
248 // parse the identity list from the client hello
249 let client_hello = connection.client_hello()?;
250 let identities = match retrieve_psk_identities(client_hello) {
251 Ok(identities) => identities,
252 Err(e) => {
253 return Err(s2n_tls::error::Error::application(e.into()));
254 }
255 };
256
257 // extract the identity bytes from the first PSK entry. We assume that we
258 // are talking to a PskProvider, so we don't look at any additional entries.
259 let psk_identity = match identities.list().first() {
260 Some(id) => id.identity.blob(),
261 None => {
262 return Err(s2n_tls::error::Error::application(
263 "identities list was zero-length".into(),
264 ))
265 }
266 };
267
268 // parse the identity bytes to a PskIdentity
269 let client_identity = PskIdentity::decode_from_exact(psk_identity)
270 .map_err(|e| s2n_tls::error::Error::application(e.into()))?;
271 tracing::trace!("server received: {client_identity:?}");
272
273 let psk = self
274 .secrets
275 .find_match(client_identity)
276 .map_err(|e| S2NError::application(e.into()))?;
277 connection.append_psk(&psk)?;
278 Ok(None)
279 }
280 }
281
282 #[cfg(test)]
283 mod secret_state_tests {
284 use crate::{
285 epoch_schedule::{self},
286 psk_derivation::{EpochSecret, PskIdentity},
287 receiver::ReceiverSecrets,
288 test_utils::{self, mocked_kms_client, KMS_KEY_ARN_A, KMS_KEY_ARN_B},
289 PskReceiver,
290 };
291 use aws_sdk_kms::{
292 operation::generate_mac::{GenerateMacError, GenerateMacOutput},
293 primitives::Blob,
294 Client,
295 };
296 use aws_smithy_mocks::{mock, mock_client};
297 use std::{
298 sync::{
299 atomic::{AtomicUsize, Ordering},
300 Arc,
301 },
302 time::Duration,
303 };
304
305 #[test]
306 fn key_insertion() {
307 let secret_state = ReceiverSecrets::new(vec![]);
308 assert!(secret_state.epoch_secrets.read().unwrap().is_empty());
309 let secret_a = EpochSecret {
310 key_arn: "arn:1235:abc".to_owned(),
311 key_epoch: 31456,
312 secret: b"some secret".to_vec(),
313 };
314 let secret_b = EpochSecret {
315 key_arn: "arn:1235:abd".to_owned(),
316 key_epoch: 31457,
317 secret: b"some secret".to_vec(),
318 };
319
320 {
321 secret_state.insert_secret(secret_a.clone());
322 let epoch_map = secret_state.epoch_secrets.read().unwrap();
323 assert_eq!(epoch_map.len(), 1);
324 assert_eq!(epoch_map.get(&secret_a.key_epoch).unwrap().len(), 1);
325 assert_eq!(
326 epoch_map
327 .get(&secret_a.key_epoch)
328 .unwrap()
329 .get(&secret_a.key_arn),
330 Some(&secret_a)
331 );
332 }
333
334 {
335 secret_state.insert_secret(secret_b.clone());
336 let epoch_map = secret_state.epoch_secrets.read().unwrap();
337 assert_eq!(epoch_map.len(), 2);
338 assert_eq!(epoch_map.get(&secret_b.key_epoch).unwrap().len(), 1);
339 assert_eq!(
340 epoch_map
341 .get(&secret_b.key_epoch)
342 .unwrap()
343 .get(&secret_b.key_arn),
344 Some(&secret_b)
345 );
346 }
347
348 let available = secret_state.available_secrets();
349 assert!(available.contains(&(secret_a.key_epoch, secret_a.key_arn)));
350 assert!(available.contains(&(secret_b.key_epoch, secret_b.key_arn)));
351 assert_eq!(available.len(), 2);
352 }
353
354 #[test]
355 fn psk_matching() {
356 let secret_state = ReceiverSecrets::new(vec!["arn:1235:abc".to_owned()]);
357 let epoch_secret = EpochSecret {
358 key_arn: "arn:1235:abc".to_owned(),
359 key_epoch: 31456,
360 secret: b"some secret".to_vec(),
361 };
362 secret_state.insert_secret(epoch_secret.clone());
363
364 // matching PSK identity
365 let session_name = b"test_session".to_vec();
366 let psk_identity = PskIdentity::new(&session_name, &epoch_secret).unwrap();
367 secret_state.find_match(psk_identity.clone()).unwrap();
368
369 // non-matching PSK identity - right epoch, wrong key
370 let other_secret = EpochSecret {
371 key_arn: "arn:1235:different".to_owned(),
372 key_epoch: 31456,
373 secret: b"some secret".to_vec(),
374 };
375 let different_identity = PskIdentity::new(&session_name, &other_secret).unwrap();
376 let error = secret_state.find_match(different_identity).unwrap_err();
377 assert!(error
378 .to_string()
379 .contains("no matching kms binder found for session"));
380
381 // non-matching PSK identity - wrong epoch
382 let non_existent_epoch_secret = EpochSecret {
383 key_arn: "arn:1235:abc".to_owned(),
384 key_epoch: 99999,
385 secret: b"some secret".to_vec(),
386 };
387 let non_existent_identity =
388 PskIdentity::new(&session_name, &non_existent_epoch_secret).unwrap();
389 let error = secret_state.find_match(non_existent_identity).unwrap_err();
390 assert_eq!(error.to_string(), "no keys found for client epoch 99999");
391 }
392
393 #[tokio::test]
394 async fn initialization_fetches_keys() {
395 let kms_client = test_utils::mocked_kms_client();
396 let trusted_key_arns = vec![KMS_KEY_ARN_A.to_owned()];
397 let receiver = PskReceiver::initialize(kms_client, trusted_key_arns, |_| {})
398 .await
399 .unwrap();
400 assert_eq!(receiver.secrets.available_secrets().len(), 4);
401
402 let kms_client = test_utils::mocked_kms_client();
403 let trusted_key_arns = vec![KMS_KEY_ARN_A.to_owned(), KMS_KEY_ARN_B.to_owned()];
404 let receiver = PskReceiver::initialize(kms_client, trusted_key_arns, |_| {})
405 .await
406 .unwrap();
407 assert_eq!(receiver.secrets.available_secrets().len(), 8);
408 }
409
410 #[tokio::test]
411 async fn poll_update() -> Result<(), Duration> {
412 let psk_provider =
413 PskReceiver::initialize(mocked_kms_client(), vec![KMS_KEY_ARN_A.to_owned()], |_| {})
414 .await
415 .unwrap();
416 let mut this_epoch = epoch_schedule::current_epoch();
417 let client = mocked_kms_client();
418 let secret_state = psk_provider.secrets;
419
420 secret_state
421 .poll_update(&client, this_epoch, &|_| {})
422 .await?;
423 let available = secret_state.available_secrets();
424 assert_eq!(available.len(), 4);
425 assert!(available.contains(&(this_epoch - 1, KMS_KEY_ARN_A.to_owned())));
426 assert!(available.contains(&(this_epoch, KMS_KEY_ARN_A.to_owned())));
427 assert!(available.contains(&(this_epoch + 1, KMS_KEY_ARN_A.to_owned())));
428 assert!(available.contains(&(this_epoch + 2, KMS_KEY_ARN_A.to_owned())));
429
430 // idempotent if the time hasn't changed
431 secret_state
432 .poll_update(&client, this_epoch, &|_| {})
433 .await?;
434 assert_eq!(secret_state.available_secrets(), available);
435
436 this_epoch += 1;
437 // when time advances, we
438 // 1. fetch a new secret
439 // 2. rotate the current one
440 // 3. drop the old one
441 secret_state
442 .poll_update(&client, this_epoch, &|_| {})
443 .await?;
444 let available = secret_state.available_secrets();
445 assert_eq!(available.len(), 4);
446 assert!(available.contains(&(this_epoch - 1, KMS_KEY_ARN_A.to_owned())));
447 assert!(available.contains(&(this_epoch, KMS_KEY_ARN_A.to_owned())));
448 assert!(available.contains(&(this_epoch + 1, KMS_KEY_ARN_A.to_owned())));
449 assert!(available.contains(&(this_epoch + 2, KMS_KEY_ARN_A.to_owned())));
450
451 this_epoch += 2;
452 // time skips are gracefully handled
453 secret_state
454 .poll_update(&client, this_epoch, &|_| {})
455 .await?;
456 let available = secret_state.available_secrets();
457 assert_eq!(available.len(), 4);
458 assert!(available.contains(&(this_epoch - 1, KMS_KEY_ARN_A.to_owned())));
459 assert!(available.contains(&(this_epoch, KMS_KEY_ARN_A.to_owned())));
460 assert!(available.contains(&(this_epoch + 1, KMS_KEY_ARN_A.to_owned())));
461 assert!(available.contains(&(this_epoch + 2, KMS_KEY_ARN_A.to_owned())));
462 Ok(())
463 }
464
465 #[tokio::test]
466 async fn poll_update_with_failure() {
467 let error_count = Arc::new(AtomicUsize::new(0));
468 let notification_fn = {
469 let error_count = Arc::clone(&error_count);
470 move |_: anyhow::Error| {
471 error_count.fetch_add(1, Ordering::SeqCst);
472 }
473 };
474
475 let rule = mock!(Client::generate_mac)
476 .sequence()
477 .output(|| {
478 GenerateMacOutput::builder()
479 .mac(Blob::new(b"mock_mac_output".to_vec()))
480 .build()
481 })
482 .times(5)
483 .error(|| GenerateMacError::unhandled("MockedFailure"))
484 .output(|| {
485 GenerateMacOutput::builder()
486 .mac(Blob::new(b"mock_mac_output".to_vec()))
487 .build()
488 })
489 .build();
490 let kms_client = mock_client!(aws_sdk_kms, [&rule]);
491
492 let psk_receiver = PskReceiver::initialize(
493 kms_client.clone(),
494 vec![KMS_KEY_ARN_A.to_owned()],
495 notification_fn.clone(),
496 )
497 .await
498 .unwrap();
499 assert_eq!(rule.num_calls(), 4);
500 let current_epoch = epoch_schedule::current_epoch();
501
502 assert_eq!(error_count.load(Ordering::SeqCst), 0);
503 psk_receiver
504 .secrets
505 .poll_update(&kms_client, current_epoch + 1, &notification_fn)
506 .await
507 .unwrap();
508 assert_eq!(rule.num_calls(), 5);
509
510 assert_eq!(psk_receiver.secrets.available_secrets().len(), 4);
511 psk_receiver
512 .secrets
513 .poll_update(&kms_client, current_epoch + 2, &notification_fn)
514 .await
515 .unwrap_err();
516 assert_eq!(psk_receiver.secrets.available_secrets().len(), 3);
517 assert_eq!(rule.num_calls(), 6);
518 assert_eq!(error_count.load(Ordering::SeqCst), 1);
519
520 psk_receiver
521 .secrets
522 .poll_update(&kms_client, current_epoch + 2, &notification_fn)
523 .await
524 .unwrap();
525 assert_eq!(psk_receiver.secrets.available_secrets().len(), 4);
526 }
527
528 #[tokio::test]
529 async fn initialize_fails_with_invalid_kms() {
530 use aws_smithy_mocks::{mock, mock_client, RuleMode};
531
532 // Create a mock KMS client that always fails
533 let fail_rule = mock!(Client::generate_mac).then_error(|| {
534 aws_sdk_kms::operation::generate_mac::GenerateMacError::unhandled("MockedFailure")
535 });
536
537 let kms_client = mock_client!(aws_sdk_kms, RuleMode::MatchAny, [&fail_rule]);
538
539 // Initialize should fail because all KMS calls fail
540 let result =
541 PskReceiver::initialize(kms_client, vec![KMS_KEY_ARN_A.to_owned()], |_| {}).await;
542
543 assert!(result.is_err());
544 assert!(result
545 .unwrap_err()
546 .to_string()
547 .contains("failed to fetch keys during startup"));
548 }
549 }