From 9f268f6f04306fe168d47acdfd42002cfed4d230 Mon Sep 17 00:00:00 2001 From: Xynnn007 Date: Mon, 25 Nov 2024 11:06:52 +0800 Subject: [PATCH] KBS: fix JWE format Fixes #583. Due to RFC 7516, the JWE AEAD Auth Tag should be expcilitly be included inside the `tag` part. Before this commit, the tag is actually included as the suffix of the `ciphertest`. Although this is also secure, it's not standard. We fix this by expcilitly extract the tag and include it into the jwe body. Also, we use an AAD `CoCo` to do AEAD. This should be align with the guest-components side. Signed-off-by: Xynnn007 --- kbs/src/jwe.rs | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/kbs/src/jwe.rs b/kbs/src/jwe.rs index 44e68d1b1..22b8edd02 100644 --- a/kbs/src/jwe.rs +++ b/kbs/src/jwe.rs @@ -2,7 +2,7 @@ // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 -use aes_gcm::{aead::Aead, Aes256Gcm, KeyInit, Nonce}; +use aes_gcm::{aead::AeadMutInPlace, Aes256Gcm, KeyInit, Nonce}; use anyhow::{anyhow, bail, Context, Result}; use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; use kbs_types::{Response, TeePubKey}; @@ -12,8 +12,9 @@ use serde_json::json; const RSA_ALGORITHM: &str = "RSA1_5"; const AES_GCM_256_ALGORITHM: &str = "A256GCM"; +const AEAD_AAD: &[u8] = b"CoCo"; -pub fn jwe(tee_pub_key: TeePubKey, payload_data: Vec) -> Result { +pub fn jwe(tee_pub_key: TeePubKey, mut payload_data: Vec) -> Result { let TeePubKey::RSA { alg, k_mod, k_exp } = tee_pub_key else { bail!("Only RSA key is support for TEE pub key") }; @@ -25,11 +26,11 @@ pub fn jwe(tee_pub_key: TeePubKey, payload_data: Vec) -> Result { let mut rng = rand::thread_rng(); let aes_sym_key = Aes256Gcm::generate_key(&mut OsRng); - let cipher = Aes256Gcm::new(&aes_sym_key); + let mut cipher = Aes256Gcm::new(&aes_sym_key); let iv = rng.gen::<[u8; 12]>(); let nonce = Nonce::from_slice(&iv); - let encrypted_payload_data = cipher - .encrypt(nonce, payload_data.as_slice()) + let tag = cipher + .encrypt_in_place_detached(nonce, AEAD_AAD, &mut payload_data) .map_err(|e| anyhow!("AES encrypt Resource payload failed: {e}"))?; let k_mod = URL_SAFE_NO_PAD @@ -59,7 +60,7 @@ pub fn jwe(tee_pub_key: TeePubKey, payload_data: Vec) -> Result { .context("serde protected_header failed")?, encrypted_key: URL_SAFE_NO_PAD.encode(wrapped_sym_key), iv: URL_SAFE_NO_PAD.encode(iv), - ciphertext: URL_SAFE_NO_PAD.encode(encrypted_payload_data), - tag: "".to_string(), + ciphertext: URL_SAFE_NO_PAD.encode(payload_data), + tag: URL_SAFE_NO_PAD.encode(tag), }) }