| 1 |
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 |
// Copyright by contributors to this project. |
| 3 |
// SPDX-License-Identifier: (Apache-2.0 OR MIT) |
| 4 |
|
| 5 |
use core::fmt::Debug; |
| 6 |
|
| 7 |
use crate::alloc::borrow::ToOwned; |
| 8 |
|
| 9 |
use mls_rs_core::{ |
| 10 |
crypto::{ |
| 11 |
HpkeCiphertext, HpkeContextR, HpkeContextS, HpkeModeId, HpkePublicKey, HpkeSecretKey, |
| 12 |
}, |
| 13 |
error::{AnyError, IntoAnyError}, |
| 14 |
}; |
| 15 |
|
| 16 |
use mls_rs_crypto_traits::{AeadType, KdfType, KemType, AEAD_ID_EXPORT_ONLY}; |
| 17 |
|
| 18 |
use zeroize::Zeroizing; |
| 19 |
|
| 20 |
use crate::{ |
| 21 |
context::{Context, ContextR, ContextS, EncryptionContext}, |
| 22 |
kdf::HpkeKdf, |
| 23 |
}; |
| 24 |
|
| 25 |
use alloc::vec::Vec; |
| 26 |
|
| 27 |
#[derive(Debug)] |
| 28 |
#[cfg_attr(feature = "std", derive(thiserror::Error))] |
| 29 |
pub enum HpkeError { |
| 30 |
#[cfg_attr(feature = "std", error(transparent))] |
| 31 |
KemError(AnyError), |
| 32 |
#[cfg_attr(feature = "std", error(transparent))] |
| 33 |
KdfError(AnyError), |
| 34 |
#[cfg_attr(feature = "std", error(transparent))] |
| 35 |
AeadError(AnyError), |
| 36 |
/// An invalid PSK was supplied. A PSK MUST have 32 bytes of entropy |
| 37 |
#[cfg_attr(feature = "std", error("PSK must be at least 32 bytes in length"))] |
| 38 |
InsufficientPskLength, |
| 39 |
/// An AEAD nonce of incorrect length was supplied. |
| 40 |
#[cfg_attr( |
| 41 |
feature = "std", |
| 42 |
error("AEAD nonce of length {0} does not match the expected length {1}") |
| 43 |
)] |
| 44 |
IncorrectNonceLen(usize, usize), |
| 45 |
/// An AEAD key of incorrect length was supplied. |
| 46 |
#[cfg_attr( |
| 47 |
feature = "std", |
| 48 |
error("AEAD key of length {0} does not match the expected length {1}") |
| 49 |
)] |
| 50 |
IncorrectKeyLen(usize, usize), |
| 51 |
#[cfg_attr( |
| 52 |
feature = "std", |
| 53 |
error("Encryption API disabled due to export only AeadId") |
| 54 |
)] |
| 55 |
ExportOnlyMode, |
| 56 |
/// Max sequence number exceeded, currently allowed up to MAX u64 |
| 57 |
#[cfg_attr(feature = "std", error("Sequence number overflow"))] |
| 58 |
SequenceNumberOverflow, |
| 59 |
} |
| 60 |
|
| 61 |
impl IntoAnyError for HpkeError { |
| 62 |
#[cfg(feature = "std")] |
| 63 |
fn into_dyn_error(self) -> Result<Box<dyn std::error::Error + Send + Sync>, Self> { |
| 64 |
Ok(self.into()) |
| 65 |
} |
| 66 |
} |
| 67 |
|
| 68 |
#[derive(Clone)] |
| 69 |
pub struct Hpke<KEM: KemType, KDF: KdfType, AEAD: AeadType> { |
| 70 |
pub(crate) kem: KEM, |
| 71 |
pub(crate) kdf: HpkeKdf<KDF>, |
| 72 |
pub(crate) aead: Option<AEAD>, |
| 73 |
kem_kdf: HpkeKdf<KDF>, |
| 74 |
} |
| 75 |
|
| 76 |
#[derive(Debug, Clone, Eq, PartialEq, Default)] |
| 77 |
pub struct Psk<'a> { |
| 78 |
id: &'a [u8], |
| 79 |
value: &'a [u8], |
| 80 |
} |
| 81 |
|
| 82 |
impl<'a> Psk<'a> { |
| 83 |
pub fn new(id: &'a [u8], value: &'a [u8]) -> Self { |
| 84 |
Self { id, value } |
| 85 |
} |
| 86 |
} |
| 87 |
|
| 88 |
impl<KEM, KDF, AEAD> Hpke<KEM, KDF, AEAD> |
| 89 |
where |
| 90 |
KEM: KemType, |
| 91 |
KDF: KdfType + Clone, |
| 92 |
AEAD: AeadType + Clone, |
| 93 |
{ |
| 94 |
pub fn new(kem: KEM, kdf: KDF, aead: Option<AEAD>) -> Self { |
| 95 |
let aead_id = aead |
| 96 |
.as_ref() |
| 97 |
.map(|aead| aead.aead_id()) |
| 98 |
.unwrap_or(AEAD_ID_EXPORT_ONLY); |
| 99 |
|
| 100 |
let suite_id = [ |
| 101 |
b"HPKE", |
| 102 |
&kem.kem_id().to_be_bytes() as &[u8], |
| 103 |
&kdf.kdf_id().to_be_bytes() as &[u8], |
| 104 |
&aead_id.to_be_bytes() as &[u8], |
| 105 |
] |
| 106 |
.concat(); |
| 107 |
|
| 108 |
let kem_suite_id = [b"KEM", &kem.kem_id().to_be_bytes() as &[u8]].concat(); |
| 109 |
|
| 110 |
Self { |
| 111 |
kem, |
| 112 |
aead, |
| 113 |
kdf: HpkeKdf::new(suite_id, kdf.clone()), |
| 114 |
kem_kdf: HpkeKdf::new(kem_suite_id, kdf), |
| 115 |
} |
| 116 |
} |
| 117 |
|
| 118 |
/// Based on RFC 9180 Single-Shot APIs. This function combines the action |
| 119 |
/// of the [setup_sender](Hpke::setup_sender) and then calling [seal](ContextS::seal) |
| 120 |
/// on the resulting [ContextS](self::ContextS). |
| 121 |
#[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)] |
| 122 |
pub async fn seal( |
| 123 |
&self, |
| 124 |
remote_key: &HpkePublicKey, |
| 125 |
info: &[u8], |
| 126 |
psk: Option<Psk<'_>>, |
| 127 |
aad: Option<&[u8]>, |
| 128 |
pt: &[u8], |
| 129 |
) -> Result<HpkeCiphertext, HpkeError> { |
| 130 |
let (kem_output, mut ctx) = self.setup_sender(remote_key, info, psk).await?; |
| 131 |
|
| 132 |
Ok(HpkeCiphertext { |
| 133 |
kem_output, |
| 134 |
ciphertext: ctx.seal(aad, pt).await?, |
| 135 |
}) |
| 136 |
} |
| 137 |
|
| 138 |
/// Based on RFC 9180 Single-Shot APIs. This function combines the action |
| 139 |
/// of the [setup_receiver](Hpke::setup_receiver) and then calling |
| 140 |
/// [open](ContextR::open) on the resulting [ContextR](self::ContextR). |
| 141 |
#[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)] |
| 142 |
pub async fn open( |
| 143 |
&self, |
| 144 |
ciphertext: &HpkeCiphertext, |
| 145 |
local_secret: &HpkeSecretKey, |
| 146 |
local_public: &HpkePublicKey, |
| 147 |
info: &[u8], |
| 148 |
psk: Option<Psk<'_>>, |
| 149 |
aad: Option<&[u8]>, |
| 150 |
) -> Result<Vec<u8>, HpkeError> { |
| 151 |
let mut hpke_ctx = self |
| 152 |
.setup_receiver( |
| 153 |
&ciphertext.kem_output, |
| 154 |
local_secret, |
| 155 |
local_public, |
| 156 |
info, |
| 157 |
psk, |
| 158 |
) |
| 159 |
.await?; |
| 160 |
|
| 161 |
hpke_ctx.open(aad, &ciphertext.ciphertext).await |
| 162 |
} |
| 163 |
|
| 164 |
/// Generate an HPKE context using the base setup mode. This function returns a tuple |
| 165 |
/// containing the `enc` value that can be used as the input to |
| 166 |
/// [setup_receiver](Hpke::setup_receiver), as well as the [ContextS](self::ContextS) |
| 167 |
/// that can be used to generate AEAD ciphertexts. Note that for ECDH based kem |
| 168 |
/// functions, `remote_key` is expected to be in uncompressed public key format. |
| 169 |
#[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)] |
| 170 |
pub async fn setup_sender( |
| 171 |
&self, |
| 172 |
remote_key: &HpkePublicKey, |
| 173 |
info: &[u8], |
| 174 |
psk: Option<Psk<'_>>, |
| 175 |
) -> Result<(Vec<u8>, ContextS<KDF, AEAD>), HpkeError> { |
| 176 |
let mode = self.base_mode(&psk); |
| 177 |
|
| 178 |
let kem_res = self |
| 179 |
.kem |
| 180 |
.encap(remote_key) |
| 181 |
.await |
| 182 |
.map_err(|e| HpkeError::KemError(e.into_any_error()))?; |
| 183 |
|
| 184 |
let ctx = self |
| 185 |
.key_schedule(mode, kem_res.shared_secret(), info, psk) |
| 186 |
.await?; |
| 187 |
|
| 188 |
Ok((kem_res.enc().to_owned(), ContextS(ctx))) |
| 189 |
} |
| 190 |
|
| 191 |
/// Set up an HPKE context by receiving an `enc` value from the output of |
| 192 |
/// [setup_sender](Hpke::setup_sender) as well as your `local_secret` key based on |
| 193 |
/// the KEM type being used. This function returns an HPKE context that can be used for AEAD |
| 194 |
/// decryption. Note that for ECDH based kem functions, `local_secret` |
| 195 |
/// is expected to be in raw byte key format. |
| 196 |
#[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)] |
| 197 |
pub async fn setup_receiver( |
| 198 |
&self, |
| 199 |
enc: &[u8], |
| 200 |
local_secret: &HpkeSecretKey, |
| 201 |
local_public: &HpkePublicKey, |
| 202 |
info: &[u8], |
| 203 |
psk: Option<Psk<'_>>, |
| 204 |
) -> Result<ContextR<KDF, AEAD>, HpkeError> { |
| 205 |
let mode = self.base_mode(&psk); |
| 206 |
|
| 207 |
let shared_secret = self |
| 208 |
.kem |
| 209 |
.decap(enc, local_secret, local_public) |
| 210 |
.await |
| 211 |
.map_err(|e| HpkeError::KemError(e.into_any_error()))?; |
| 212 |
|
| 213 |
self.key_schedule(mode, &shared_secret, info, psk) |
| 214 |
.await |
| 215 |
.map(ContextR) |
| 216 |
} |
| 217 |
|
| 218 |
#[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)] |
| 219 |
pub async fn derive(&self, ikm: &[u8]) -> Result<(HpkeSecretKey, HpkePublicKey), HpkeError> { |
| 220 |
let dkp_prk = self |
| 221 |
.kem_kdf |
| 222 |
.labeled_extract(&[], b"dkp_prk", ikm) |
| 223 |
.await |
| 224 |
.map_err(|e| HpkeError::KdfError(e.into_any_error()))?; |
| 225 |
|
| 226 |
self.kem |
| 227 |
.generate_deterministic(&dkp_prk) |
| 228 |
.await |
| 229 |
.map_err(|e| HpkeError::KemError(e.into_any_error())) |
| 230 |
} |
| 231 |
|
| 232 |
#[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)] |
| 233 |
pub async fn generate(&self) -> Result<(HpkeSecretKey, HpkePublicKey), HpkeError> { |
| 234 |
self.kem |
| 235 |
.generate() |
| 236 |
.await |
| 237 |
.map_err(|e| HpkeError::KemError(e.into_any_error())) |
| 238 |
} |
| 239 |
|
| 240 |
pub fn public_key_validate(&self, key: &HpkePublicKey) -> Result<(), HpkeError> { |
| 241 |
self.kem |
| 242 |
.public_key_validate(key) |
| 243 |
.map_err(|e| HpkeError::KemError(e.into_any_error())) |
| 244 |
} |
| 245 |
|
| 246 |
#[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)] |
| 247 |
async fn key_schedule( |
| 248 |
&self, |
| 249 |
mode: HpkeModeId, |
| 250 |
shared_secret: &[u8], |
| 251 |
info: &[u8], |
| 252 |
psk: Option<Psk<'_>>, |
| 253 |
) -> Result<Context<KDF, AEAD>, HpkeError> { |
| 254 |
self.check_psk(psk.as_ref())?; |
| 255 |
|
| 256 |
let psk = psk.unwrap_or_default(); |
| 257 |
|
| 258 |
let psk_id_hash = self |
| 259 |
.kdf |
| 260 |
.labeled_extract(&[], b"psk_id_hash", psk.id) |
| 261 |
.await |
| 262 |
.map_err(|e| HpkeError::KdfError(e.into_any_error()))?; |
| 263 |
|
| 264 |
let info_hash = self |
| 265 |
.kdf |
| 266 |
.labeled_extract(&[], b"info_hash", info) |
| 267 |
.await |
| 268 |
.map_err(|e| HpkeError::KdfError(e.into_any_error()))?; |
| 269 |
|
| 270 |
let secret = self |
| 271 |
.kdf |
| 272 |
.labeled_extract(shared_secret, b"secret", psk.value) |
| 273 |
.await |
| 274 |
.map(Zeroizing::new) |
| 275 |
.map_err(|e| HpkeError::KdfError(e.into_any_error()))?; |
| 276 |
|
| 277 |
let key_schedule_context = [ |
| 278 |
&(mode as u8).to_be_bytes() as &[u8], |
| 279 |
&psk_id_hash, |
| 280 |
&info_hash, |
| 281 |
] |
| 282 |
.concat(); |
| 283 |
|
| 284 |
let encryption_context = if let Some(aead) = &self.aead { |
| 285 |
let key = self |
| 286 |
.kdf |
| 287 |
.labeled_expand(&secret, b"key", &key_schedule_context, aead.key_size()) |
| 288 |
.await |
| 289 |
.map_err(|e| HpkeError::KdfError(e.into_any_error()))?; |
| 290 |
|
| 291 |
let base_nonce = self |
| 292 |
.kdf |
| 293 |
.labeled_expand( |
| 294 |
&secret, |
| 295 |
b"base_nonce", |
| 296 |
&key_schedule_context, |
| 297 |
aead.nonce_size(), |
| 298 |
) |
| 299 |
.await |
| 300 |
.map_err(|e| HpkeError::KdfError(e.into_any_error()))?; |
| 301 |
|
| 302 |
Some(EncryptionContext::new(base_nonce, aead.clone(), key)?) |
| 303 |
} else { |
| 304 |
None |
| 305 |
}; |
| 306 |
|
| 307 |
let len = self.kdf.extract_size(); |
| 308 |
|
| 309 |
let exporter_secret = self |
| 310 |
.kdf |
| 311 |
.labeled_expand(&secret, b"exp", &key_schedule_context, len) |
| 312 |
.await |
| 313 |
.map_err(|e| HpkeError::KdfError(e.into_any_error()))?; |
| 314 |
|
| 315 |
Ok(Context::new( |
| 316 |
encryption_context, |
| 317 |
exporter_secret, |
| 318 |
self.kdf.clone(), |
| 319 |
)) |
| 320 |
} |
| 321 |
|
| 322 |
fn check_psk(&self, psk: Option<&Psk>) -> Result<(), HpkeError> { |
| 323 |
if let Some(psk) = &psk { |
| 324 |
if psk.value.len() < 32 { |
| 325 |
return Err(HpkeError::InsufficientPskLength); |
| 326 |
} |
| 327 |
} |
| 328 |
|
| 329 |
Ok(()) |
| 330 |
} |
| 331 |
|
| 332 |
#[inline(always)] |
| 333 |
fn base_mode(&self, psk: &Option<Psk>) -> HpkeModeId { |
| 334 |
if psk.is_some() { |
| 335 |
HpkeModeId::Psk |
| 336 |
} else { |
| 337 |
HpkeModeId::Base |
| 338 |
} |
| 339 |
} |
| 340 |
} |