Vendor dimpl 0.7.4 unmodified and patch it in from third_party
str0m's DTLS stack (dimpl) hard-codes the SRTP profile a DTLS server picks (AES-256-GCM first), with no way to configure it. Official TeamSpeak 6 clients use AES_CM_128_HMAC_SHA1_80, so we need to patch dimpl. This commit only vendors the crate as published and routes crates.io's dimpl to it; the change follows separately so it can be reviewed and dropped on its own. third_party is excluded from the workspace so dimpl's dev-dependencies and tests stay out of our builds, and own-crates.sh skips it like crates/proto. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
152 files changed
+56138
-5
No files matched your search
@@ -0,0 +1,458 @@
|
||||
//! Cipher suite implementations using aws-lc-rs.
|
||||
|
||||
use aws_lc_rs::aead::quic::{self as aws_quic, HeaderProtectionKey};
|
||||
use aws_lc_rs::aead::{AES_128_GCM, AES_256_GCM, CHACHA20_POLY1305, UnboundKey};
|
||||
use aws_lc_rs::aead::{Aad as AwsAad, LessSafeKey, Nonce as AwsNonce};
|
||||
use aws_lc_rs::cipher::{self as aws_cipher, AES_128, AES_256, EncryptingKey, UnboundCipherKey};
|
||||
|
||||
use super::super::{Cipher, SupportedDtls12CipherSuite, SupportedDtls13CipherSuite};
|
||||
use crate::buffer::{Buf, TmpBuf};
|
||||
use crate::crypto::{Aad, Nonce};
|
||||
use crate::dtls12::message::Dtls12CipherSuite;
|
||||
use crate::error::bounded_error_len;
|
||||
use crate::types::{Dtls13CipherSuite, HashAlgorithm};
|
||||
use crate::{CryptoError, CryptoOperation};
|
||||
|
||||
/// AES-GCM cipher implementation using aws-lc-rs.
|
||||
struct AesGcm {
|
||||
key: LessSafeKey,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for AesGcm {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("AesGcm").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl AesGcm {
|
||||
fn new(key: &[u8]) -> Result<Self, CryptoError> {
|
||||
let algorithm = match key.len() {
|
||||
16 => &AES_128_GCM,
|
||||
32 => &AES_256_GCM,
|
||||
_ => {
|
||||
return Err(CryptoError::InvalidAesGcmKeySize {
|
||||
actual: bounded_error_len(key.len()),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
let unbound_key = UnboundKey::new(algorithm, key)
|
||||
.map_err(|_| CryptoError::OperationFailed(CryptoOperation::CreateCipher))?;
|
||||
|
||||
Ok(AesGcm {
|
||||
key: LessSafeKey::new(unbound_key),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Cipher for AesGcm {
|
||||
fn encrypt(&mut self, plaintext: &mut Buf, aad: Aad, nonce: Nonce) -> Result<(), CryptoError> {
|
||||
let aws_nonce =
|
||||
AwsNonce::try_assume_unique_for_key(&nonce).map_err(|_| CryptoError::InvalidNonce)?;
|
||||
|
||||
let aws_aad = AwsAad::from(&aad[..]);
|
||||
|
||||
self.key
|
||||
.seal_in_place_append_tag(aws_nonce, aws_aad, plaintext)
|
||||
.map_err(|_| CryptoError::OperationFailed(CryptoOperation::Encrypt))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn decrypt(
|
||||
&mut self,
|
||||
ciphertext: &mut TmpBuf,
|
||||
aad: Aad,
|
||||
nonce: Nonce,
|
||||
) -> Result<(), CryptoError> {
|
||||
if ciphertext.len() < 16 {
|
||||
return Err(CryptoError::CiphertextTooShort {
|
||||
minimum: 16,
|
||||
actual: ciphertext.len() as u8,
|
||||
});
|
||||
}
|
||||
|
||||
let aws_nonce =
|
||||
AwsNonce::try_assume_unique_for_key(&nonce).map_err(|_| CryptoError::InvalidNonce)?;
|
||||
|
||||
let aws_aad = AwsAad::from(&aad[..]);
|
||||
|
||||
let plaintext = self
|
||||
.key
|
||||
.open_in_place(aws_nonce, aws_aad, ciphertext.as_mut())
|
||||
.map_err(|_| CryptoError::OperationFailed(CryptoOperation::Decrypt))?;
|
||||
|
||||
let plaintext_len = plaintext.len();
|
||||
ciphertext.truncate(plaintext_len);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// ChaCha20-Poly1305 cipher implementation using aws-lc-rs.
|
||||
struct ChaCha20Poly1305Cipher {
|
||||
key: LessSafeKey,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ChaCha20Poly1305Cipher {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("ChaCha20Poly1305Cipher")
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl ChaCha20Poly1305Cipher {
|
||||
fn new(key: &[u8]) -> Result<Self, CryptoError> {
|
||||
// The UnboundKey::new call also validates length, but doesnt give us
|
||||
// a reasonable error message. This makes it equivalent to RustCrypto
|
||||
if key.len() != 32 {
|
||||
return Err(CryptoError::InvalidChacha20Poly1305KeySize {
|
||||
actual: bounded_error_len(key.len()),
|
||||
});
|
||||
}
|
||||
let unbound_key = UnboundKey::new(&CHACHA20_POLY1305, key)
|
||||
.map_err(|_| CryptoError::OperationFailed(CryptoOperation::CreateCipher))?;
|
||||
|
||||
Ok(ChaCha20Poly1305Cipher {
|
||||
key: LessSafeKey::new(unbound_key),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Cipher for ChaCha20Poly1305Cipher {
|
||||
fn encrypt(&mut self, plaintext: &mut Buf, aad: Aad, nonce: Nonce) -> Result<(), CryptoError> {
|
||||
let aws_nonce =
|
||||
AwsNonce::try_assume_unique_for_key(&nonce).map_err(|_| CryptoError::InvalidNonce)?;
|
||||
|
||||
let aws_aad = AwsAad::from(&aad[..]);
|
||||
|
||||
self.key
|
||||
.seal_in_place_append_tag(aws_nonce, aws_aad, plaintext)
|
||||
.map_err(|_| CryptoError::OperationFailed(CryptoOperation::Encrypt))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn decrypt(
|
||||
&mut self,
|
||||
ciphertext: &mut TmpBuf,
|
||||
aad: Aad,
|
||||
nonce: Nonce,
|
||||
) -> Result<(), CryptoError> {
|
||||
if ciphertext.len() < 16 {
|
||||
return Err(CryptoError::CiphertextTooShort {
|
||||
minimum: 16,
|
||||
actual: ciphertext.len() as u8,
|
||||
});
|
||||
}
|
||||
|
||||
let aws_nonce =
|
||||
AwsNonce::try_assume_unique_for_key(&nonce).map_err(|_| CryptoError::InvalidNonce)?;
|
||||
|
||||
let aws_aad = AwsAad::from(&aad[..]);
|
||||
|
||||
let plaintext = self
|
||||
.key
|
||||
.open_in_place(aws_nonce, aws_aad, ciphertext.as_mut())
|
||||
.map_err(|_| CryptoError::OperationFailed(CryptoOperation::Decrypt))?;
|
||||
|
||||
let plaintext_len = plaintext.len();
|
||||
ciphertext.truncate(plaintext_len);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 cipher suite.
|
||||
#[derive(Debug)]
|
||||
struct Aes128GcmSha256;
|
||||
|
||||
impl SupportedDtls12CipherSuite for Aes128GcmSha256 {
|
||||
fn suite(&self) -> Dtls12CipherSuite {
|
||||
Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256
|
||||
}
|
||||
|
||||
fn hash_algorithm(&self) -> HashAlgorithm {
|
||||
HashAlgorithm::SHA256
|
||||
}
|
||||
|
||||
fn key_lengths(&self) -> (usize, usize, usize) {
|
||||
(0, 16, 4) // (mac_key_len, enc_key_len, fixed_iv_len)
|
||||
}
|
||||
|
||||
fn explicit_nonce_len(&self) -> usize {
|
||||
8
|
||||
}
|
||||
|
||||
fn tag_len(&self) -> usize {
|
||||
16
|
||||
}
|
||||
|
||||
fn create_cipher(&self, key: &[u8]) -> Result<Box<dyn Cipher>, CryptoError> {
|
||||
Ok(Box::new(AesGcm::new(key)?))
|
||||
}
|
||||
}
|
||||
|
||||
/// TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 cipher suite.
|
||||
#[derive(Debug)]
|
||||
struct Aes256GcmSha384;
|
||||
|
||||
impl SupportedDtls12CipherSuite for Aes256GcmSha384 {
|
||||
fn suite(&self) -> Dtls12CipherSuite {
|
||||
Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384
|
||||
}
|
||||
|
||||
fn hash_algorithm(&self) -> HashAlgorithm {
|
||||
HashAlgorithm::SHA384
|
||||
}
|
||||
|
||||
fn key_lengths(&self) -> (usize, usize, usize) {
|
||||
(0, 32, 4) // (mac_key_len, enc_key_len, fixed_iv_len)
|
||||
}
|
||||
|
||||
fn explicit_nonce_len(&self) -> usize {
|
||||
8
|
||||
}
|
||||
|
||||
fn tag_len(&self) -> usize {
|
||||
16
|
||||
}
|
||||
|
||||
fn create_cipher(&self, key: &[u8]) -> Result<Box<dyn Cipher>, CryptoError> {
|
||||
Ok(Box::new(AesGcm::new(key)?))
|
||||
}
|
||||
}
|
||||
|
||||
/// TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 cipher suite.
|
||||
#[derive(Debug)]
|
||||
struct ChaCha20Poly1305Sha256;
|
||||
|
||||
impl SupportedDtls12CipherSuite for ChaCha20Poly1305Sha256 {
|
||||
fn suite(&self) -> Dtls12CipherSuite {
|
||||
Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256
|
||||
}
|
||||
|
||||
fn hash_algorithm(&self) -> HashAlgorithm {
|
||||
HashAlgorithm::SHA256
|
||||
}
|
||||
|
||||
fn key_lengths(&self) -> (usize, usize, usize) {
|
||||
(0, 32, 12) // (mac_key_len, enc_key_len, fixed_iv_len)
|
||||
}
|
||||
|
||||
fn explicit_nonce_len(&self) -> usize {
|
||||
0
|
||||
}
|
||||
|
||||
fn tag_len(&self) -> usize {
|
||||
16
|
||||
}
|
||||
|
||||
fn create_cipher(&self, key: &[u8]) -> Result<Box<dyn Cipher>, CryptoError> {
|
||||
Ok(Box::new(ChaCha20Poly1305Cipher::new(key)?))
|
||||
}
|
||||
}
|
||||
|
||||
/// TLS_PSK_WITH_AES_128_CCM_8 cipher suite.
|
||||
#[derive(Debug)]
|
||||
struct PskAes128Ccm8;
|
||||
|
||||
impl SupportedDtls12CipherSuite for PskAes128Ccm8 {
|
||||
fn suite(&self) -> Dtls12CipherSuite {
|
||||
Dtls12CipherSuite::PSK_AES128_CCM_8
|
||||
}
|
||||
|
||||
fn hash_algorithm(&self) -> HashAlgorithm {
|
||||
HashAlgorithm::SHA256
|
||||
}
|
||||
|
||||
fn key_lengths(&self) -> (usize, usize, usize) {
|
||||
(0, 16, 4) // (mac_key_len, enc_key_len, fixed_iv_len)
|
||||
}
|
||||
|
||||
fn explicit_nonce_len(&self) -> usize {
|
||||
8
|
||||
}
|
||||
|
||||
fn tag_len(&self) -> usize {
|
||||
8
|
||||
}
|
||||
|
||||
fn create_cipher(&self, key: &[u8]) -> Result<Box<dyn Cipher>, CryptoError> {
|
||||
Ok(Box::new(crate::crypto::ccm_cipher::AesCcm8Cipher::new(
|
||||
key,
|
||||
)?))
|
||||
}
|
||||
}
|
||||
|
||||
/// Static instances of supported DTLS 1.2 cipher suites.
|
||||
static AES_128_GCM_SHA256: Aes128GcmSha256 = Aes128GcmSha256;
|
||||
static AES_256_GCM_SHA384: Aes256GcmSha384 = Aes256GcmSha384;
|
||||
static CHACHA20_POLY1305_SHA256: ChaCha20Poly1305Sha256 = ChaCha20Poly1305Sha256;
|
||||
static PSK_AES_128_CCM_8: PskAes128Ccm8 = PskAes128Ccm8;
|
||||
|
||||
/// All supported DTLS 1.2 cipher suites.
|
||||
pub(super) static ALL_CIPHER_SUITES: &[&dyn SupportedDtls12CipherSuite] = &[
|
||||
&AES_128_GCM_SHA256,
|
||||
&AES_256_GCM_SHA384,
|
||||
&CHACHA20_POLY1305_SHA256,
|
||||
&PSK_AES_128_CCM_8,
|
||||
];
|
||||
|
||||
// ============================================================================
|
||||
// DTLS 1.3 Cipher Suites
|
||||
// ============================================================================
|
||||
|
||||
/// TLS_AES_128_GCM_SHA256 cipher suite (TLS 1.3 / DTLS 1.3).
|
||||
#[derive(Debug)]
|
||||
struct Tls13Aes128GcmSha256;
|
||||
|
||||
impl SupportedDtls13CipherSuite for Tls13Aes128GcmSha256 {
|
||||
fn suite(&self) -> Dtls13CipherSuite {
|
||||
Dtls13CipherSuite::AES_128_GCM_SHA256
|
||||
}
|
||||
|
||||
fn hash_algorithm(&self) -> HashAlgorithm {
|
||||
HashAlgorithm::SHA256
|
||||
}
|
||||
|
||||
fn key_len(&self) -> usize {
|
||||
16 // AES-128
|
||||
}
|
||||
|
||||
fn iv_len(&self) -> usize {
|
||||
12 // GCM IV
|
||||
}
|
||||
|
||||
fn tag_len(&self) -> usize {
|
||||
16 // GCM tag
|
||||
}
|
||||
|
||||
fn create_cipher(&self, key: &[u8]) -> Result<Box<dyn Cipher>, CryptoError> {
|
||||
Ok(Box::new(AesGcm::new(key)?))
|
||||
}
|
||||
|
||||
fn encrypt_sn(&self, sn_key: &[u8], sample: &[u8; 16]) -> [u8; 16] {
|
||||
aes_ecb_encrypt(&AES_128, sn_key, sample)
|
||||
}
|
||||
}
|
||||
|
||||
/// TLS_AES_256_GCM_SHA384 cipher suite (TLS 1.3 / DTLS 1.3).
|
||||
#[derive(Debug)]
|
||||
struct Tls13Aes256GcmSha384;
|
||||
|
||||
impl SupportedDtls13CipherSuite for Tls13Aes256GcmSha384 {
|
||||
fn suite(&self) -> Dtls13CipherSuite {
|
||||
Dtls13CipherSuite::AES_256_GCM_SHA384
|
||||
}
|
||||
|
||||
fn hash_algorithm(&self) -> HashAlgorithm {
|
||||
HashAlgorithm::SHA384
|
||||
}
|
||||
|
||||
fn key_len(&self) -> usize {
|
||||
32 // AES-256
|
||||
}
|
||||
|
||||
fn iv_len(&self) -> usize {
|
||||
12 // GCM IV
|
||||
}
|
||||
|
||||
fn tag_len(&self) -> usize {
|
||||
16 // GCM tag
|
||||
}
|
||||
|
||||
fn create_cipher(&self, key: &[u8]) -> Result<Box<dyn Cipher>, CryptoError> {
|
||||
Ok(Box::new(AesGcm::new(key)?))
|
||||
}
|
||||
|
||||
fn encrypt_sn(&self, sn_key: &[u8], sample: &[u8; 16]) -> [u8; 16] {
|
||||
aes_ecb_encrypt(&AES_256, sn_key, sample)
|
||||
}
|
||||
}
|
||||
|
||||
/// TLS_CHACHA20_POLY1305_SHA256 cipher suite (TLS 1.3 / DTLS 1.3).
|
||||
#[derive(Debug)]
|
||||
struct Tls13ChaCha20Poly1305Sha256;
|
||||
|
||||
impl SupportedDtls13CipherSuite for Tls13ChaCha20Poly1305Sha256 {
|
||||
fn suite(&self) -> Dtls13CipherSuite {
|
||||
Dtls13CipherSuite::CHACHA20_POLY1305_SHA256
|
||||
}
|
||||
|
||||
fn hash_algorithm(&self) -> HashAlgorithm {
|
||||
HashAlgorithm::SHA256
|
||||
}
|
||||
|
||||
fn key_len(&self) -> usize {
|
||||
32 // ChaCha20 key
|
||||
}
|
||||
|
||||
fn iv_len(&self) -> usize {
|
||||
12 // Poly1305 nonce
|
||||
}
|
||||
|
||||
fn tag_len(&self) -> usize {
|
||||
16 // Poly1305 tag
|
||||
}
|
||||
|
||||
fn create_cipher(&self, key: &[u8]) -> Result<Box<dyn Cipher>, CryptoError> {
|
||||
Ok(Box::new(ChaCha20Poly1305Cipher::new(key)?))
|
||||
}
|
||||
|
||||
fn encrypt_sn(&self, sn_key: &[u8], sample: &[u8; 16]) -> [u8; 16] {
|
||||
// RFC 9001 Section 5.4.4: ChaCha20 header protection
|
||||
// counter = sample[0..4] (LE), nonce = sample[4..16]
|
||||
// mask = ChaCha20(sn_key, counter, nonce, <5 zero bytes>)
|
||||
// unwrap: sn_key length is validated by caller (32 bytes for ChaCha20)
|
||||
let hp_key = HeaderProtectionKey::new(&aws_quic::CHACHA20, sn_key).unwrap();
|
||||
// unwrap: sample is exactly 16 bytes as required
|
||||
let mask = hp_key.new_mask(sample).unwrap();
|
||||
let mut out = [0u8; 16];
|
||||
out[..5].copy_from_slice(&mask);
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// Static instances of supported DTLS 1.3 cipher suites.
|
||||
static TLS13_AES_128_GCM_SHA256: Tls13Aes128GcmSha256 = Tls13Aes128GcmSha256;
|
||||
static TLS13_AES_256_GCM_SHA384: Tls13Aes256GcmSha384 = Tls13Aes256GcmSha384;
|
||||
static TLS13_CHACHA20_POLY1305_SHA256: Tls13ChaCha20Poly1305Sha256 = Tls13ChaCha20Poly1305Sha256;
|
||||
|
||||
/// All supported DTLS 1.3 cipher suites.
|
||||
pub(super) static ALL_DTLS13_CIPHER_SUITES: &[&dyn SupportedDtls13CipherSuite] = &[
|
||||
&TLS13_AES_128_GCM_SHA256,
|
||||
&TLS13_AES_256_GCM_SHA384,
|
||||
&TLS13_CHACHA20_POLY1305_SHA256,
|
||||
];
|
||||
|
||||
/// AES-ECB single block encryption for record number protection.
|
||||
fn aes_ecb_encrypt(
|
||||
algorithm: &'static aws_cipher::Algorithm,
|
||||
key: &[u8],
|
||||
input: &[u8; 16],
|
||||
) -> [u8; 16] {
|
||||
// unwrap: key length is validated by caller (matches algorithm)
|
||||
let unbound = UnboundCipherKey::new(algorithm, key).unwrap();
|
||||
// unwrap: ECB key construction cannot fail for valid AES keys
|
||||
let ecb_key = EncryptingKey::ecb(unbound).unwrap();
|
||||
let mut block = *input;
|
||||
// unwrap: 16-byte input is exactly one AES block
|
||||
ecb_key.encrypt(&mut block).unwrap();
|
||||
block
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn chacha20_poly1305_key_len_validation() {
|
||||
// incorrect length (should be 32)
|
||||
let result = ChaCha20Poly1305Cipher::new(&[0, 1, 2, 3, 4, 5]);
|
||||
assert_eq!(
|
||||
CryptoError::InvalidChacha20Poly1305KeySize { actual: 6 },
|
||||
result.unwrap_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
//! Hash implementations using aws-lc-rs.
|
||||
|
||||
use aws_lc_rs::digest::{Context, SHA256, SHA384};
|
||||
|
||||
use super::super::{HashContext, HashProvider};
|
||||
use crate::buffer::Buf;
|
||||
use crate::types::HashAlgorithm;
|
||||
|
||||
/// Hash context implementation using aws-lc-rs.
|
||||
struct AwsLcHashContext {
|
||||
context: Context,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for AwsLcHashContext {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("AwsLcHashContext").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl HashContext for AwsLcHashContext {
|
||||
fn update(&mut self, data: &[u8]) {
|
||||
self.context.update(data);
|
||||
}
|
||||
|
||||
fn clone_and_finalize(&self, out: &mut Buf) {
|
||||
let digest = self.context.clone().finish();
|
||||
out.clear();
|
||||
out.extend_from_slice(digest.as_ref());
|
||||
}
|
||||
}
|
||||
|
||||
/// Hash provider implementation.
|
||||
#[derive(Debug)]
|
||||
pub(super) struct AwsLcHashProvider;
|
||||
|
||||
impl HashProvider for AwsLcHashProvider {
|
||||
fn create_hash(&self, algorithm: HashAlgorithm) -> Box<dyn HashContext> {
|
||||
let context = match algorithm {
|
||||
HashAlgorithm::SHA256 => Context::new(&SHA256),
|
||||
HashAlgorithm::SHA384 => Context::new(&SHA384),
|
||||
_ => panic!("Unsupported hash algorithm: {:?}", algorithm),
|
||||
};
|
||||
Box::new(AwsLcHashContext { context })
|
||||
}
|
||||
}
|
||||
|
||||
/// Static instance of the hash provider.
|
||||
pub(super) static HASH_PROVIDER: AwsLcHashProvider = AwsLcHashProvider;
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
//! HMAC implementation using aws-lc-rs.
|
||||
|
||||
use aws_lc_rs::hmac;
|
||||
|
||||
use super::super::HmacProvider;
|
||||
use crate::CryptoError;
|
||||
use crate::types::HashAlgorithm;
|
||||
|
||||
/// Get HMAC algorithm from hash algorithm.
|
||||
fn hmac_algorithm(hash: HashAlgorithm) -> Result<hmac::Algorithm, CryptoError> {
|
||||
match hash {
|
||||
HashAlgorithm::SHA256 => Ok(hmac::HMAC_SHA256),
|
||||
HashAlgorithm::SHA384 => Ok(hmac::HMAC_SHA384),
|
||||
_ => Err(CryptoError::UnsupportedHmacHash(hash)),
|
||||
}
|
||||
}
|
||||
|
||||
/// HMAC provider implementation.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct AwsLcHmacProvider;
|
||||
|
||||
impl HmacProvider for AwsLcHmacProvider {
|
||||
fn hmac(
|
||||
&self,
|
||||
hash: HashAlgorithm,
|
||||
key: &[u8],
|
||||
data: &[u8],
|
||||
out: &mut [u8],
|
||||
) -> Result<usize, CryptoError> {
|
||||
let algorithm = hmac_algorithm(hash)?;
|
||||
let hmac_key = hmac::Key::new(algorithm, key);
|
||||
let tag = hmac::sign(&hmac_key, data);
|
||||
let len = tag.as_ref().len();
|
||||
out[..len].copy_from_slice(tag.as_ref());
|
||||
Ok(len)
|
||||
}
|
||||
}
|
||||
|
||||
/// Static instance of the HMAC provider.
|
||||
pub(crate) static HMAC_PROVIDER: AwsLcHmacProvider = AwsLcHmacProvider;
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
//! Key exchange group implementations using aws-lc-rs.
|
||||
|
||||
use aws_lc_rs::agreement::{ECDH_P256, ECDH_P384, UnparsedPublicKey, X25519};
|
||||
use aws_lc_rs::agreement::{EphemeralPrivateKey, agree_ephemeral};
|
||||
|
||||
use super::super::{ActiveKeyExchange, SupportedKxGroup};
|
||||
use crate::buffer::Buf;
|
||||
use crate::types::NamedGroup;
|
||||
use crate::{CryptoError, CryptoOperation};
|
||||
|
||||
/// ECDHE key exchange implementation.
|
||||
struct EcdhKeyExchange {
|
||||
group: NamedGroup,
|
||||
private_key: EphemeralPrivateKey,
|
||||
public_key: Buf,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for EcdhKeyExchange {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("EcdhKeyExchange")
|
||||
.field("group", &self.group)
|
||||
.field("public_key_len", &self.public_key.len())
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl EcdhKeyExchange {
|
||||
fn new(group: NamedGroup, mut buf: Buf) -> Result<Self, CryptoError> {
|
||||
let algorithm = match group {
|
||||
NamedGroup::X25519 => &X25519,
|
||||
NamedGroup::Secp256r1 => &ECDH_P256,
|
||||
NamedGroup::Secp384r1 => &ECDH_P384,
|
||||
_ => return Err(CryptoError::UnsupportedKeyExchangeGroup(group)),
|
||||
};
|
||||
|
||||
let rng = aws_lc_rs::rand::SystemRandom::new();
|
||||
let private_key = EphemeralPrivateKey::generate(algorithm, &rng)
|
||||
.map_err(|_| CryptoError::OperationFailed(CryptoOperation::GenerateEphemeralKey))?;
|
||||
|
||||
let pk = private_key
|
||||
.compute_public_key()
|
||||
.map_err(|_| CryptoError::OperationFailed(CryptoOperation::ComputePublicKey))?;
|
||||
|
||||
buf.clear();
|
||||
buf.extend_from_slice(pk.as_ref());
|
||||
|
||||
Ok(EcdhKeyExchange {
|
||||
group,
|
||||
private_key,
|
||||
public_key: buf,
|
||||
})
|
||||
}
|
||||
|
||||
fn algorithm(&self) -> &'static aws_lc_rs::agreement::Algorithm {
|
||||
match self.group {
|
||||
NamedGroup::X25519 => &X25519,
|
||||
NamedGroup::Secp256r1 => &ECDH_P256,
|
||||
NamedGroup::Secp384r1 => &ECDH_P384,
|
||||
_ => unreachable!("Unsupported group"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ActiveKeyExchange for EcdhKeyExchange {
|
||||
fn pub_key(&self) -> &[u8] {
|
||||
&self.public_key
|
||||
}
|
||||
|
||||
fn complete(self: Box<Self>, peer_pub: &[u8], out: &mut Buf) -> Result<(), CryptoError> {
|
||||
let algorithm = self.algorithm();
|
||||
let peer_key = UnparsedPublicKey::new(algorithm, peer_pub);
|
||||
|
||||
// RFC 7748 §6.1: agree_ephemeral rejects non-contributory shared secrets internally
|
||||
agree_ephemeral(
|
||||
self.private_key,
|
||||
peer_key,
|
||||
"ECDH agreement failed",
|
||||
|secret| {
|
||||
out.clear();
|
||||
out.extend_from_slice(secret);
|
||||
Ok(())
|
||||
},
|
||||
)
|
||||
.map_err(|_| CryptoError::InvalidPublicKey(self.group))
|
||||
}
|
||||
|
||||
fn group(&self) -> NamedGroup {
|
||||
self.group
|
||||
}
|
||||
}
|
||||
|
||||
/// X25519 key exchange group.
|
||||
#[derive(Debug)]
|
||||
struct X25519Kx;
|
||||
|
||||
impl SupportedKxGroup for X25519Kx {
|
||||
fn name(&self) -> NamedGroup {
|
||||
NamedGroup::X25519
|
||||
}
|
||||
|
||||
fn start_exchange(&self, buf: Buf) -> Result<Box<dyn ActiveKeyExchange>, CryptoError> {
|
||||
Ok(Box::new(EcdhKeyExchange::new(NamedGroup::X25519, buf)?))
|
||||
}
|
||||
}
|
||||
|
||||
/// P-256 (secp256r1) key exchange group.
|
||||
#[derive(Debug)]
|
||||
struct P256;
|
||||
|
||||
impl SupportedKxGroup for P256 {
|
||||
fn name(&self) -> NamedGroup {
|
||||
NamedGroup::Secp256r1
|
||||
}
|
||||
|
||||
fn start_exchange(&self, buf: Buf) -> Result<Box<dyn ActiveKeyExchange>, CryptoError> {
|
||||
Ok(Box::new(EcdhKeyExchange::new(NamedGroup::Secp256r1, buf)?))
|
||||
}
|
||||
}
|
||||
|
||||
/// P-384 (secp384r1) key exchange group.
|
||||
#[derive(Debug)]
|
||||
struct P384;
|
||||
|
||||
impl SupportedKxGroup for P384 {
|
||||
fn name(&self) -> NamedGroup {
|
||||
NamedGroup::Secp384r1
|
||||
}
|
||||
|
||||
fn start_exchange(&self, buf: Buf) -> Result<Box<dyn ActiveKeyExchange>, CryptoError> {
|
||||
Ok(Box::new(EcdhKeyExchange::new(NamedGroup::Secp384r1, buf)?))
|
||||
}
|
||||
}
|
||||
|
||||
/// Static instances of supported key exchange groups.
|
||||
static KX_GROUP_X25519: X25519Kx = X25519Kx;
|
||||
static KX_GROUP_P256: P256 = P256;
|
||||
static KX_GROUP_P384: P384 = P384;
|
||||
|
||||
/// All supported key exchange groups.
|
||||
pub(super) static ALL_KX_GROUPS: &[&dyn SupportedKxGroup] =
|
||||
&[&KX_GROUP_X25519, &KX_GROUP_P256, &KX_GROUP_P384];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn x25519_non_contributory_peer_key_returns_invalid_public_key() {
|
||||
let exchange = X25519Kx
|
||||
.start_exchange(Buf::new())
|
||||
.expect("start key exchange");
|
||||
let mut out = Buf::new();
|
||||
|
||||
assert_eq!(
|
||||
exchange.complete(&[0; 32], &mut out),
|
||||
Err(CryptoError::InvalidPublicKey(NamedGroup::X25519))
|
||||
);
|
||||
}
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
//! AWS-LC-RS cryptographic provider implementation for dimpl.
|
||||
//!
|
||||
//! This module provides the default cryptographic backend for dimpl using
|
||||
//! [aws-lc-rs](https://github.com/aws/aws-lc-rs), Amazon's cryptographic library
|
||||
//! based on AWS-LC (a fork of BoringSSL).
|
||||
//!
|
||||
//! # Feature Flag
|
||||
//!
|
||||
//! This module is only available when the `aws-lc-rs` feature is enabled. The `aws-lc-rs`
|
||||
//! feature is included in the default features, so it's enabled by default. To use
|
||||
//! dimpl without this module, disable default features:
|
||||
//!
|
||||
//! ```toml
|
||||
//! dimpl = { version = "...", default-features = false }
|
||||
//! ```
|
||||
//!
|
||||
//! # Usage
|
||||
//!
|
||||
//! The default provider is used automatically when no custom provider is specified:
|
||||
//!
|
||||
//! ```
|
||||
//! # #[cfg(feature = "rcgen")]
|
||||
//! # fn main() {
|
||||
//! use std::sync::Arc;
|
||||
//! use std::time::Instant;
|
||||
//! use dimpl::{Config, Dtls, certificate};
|
||||
//!
|
||||
//! let cert = certificate::generate_self_signed_certificate().unwrap();
|
||||
//! // Implicitly uses aws-lc-rs default provider
|
||||
//! let config = Arc::new(Config::default());
|
||||
//! let dtls = Dtls::new_12(config, cert, Instant::now());
|
||||
//! # }
|
||||
//! # #[cfg(not(feature = "rcgen"))]
|
||||
//! # fn main() {}
|
||||
//! ```
|
||||
//!
|
||||
//! Or explicitly:
|
||||
//!
|
||||
//! ```
|
||||
//! # #[cfg(feature = "rcgen")]
|
||||
//! # fn main() {
|
||||
//! use std::sync::Arc;
|
||||
//! use std::time::Instant;
|
||||
//! use dimpl::{Config, Dtls, certificate};
|
||||
//! use dimpl::crypto::aws_lc_rs;
|
||||
//!
|
||||
//! let cert = certificate::generate_self_signed_certificate().unwrap();
|
||||
//! let config = Arc::new(
|
||||
//! Config::builder()
|
||||
//! .with_crypto_provider(aws_lc_rs::default_provider())
|
||||
//! .build()
|
||||
//! .unwrap()
|
||||
//! );
|
||||
//! let dtls = Dtls::new_12(config, cert, Instant::now());
|
||||
//! # }
|
||||
//! # #[cfg(not(feature = "rcgen"))]
|
||||
//! # fn main() {}
|
||||
//! ```
|
||||
|
||||
mod cipher_suite;
|
||||
mod hash;
|
||||
pub(crate) mod hmac;
|
||||
mod kx_group;
|
||||
mod random;
|
||||
mod sign;
|
||||
|
||||
use super::CryptoProvider;
|
||||
|
||||
/// Get the default aws-lc-rs based crypto provider.
|
||||
///
|
||||
/// This provider implements all cryptographic operations required for DTLS 1.2
|
||||
/// using the aws-lc-rs library (AWS's cryptographic library based on BoringSSL/AWS-LC).
|
||||
///
|
||||
/// # Supported Cipher Suites
|
||||
///
|
||||
/// - `TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256` (0xC02B)
|
||||
/// - `TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384` (0xC02C)
|
||||
/// - `TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256` (0xCCA9)
|
||||
///
|
||||
/// # Supported Key Exchange Groups
|
||||
///
|
||||
/// - `x25519` (X25519 / Curve25519)
|
||||
/// - `secp256r1` (P-256, NIST Curve)
|
||||
/// - `secp384r1` (P-384, NIST Curve)
|
||||
///
|
||||
/// # Supported Signature Algorithms
|
||||
///
|
||||
/// - ECDSA with P-256 and SHA-256
|
||||
/// - ECDSA with P-384 and SHA-384
|
||||
///
|
||||
/// # Supported Hash Algorithms
|
||||
///
|
||||
/// - SHA-256
|
||||
/// - SHA-384
|
||||
///
|
||||
/// # Key Formats
|
||||
///
|
||||
/// The key provider supports loading private keys in:
|
||||
/// - PKCS#8 DER format (most common)
|
||||
/// - SEC1 DER format (OpenSSL EC private key format)
|
||||
/// - PEM encoded versions of the above
|
||||
///
|
||||
/// # Random Number Generation
|
||||
///
|
||||
/// Uses `SystemRandom` from aws-lc-rs for cryptographically secure random number generation.
|
||||
pub fn default_provider() -> CryptoProvider {
|
||||
CryptoProvider {
|
||||
// Shared components
|
||||
kx_groups: kx_group::ALL_KX_GROUPS,
|
||||
signature_verification: &sign::SIGNATURE_VERIFIER,
|
||||
key_provider: &sign::KEY_PROVIDER,
|
||||
secure_random: &random::SECURE_RANDOM,
|
||||
hash_provider: &hash::HASH_PROVIDER,
|
||||
hmac_provider: &hmac::HMAC_PROVIDER,
|
||||
// DTLS 1.2 components
|
||||
cipher_suites: cipher_suite::ALL_CIPHER_SUITES,
|
||||
// DTLS 1.3 components
|
||||
dtls13_cipher_suites: cipher_suite::ALL_DTLS13_CIPHER_SUITES,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
//! Secure random number generation using aws-lc-rs.
|
||||
|
||||
use super::super::SecureRandom;
|
||||
use crate::{CryptoError, CryptoOperation};
|
||||
|
||||
/// Secure random number generator implementation.
|
||||
#[derive(Debug)]
|
||||
pub(super) struct AwsLcSecureRandom;
|
||||
|
||||
impl SecureRandom for AwsLcSecureRandom {
|
||||
fn fill(&self, buf: &mut [u8]) -> Result<(), CryptoError> {
|
||||
use aws_lc_rs::rand::SecureRandom as _;
|
||||
let rng = aws_lc_rs::rand::SystemRandom::new();
|
||||
rng.fill(buf)
|
||||
.map_err(|_| CryptoError::OperationFailed(CryptoOperation::FillRandom))
|
||||
}
|
||||
}
|
||||
|
||||
/// Static instance of the secure random generator.
|
||||
pub(super) static SECURE_RANDOM: AwsLcSecureRandom = AwsLcSecureRandom;
|
||||
+295
@@ -0,0 +1,295 @@
|
||||
//! Signing and key loading implementations using aws-lc-rs.
|
||||
|
||||
use std::str;
|
||||
|
||||
use aws_lc_rs::signature::ECDSA_P384_SHA384_ASN1_SIGNING;
|
||||
use aws_lc_rs::signature::{ECDSA_P256_SHA256_ASN1, ECDSA_P256_SHA384_ASN1};
|
||||
use aws_lc_rs::signature::{ECDSA_P256_SHA256_ASN1_SIGNING, UnparsedPublicKey};
|
||||
use aws_lc_rs::signature::{ECDSA_P384_SHA256_ASN1, ECDSA_P384_SHA384_ASN1};
|
||||
use aws_lc_rs::signature::{EcdsaKeyPair, EcdsaSigningAlgorithm, EcdsaVerificationAlgorithm};
|
||||
use der::{Decode, Encode};
|
||||
use spki::ObjectIdentifier;
|
||||
use x509_cert::Certificate as X509Certificate;
|
||||
|
||||
use super::super::{KeyProvider, SignatureVerifier, SigningKey, check_verify_scheme};
|
||||
use super::super::{OID_P256, OID_P384};
|
||||
use crate::buffer::Buf;
|
||||
use crate::types::{HashAlgorithm, NamedGroup, SignatureAlgorithm};
|
||||
use crate::{CryptoError, CryptoOperation};
|
||||
|
||||
/// ECDSA signing key implementation.
|
||||
struct EcdsaSigningKey {
|
||||
key_pair: EcdsaKeyPair,
|
||||
signing_algorithm: &'static EcdsaSigningAlgorithm,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for EcdsaSigningKey {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("EcdsaSigningKey")
|
||||
.field("signing_algorithm", &self.signing_algorithm)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl SigningKey for EcdsaSigningKey {
|
||||
fn sign(
|
||||
&mut self,
|
||||
data: &[u8],
|
||||
hash_alg: HashAlgorithm,
|
||||
buf: &mut Buf,
|
||||
) -> Result<(), CryptoError> {
|
||||
let key_hash = self.hash_algorithm();
|
||||
if hash_alg != key_hash {
|
||||
return Err(CryptoError::SigningKeyHashMismatch {
|
||||
key_hash,
|
||||
requested: hash_alg,
|
||||
});
|
||||
}
|
||||
let rng = aws_lc_rs::rand::SystemRandom::new();
|
||||
let signature = self
|
||||
.key_pair
|
||||
.sign(&rng, data)
|
||||
.map_err(|_| CryptoError::OperationFailed(CryptoOperation::Sign))?;
|
||||
buf.clear();
|
||||
buf.extend_from_slice(signature.as_ref());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn algorithm(&self) -> SignatureAlgorithm {
|
||||
SignatureAlgorithm::ECDSA
|
||||
}
|
||||
|
||||
fn hash_algorithm(&self) -> HashAlgorithm {
|
||||
if self.signing_algorithm == &ECDSA_P256_SHA256_ASN1_SIGNING {
|
||||
HashAlgorithm::SHA256
|
||||
} else if self.signing_algorithm == &ECDSA_P384_SHA384_ASN1_SIGNING {
|
||||
HashAlgorithm::SHA384
|
||||
} else {
|
||||
panic!("Unsupported signing algorithm")
|
||||
}
|
||||
}
|
||||
|
||||
fn supported_hash_algorithms(&self) -> &[HashAlgorithm] {
|
||||
// aws-lc-rs locks the hash at key-load time; only one is supported.
|
||||
if self.signing_algorithm == &ECDSA_P256_SHA256_ASN1_SIGNING {
|
||||
&[HashAlgorithm::SHA256]
|
||||
} else if self.signing_algorithm == &ECDSA_P384_SHA384_ASN1_SIGNING {
|
||||
&[HashAlgorithm::SHA384]
|
||||
} else {
|
||||
panic!("Unsupported signing algorithm")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Key provider implementation.
|
||||
#[derive(Debug)]
|
||||
pub(super) struct AwsLcKeyProvider;
|
||||
|
||||
impl KeyProvider for AwsLcKeyProvider {
|
||||
fn load_private_key(&self, key_der: &[u8]) -> Result<Box<dyn SigningKey>, CryptoError> {
|
||||
// Try PKCS#8 DER format first (most common)
|
||||
if let Ok(key_pair) = EcdsaKeyPair::from_pkcs8(&ECDSA_P256_SHA256_ASN1_SIGNING, key_der) {
|
||||
return Ok(Box::new(EcdsaSigningKey {
|
||||
key_pair,
|
||||
signing_algorithm: &ECDSA_P256_SHA256_ASN1_SIGNING,
|
||||
}));
|
||||
}
|
||||
if let Ok(key_pair) = EcdsaKeyPair::from_pkcs8(&ECDSA_P384_SHA384_ASN1_SIGNING, key_der) {
|
||||
return Ok(Box::new(EcdsaSigningKey {
|
||||
key_pair,
|
||||
signing_algorithm: &ECDSA_P384_SHA384_ASN1_SIGNING,
|
||||
}));
|
||||
}
|
||||
|
||||
// Try parsing as SEC1 DER format (OpenSSL EC private key format)
|
||||
if let Ok(ec_key) = sec1::EcPrivateKey::try_from(key_der) {
|
||||
let private_key_len = ec_key.private_key.len();
|
||||
|
||||
let curve_oid = if let Some(params) = &ec_key.parameters {
|
||||
match params {
|
||||
sec1::EcParameters::NamedCurve(oid) => Some(*oid),
|
||||
}
|
||||
} else if private_key_len == 32 {
|
||||
Some(ObjectIdentifier::new_unwrap("1.2.840.10045.3.1.7")) // P-256
|
||||
} else if private_key_len == 48 {
|
||||
Some(ObjectIdentifier::new_unwrap("1.3.132.0.34")) // P-384
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if let Some(curve_oid) = curve_oid {
|
||||
let ec_alg_oid = ObjectIdentifier::new_unwrap("1.2.840.10045.2.1");
|
||||
let curve_params_der = curve_oid
|
||||
.to_der()
|
||||
.map_err(|_| CryptoError::OperationFailed(CryptoOperation::EncodeKey))?;
|
||||
let curve_params_any = der::asn1::AnyRef::try_from(curve_params_der.as_slice())
|
||||
.map_err(|_| CryptoError::OperationFailed(CryptoOperation::EncodeKey))?;
|
||||
|
||||
let algorithm = spki::AlgorithmIdentifierRef {
|
||||
oid: ec_alg_oid,
|
||||
parameters: Some(curve_params_any),
|
||||
};
|
||||
|
||||
let pkcs8 = pkcs8::PrivateKeyInfo {
|
||||
algorithm,
|
||||
private_key: key_der,
|
||||
public_key: None,
|
||||
};
|
||||
|
||||
let pkcs8_der = pkcs8
|
||||
.to_der()
|
||||
.map_err(|_| CryptoError::OperationFailed(CryptoOperation::EncodeKey))?;
|
||||
|
||||
let p256_curve = ObjectIdentifier::new_unwrap("1.2.840.10045.3.1.7");
|
||||
if curve_oid == p256_curve {
|
||||
if let Ok(key_pair) =
|
||||
EcdsaKeyPair::from_pkcs8(&ECDSA_P256_SHA256_ASN1_SIGNING, &pkcs8_der)
|
||||
{
|
||||
return Ok(Box::new(EcdsaSigningKey {
|
||||
key_pair,
|
||||
signing_algorithm: &ECDSA_P256_SHA256_ASN1_SIGNING,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
let p384_curve = ObjectIdentifier::new_unwrap("1.3.132.0.34");
|
||||
if curve_oid == p384_curve {
|
||||
if let Ok(key_pair) =
|
||||
EcdsaKeyPair::from_pkcs8(&ECDSA_P384_SHA384_ASN1_SIGNING, &pkcs8_der)
|
||||
{
|
||||
return Ok(Box::new(EcdsaSigningKey {
|
||||
key_pair,
|
||||
signing_algorithm: &ECDSA_P384_SHA384_ASN1_SIGNING,
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check if it's a PEM encoded key
|
||||
if let Ok(pem_str) = str::from_utf8(key_der) {
|
||||
if pem_str.contains("-----BEGIN") {
|
||||
if let Ok((_label, doc)) = pkcs8::Document::from_pem(pem_str) {
|
||||
return self.load_private_key(doc.as_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Err(CryptoError::InvalidPrivateKey)
|
||||
}
|
||||
}
|
||||
|
||||
/// Signature verifier implementation.
|
||||
#[derive(Debug)]
|
||||
pub(super) struct AwsLcSignatureVerifier;
|
||||
|
||||
impl SignatureVerifier for AwsLcSignatureVerifier {
|
||||
fn verify_signature(
|
||||
&self,
|
||||
cert_der: &[u8],
|
||||
data: &[u8],
|
||||
signature: &[u8],
|
||||
hash_alg: HashAlgorithm,
|
||||
sig_alg: SignatureAlgorithm,
|
||||
) -> Result<(), CryptoError> {
|
||||
if sig_alg != SignatureAlgorithm::ECDSA {
|
||||
return Err(CryptoError::UnsupportedSignatureAlgorithm(sig_alg));
|
||||
}
|
||||
|
||||
let cert =
|
||||
X509Certificate::from_der(cert_der).map_err(|_| CryptoError::CertificateParseFailed)?;
|
||||
let spki = &cert.tbs_certificate.subject_public_key_info;
|
||||
|
||||
const OID_EC_PUBLIC_KEY: ObjectIdentifier =
|
||||
ObjectIdentifier::new_unwrap("1.2.840.10045.2.1");
|
||||
|
||||
if spki.algorithm.oid != OID_EC_PUBLIC_KEY {
|
||||
return Err(CryptoError::UnsupportedPublicKeyAlgorithm);
|
||||
}
|
||||
|
||||
let pubkey_bytes = spki
|
||||
.subject_public_key
|
||||
.as_bytes()
|
||||
.ok_or(CryptoError::InvalidSubjectPublicKey)?;
|
||||
|
||||
let curve_oid: ObjectIdentifier = spki
|
||||
.algorithm
|
||||
.parameters
|
||||
.as_ref()
|
||||
.ok_or(CryptoError::MissingEcCurveParameter)?
|
||||
.decode_as()
|
||||
.map_err(|_| CryptoError::InvalidEcCurveParameter)?;
|
||||
|
||||
let group = match curve_oid {
|
||||
OID_P256 => NamedGroup::Secp256r1,
|
||||
OID_P384 => NamedGroup::Secp384r1,
|
||||
_ => return Err(CryptoError::UnsupportedEcCurve),
|
||||
};
|
||||
|
||||
check_verify_scheme(sig_alg, hash_alg, group)?;
|
||||
|
||||
let algorithm: &EcdsaVerificationAlgorithm = match (group, hash_alg) {
|
||||
(NamedGroup::Secp256r1, HashAlgorithm::SHA256) => &ECDSA_P256_SHA256_ASN1,
|
||||
(NamedGroup::Secp256r1, HashAlgorithm::SHA384) => &ECDSA_P256_SHA384_ASN1,
|
||||
(NamedGroup::Secp384r1, HashAlgorithm::SHA256) => &ECDSA_P384_SHA256_ASN1,
|
||||
(NamedGroup::Secp384r1, HashAlgorithm::SHA384) => &ECDSA_P384_SHA384_ASN1,
|
||||
// unreachable: check_verify_scheme already validated
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
let public_key = UnparsedPublicKey::new(algorithm, pubkey_bytes);
|
||||
public_key
|
||||
.verify(data, signature)
|
||||
.map_err(|_| CryptoError::SignatureVerificationFailed {
|
||||
signature: sig_alg,
|
||||
hash: hash_alg,
|
||||
group,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Static instance of the key provider.
|
||||
pub(super) static KEY_PROVIDER: AwsLcKeyProvider = AwsLcKeyProvider;
|
||||
|
||||
/// Static instance of the signature verifier.
|
||||
pub(super) static SIGNATURE_VERIFIER: AwsLcSignatureVerifier = AwsLcSignatureVerifier;
|
||||
|
||||
#[cfg(all(test, feature = "rcgen"))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::certificate::generate_self_signed_certificate;
|
||||
|
||||
#[test]
|
||||
fn invalid_signature_returns_structured_verification_error() {
|
||||
let cert = generate_self_signed_certificate().expect("generate cert");
|
||||
let mut key = KEY_PROVIDER
|
||||
.load_private_key(&cert.private_key)
|
||||
.expect("load private key");
|
||||
let data = b"signed data";
|
||||
let mut signature = Buf::new();
|
||||
key.sign(data, HashAlgorithm::SHA256, &mut signature)
|
||||
.expect("sign data");
|
||||
|
||||
let last = signature.len() - 1;
|
||||
signature[last] ^= 0x01;
|
||||
|
||||
let err = SIGNATURE_VERIFIER
|
||||
.verify_signature(
|
||||
&cert.certificate,
|
||||
data,
|
||||
&signature,
|
||||
HashAlgorithm::SHA256,
|
||||
SignatureAlgorithm::ECDSA,
|
||||
)
|
||||
.expect_err("corrupt signature should fail");
|
||||
|
||||
assert_eq!(
|
||||
err,
|
||||
CryptoError::SignatureVerificationFailed {
|
||||
signature: SignatureAlgorithm::ECDSA,
|
||||
hash: HashAlgorithm::SHA256,
|
||||
group: NamedGroup::Secp256r1,
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
//! AES-128-CCM-8 cipher implementation using the RustCrypto `ccm` crate.
|
||||
//!
|
||||
//! Shared by both aws-lc-rs and rust-crypto backends since aws-lc-rs
|
||||
//! does not expose CCM in its high-level API.
|
||||
|
||||
use ccm::aead::AeadInPlace;
|
||||
use ccm::aead::KeyInit;
|
||||
use ccm::consts::{U8, U12};
|
||||
|
||||
use super::{Aad, Cipher, Nonce};
|
||||
use crate::buffer::{Buf, TmpBuf};
|
||||
use crate::error::bounded_error_len;
|
||||
use crate::{CryptoError, CryptoOperation};
|
||||
|
||||
/// AES-128-CCM with 8-byte tag, 12-byte nonce.
|
||||
type Aes128Ccm8 = ccm::Ccm<aes::Aes128, U8, U12>;
|
||||
|
||||
/// AES-128-CCM-8 cipher for TLS_PSK_WITH_AES_128_CCM_8.
|
||||
pub struct AesCcm8Cipher {
|
||||
cipher: Box<Aes128Ccm8>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for AesCcm8Cipher {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("AesCcm8Cipher").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl AesCcm8Cipher {
|
||||
pub fn new(key: &[u8]) -> Result<Self, CryptoError> {
|
||||
if key.len() != 16 {
|
||||
return Err(CryptoError::InvalidAes128Ccm8KeySize {
|
||||
actual: bounded_error_len(key.len()),
|
||||
});
|
||||
}
|
||||
let cipher = Aes128Ccm8::new_from_slice(key)
|
||||
.map_err(|_| CryptoError::OperationFailed(CryptoOperation::CreateCipher))?;
|
||||
Ok(AesCcm8Cipher {
|
||||
cipher: Box::new(cipher),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Cipher for AesCcm8Cipher {
|
||||
fn encrypt(&mut self, plaintext: &mut Buf, aad: Aad, nonce: Nonce) -> Result<(), CryptoError> {
|
||||
let ccm_nonce = ccm::aead::generic_array::GenericArray::from_slice(&nonce[..12]);
|
||||
let tag = self
|
||||
.cipher
|
||||
.encrypt_in_place_detached(ccm_nonce, &aad[..], plaintext.as_mut())
|
||||
.map_err(|_| CryptoError::OperationFailed(CryptoOperation::Encrypt))?;
|
||||
|
||||
// Append the 8-byte tag
|
||||
plaintext.extend_from_slice(&tag);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn decrypt(
|
||||
&mut self,
|
||||
ciphertext: &mut TmpBuf,
|
||||
aad: Aad,
|
||||
nonce: Nonce,
|
||||
) -> Result<(), CryptoError> {
|
||||
if ciphertext.len() < 8 {
|
||||
return Err(CryptoError::CiphertextTooShort {
|
||||
minimum: 8,
|
||||
actual: ciphertext.len() as u8,
|
||||
});
|
||||
}
|
||||
|
||||
let ccm_nonce = ccm::aead::generic_array::GenericArray::from_slice(&nonce[..12]);
|
||||
|
||||
// Split off the 8-byte tag from the end
|
||||
let data_len = ciphertext.len() - 8;
|
||||
let mut tag_bytes = [0u8; 8];
|
||||
tag_bytes.copy_from_slice(&ciphertext.as_ref()[data_len..]);
|
||||
let tag = ccm::aead::generic_array::GenericArray::from(tag_bytes);
|
||||
|
||||
// Truncate to just the ciphertext (without tag)
|
||||
ciphertext.truncate(data_len);
|
||||
|
||||
self.cipher
|
||||
.decrypt_in_place_detached(ccm_nonce, &aad[..], ciphertext.as_mut(), &tag)
|
||||
.map_err(|_| CryptoError::OperationFailed(CryptoOperation::Decrypt))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
+207
@@ -0,0 +1,207 @@
|
||||
//! DTLS AEAD record formatting types and constants.
|
||||
//!
|
||||
//! This module contains types and constants specific to DTLS AEAD record formatting,
|
||||
//! separate from the pluggable crypto provider abstraction.
|
||||
|
||||
use arrayvec::ArrayVec;
|
||||
|
||||
use crate::types::{ContentType, Sequence};
|
||||
|
||||
/// Explicit nonce length for DTLS AEAD records.
|
||||
///
|
||||
/// The explicit nonce is transmitted with each record.
|
||||
#[cfg(test)]
|
||||
pub(crate) const DTLS_EXPLICIT_NONCE_LEN: usize = 8;
|
||||
|
||||
/// GCM authentication tag length.
|
||||
///
|
||||
/// The tag is appended to the ciphertext.
|
||||
#[cfg(test)]
|
||||
pub(crate) const GCM_TAG_LEN: usize = 16;
|
||||
|
||||
/// Overhead per DTLS 1.2 AES-GCM record (explicit nonce + tag).
|
||||
///
|
||||
/// This equals 24 bytes for DTLS AES-GCM.
|
||||
#[cfg(test)]
|
||||
pub(crate) const DTLS_AEAD_OVERHEAD: usize = DTLS_EXPLICIT_NONCE_LEN + GCM_TAG_LEN; // 24
|
||||
|
||||
/// Compute AAD length from plaintext length for DTLS 1.2 AES-GCM records.
|
||||
#[inline]
|
||||
#[cfg(test)]
|
||||
pub fn aad_len_from_plaintext_len(plaintext_len: u16) -> u16 {
|
||||
plaintext_len
|
||||
}
|
||||
|
||||
/// Compute fragment length from plaintext length for DTLS 1.2 AES-GCM records.
|
||||
/// fragment_len = explicit_nonce(8) + ciphertext(plaintext_len + 16 tag)
|
||||
#[inline]
|
||||
#[cfg(test)]
|
||||
pub fn fragment_len_from_plaintext_len(plaintext_len: usize) -> usize {
|
||||
DTLS_EXPLICIT_NONCE_LEN + plaintext_len + GCM_TAG_LEN
|
||||
}
|
||||
|
||||
/// Compute plaintext length from fragment length for DTLS 1.2 AES-GCM records.
|
||||
/// Returns None if the fragment is smaller than the mandatory AEAD overhead.
|
||||
#[inline]
|
||||
#[cfg(test)]
|
||||
pub fn plaintext_len_from_fragment_len(fragment_len: usize) -> Option<usize> {
|
||||
fragment_len.checked_sub(DTLS_AEAD_OVERHEAD)
|
||||
}
|
||||
|
||||
/// Fixed IV portion for DTLS AEAD.
|
||||
///
|
||||
/// DTLS 1.2 uses:
|
||||
/// - AES-GCM: 4-byte fixed IV + 8-byte explicit nonce (per record)
|
||||
/// - ChaCha20-Poly1305: 12-byte fixed IV + 0-byte explicit nonce
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) struct Iv {
|
||||
bytes: [u8; 12],
|
||||
len: u8,
|
||||
}
|
||||
|
||||
impl Iv {
|
||||
pub(crate) fn new(iv: &[u8]) -> Self {
|
||||
assert!(
|
||||
iv.len() <= 12,
|
||||
"invalid IV length: expected <= 12, got {}",
|
||||
iv.len()
|
||||
);
|
||||
let mut bytes = [0u8; 12];
|
||||
bytes[..iv.len()].copy_from_slice(iv);
|
||||
Self {
|
||||
bytes,
|
||||
len: iv.len() as u8,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn len(&self) -> usize {
|
||||
self.len as usize
|
||||
}
|
||||
|
||||
pub(crate) fn as_slice(&self) -> &[u8] {
|
||||
&self.bytes[..self.len()]
|
||||
}
|
||||
|
||||
/// Returns the full 12-byte backing array.
|
||||
///
|
||||
/// Only valid for 12-byte IVs (ChaCha20-Poly1305). For 4-byte IVs
|
||||
/// (AES-GCM), use [`as_slice`] instead.
|
||||
pub(crate) fn as_12_bytes(&self) -> &[u8; 12] {
|
||||
assert_eq!(
|
||||
self.len(),
|
||||
12,
|
||||
"as_12_bytes called on {}-byte IV",
|
||||
self.len()
|
||||
);
|
||||
&self.bytes
|
||||
}
|
||||
}
|
||||
|
||||
/// Full AEAD nonce (fixed IV + explicit nonce).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Nonce(pub [u8; 12]);
|
||||
|
||||
impl Nonce {
|
||||
/// Create a new AEAD nonce by combining fixed IV and explicit nonce (DTLS 1.2).
|
||||
pub(crate) fn new(iv: Iv, explicit_nonce: &[u8]) -> Self {
|
||||
assert_eq!(
|
||||
iv.len() + explicit_nonce.len(),
|
||||
12,
|
||||
"invalid DTLS 1.2 nonce parts: iv_len={}, explicit_nonce_len={}",
|
||||
iv.len(),
|
||||
explicit_nonce.len()
|
||||
);
|
||||
let mut nonce = [0u8; 12];
|
||||
let iv_len = iv.len();
|
||||
nonce[..iv_len].copy_from_slice(iv.as_slice());
|
||||
nonce[iv_len..].copy_from_slice(explicit_nonce);
|
||||
Self(nonce)
|
||||
}
|
||||
|
||||
/// Create a nonce by XORing the IV with the padded sequence number.
|
||||
///
|
||||
/// Used by both DTLS 1.2 (ChaCha20-Poly1305) and DTLS 1.3:
|
||||
/// nonce = iv XOR pad_left(sequence_number, 12)
|
||||
/// See RFC 8446 Section 5.3 / RFC 7905.
|
||||
pub(crate) fn xor(iv: &[u8; 12], seq: u64) -> Self {
|
||||
let mut nonce = *iv;
|
||||
let seq_bytes = seq.to_be_bytes(); // 8 bytes
|
||||
// XOR the last 8 bytes of the 12-byte IV with the sequence number
|
||||
for i in 0..8 {
|
||||
nonce[4 + i] ^= seq_bytes[i];
|
||||
}
|
||||
Self(nonce)
|
||||
}
|
||||
}
|
||||
|
||||
/// Additional Authenticated Data for DTLS records.
|
||||
///
|
||||
/// Variable-length to support both DTLS 1.2 (13 bytes) and DTLS 1.3 (3-5 bytes).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Aad(pub ArrayVec<u8, 13>);
|
||||
|
||||
impl Aad {
|
||||
/// Create Additional Authenticated Data for a DTLS 1.2 record.
|
||||
pub(crate) fn new_dtls12(content_type: ContentType, sequence: Sequence, length: u16) -> Self {
|
||||
let mut aad = ArrayVec::new();
|
||||
|
||||
// First set the full 8-byte sequence number
|
||||
let seq_bytes = sequence.sequence_number.to_be_bytes();
|
||||
aad.try_extend_from_slice(&seq_bytes).unwrap();
|
||||
|
||||
// Overwrite the first 2 bytes with epoch
|
||||
let epoch_bytes = sequence.epoch.to_be_bytes();
|
||||
aad[0] = epoch_bytes[0];
|
||||
aad[1] = epoch_bytes[1];
|
||||
|
||||
// Content type at index 8
|
||||
aad.push(content_type.as_u8());
|
||||
|
||||
// Protocol version bytes (major:minor) at indexes 9-10
|
||||
aad.push(0xfe); // DTLS 1.2 major version
|
||||
aad.push(0xfd); // DTLS 1.2 minor version
|
||||
|
||||
// Payload length (2 bytes) at indexes 11-12
|
||||
aad.try_extend_from_slice(&length.to_be_bytes()).unwrap();
|
||||
|
||||
Aad(aad)
|
||||
}
|
||||
|
||||
/// Create Additional Authenticated Data for a DTLS 1.3 record.
|
||||
///
|
||||
/// The AAD is the raw unified header bytes (3-5 bytes).
|
||||
pub(crate) fn new_dtls13(header_bytes: &[u8]) -> Self {
|
||||
let mut aad = ArrayVec::new();
|
||||
// unwrap: header_bytes is at most 5 bytes, well within capacity 13
|
||||
aad.try_extend_from_slice(header_bytes).unwrap();
|
||||
Aad(aad)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn aead_constants_and_length_helpers() {
|
||||
assert_eq!(DTLS_EXPLICIT_NONCE_LEN, 8);
|
||||
assert_eq!(GCM_TAG_LEN, 16);
|
||||
assert_eq!(DTLS_AEAD_OVERHEAD, 24);
|
||||
|
||||
for &pt_len in &[0usize, 1, 37, 512, 1350, 16384] {
|
||||
let aad_len = aad_len_from_plaintext_len(pt_len as u16);
|
||||
assert_eq!(aad_len as usize, pt_len);
|
||||
|
||||
let frag_len = fragment_len_from_plaintext_len(pt_len);
|
||||
assert_eq!(frag_len, DTLS_EXPLICIT_NONCE_LEN + pt_len + GCM_TAG_LEN);
|
||||
|
||||
let roundtrip =
|
||||
plaintext_len_from_fragment_len(frag_len).expect("frag_len >= overhead");
|
||||
assert_eq!(roundtrip, pt_len);
|
||||
}
|
||||
|
||||
assert!(plaintext_len_from_fragment_len(0).is_none());
|
||||
assert!(plaintext_len_from_fragment_len(3).is_none());
|
||||
assert!(plaintext_len_from_fragment_len(DTLS_AEAD_OVERHEAD - 1).is_none());
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
//! SRTP keying material types and profiles used by DTLS-SRTP.
|
||||
use std::ops::Deref;
|
||||
|
||||
/// Keying material used as master key for SRTP.
|
||||
pub struct KeyingMaterial(Vec<u8>);
|
||||
|
||||
impl KeyingMaterial {
|
||||
/// Create a new wrapper for DTLS-SRTP keying material bytes.
|
||||
pub fn new(m: &[u8]) -> Self {
|
||||
KeyingMaterial(m.to_vec())
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for KeyingMaterial {
|
||||
type Target = [u8];
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for KeyingMaterial {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "KeyingMaterial")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[allow(non_camel_case_types)]
|
||||
#[non_exhaustive]
|
||||
/// Supported SRTP protection profiles (RFC 5764).
|
||||
pub enum SrtpProfile {
|
||||
/// SRTP_AES128_CM_HMAC_SHA1_80 (RFC 5764)
|
||||
AES128_CM_SHA1_80,
|
||||
/// AEAD_AES_128_GCM (RFC 7714)
|
||||
AEAD_AES_128_GCM,
|
||||
/// AEAD_AES_256_GCM (RFC 7714)
|
||||
AEAD_AES_256_GCM,
|
||||
}
|
||||
|
||||
impl SrtpProfile {
|
||||
/// All supported profiles ordered by preference.
|
||||
pub const ALL: &'static [SrtpProfile] = &[
|
||||
SrtpProfile::AEAD_AES_256_GCM,
|
||||
SrtpProfile::AEAD_AES_128_GCM,
|
||||
SrtpProfile::AES128_CM_SHA1_80,
|
||||
];
|
||||
|
||||
/// The length of keying material to extract from the DTLS session in bytes.
|
||||
#[rustfmt::skip]
|
||||
pub fn keying_material_len(&self) -> usize {
|
||||
match self {
|
||||
// MASTER_KEY_LEN * 2 + MASTER_SALT * 2
|
||||
// TODO: This is a duplication of info that is held in srtp.rs, because we
|
||||
// don't want a dependency in that direction.
|
||||
SrtpProfile::AES128_CM_SHA1_80 => 16 * 2 + 14 * 2,
|
||||
SrtpProfile::AEAD_AES_128_GCM => 16 * 2 + 12 * 2,
|
||||
SrtpProfile::AEAD_AES_256_GCM => 32 * 2 + 12 * 2,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for SrtpProfile {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
SrtpProfile::AES128_CM_SHA1_80 => write!(f, "SRTP_AES128_CM_SHA1_80"),
|
||||
SrtpProfile::AEAD_AES_128_GCM => write!(f, "SRTP_AEAD_AES_128_GCM"),
|
||||
SrtpProfile::AEAD_AES_256_GCM => write!(f, "SRTP_AEAD_AES_256_GCM"),
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+62
@@ -0,0 +1,62 @@
|
||||
//! Cryptographic primitives and helpers used by the DTLS engine.
|
||||
|
||||
use std::ops::Deref;
|
||||
|
||||
// Internal module imports
|
||||
mod keying;
|
||||
|
||||
// Provider traits and implementations
|
||||
#[cfg(feature = "aws-lc-rs")]
|
||||
pub mod aws_lc_rs;
|
||||
|
||||
#[cfg(feature = "rust-crypto")]
|
||||
pub mod rust_crypto;
|
||||
|
||||
#[cfg(any(feature = "aws-lc-rs", feature = "rust-crypto"))]
|
||||
pub(crate) mod ccm_cipher;
|
||||
|
||||
mod dtls_aead;
|
||||
pub mod prf_hkdf;
|
||||
mod provider;
|
||||
mod validation;
|
||||
|
||||
pub use keying::{KeyingMaterial, SrtpProfile};
|
||||
|
||||
// Re-export AEAD types needed for Cipher trait implementations (public API)
|
||||
pub use dtls_aead::{Aad, Nonce};
|
||||
|
||||
// Re-export internal AEAD constants/types for crate-internal use
|
||||
pub(crate) use dtls_aead::Iv;
|
||||
|
||||
// Re-export buffer types for provider trait implementations
|
||||
pub use crate::buffer::{Buf, TmpBuf};
|
||||
|
||||
// Re-export all provider traits and types (similar to rustls structure)
|
||||
// This allows users to do: use dimpl::crypto::{CryptoProvider, SupportedDtls12CipherSuite, ...};
|
||||
pub use provider::{
|
||||
ActiveKeyExchange, Cipher, CryptoProvider, CryptoSafe, HashContext, HashProvider, HmacProvider,
|
||||
KeyProvider, SecureRandom, SignatureVerifier, SigningKey, SupportedDtls12CipherSuite,
|
||||
SupportedDtls13CipherSuite, SupportedKxGroup, check_verify_scheme,
|
||||
};
|
||||
#[cfg(feature = "_crypto-common")]
|
||||
pub use provider::{OID_P256, OID_P384, cert_named_group};
|
||||
|
||||
// Re-export shared types for provider trait implementations
|
||||
pub use crate::dtls12::message::Dtls12CipherSuite;
|
||||
pub use crate::types::{
|
||||
Dtls13CipherSuite, HashAlgorithm, NamedGroup, SignatureAlgorithm, SignatureScheme,
|
||||
};
|
||||
|
||||
impl Deref for Aad {
|
||||
type Target = [u8];
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0[..]
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for Nonce {
|
||||
type Target = [u8];
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
+538
@@ -0,0 +1,538 @@
|
||||
//! PRF and HKDF key derivation built on top of [`HmacProvider`].
|
||||
//!
|
||||
//! Both TLS 1.2 PRF and TLS 1.3 HKDF are pure compositions of HMAC calls.
|
||||
//! This module provides generic implementations so that crypto backends only
|
||||
//! need to implement [`HmacProvider`] — no separate PRF or HKDF providers.
|
||||
|
||||
use crate::CryptoError;
|
||||
use crate::buffer::Buf;
|
||||
use crate::types::HashAlgorithm;
|
||||
|
||||
use super::HmacProvider;
|
||||
|
||||
/// Maximum HMAC output size we support (SHA-384 = 48 bytes).
|
||||
const MAX_HASH_LEN: usize = 48;
|
||||
|
||||
// ============================================================================
|
||||
// TLS 1.2 PRF (RFC 5246 Section 5)
|
||||
// ============================================================================
|
||||
|
||||
/// TLS 1.2 PRF: `PRF(secret, label, seed)` writing `output_len` bytes to `out`.
|
||||
///
|
||||
/// Uses `scratch` for temporary concatenation of label+seed.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn prf_tls12(
|
||||
hmac: &dyn HmacProvider,
|
||||
secret: &[u8],
|
||||
label: &str,
|
||||
seed: &[u8],
|
||||
out: &mut Buf,
|
||||
output_len: usize,
|
||||
scratch: &mut Buf,
|
||||
hash: HashAlgorithm,
|
||||
) -> Result<(), CryptoError> {
|
||||
let mut hmac_a = [0u8; MAX_HASH_LEN];
|
||||
|
||||
// Build label + seed
|
||||
scratch.clear();
|
||||
scratch.extend_from_slice(label.as_bytes());
|
||||
scratch.extend_from_slice(seed);
|
||||
let label_seed = scratch.as_ref();
|
||||
|
||||
// A(1) = HMAC(secret, label_seed)
|
||||
let hash_len = hmac.hmac(hash, secret, label_seed, &mut hmac_a)?;
|
||||
|
||||
// Build payload = A(i) || label || seed
|
||||
scratch.clear();
|
||||
scratch.extend_from_slice(&hmac_a[..hash_len]);
|
||||
scratch.extend_from_slice(label.as_bytes());
|
||||
scratch.extend_from_slice(seed);
|
||||
let payload = scratch.as_mut();
|
||||
|
||||
out.clear();
|
||||
while out.len() < output_len {
|
||||
// P(i) = HMAC(secret, A(i) || label || seed)
|
||||
let mut hmac_block = [0u8; MAX_HASH_LEN];
|
||||
let block_len = hmac.hmac(hash, secret, payload, &mut hmac_block)?;
|
||||
|
||||
let remaining = output_len - out.len();
|
||||
let to_copy = remaining.min(block_len);
|
||||
out.extend_from_slice(&hmac_block[..to_copy]);
|
||||
|
||||
if out.len() < output_len {
|
||||
// A(i+1) = HMAC(secret, A(i))
|
||||
hmac.hmac(hash, secret, &payload[..hash_len], &mut hmac_a)?;
|
||||
payload[..hash_len].copy_from_slice(&hmac_a[..hash_len]);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// HKDF (RFC 5869)
|
||||
// ============================================================================
|
||||
|
||||
/// HKDF-Extract: `PRK = HMAC-Hash(salt, IKM)`.
|
||||
pub fn hkdf_extract(
|
||||
hmac: &dyn HmacProvider,
|
||||
hash: HashAlgorithm,
|
||||
salt: &[u8],
|
||||
ikm: &[u8],
|
||||
out: &mut Buf,
|
||||
) -> Result<(), CryptoError> {
|
||||
out.clear();
|
||||
|
||||
let hash_len = hash.output_len();
|
||||
let zero_salt: Vec<u8>;
|
||||
let actual_salt = if salt.is_empty() {
|
||||
zero_salt = vec![0u8; hash_len];
|
||||
&zero_salt[..]
|
||||
} else {
|
||||
salt
|
||||
};
|
||||
|
||||
let mut prk = [0u8; MAX_HASH_LEN];
|
||||
let prk_len = hmac.hmac(hash, actual_salt, ikm, &mut prk)?;
|
||||
out.extend_from_slice(&prk[..prk_len]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// HKDF-Expand: expand `prk` to `output_len` bytes.
|
||||
pub fn hkdf_expand(
|
||||
hmac: &dyn HmacProvider,
|
||||
hash: HashAlgorithm,
|
||||
prk: &[u8],
|
||||
info: &[u8],
|
||||
out: &mut Buf,
|
||||
output_len: usize,
|
||||
) -> Result<(), CryptoError> {
|
||||
let hash_len = hash.output_len();
|
||||
let n = output_len.div_ceil(hash_len);
|
||||
if n > 255 {
|
||||
return Err(CryptoError::HkdfOutputTooLong);
|
||||
}
|
||||
|
||||
let mut t_prev = [0u8; MAX_HASH_LEN];
|
||||
let mut t_prev_len = 0usize;
|
||||
|
||||
out.clear();
|
||||
for i in 1..=n {
|
||||
let mut input = Vec::with_capacity(t_prev_len + info.len() + 1);
|
||||
input.extend_from_slice(&t_prev[..t_prev_len]);
|
||||
input.extend_from_slice(info);
|
||||
input.push(i as u8);
|
||||
|
||||
t_prev_len = hmac.hmac(hash, prk, &input, &mut t_prev)?;
|
||||
|
||||
let remaining = output_len - out.len();
|
||||
let to_copy = remaining.min(t_prev_len);
|
||||
out.extend_from_slice(&t_prev[..to_copy]);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// HKDF-Expand-Label for TLS 1.3 (RFC 8446 Section 7.1).
|
||||
///
|
||||
/// Uses the `"tls13 "` prefix.
|
||||
pub fn hkdf_expand_label(
|
||||
hmac: &dyn HmacProvider,
|
||||
hash: HashAlgorithm,
|
||||
secret: &[u8],
|
||||
label: &[u8],
|
||||
context: &[u8],
|
||||
out: &mut Buf,
|
||||
output_len: usize,
|
||||
) -> Result<(), CryptoError> {
|
||||
let info = build_hkdf_label(b"tls13 ", label, context, output_len)?;
|
||||
hkdf_expand(hmac, hash, secret, &info, out, output_len)
|
||||
}
|
||||
|
||||
/// HKDF-Expand-Label for DTLS 1.3 (RFC 9147).
|
||||
///
|
||||
/// Uses the `"dtls13"` prefix (no trailing space).
|
||||
pub fn hkdf_expand_label_dtls13(
|
||||
hmac: &dyn HmacProvider,
|
||||
hash: HashAlgorithm,
|
||||
secret: &[u8],
|
||||
label: &[u8],
|
||||
context: &[u8],
|
||||
out: &mut Buf,
|
||||
output_len: usize,
|
||||
) -> Result<(), CryptoError> {
|
||||
let info = build_hkdf_label(b"dtls13", label, context, output_len)?;
|
||||
hkdf_expand(hmac, hash, secret, &info, out, output_len)
|
||||
}
|
||||
|
||||
/// Build the HkdfLabel structure.
|
||||
///
|
||||
/// ```text
|
||||
/// struct {
|
||||
/// uint16 length;
|
||||
/// opaque label<6..255> = prefix + Label;
|
||||
/// opaque context<0..255> = Context;
|
||||
/// } HkdfLabel;
|
||||
/// ```
|
||||
fn build_hkdf_label(
|
||||
prefix: &[u8],
|
||||
label: &[u8],
|
||||
context: &[u8],
|
||||
output_len: usize,
|
||||
) -> Result<Vec<u8>, CryptoError> {
|
||||
let full_label_len = prefix.len() + label.len();
|
||||
|
||||
if full_label_len > 255 {
|
||||
return Err(CryptoError::HkdfLabelTooLong);
|
||||
}
|
||||
if context.len() > 255 {
|
||||
return Err(CryptoError::HkdfContextTooLong);
|
||||
}
|
||||
if output_len > 65535 {
|
||||
return Err(CryptoError::HkdfOutputLengthTooLarge);
|
||||
}
|
||||
|
||||
let info_len = 2 + 1 + full_label_len + 1 + context.len();
|
||||
let mut info = Vec::with_capacity(info_len);
|
||||
|
||||
// uint16 length
|
||||
info.extend_from_slice(&(output_len as u16).to_be_bytes());
|
||||
// opaque label
|
||||
info.push(full_label_len as u8);
|
||||
info.extend_from_slice(prefix);
|
||||
info.extend_from_slice(label);
|
||||
// opaque context
|
||||
info.push(context.len() as u8);
|
||||
info.extend_from_slice(context);
|
||||
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn hex_to_vec(hex: &str) -> Vec<u8> {
|
||||
let hex = hex.replace([' ', '\n'], "");
|
||||
let mut v = Vec::new();
|
||||
for i in 0..hex.len() / 2 {
|
||||
// unwrap: test-only hex parsing
|
||||
let byte = u8::from_str_radix(&hex[i * 2..i * 2 + 2], 16).unwrap();
|
||||
v.push(byte);
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
fn slice_to_hex(data: &[u8]) -> String {
|
||||
let mut s = String::new();
|
||||
for byte in data.iter() {
|
||||
s.push_str(&format!("{:02x}", byte));
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// Convert an ASCII hex array into a byte array at compile time.
|
||||
macro_rules! hex_as_bytes {
|
||||
($input:expr) => {{
|
||||
const fn from_hex_char(c: u8) -> u8 {
|
||||
match c {
|
||||
b'0'..=b'9' => c - b'0',
|
||||
b'a'..=b'f' => c - b'a' + 10,
|
||||
b'A'..=b'F' => c - b'A' + 10,
|
||||
_ => panic!("Invalid hex character"),
|
||||
}
|
||||
}
|
||||
|
||||
const INPUT: &[u8] = $input;
|
||||
const LEN: usize = INPUT.len();
|
||||
const OUTPUT_LEN: usize = LEN / 2;
|
||||
|
||||
const fn convert() -> [u8; OUTPUT_LEN] {
|
||||
assert!(LEN % 2 == 0, "Hex string length must be even");
|
||||
|
||||
let mut out = [0u8; OUTPUT_LEN];
|
||||
let mut i = 0;
|
||||
while i < LEN {
|
||||
out[i / 2] = (from_hex_char(INPUT[i]) << 4) | from_hex_char(INPUT[i + 1]);
|
||||
i += 2;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
convert()
|
||||
}};
|
||||
}
|
||||
|
||||
/// We need a concrete HmacProvider for tests. Use the default feature-gated one.
|
||||
fn hmac_provider() -> &'static dyn HmacProvider {
|
||||
#[cfg(feature = "aws-lc-rs")]
|
||||
{
|
||||
&crate::crypto::aws_lc_rs::hmac::HMAC_PROVIDER
|
||||
}
|
||||
#[cfg(all(not(feature = "aws-lc-rs"), feature = "rust-crypto"))]
|
||||
{
|
||||
&crate::crypto::rust_crypto::hmac::HMAC_PROVIDER
|
||||
}
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// HMAC-SHA-256 Test Vectors from RFC 4231
|
||||
// ========================================================================
|
||||
|
||||
#[test]
|
||||
fn hmac_sha256_test_case_1() {
|
||||
let key = hex_to_vec("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b");
|
||||
let data = b"Hi There";
|
||||
let expected = "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7";
|
||||
|
||||
let result = hmac_provider().hmac_sha256(&key, data).unwrap();
|
||||
assert_eq!(slice_to_hex(&result), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hmac_sha256_test_case_2() {
|
||||
let key = b"Jefe";
|
||||
let data = b"what do ya want for nothing?";
|
||||
let expected = "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843";
|
||||
|
||||
let result = hmac_provider().hmac_sha256(key, data).unwrap();
|
||||
assert_eq!(slice_to_hex(&result), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hmac_sha256_test_case_3() {
|
||||
let key = hex_to_vec("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
|
||||
let data = hex_to_vec(
|
||||
"dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd\
|
||||
dddddddddddddddddddddddddddddddddddd",
|
||||
);
|
||||
let expected = "773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe";
|
||||
|
||||
let result = hmac_provider().hmac_sha256(&key, &data).unwrap();
|
||||
assert_eq!(slice_to_hex(&result), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hmac_sha256_test_case_4() {
|
||||
let key = hex_to_vec("0102030405060708090a0b0c0d0e0f10111213141516171819");
|
||||
let data = hex_to_vec(
|
||||
"cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd\
|
||||
cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd",
|
||||
);
|
||||
let expected = "82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff46729665b";
|
||||
|
||||
let result = hmac_provider().hmac_sha256(&key, &data).unwrap();
|
||||
assert_eq!(slice_to_hex(&result), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hmac_sha256_test_case_6() {
|
||||
// Test with a key larger than block size (> 64 bytes)
|
||||
let key = vec![0xaa; 131];
|
||||
let data = b"Test Using Larger Than Block-Size Key - Hash Key First";
|
||||
let expected = "60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54";
|
||||
|
||||
let result = hmac_provider().hmac_sha256(&key, data).unwrap();
|
||||
assert_eq!(slice_to_hex(&result), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hmac_sha256_test_case_7() {
|
||||
// Test with a key larger than block size and large data
|
||||
let key = vec![0xaa; 131];
|
||||
let data =
|
||||
b"This is a test using a larger than block-size key and a larger than block-size \
|
||||
data. The key needs to be hashed before being used by the HMAC algorithm.";
|
||||
let expected = "9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f51535c3a35e2";
|
||||
|
||||
let result = hmac_provider().hmac_sha256(&key, data).unwrap();
|
||||
assert_eq!(slice_to_hex(&result), expected);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// TLS 1.2 PRF
|
||||
// ========================================================================
|
||||
|
||||
#[test]
|
||||
fn prf_tls12_sha256() {
|
||||
// Test vector from https://github.com/xomexh/TLS-PRF
|
||||
let mut output = Buf::new();
|
||||
let mut scratch = Buf::new();
|
||||
prf_tls12(
|
||||
hmac_provider(),
|
||||
&hex_as_bytes!(b"9bbe436ba940f017b17652849a71db35"),
|
||||
"test label",
|
||||
&hex_as_bytes!(b"a0ba9f936cda311827a6f796ffd5198c"),
|
||||
&mut output,
|
||||
100,
|
||||
&mut scratch,
|
||||
HashAlgorithm::SHA256,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
output.as_ref(),
|
||||
&hex_as_bytes!(
|
||||
b"e3f229ba727be17b8d122620557cd453c2aab21d\
|
||||
07c3d495329b52d4e61edb5a6b301791e90d35c9\
|
||||
c9a46b4e14baf9af0fa022f7077def17abfd3797\
|
||||
c0564bab4fbc91666e9def9b97fce34f796789ba\
|
||||
a48082d122ee42c5a72e5a5110fff70187347b66"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// HKDF Test Vectors from RFC 5869
|
||||
// ========================================================================
|
||||
|
||||
#[test]
|
||||
fn hkdf_sha256_rfc5869_case1() {
|
||||
// Test Case 1 - Basic test case with SHA-256
|
||||
let ikm = hex_to_vec("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b");
|
||||
let salt = hex_to_vec("000102030405060708090a0b0c");
|
||||
let info = hex_to_vec("f0f1f2f3f4f5f6f7f8f9");
|
||||
let expected_prk = "077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5";
|
||||
let expected_okm = "3cb25f25faacd57a90434f64d0362f2a\
|
||||
2d2d0a90cf1a5a4c5db02d56ecc4c5bf\
|
||||
34007208d5b887185865";
|
||||
|
||||
let h = hmac_provider();
|
||||
|
||||
let mut prk = Buf::new();
|
||||
hkdf_extract(h, HashAlgorithm::SHA256, &salt, &ikm, &mut prk).unwrap();
|
||||
assert_eq!(slice_to_hex(prk.as_ref()), expected_prk);
|
||||
|
||||
let mut okm = Buf::new();
|
||||
hkdf_expand(h, HashAlgorithm::SHA256, prk.as_ref(), &info, &mut okm, 42).unwrap();
|
||||
assert_eq!(slice_to_hex(okm.as_ref()), expected_okm);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hkdf_sha256_rfc5869_case2() {
|
||||
// Test Case 2 - Longer inputs/outputs with SHA-256
|
||||
let ikm = hex_to_vec(
|
||||
"000102030405060708090a0b0c0d0e0f\
|
||||
101112131415161718191a1b1c1d1e1f\
|
||||
202122232425262728292a2b2c2d2e2f\
|
||||
303132333435363738393a3b3c3d3e3f\
|
||||
404142434445464748494a4b4c4d4e4f",
|
||||
);
|
||||
let salt = hex_to_vec(
|
||||
"606162636465666768696a6b6c6d6e6f\
|
||||
707172737475767778797a7b7c7d7e7f\
|
||||
808182838485868788898a8b8c8d8e8f\
|
||||
909192939495969798999a9b9c9d9e9f\
|
||||
a0a1a2a3a4a5a6a7a8a9aaabacadaeaf",
|
||||
);
|
||||
let info = hex_to_vec(
|
||||
"b0b1b2b3b4b5b6b7b8b9babbbcbdbebf\
|
||||
c0c1c2c3c4c5c6c7c8c9cacbcccdcecf\
|
||||
d0d1d2d3d4d5d6d7d8d9dadbdcdddedf\
|
||||
e0e1e2e3e4e5e6e7e8e9eaebecedeeef\
|
||||
f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
|
||||
);
|
||||
let expected_prk = "06a6b88c5853361a06104c9ceb35b45cef760014904671014a193f40c15fc244";
|
||||
let expected_okm = "b11e398dc80327a1c8e7f78c596a4934\
|
||||
4f012eda2d4efad8a050cc4c19afa97c\
|
||||
59045a99cac7827271cb41c65e590e09\
|
||||
da3275600c2f09b8367793a9aca3db71\
|
||||
cc30c58179ec3e87c14c01d5c1f3434f\
|
||||
1d87";
|
||||
|
||||
let h = hmac_provider();
|
||||
|
||||
let mut prk = Buf::new();
|
||||
hkdf_extract(h, HashAlgorithm::SHA256, &salt, &ikm, &mut prk).unwrap();
|
||||
assert_eq!(slice_to_hex(prk.as_ref()), expected_prk);
|
||||
|
||||
let mut okm = Buf::new();
|
||||
hkdf_expand(h, HashAlgorithm::SHA256, prk.as_ref(), &info, &mut okm, 82).unwrap();
|
||||
assert_eq!(slice_to_hex(okm.as_ref()), expected_okm);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hkdf_sha256_rfc5869_case3() {
|
||||
// Test Case 3 - Zero-length salt and info with SHA-256
|
||||
let ikm = hex_to_vec("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b");
|
||||
let salt = vec![];
|
||||
let info = vec![];
|
||||
let expected_prk = "19ef24a32c717b167f33a91d6f648bdf96596776afdb6377ac434c1c293ccb04";
|
||||
let expected_okm = "8da4e775a563c18f715f802a063c5a31\
|
||||
b8a11f5c5ee1879ec3454e5f3c738d2d\
|
||||
9d201395faa4b61a96c8";
|
||||
|
||||
let h = hmac_provider();
|
||||
|
||||
let mut prk = Buf::new();
|
||||
hkdf_extract(h, HashAlgorithm::SHA256, &salt, &ikm, &mut prk).unwrap();
|
||||
assert_eq!(slice_to_hex(prk.as_ref()), expected_prk);
|
||||
|
||||
let mut okm = Buf::new();
|
||||
hkdf_expand(h, HashAlgorithm::SHA256, prk.as_ref(), &info, &mut okm, 42).unwrap();
|
||||
assert_eq!(slice_to_hex(okm.as_ref()), expected_okm);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// HKDF-Expand-Label
|
||||
// ========================================================================
|
||||
|
||||
#[test]
|
||||
fn hkdf_expand_label_basic() {
|
||||
let h = hmac_provider();
|
||||
let secret = [0u8; 32];
|
||||
let mut out = Buf::new();
|
||||
|
||||
hkdf_expand_label(h, HashAlgorithm::SHA256, &secret, b"key", &[], &mut out, 16).unwrap();
|
||||
assert_eq!(out.len(), 16);
|
||||
|
||||
hkdf_expand_label(
|
||||
h,
|
||||
HashAlgorithm::SHA256,
|
||||
&secret,
|
||||
b"iv",
|
||||
&[1, 2, 3, 4],
|
||||
&mut out,
|
||||
12,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(out.len(), 12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hkdf_expand_label_dtls13_basic() {
|
||||
let h = hmac_provider();
|
||||
let secret = [0u8; 32];
|
||||
let mut out = Buf::new();
|
||||
|
||||
hkdf_expand_label_dtls13(h, HashAlgorithm::SHA256, &secret, b"key", &[], &mut out, 16)
|
||||
.unwrap();
|
||||
assert_eq!(out.len(), 16);
|
||||
|
||||
// TLS 1.3 and DTLS 1.3 with same inputs should produce different outputs
|
||||
let mut tls_out = Buf::new();
|
||||
let mut dtls_out = Buf::new();
|
||||
|
||||
hkdf_expand_label(
|
||||
h,
|
||||
HashAlgorithm::SHA256,
|
||||
&secret,
|
||||
b"key",
|
||||
&[],
|
||||
&mut tls_out,
|
||||
16,
|
||||
)
|
||||
.unwrap();
|
||||
hkdf_expand_label_dtls13(
|
||||
h,
|
||||
HashAlgorithm::SHA256,
|
||||
&secret,
|
||||
b"key",
|
||||
&[],
|
||||
&mut dtls_out,
|
||||
16,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_ne!(tls_out.as_ref(), dtls_out.as_ref());
|
||||
}
|
||||
}
|
||||
+665
@@ -0,0 +1,665 @@
|
||||
//! Cryptographic provider traits for pluggable crypto backends.
|
||||
//!
|
||||
//! This module defines the trait-based interface for cryptographic operations
|
||||
//! in dimpl, allowing users to provide custom crypto implementations.
|
||||
//!
|
||||
//! # Overview
|
||||
//!
|
||||
//! The crypto provider system is inspired by rustls's design and uses a component-based
|
||||
//! approach where the [`CryptoProvider`] struct holds static references to various
|
||||
//! trait objects, each representing a specific cryptographic capability.
|
||||
//!
|
||||
//! # Architecture
|
||||
//!
|
||||
//! The provider system is organized into these main components:
|
||||
//!
|
||||
//! - **Cipher Suites** ([`SupportedDtls12CipherSuite`]): Factory for AEAD ciphers
|
||||
//! - **Key Exchange Groups** ([`SupportedKxGroup`]): Factory for ECDHE key exchanges
|
||||
//! - **Signature Verification** ([`SignatureVerifier`]): Verify signatures in certificates
|
||||
//! - **Key Provider** ([`KeyProvider`]): Parse and load private keys
|
||||
//! - **Secure Random** ([`SecureRandom`]): Cryptographically secure RNG
|
||||
//! - **Hash Provider** ([`HashProvider`]): Factory for hash contexts
|
||||
//! - **HMAC Provider** ([`HmacProvider`]): Compute HMAC signatures (also drives PRF and HKDF)
|
||||
//!
|
||||
//! # Using a Custom Provider
|
||||
//!
|
||||
//! To use a custom crypto provider, create one and pass it to the [`Config`](crate::Config):
|
||||
//!
|
||||
//! ```
|
||||
//! # #[cfg(all(feature = "aws-lc-rs", feature = "rcgen"))]
|
||||
//! # fn main() {
|
||||
//! use std::sync::Arc;
|
||||
//! use std::time::Instant;
|
||||
//! use dimpl::{Config, Dtls, certificate};
|
||||
//! use dimpl::crypto::aws_lc_rs;
|
||||
//!
|
||||
//! let cert = certificate::generate_self_signed_certificate().unwrap();
|
||||
//! // Use the default aws-lc-rs provider (implicit)
|
||||
//! let config = Arc::new(Config::default());
|
||||
//!
|
||||
//! // Or explicitly set the provider
|
||||
//! let config = Arc::new(
|
||||
//! Config::builder()
|
||||
//! .with_crypto_provider(aws_lc_rs::default_provider())
|
||||
//! .build()
|
||||
//! .unwrap()
|
||||
//! );
|
||||
//!
|
||||
//! // Or use your own custom provider
|
||||
//! // let config = Arc::new(
|
||||
//! // Config::builder()
|
||||
//! // .with_crypto_provider(my_custom_provider())
|
||||
//! // .build()
|
||||
//! // .unwrap()
|
||||
//! // );
|
||||
//!
|
||||
//! let dtls = Dtls::new_12(config, cert, Instant::now());
|
||||
//! # }
|
||||
//! # #[cfg(not(all(feature = "aws-lc-rs", feature = "rcgen")))]
|
||||
//! # fn main() {}
|
||||
//! ```
|
||||
//!
|
||||
//! # Implementing a Custom Provider
|
||||
//!
|
||||
//! To implement a custom provider, you need to:
|
||||
//!
|
||||
//! 1. Implement the required traits for your crypto backend
|
||||
//! 2. Create static instances of your implementations
|
||||
//! 3. Build a [`CryptoProvider`] struct with references to those statics
|
||||
//!
|
||||
//! ## Example: Custom Cipher Suite
|
||||
//!
|
||||
//! ```
|
||||
//! use dimpl::CryptoError;
|
||||
//! use dimpl::crypto::{SupportedDtls12CipherSuite, Cipher, Dtls12CipherSuite, HashAlgorithm};
|
||||
//! use dimpl::crypto::{Buf, TmpBuf};
|
||||
//! use dimpl::crypto::{Aad, Nonce};
|
||||
//!
|
||||
//! #[derive(Debug)]
|
||||
//! struct MyCipher;
|
||||
//!
|
||||
//! impl MyCipher {
|
||||
//! fn new(_key: &[u8]) -> Result<Self, CryptoError> {
|
||||
//! Ok(Self)
|
||||
//! }
|
||||
//! }
|
||||
//!
|
||||
//! impl Cipher for MyCipher {
|
||||
//! fn encrypt(&mut self, _: &mut Buf, _: Aad, _: Nonce) -> Result<(), CryptoError> {
|
||||
//! Ok(())
|
||||
//! }
|
||||
//! fn decrypt(&mut self, _: &mut TmpBuf, _: Aad, _: Nonce) -> Result<(), CryptoError> {
|
||||
//! Ok(())
|
||||
//! }
|
||||
//! }
|
||||
//!
|
||||
//! #[derive(Debug)]
|
||||
//! struct MyDtls12CipherSuite;
|
||||
//!
|
||||
//! impl SupportedDtls12CipherSuite for MyDtls12CipherSuite {
|
||||
//! fn suite(&self) -> Dtls12CipherSuite {
|
||||
//! Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256
|
||||
//! }
|
||||
//!
|
||||
//! fn hash_algorithm(&self) -> HashAlgorithm {
|
||||
//! HashAlgorithm::SHA256
|
||||
//! }
|
||||
//!
|
||||
//! fn key_lengths(&self) -> (usize, usize, usize) {
|
||||
//! (0, 16, 4) // (mac_key_len, enc_key_len, fixed_iv_len)
|
||||
//! }
|
||||
//!
|
||||
//! fn explicit_nonce_len(&self) -> usize {
|
||||
//! 8 // AES-GCM: 8-byte explicit nonce per record
|
||||
//! }
|
||||
//!
|
||||
//! fn tag_len(&self) -> usize {
|
||||
//! 16 // 128-bit authentication tag
|
||||
//! }
|
||||
//!
|
||||
//! fn create_cipher(&self, key: &[u8]) -> Result<Box<dyn Cipher>, CryptoError> {
|
||||
//! // Create your cipher implementation here
|
||||
//! Ok(Box::new(MyCipher::new(key)?))
|
||||
//! }
|
||||
//! }
|
||||
//!
|
||||
//! static MY_CIPHER_SUITE: MyDtls12CipherSuite = MyDtls12CipherSuite;
|
||||
//! static ALL_CIPHER_SUITES: &[&dyn SupportedDtls12CipherSuite] = &[&MY_CIPHER_SUITE];
|
||||
//! ```
|
||||
//!
|
||||
//! # Requirements
|
||||
//!
|
||||
//! For DTLS 1.2, implementations must support:
|
||||
//!
|
||||
//! - **Cipher suites**: ECDHE_ECDSA with AES-128-GCM, AES-256-GCM, or CHACHA20_POLY1305
|
||||
//! - **Key exchange**: ECDHE with X25519, P-256, or P-384 curves
|
||||
//! - **Signatures**: ECDSA with P-256/SHA-256 or P-384/SHA-384
|
||||
//! - **Hash**: SHA-256 and SHA-384
|
||||
//! - **HMAC**: HMAC-SHA256 and HMAC-SHA384 (used for PRF, HKDF, and cookies)
|
||||
//!
|
||||
//! # Thread Safety
|
||||
//!
|
||||
//! All provider traits require `Send + Sync + UnwindSafe + RefUnwindSafe` to ensure
|
||||
//! safe usage across threads and panic boundaries.
|
||||
|
||||
use std::fmt::Debug;
|
||||
use std::panic::{RefUnwindSafe, UnwindSafe};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use crate::buffer::{Buf, TmpBuf};
|
||||
use crate::crypto::{Aad, Nonce};
|
||||
use crate::dtls12::message::Dtls12CipherSuite;
|
||||
use crate::types::{Dtls13CipherSuite, HashAlgorithm, NamedGroup, SignatureAlgorithm};
|
||||
use crate::{CertificateError, CryptoError};
|
||||
|
||||
/// OID for the P-256 elliptic curve (secp256r1 / prime256v1).
|
||||
#[cfg(feature = "_crypto-common")]
|
||||
pub const OID_P256: spki::ObjectIdentifier =
|
||||
spki::ObjectIdentifier::new_unwrap("1.2.840.10045.3.1.7");
|
||||
|
||||
/// OID for the P-384 elliptic curve (secp384r1).
|
||||
#[cfg(feature = "_crypto-common")]
|
||||
pub const OID_P384: spki::ObjectIdentifier = spki::ObjectIdentifier::new_unwrap("1.3.132.0.34");
|
||||
|
||||
// ============================================================================
|
||||
// Marker Trait
|
||||
// ============================================================================
|
||||
|
||||
/// Marker trait for types that are safe to use in crypto provider components.
|
||||
///
|
||||
/// This trait combines the common bounds required for crypto provider trait objects:
|
||||
/// - [`Send`] + [`Sync`]: Thread-safe
|
||||
/// - [`Debug`]: Support debugging
|
||||
/// - [`UnwindSafe`] + [`RefUnwindSafe`]: Panic-safe
|
||||
///
|
||||
/// This trait is automatically implemented for all types that satisfy these bounds.
|
||||
pub trait CryptoSafe: Send + Sync + Debug + UnwindSafe + RefUnwindSafe {}
|
||||
|
||||
/// Blanket implementation: any type satisfying the bounds implements [`CryptoSafe`].
|
||||
impl<T: Send + Sync + Debug + UnwindSafe + RefUnwindSafe> CryptoSafe for T {}
|
||||
|
||||
// ============================================================================
|
||||
// Instance Traits (Level 2 - created by factories)
|
||||
// ============================================================================
|
||||
|
||||
/// AEAD cipher for in-place encryption/decryption.
|
||||
pub trait Cipher: CryptoSafe {
|
||||
/// Encrypt plaintext in-place, appending authentication tag.
|
||||
fn encrypt(&mut self, plaintext: &mut Buf, aad: Aad, nonce: Nonce) -> Result<(), CryptoError>;
|
||||
|
||||
/// Decrypt ciphertext in-place, verifying and removing authentication tag.
|
||||
fn decrypt(
|
||||
&mut self,
|
||||
ciphertext: &mut TmpBuf,
|
||||
aad: Aad,
|
||||
nonce: Nonce,
|
||||
) -> Result<(), CryptoError>;
|
||||
}
|
||||
|
||||
/// Stateful hash context for incremental hashing.
|
||||
pub trait HashContext: CryptoSafe {
|
||||
/// Update the hash with new data.
|
||||
fn update(&mut self, data: &[u8]);
|
||||
|
||||
/// Clone the context and finalize it, writing the hash to `out`.
|
||||
/// The original context can continue to be updated.
|
||||
fn clone_and_finalize(&self, out: &mut Buf);
|
||||
}
|
||||
|
||||
/// Signing key for generating digital signatures.
|
||||
pub trait SigningKey: CryptoSafe {
|
||||
/// Sign data using the specified hash algorithm and return the signature.
|
||||
fn sign(
|
||||
&mut self,
|
||||
data: &[u8],
|
||||
hash_alg: HashAlgorithm,
|
||||
out: &mut Buf,
|
||||
) -> Result<(), CryptoError>;
|
||||
|
||||
/// Signature algorithm used by this key.
|
||||
fn algorithm(&self) -> SignatureAlgorithm;
|
||||
|
||||
/// Default hash algorithm for this key.
|
||||
fn hash_algorithm(&self) -> HashAlgorithm;
|
||||
|
||||
/// Hash algorithms this key can sign with.
|
||||
///
|
||||
/// Used during negotiation to intersect with the peer's offered
|
||||
/// algorithms. Backends that lock the hash at key-load time (e.g.
|
||||
/// aws-lc-rs) return only the locked hash; backends that support
|
||||
/// arbitrary prehash signing (e.g. RustCrypto) may return several.
|
||||
fn supported_hash_algorithms(&self) -> &[HashAlgorithm];
|
||||
}
|
||||
|
||||
/// Active key exchange instance (ephemeral keypair for one handshake).
|
||||
pub trait ActiveKeyExchange: CryptoSafe {
|
||||
/// Get the public key for this exchange.
|
||||
fn pub_key(&self) -> &[u8];
|
||||
|
||||
/// Complete exchange with peer's public key, returning shared secret.
|
||||
fn complete(self: Box<Self>, peer_pub: &[u8], out: &mut Buf) -> Result<(), CryptoError>;
|
||||
|
||||
/// Get the named group for this exchange.
|
||||
fn group(&self) -> NamedGroup;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Factory Traits (Level 1 - used by CryptoProvider)
|
||||
// ============================================================================
|
||||
|
||||
/// Cipher suite support (factory for Cipher instances).
|
||||
pub trait SupportedDtls12CipherSuite: CryptoSafe {
|
||||
/// The cipher suite this supports.
|
||||
fn suite(&self) -> Dtls12CipherSuite;
|
||||
|
||||
/// Hash algorithm used by this suite.
|
||||
fn hash_algorithm(&self) -> HashAlgorithm;
|
||||
|
||||
/// Key material lengths: (mac_key_len, enc_key_len, fixed_iv_len).
|
||||
fn key_lengths(&self) -> (usize, usize, usize);
|
||||
|
||||
/// Length in bytes of the per-record explicit nonce (carried in the record body).
|
||||
///
|
||||
/// AES-GCM suites carry an 8-byte explicit nonce; ChaCha20-Poly1305 carries none.
|
||||
fn explicit_nonce_len(&self) -> usize;
|
||||
|
||||
/// AEAD authentication tag length in bytes.
|
||||
fn tag_len(&self) -> usize;
|
||||
|
||||
/// Minimum length, in bytes, of a protected record's encrypted fragment.
|
||||
///
|
||||
/// For AEAD suites this equals explicit nonce + authentication tag; a CBC
|
||||
/// suite would override this to `IV + MAC + 1` (one padding byte). Records
|
||||
/// shorter than this cannot be valid regardless of cipher mode and are
|
||||
/// rejected at the record boundary.
|
||||
fn min_protected_fragment_len(&self) -> usize {
|
||||
self.explicit_nonce_len() + self.tag_len()
|
||||
}
|
||||
|
||||
/// Create a cipher instance with the given key.
|
||||
fn create_cipher(&self, key: &[u8]) -> Result<Box<dyn Cipher>, CryptoError>;
|
||||
}
|
||||
|
||||
/// Key exchange group support (factory for ActiveKeyExchange).
|
||||
pub trait SupportedKxGroup: CryptoSafe {
|
||||
/// Named group for this key exchange group.
|
||||
fn name(&self) -> NamedGroup;
|
||||
|
||||
/// Start a new key exchange, generating ephemeral keypair.
|
||||
/// The provided `buf` will be used to store the public key.
|
||||
fn start_exchange(&self, buf: Buf) -> Result<Box<dyn ActiveKeyExchange>, CryptoError>;
|
||||
}
|
||||
|
||||
/// Signature verification against certificates.
|
||||
pub trait SignatureVerifier: CryptoSafe {
|
||||
/// Verify a signature on data using a DER-encoded X.509 certificate.
|
||||
fn verify_signature(
|
||||
&self,
|
||||
cert_der: &[u8],
|
||||
data: &[u8],
|
||||
signature: &[u8],
|
||||
hash_alg: HashAlgorithm,
|
||||
sig_alg: SignatureAlgorithm,
|
||||
) -> Result<(), CryptoError>;
|
||||
}
|
||||
|
||||
/// Allow-list of supported (signature, hash, curve) combinations for
|
||||
/// DTLS 1.2 signature verification.
|
||||
///
|
||||
/// In DTLS 1.2 the hash algorithm and the certificate's curve are
|
||||
/// independent choices, so all cross-combinations are valid.
|
||||
///
|
||||
/// Signature | Hash | Curve
|
||||
/// -----------+---------+-----------
|
||||
/// ECDSA | SHA-256 | P-256
|
||||
/// ECDSA | SHA-256 | P-384
|
||||
/// ECDSA | SHA-384 | P-256
|
||||
/// ECDSA | SHA-384 | P-384
|
||||
const SUPPORTED_VERIFY_SCHEMES: &[(SignatureAlgorithm, HashAlgorithm, NamedGroup)] = &[
|
||||
(
|
||||
SignatureAlgorithm::ECDSA,
|
||||
HashAlgorithm::SHA256,
|
||||
NamedGroup::Secp256r1,
|
||||
),
|
||||
(
|
||||
SignatureAlgorithm::ECDSA,
|
||||
HashAlgorithm::SHA256,
|
||||
NamedGroup::Secp384r1,
|
||||
),
|
||||
(
|
||||
SignatureAlgorithm::ECDSA,
|
||||
HashAlgorithm::SHA384,
|
||||
NamedGroup::Secp256r1,
|
||||
),
|
||||
(
|
||||
SignatureAlgorithm::ECDSA,
|
||||
HashAlgorithm::SHA384,
|
||||
NamedGroup::Secp384r1,
|
||||
),
|
||||
];
|
||||
|
||||
/// Check that a (signature, hash, curve) combination is in the allow-list.
|
||||
pub fn check_verify_scheme(
|
||||
sig_alg: SignatureAlgorithm,
|
||||
hash_alg: HashAlgorithm,
|
||||
group: NamedGroup,
|
||||
) -> Result<(), CryptoError> {
|
||||
if SUPPORTED_VERIFY_SCHEMES
|
||||
.iter()
|
||||
.any(|(s, h, g)| *s == sig_alg && *h == hash_alg && *g == group)
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err(CryptoError::UnsupportedSignatureVerification {
|
||||
signature: sig_alg,
|
||||
hash: hash_alg,
|
||||
group,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract the EC curve ([`NamedGroup`]) from a DER-encoded X.509 certificate.
|
||||
///
|
||||
/// Used by DTLS 1.3 to verify that the [`SignatureScheme`](crate::types::SignatureScheme)
|
||||
/// in `CertificateVerify` is consistent with the peer's certificate key.
|
||||
#[cfg(feature = "_crypto-common")]
|
||||
pub fn cert_named_group(cert_der: &[u8]) -> Result<NamedGroup, CertificateError> {
|
||||
use der::Decode;
|
||||
use spki::ObjectIdentifier;
|
||||
use x509_cert::Certificate as X509Certificate;
|
||||
|
||||
let cert = X509Certificate::from_der(cert_der).map_err(|_| CertificateError::ParseFailed)?;
|
||||
let spki = &cert.tbs_certificate.subject_public_key_info;
|
||||
|
||||
let curve_oid: ObjectIdentifier = spki
|
||||
.algorithm
|
||||
.parameters
|
||||
.as_ref()
|
||||
.ok_or(CertificateError::MissingEcCurveParameter)?
|
||||
.decode_as()
|
||||
.map_err(|_| CertificateError::InvalidEcCurveParameter)?;
|
||||
|
||||
match curve_oid {
|
||||
OID_P256 => Ok(NamedGroup::Secp256r1),
|
||||
OID_P384 => Ok(NamedGroup::Secp384r1),
|
||||
_ => Err(CertificateError::UnsupportedEcCurve),
|
||||
}
|
||||
}
|
||||
|
||||
/// Private key parser (factory for SigningKey).
|
||||
pub trait KeyProvider: CryptoSafe {
|
||||
/// Parse and load a private key from DER/PEM bytes.
|
||||
fn load_private_key(&self, key_der: &[u8]) -> Result<Box<dyn SigningKey>, CryptoError>;
|
||||
}
|
||||
|
||||
/// Secure random number generator.
|
||||
pub trait SecureRandom: CryptoSafe {
|
||||
/// Fill buffer with cryptographically secure random bytes.
|
||||
fn fill(&self, buf: &mut [u8]) -> Result<(), CryptoError>;
|
||||
}
|
||||
|
||||
/// Hash provider (factory for HashContext).
|
||||
pub trait HashProvider: CryptoSafe {
|
||||
/// Create a new hash context for the specified algorithm.
|
||||
fn create_hash(&self, algorithm: HashAlgorithm) -> Box<dyn HashContext>;
|
||||
}
|
||||
|
||||
/// HMAC provider for computing HMAC signatures.
|
||||
pub trait HmacProvider: CryptoSafe {
|
||||
/// Compute HMAC-SHA256(key, data) and return the result.
|
||||
fn hmac_sha256(&self, key: &[u8], data: &[u8]) -> Result<[u8; 32], CryptoError> {
|
||||
let mut out = [0u8; 32];
|
||||
self.hmac(HashAlgorithm::SHA256, key, data, &mut out)?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Compute HMAC for the given hash algorithm, writing the result to `out`.
|
||||
///
|
||||
/// Returns the number of bytes written.
|
||||
fn hmac(
|
||||
&self,
|
||||
hash: HashAlgorithm,
|
||||
key: &[u8],
|
||||
data: &[u8],
|
||||
out: &mut [u8],
|
||||
) -> Result<usize, CryptoError>;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// DTLS 1.3 Factory Traits
|
||||
// ============================================================================
|
||||
|
||||
/// Cipher suite support for DTLS 1.3 (factory for Cipher instances).
|
||||
///
|
||||
/// Unlike DTLS 1.2 cipher suites, TLS 1.3 cipher suites only specify the
|
||||
/// AEAD algorithm and hash function. Key exchange is negotiated separately.
|
||||
pub trait SupportedDtls13CipherSuite: CryptoSafe {
|
||||
/// The cipher suite this supports.
|
||||
fn suite(&self) -> Dtls13CipherSuite;
|
||||
|
||||
/// Hash algorithm used by this suite.
|
||||
fn hash_algorithm(&self) -> HashAlgorithm;
|
||||
|
||||
/// AEAD key length in bytes.
|
||||
fn key_len(&self) -> usize;
|
||||
|
||||
/// AEAD nonce/IV length in bytes.
|
||||
fn iv_len(&self) -> usize;
|
||||
|
||||
/// AEAD tag length in bytes.
|
||||
fn tag_len(&self) -> usize;
|
||||
|
||||
/// Minimum length, in bytes, of a protected record's encrypted fragment.
|
||||
/// DTLS 1.3 has no explicit nonce in the record, so this equals
|
||||
/// [`Self::tag_len`]. Records shorter than this cannot hold a valid
|
||||
/// ciphertext + tag and are rejected at the record boundary.
|
||||
fn min_protected_fragment_len(&self) -> usize {
|
||||
self.tag_len()
|
||||
}
|
||||
|
||||
/// Create a cipher instance with the given key.
|
||||
fn create_cipher(&self, key: &[u8]) -> Result<Box<dyn Cipher>, CryptoError>;
|
||||
|
||||
/// Compute a mask for record number encryption (RFC 9147 Section 4.2.3).
|
||||
///
|
||||
/// The mask is XORed over the sequence number bytes in the header.
|
||||
/// `sample` is the first 16 bytes of the ciphertext.
|
||||
///
|
||||
/// For AES-based suites: `mask = AES-ECB(sn_key, sample)`.
|
||||
///
|
||||
/// For ChaCha20-based suites (RFC 9001 Section 5.4.4):
|
||||
/// `counter = sample[0..4]` (LE u32), `nonce = sample[4..16]`,
|
||||
/// `mask = ChaCha20(sn_key, counter, nonce, <zero bytes>)`.
|
||||
fn encrypt_sn(&self, sn_key: &[u8], sample: &[u8; 16]) -> [u8; 16];
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Core Provider Struct
|
||||
// ============================================================================
|
||||
|
||||
/// Cryptographic provider for DTLS operations.
|
||||
///
|
||||
/// This struct holds references to all cryptographic components needed
|
||||
/// for DTLS. Users can provide custom implementations of each component
|
||||
/// to replace the default aws-lc-rs-based provider.
|
||||
///
|
||||
/// # Version-Specific Components
|
||||
///
|
||||
/// Shared components like `kx_groups`, `signature_verification`, `key_provider`,
|
||||
/// `secure_random`, `hash_provider`, and `hmac_provider` are used by both versions.
|
||||
/// PRF (TLS 1.2) and HKDF (TLS 1.3) key derivation are built generically on top
|
||||
/// of `hmac_provider` — see the [`prf_hkdf`](super::prf_hkdf) module.
|
||||
///
|
||||
/// # Design
|
||||
///
|
||||
/// The provider uses static trait object references (`&'static dyn Trait`) which
|
||||
/// provides zero runtime overhead for trait dispatch. This design is inspired by
|
||||
/// rustls's CryptoProvider and ensures efficient crypto operations.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// # #[cfg(feature = "aws-lc-rs")]
|
||||
/// # fn main() {
|
||||
/// use dimpl::crypto::{CryptoProvider, aws_lc_rs};
|
||||
///
|
||||
/// // Use the default provider
|
||||
/// let provider = aws_lc_rs::default_provider();
|
||||
///
|
||||
/// // Or build a custom one (using defaults for demonstration)
|
||||
/// let custom_provider = CryptoProvider {
|
||||
/// // Shared components
|
||||
/// kx_groups: provider.kx_groups,
|
||||
/// signature_verification: provider.signature_verification,
|
||||
/// key_provider: provider.key_provider,
|
||||
/// secure_random: provider.secure_random,
|
||||
/// hash_provider: provider.hash_provider,
|
||||
/// hmac_provider: provider.hmac_provider,
|
||||
/// // DTLS 1.2 components
|
||||
/// cipher_suites: provider.cipher_suites,
|
||||
/// // DTLS 1.3 components
|
||||
/// dtls13_cipher_suites: provider.dtls13_cipher_suites,
|
||||
/// };
|
||||
/// # }
|
||||
/// # #[cfg(not(feature = "aws-lc-rs"))]
|
||||
/// # fn main() {}
|
||||
/// ```
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CryptoProvider {
|
||||
// =========================================================================
|
||||
// Shared components (used by both DTLS 1.2 and DTLS 1.3)
|
||||
// =========================================================================
|
||||
/// Supported key exchange groups (P-256, P-384, X25519).
|
||||
///
|
||||
/// Used for ECDHE key exchange in both DTLS versions.
|
||||
pub kx_groups: &'static [&'static dyn SupportedKxGroup],
|
||||
|
||||
/// Signature verification for certificates.
|
||||
pub signature_verification: &'static dyn SignatureVerifier,
|
||||
|
||||
/// Key provider for parsing private keys.
|
||||
pub key_provider: &'static dyn KeyProvider,
|
||||
|
||||
/// Secure random number generator.
|
||||
pub secure_random: &'static dyn SecureRandom,
|
||||
|
||||
/// Hash provider for handshake hashing.
|
||||
pub hash_provider: &'static dyn HashProvider,
|
||||
|
||||
/// HMAC provider for computing HMAC signatures.
|
||||
pub hmac_provider: &'static dyn HmacProvider,
|
||||
|
||||
// =========================================================================
|
||||
// DTLS 1.2 specific components
|
||||
// =========================================================================
|
||||
/// Supported DTLS 1.2 cipher suites (for negotiation).
|
||||
///
|
||||
/// These cipher suites bundle key exchange, authentication, encryption,
|
||||
/// and MAC algorithms together (e.g., TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256).
|
||||
pub cipher_suites: &'static [&'static dyn SupportedDtls12CipherSuite],
|
||||
|
||||
// =========================================================================
|
||||
// DTLS 1.3 specific components
|
||||
// =========================================================================
|
||||
/// Supported DTLS 1.3 cipher suites (for negotiation).
|
||||
///
|
||||
/// TLS 1.3 cipher suites only specify the AEAD and hash algorithms
|
||||
/// (e.g., TLS_AES_128_GCM_SHA256). Key exchange is negotiated separately.
|
||||
pub dtls13_cipher_suites: &'static [&'static dyn SupportedDtls13CipherSuite],
|
||||
}
|
||||
|
||||
/// Static storage for the default crypto provider.
|
||||
///
|
||||
/// This is set by `install_default()` and retrieved by `get_default()`.
|
||||
static DEFAULT: OnceLock<CryptoProvider> = OnceLock::new();
|
||||
|
||||
impl CryptoProvider {
|
||||
/// Install a default crypto provider for the process.
|
||||
///
|
||||
/// This sets a global default provider that will be used by
|
||||
/// [`Config::builder()`](crate::Config::builder)
|
||||
/// when no explicit provider is specified. This is useful for applications that want
|
||||
/// to override the default provider per process.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if called more than once. The default provider can only be set once per process.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// # #[cfg(feature = "aws-lc-rs")]
|
||||
/// # fn main() {
|
||||
/// use dimpl::crypto::{CryptoProvider, aws_lc_rs};
|
||||
///
|
||||
/// // Install a default provider (can only be called once per process)
|
||||
/// CryptoProvider::install_default(aws_lc_rs::default_provider());
|
||||
/// # }
|
||||
/// # #[cfg(not(feature = "aws-lc-rs"))]
|
||||
/// # fn main() {}
|
||||
/// ```
|
||||
pub fn install_default(provider: CryptoProvider) {
|
||||
DEFAULT
|
||||
.set(provider)
|
||||
.expect("CryptoProvider::install_default() called more than once");
|
||||
}
|
||||
|
||||
/// Get the default crypto provider, if one has been installed.
|
||||
///
|
||||
/// Returns `Some(&provider)` if a default provider has been installed via
|
||||
/// [`Self::install_default()`], or `None` if no default provider is available.
|
||||
///
|
||||
/// This method does not panic. Use [`Config::builder()`](crate::Config::builder) which will handle
|
||||
/// the fallback logic automatically.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use dimpl::crypto::CryptoProvider;
|
||||
///
|
||||
/// if let Some(provider) = CryptoProvider::get_default() {
|
||||
/// // Use the installed default provider
|
||||
/// }
|
||||
/// ```
|
||||
pub fn get_default() -> Option<&'static CryptoProvider> {
|
||||
DEFAULT.get()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "rcgen")]
|
||||
fn cert_named_group_p256() {
|
||||
use rcgen::{CertificateParams, KeyPair, PKCS_ECDSA_P256_SHA256};
|
||||
|
||||
let key_pair = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap();
|
||||
let params = CertificateParams::new(Vec::<String>::new()).unwrap();
|
||||
let cert = params.self_signed(&key_pair).unwrap();
|
||||
|
||||
let group = cert_named_group(cert.der()).unwrap();
|
||||
assert_eq!(group, NamedGroup::Secp256r1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "rcgen")]
|
||||
fn cert_named_group_p384() {
|
||||
use rcgen::{CertificateParams, KeyPair, PKCS_ECDSA_P384_SHA384};
|
||||
|
||||
let key_pair = KeyPair::generate_for(&PKCS_ECDSA_P384_SHA384).unwrap();
|
||||
let params = CertificateParams::new(Vec::<String>::new()).unwrap();
|
||||
let cert = params.self_signed(&key_pair).unwrap();
|
||||
|
||||
let group = cert_named_group(cert.der()).unwrap();
|
||||
assert_eq!(group, NamedGroup::Secp384r1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "rcgen")]
|
||||
fn cert_named_group_invalid_der() {
|
||||
let result = cert_named_group(&[0x00, 0x01, 0x02]);
|
||||
assert!(result.is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,482 @@
|
||||
//! Cipher suite implementations using RustCrypto.
|
||||
use aes_gcm::aead::AeadInPlace;
|
||||
use aes_gcm::aes::cipher::{BlockEncrypt, KeyInit as BlockKeyInit};
|
||||
use aes_gcm::aes::{Aes128, Aes256};
|
||||
use aes_gcm::{Aes128Gcm, Aes256Gcm, Key};
|
||||
use chacha20::cipher::{KeyIvInit, StreamCipher, StreamCipherSeek};
|
||||
use chacha20poly1305::ChaCha20Poly1305 as ChaCha20Poly1305Aead;
|
||||
|
||||
use super::super::{Cipher, SupportedDtls12CipherSuite, SupportedDtls13CipherSuite};
|
||||
use crate::buffer::{Buf, TmpBuf};
|
||||
use crate::crypto::{Aad, Nonce};
|
||||
use crate::dtls12::message::Dtls12CipherSuite;
|
||||
use crate::error::bounded_error_len;
|
||||
use crate::types::{Dtls13CipherSuite, HashAlgorithm};
|
||||
use crate::{CryptoError, CryptoOperation};
|
||||
|
||||
/// AES-GCM cipher implementation using RustCrypto.
|
||||
enum AesGcm {
|
||||
Aes128(Box<Aes128Gcm>),
|
||||
Aes256(Box<Aes256Gcm>),
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for AesGcm {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
AesGcm::Aes128(_) => f.debug_tuple("AesGcm::Aes128").finish(),
|
||||
AesGcm::Aes256(_) => f.debug_tuple("AesGcm::Aes256").finish(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AesGcm {
|
||||
fn new(key: &[u8]) -> Result<Self, CryptoError> {
|
||||
match key.len() {
|
||||
16 => {
|
||||
let key = Key::<Aes128Gcm>::from_slice(key);
|
||||
Ok(AesGcm::Aes128(Box::new(Aes128Gcm::new(key))))
|
||||
}
|
||||
32 => {
|
||||
let key = Key::<Aes256Gcm>::from_slice(key);
|
||||
Ok(AesGcm::Aes256(Box::new(Aes256Gcm::new(key))))
|
||||
}
|
||||
_ => Err(CryptoError::InvalidAesGcmKeySize {
|
||||
actual: bounded_error_len(key.len()),
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Cipher for AesGcm {
|
||||
fn encrypt(&mut self, data: &mut Buf, aad: Aad, nonce: Nonce) -> Result<(), CryptoError> {
|
||||
// Create nonce from the provided nonce bytes
|
||||
let nonce_array: [u8; 12] = nonce[..12]
|
||||
.try_into()
|
||||
.map_err(|_| CryptoError::InvalidNonce)?;
|
||||
|
||||
match self {
|
||||
AesGcm::Aes128(cipher) => {
|
||||
// Create nonce from fixed-size array - AesNonce is GenericArray<u8, U12>
|
||||
use generic_array::{GenericArray, typenum::U12};
|
||||
let aes_nonce = GenericArray::<u8, U12>::clone_from_slice(&nonce_array);
|
||||
cipher
|
||||
.encrypt_in_place(&aes_nonce, &aad, data)
|
||||
.map_err(|_| CryptoError::OperationFailed(CryptoOperation::Encrypt))?;
|
||||
}
|
||||
AesGcm::Aes256(cipher) => {
|
||||
// Create nonce from fixed-size array - AesNonce is GenericArray<u8, U12>
|
||||
use generic_array::{GenericArray, typenum::U12};
|
||||
let aes_nonce = GenericArray::<u8, U12>::clone_from_slice(&nonce_array);
|
||||
cipher
|
||||
.encrypt_in_place(&aes_nonce, &aad, data)
|
||||
.map_err(|_| CryptoError::OperationFailed(CryptoOperation::Encrypt))?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn decrypt(
|
||||
&mut self,
|
||||
ciphertext: &mut TmpBuf,
|
||||
aad: Aad,
|
||||
nonce: Nonce,
|
||||
) -> Result<(), CryptoError> {
|
||||
if ciphertext.len() < 16 {
|
||||
return Err(CryptoError::CiphertextTooShort {
|
||||
minimum: 16,
|
||||
actual: ciphertext.len() as u8,
|
||||
});
|
||||
}
|
||||
|
||||
// Create nonce from the provided nonce bytes
|
||||
let nonce_array: [u8; 12] = nonce[..12]
|
||||
.try_into()
|
||||
.map_err(|_| CryptoError::InvalidNonce)?;
|
||||
|
||||
match self {
|
||||
AesGcm::Aes128(cipher) => {
|
||||
// Create nonce from fixed-size array - AesNonce is GenericArray<u8, U12>
|
||||
use generic_array::{GenericArray, typenum::U12};
|
||||
let aes_nonce = GenericArray::<u8, U12>::clone_from_slice(&nonce_array);
|
||||
cipher
|
||||
.decrypt_in_place(&aes_nonce, &aad, ciphertext)
|
||||
.map_err(|_| CryptoError::OperationFailed(CryptoOperation::Decrypt))?;
|
||||
}
|
||||
AesGcm::Aes256(cipher) => {
|
||||
// Create nonce from fixed-size array - AesNonce is GenericArray<u8, U12>
|
||||
use generic_array::{GenericArray, typenum::U12};
|
||||
let aes_nonce = GenericArray::<u8, U12>::clone_from_slice(&nonce_array);
|
||||
cipher
|
||||
.decrypt_in_place(&aes_nonce, &aad, ciphertext)
|
||||
.map_err(|_| CryptoError::OperationFailed(CryptoOperation::Decrypt))?;
|
||||
}
|
||||
}
|
||||
|
||||
// decrypt_in_place already removes the tag and shortens the buffer
|
||||
// No need to truncate further
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// ChaCha20-Poly1305 cipher implementation using RustCrypto.
|
||||
struct ChaCha20Poly1305Cipher {
|
||||
cipher: Box<ChaCha20Poly1305Aead>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ChaCha20Poly1305Cipher {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("ChaCha20Poly1305Cipher")
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl ChaCha20Poly1305Cipher {
|
||||
fn new(key: &[u8]) -> Result<Self, CryptoError> {
|
||||
use chacha20poly1305::KeyInit;
|
||||
if key.len() != 32 {
|
||||
return Err(CryptoError::InvalidChacha20Poly1305KeySize {
|
||||
actual: bounded_error_len(key.len()),
|
||||
});
|
||||
}
|
||||
let key = chacha20poly1305::Key::from_slice(key);
|
||||
Ok(ChaCha20Poly1305Cipher {
|
||||
cipher: Box::new(ChaCha20Poly1305Aead::new(key)),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Cipher for ChaCha20Poly1305Cipher {
|
||||
fn encrypt(&mut self, data: &mut Buf, aad: Aad, nonce: Nonce) -> Result<(), CryptoError> {
|
||||
let nonce_array: [u8; 12] = nonce[..12]
|
||||
.try_into()
|
||||
.map_err(|_| CryptoError::InvalidNonce)?;
|
||||
|
||||
use generic_array::{GenericArray, typenum::U12};
|
||||
let chacha_nonce = GenericArray::<u8, U12>::clone_from_slice(&nonce_array);
|
||||
self.cipher
|
||||
.encrypt_in_place(&chacha_nonce, &aad, data)
|
||||
.map_err(|_| CryptoError::OperationFailed(CryptoOperation::Encrypt))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn decrypt(
|
||||
&mut self,
|
||||
ciphertext: &mut TmpBuf,
|
||||
aad: Aad,
|
||||
nonce: Nonce,
|
||||
) -> Result<(), CryptoError> {
|
||||
if ciphertext.len() < 16 {
|
||||
return Err(CryptoError::CiphertextTooShort {
|
||||
minimum: 16,
|
||||
actual: ciphertext.len() as u8,
|
||||
});
|
||||
}
|
||||
|
||||
let nonce_array: [u8; 12] = nonce[..12]
|
||||
.try_into()
|
||||
.map_err(|_| CryptoError::InvalidNonce)?;
|
||||
|
||||
use generic_array::{GenericArray, typenum::U12};
|
||||
let chacha_nonce = GenericArray::<u8, U12>::clone_from_slice(&nonce_array);
|
||||
self.cipher
|
||||
.decrypt_in_place(&chacha_nonce, &aad, ciphertext)
|
||||
.map_err(|_| CryptoError::OperationFailed(CryptoOperation::Decrypt))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 cipher suite.
|
||||
#[derive(Debug)]
|
||||
struct Aes128GcmSha256;
|
||||
|
||||
impl SupportedDtls12CipherSuite for Aes128GcmSha256 {
|
||||
fn suite(&self) -> Dtls12CipherSuite {
|
||||
Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256
|
||||
}
|
||||
|
||||
fn hash_algorithm(&self) -> HashAlgorithm {
|
||||
HashAlgorithm::SHA256
|
||||
}
|
||||
|
||||
fn key_lengths(&self) -> (usize, usize, usize) {
|
||||
(0, 16, 4) // (mac_key_len, enc_key_len, fixed_iv_len)
|
||||
}
|
||||
|
||||
fn explicit_nonce_len(&self) -> usize {
|
||||
8
|
||||
}
|
||||
|
||||
fn tag_len(&self) -> usize {
|
||||
16
|
||||
}
|
||||
|
||||
fn create_cipher(&self, key: &[u8]) -> Result<Box<dyn Cipher>, CryptoError> {
|
||||
Ok(Box::new(AesGcm::new(key)?))
|
||||
}
|
||||
}
|
||||
|
||||
/// TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 cipher suite.
|
||||
#[derive(Debug)]
|
||||
struct Aes256GcmSha384;
|
||||
|
||||
impl SupportedDtls12CipherSuite for Aes256GcmSha384 {
|
||||
fn suite(&self) -> Dtls12CipherSuite {
|
||||
Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384
|
||||
}
|
||||
|
||||
fn hash_algorithm(&self) -> HashAlgorithm {
|
||||
HashAlgorithm::SHA384
|
||||
}
|
||||
|
||||
fn key_lengths(&self) -> (usize, usize, usize) {
|
||||
(0, 32, 4) // (mac_key_len, enc_key_len, fixed_iv_len)
|
||||
}
|
||||
|
||||
fn explicit_nonce_len(&self) -> usize {
|
||||
8
|
||||
}
|
||||
|
||||
fn tag_len(&self) -> usize {
|
||||
16
|
||||
}
|
||||
|
||||
fn create_cipher(&self, key: &[u8]) -> Result<Box<dyn Cipher>, CryptoError> {
|
||||
Ok(Box::new(AesGcm::new(key)?))
|
||||
}
|
||||
}
|
||||
|
||||
/// TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 cipher suite.
|
||||
#[derive(Debug)]
|
||||
struct ChaCha20Poly1305Sha256;
|
||||
|
||||
impl SupportedDtls12CipherSuite for ChaCha20Poly1305Sha256 {
|
||||
fn suite(&self) -> Dtls12CipherSuite {
|
||||
Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256
|
||||
}
|
||||
|
||||
fn hash_algorithm(&self) -> HashAlgorithm {
|
||||
HashAlgorithm::SHA256
|
||||
}
|
||||
|
||||
fn key_lengths(&self) -> (usize, usize, usize) {
|
||||
(0, 32, 12) // (mac_key_len, enc_key_len, fixed_iv_len)
|
||||
}
|
||||
|
||||
fn explicit_nonce_len(&self) -> usize {
|
||||
0
|
||||
}
|
||||
|
||||
fn tag_len(&self) -> usize {
|
||||
16
|
||||
}
|
||||
|
||||
fn create_cipher(&self, key: &[u8]) -> Result<Box<dyn Cipher>, CryptoError> {
|
||||
Ok(Box::new(ChaCha20Poly1305Cipher::new(key)?))
|
||||
}
|
||||
}
|
||||
|
||||
/// TLS_PSK_WITH_AES_128_CCM_8 cipher suite.
|
||||
#[derive(Debug)]
|
||||
struct PskAes128Ccm8;
|
||||
|
||||
impl SupportedDtls12CipherSuite for PskAes128Ccm8 {
|
||||
fn suite(&self) -> Dtls12CipherSuite {
|
||||
Dtls12CipherSuite::PSK_AES128_CCM_8
|
||||
}
|
||||
|
||||
fn hash_algorithm(&self) -> HashAlgorithm {
|
||||
HashAlgorithm::SHA256
|
||||
}
|
||||
|
||||
fn key_lengths(&self) -> (usize, usize, usize) {
|
||||
(0, 16, 4) // (mac_key_len, enc_key_len, fixed_iv_len)
|
||||
}
|
||||
|
||||
fn explicit_nonce_len(&self) -> usize {
|
||||
8
|
||||
}
|
||||
|
||||
fn tag_len(&self) -> usize {
|
||||
8
|
||||
}
|
||||
|
||||
fn create_cipher(&self, key: &[u8]) -> Result<Box<dyn Cipher>, CryptoError> {
|
||||
Ok(Box::new(crate::crypto::ccm_cipher::AesCcm8Cipher::new(
|
||||
key,
|
||||
)?))
|
||||
}
|
||||
}
|
||||
|
||||
/// Static instances of supported DTLS 1.2 cipher suites.
|
||||
static AES_128_GCM_SHA256: Aes128GcmSha256 = Aes128GcmSha256;
|
||||
static AES_256_GCM_SHA384: Aes256GcmSha384 = Aes256GcmSha384;
|
||||
static CHACHA20_POLY1305_SHA256: ChaCha20Poly1305Sha256 = ChaCha20Poly1305Sha256;
|
||||
static PSK_AES_128_CCM_8: PskAes128Ccm8 = PskAes128Ccm8;
|
||||
|
||||
/// All supported DTLS 1.2 cipher suites.
|
||||
pub(super) static ALL_CIPHER_SUITES: &[&dyn SupportedDtls12CipherSuite] = &[
|
||||
&AES_128_GCM_SHA256,
|
||||
&AES_256_GCM_SHA384,
|
||||
&CHACHA20_POLY1305_SHA256,
|
||||
&PSK_AES_128_CCM_8,
|
||||
];
|
||||
|
||||
// ============================================================================
|
||||
// DTLS 1.3 Cipher Suites
|
||||
// ============================================================================
|
||||
|
||||
/// TLS_AES_128_GCM_SHA256 cipher suite (TLS 1.3 / DTLS 1.3).
|
||||
#[derive(Debug)]
|
||||
struct Tls13Aes128GcmSha256;
|
||||
|
||||
impl SupportedDtls13CipherSuite for Tls13Aes128GcmSha256 {
|
||||
fn suite(&self) -> Dtls13CipherSuite {
|
||||
Dtls13CipherSuite::AES_128_GCM_SHA256
|
||||
}
|
||||
|
||||
fn hash_algorithm(&self) -> HashAlgorithm {
|
||||
HashAlgorithm::SHA256
|
||||
}
|
||||
|
||||
fn key_len(&self) -> usize {
|
||||
16 // AES-128
|
||||
}
|
||||
|
||||
fn iv_len(&self) -> usize {
|
||||
12 // GCM IV
|
||||
}
|
||||
|
||||
fn tag_len(&self) -> usize {
|
||||
16 // GCM tag
|
||||
}
|
||||
|
||||
fn create_cipher(&self, key: &[u8]) -> Result<Box<dyn Cipher>, CryptoError> {
|
||||
Ok(Box::new(AesGcm::new(key)?))
|
||||
}
|
||||
|
||||
fn encrypt_sn(&self, sn_key: &[u8], sample: &[u8; 16]) -> [u8; 16] {
|
||||
// unwrap: sn_key length matches AES-128 key size
|
||||
let cipher = Aes128::new_from_slice(sn_key).unwrap();
|
||||
let mut block = aes_gcm::aes::Block::clone_from_slice(sample);
|
||||
cipher.encrypt_block(&mut block);
|
||||
block.into()
|
||||
}
|
||||
}
|
||||
|
||||
/// TLS_AES_256_GCM_SHA384 cipher suite (TLS 1.3 / DTLS 1.3).
|
||||
#[derive(Debug)]
|
||||
struct Tls13Aes256GcmSha384;
|
||||
|
||||
impl SupportedDtls13CipherSuite for Tls13Aes256GcmSha384 {
|
||||
fn suite(&self) -> Dtls13CipherSuite {
|
||||
Dtls13CipherSuite::AES_256_GCM_SHA384
|
||||
}
|
||||
|
||||
fn hash_algorithm(&self) -> HashAlgorithm {
|
||||
HashAlgorithm::SHA384
|
||||
}
|
||||
|
||||
fn key_len(&self) -> usize {
|
||||
32 // AES-256
|
||||
}
|
||||
|
||||
fn iv_len(&self) -> usize {
|
||||
12 // GCM IV
|
||||
}
|
||||
|
||||
fn tag_len(&self) -> usize {
|
||||
16 // GCM tag
|
||||
}
|
||||
|
||||
fn create_cipher(&self, key: &[u8]) -> Result<Box<dyn Cipher>, CryptoError> {
|
||||
Ok(Box::new(AesGcm::new(key)?))
|
||||
}
|
||||
|
||||
fn encrypt_sn(&self, sn_key: &[u8], sample: &[u8; 16]) -> [u8; 16] {
|
||||
// unwrap: sn_key length matches AES-256 key size
|
||||
let cipher = Aes256::new_from_slice(sn_key).unwrap();
|
||||
let mut block = aes_gcm::aes::Block::clone_from_slice(sample);
|
||||
cipher.encrypt_block(&mut block);
|
||||
block.into()
|
||||
}
|
||||
}
|
||||
|
||||
/// TLS_CHACHA20_POLY1305_SHA256 cipher suite (TLS 1.3 / DTLS 1.3).
|
||||
#[derive(Debug)]
|
||||
struct Tls13ChaCha20Poly1305Sha256;
|
||||
|
||||
impl SupportedDtls13CipherSuite for Tls13ChaCha20Poly1305Sha256 {
|
||||
fn suite(&self) -> Dtls13CipherSuite {
|
||||
Dtls13CipherSuite::CHACHA20_POLY1305_SHA256
|
||||
}
|
||||
|
||||
fn hash_algorithm(&self) -> HashAlgorithm {
|
||||
HashAlgorithm::SHA256
|
||||
}
|
||||
|
||||
fn key_len(&self) -> usize {
|
||||
32 // ChaCha20 key
|
||||
}
|
||||
|
||||
fn iv_len(&self) -> usize {
|
||||
12 // Poly1305 nonce
|
||||
}
|
||||
|
||||
fn tag_len(&self) -> usize {
|
||||
16 // Poly1305 tag
|
||||
}
|
||||
|
||||
fn create_cipher(&self, key: &[u8]) -> Result<Box<dyn Cipher>, CryptoError> {
|
||||
Ok(Box::new(ChaCha20Poly1305Cipher::new(key)?))
|
||||
}
|
||||
|
||||
fn encrypt_sn(&self, sn_key: &[u8], sample: &[u8; 16]) -> [u8; 16] {
|
||||
// RFC 9001 Section 5.4.4: ChaCha20 header protection
|
||||
// counter = sample[0..4] (LE u32), nonce = sample[4..16]
|
||||
// mask = first 5 bytes of ChaCha20 keystream at given counter
|
||||
let counter = u32::from_le_bytes(sample[0..4].try_into().unwrap());
|
||||
let nonce: [u8; 12] = sample[4..16].try_into().unwrap();
|
||||
|
||||
let key = chacha20::Key::from_slice(sn_key);
|
||||
let nonce = chacha20::Nonce::from_slice(&nonce);
|
||||
|
||||
let mut cipher = chacha20::ChaCha20::new(key, nonce);
|
||||
// Seek to the correct block counter position (each block = 64 bytes)
|
||||
cipher.seek(counter as u64 * 64);
|
||||
|
||||
let mut out = [0u8; 16];
|
||||
cipher.apply_keystream(&mut out);
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// Static instances of supported DTLS 1.3 cipher suites.
|
||||
static TLS13_AES_128_GCM_SHA256: Tls13Aes128GcmSha256 = Tls13Aes128GcmSha256;
|
||||
static TLS13_AES_256_GCM_SHA384: Tls13Aes256GcmSha384 = Tls13Aes256GcmSha384;
|
||||
static TLS13_CHACHA20_POLY1305_SHA256: Tls13ChaCha20Poly1305Sha256 = Tls13ChaCha20Poly1305Sha256;
|
||||
|
||||
/// All supported DTLS 1.3 cipher suites.
|
||||
pub(super) static ALL_DTLS13_CIPHER_SUITES: &[&dyn SupportedDtls13CipherSuite] = &[
|
||||
&TLS13_AES_128_GCM_SHA256,
|
||||
&TLS13_AES_256_GCM_SHA384,
|
||||
&TLS13_CHACHA20_POLY1305_SHA256,
|
||||
];
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn chacha20_poly1305_key_len_validation() {
|
||||
// incorrect length (should be 32)
|
||||
let result = ChaCha20Poly1305Cipher::new(&[0, 1, 2, 3, 4, 5]);
|
||||
assert_eq!(
|
||||
CryptoError::InvalidChacha20Poly1305KeySize { actual: 6 },
|
||||
result.unwrap_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
//! Hash implementations using RustCrypto.
|
||||
|
||||
use sha2::{Digest, Sha256, Sha384};
|
||||
|
||||
use super::super::{HashContext, HashProvider};
|
||||
use crate::buffer::Buf;
|
||||
use crate::types::HashAlgorithm;
|
||||
|
||||
/// Hash context implementation using RustCrypto.
|
||||
enum RustCryptoHashContext {
|
||||
Sha256(Sha256),
|
||||
Sha384(Sha384),
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for RustCryptoHashContext {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
RustCryptoHashContext::Sha256(_) => {
|
||||
f.debug_tuple("RustCryptoHashContext::Sha256").finish()
|
||||
}
|
||||
RustCryptoHashContext::Sha384(_) => {
|
||||
f.debug_tuple("RustCryptoHashContext::Sha384").finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HashContext for RustCryptoHashContext {
|
||||
fn update(&mut self, data: &[u8]) {
|
||||
match self {
|
||||
RustCryptoHashContext::Sha256(ctx) => ctx.update(data),
|
||||
RustCryptoHashContext::Sha384(ctx) => ctx.update(data),
|
||||
}
|
||||
}
|
||||
|
||||
fn clone_and_finalize(&self, out: &mut Buf) {
|
||||
match self {
|
||||
RustCryptoHashContext::Sha256(ctx) => {
|
||||
let cloned = ctx.clone();
|
||||
let digest = cloned.finalize();
|
||||
out.clear();
|
||||
out.extend_from_slice(&digest);
|
||||
}
|
||||
RustCryptoHashContext::Sha384(ctx) => {
|
||||
let cloned = ctx.clone();
|
||||
let digest = cloned.finalize();
|
||||
out.clear();
|
||||
out.extend_from_slice(&digest);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Hash provider implementation.
|
||||
#[derive(Debug)]
|
||||
pub(super) struct RustCryptoHashProvider;
|
||||
|
||||
impl HashProvider for RustCryptoHashProvider {
|
||||
fn create_hash(&self, algorithm: HashAlgorithm) -> Box<dyn HashContext> {
|
||||
match algorithm {
|
||||
HashAlgorithm::SHA256 => Box::new(RustCryptoHashContext::Sha256(Sha256::new())),
|
||||
HashAlgorithm::SHA384 => Box::new(RustCryptoHashContext::Sha384(Sha384::new())),
|
||||
_ => panic!("Unsupported hash algorithm: {:?}", algorithm),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Static instance of the hash provider.
|
||||
pub(super) static HASH_PROVIDER: RustCryptoHashProvider = RustCryptoHashProvider;
|
||||
@@ -0,0 +1,47 @@
|
||||
//! HMAC implementation using RustCrypto.
|
||||
|
||||
use hmac::{Hmac, Mac};
|
||||
use sha2::{Sha256, Sha384};
|
||||
|
||||
use super::super::HmacProvider;
|
||||
use crate::types::HashAlgorithm;
|
||||
use crate::{CryptoError, CryptoOperation};
|
||||
|
||||
/// HMAC provider implementation.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct RustCryptoHmacProvider;
|
||||
|
||||
impl HmacProvider for RustCryptoHmacProvider {
|
||||
fn hmac(
|
||||
&self,
|
||||
hash: HashAlgorithm,
|
||||
key: &[u8],
|
||||
data: &[u8],
|
||||
out: &mut [u8],
|
||||
) -> Result<usize, CryptoError> {
|
||||
match hash {
|
||||
HashAlgorithm::SHA256 => {
|
||||
let mut mac = Hmac::<Sha256>::new_from_slice(key)
|
||||
.map_err(|_| CryptoError::OperationFailed(CryptoOperation::ComputeHmac))?;
|
||||
mac.update(data);
|
||||
let result = mac.finalize().into_bytes();
|
||||
let len = result.len();
|
||||
out[..len].copy_from_slice(&result);
|
||||
Ok(len)
|
||||
}
|
||||
HashAlgorithm::SHA384 => {
|
||||
let mut mac = Hmac::<Sha384>::new_from_slice(key)
|
||||
.map_err(|_| CryptoError::OperationFailed(CryptoOperation::ComputeHmac))?;
|
||||
mac.update(data);
|
||||
let result = mac.finalize().into_bytes();
|
||||
let len = result.len();
|
||||
out[..len].copy_from_slice(&result);
|
||||
Ok(len)
|
||||
}
|
||||
_ => Err(CryptoError::UnsupportedHmacHash(hash)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Static instance of the HMAC provider.
|
||||
pub(crate) static HMAC_PROVIDER: RustCryptoHmacProvider = RustCryptoHmacProvider;
|
||||
@@ -0,0 +1,209 @@
|
||||
//! Key exchange group implementations using RustCrypto.
|
||||
|
||||
use p256::{PublicKey as P256PublicKey, ecdh::EphemeralSecret};
|
||||
use p384::{PublicKey as P384PublicKey, ecdh::EphemeralSecret as P384EphemeralSecret};
|
||||
|
||||
use super::super::{ActiveKeyExchange, SupportedKxGroup};
|
||||
use crate::CryptoError;
|
||||
use crate::buffer::Buf;
|
||||
use crate::types::NamedGroup;
|
||||
|
||||
/// ECDHE key exchange implementation.
|
||||
enum EcdhKeyExchange {
|
||||
X25519 {
|
||||
secret: x25519_dalek::EphemeralSecret,
|
||||
public_key: Buf,
|
||||
},
|
||||
P256 {
|
||||
secret: EphemeralSecret,
|
||||
public_key: Buf,
|
||||
},
|
||||
P384 {
|
||||
secret: P384EphemeralSecret,
|
||||
public_key: Buf,
|
||||
},
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for EcdhKeyExchange {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
EcdhKeyExchange::X25519 { public_key, .. } => f
|
||||
.debug_struct("EcdhKeyExchange::X25519")
|
||||
.field("public_key_len", &public_key.len())
|
||||
.finish_non_exhaustive(),
|
||||
EcdhKeyExchange::P256 { public_key, .. } => f
|
||||
.debug_struct("EcdhKeyExchange::P256")
|
||||
.field("public_key_len", &public_key.len())
|
||||
.finish_non_exhaustive(),
|
||||
EcdhKeyExchange::P384 { public_key, .. } => f
|
||||
.debug_struct("EcdhKeyExchange::P384")
|
||||
.field("public_key_len", &public_key.len())
|
||||
.finish_non_exhaustive(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl EcdhKeyExchange {
|
||||
fn new(group: NamedGroup, mut buf: Buf) -> Result<Self, CryptoError> {
|
||||
match group {
|
||||
NamedGroup::X25519 => {
|
||||
use rand_core::OsRng;
|
||||
let secret = x25519_dalek::EphemeralSecret::random_from_rng(OsRng);
|
||||
let public_key_obj = x25519_dalek::PublicKey::from(&secret);
|
||||
buf.clear();
|
||||
buf.extend_from_slice(public_key_obj.as_bytes());
|
||||
Ok(EcdhKeyExchange::X25519 {
|
||||
secret,
|
||||
public_key: buf,
|
||||
})
|
||||
}
|
||||
NamedGroup::Secp256r1 => {
|
||||
use rand_core::OsRng;
|
||||
let secret = EphemeralSecret::random(&mut OsRng);
|
||||
let public_key_obj = P256PublicKey::from(&secret);
|
||||
let public_key_bytes = public_key_obj.to_sec1_bytes();
|
||||
buf.clear();
|
||||
buf.extend_from_slice(&public_key_bytes);
|
||||
Ok(EcdhKeyExchange::P256 {
|
||||
secret,
|
||||
public_key: buf,
|
||||
})
|
||||
}
|
||||
NamedGroup::Secp384r1 => {
|
||||
use rand_core::OsRng;
|
||||
let secret = P384EphemeralSecret::random(&mut OsRng);
|
||||
let public_key_obj = P384PublicKey::from(&secret);
|
||||
let public_key_bytes = public_key_obj.to_sec1_bytes();
|
||||
buf.clear();
|
||||
buf.extend_from_slice(&public_key_bytes);
|
||||
Ok(EcdhKeyExchange::P384 {
|
||||
secret,
|
||||
public_key: buf,
|
||||
})
|
||||
}
|
||||
_ => Err(CryptoError::UnsupportedKeyExchangeGroup(group)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ActiveKeyExchange for EcdhKeyExchange {
|
||||
fn pub_key(&self) -> &[u8] {
|
||||
match self {
|
||||
EcdhKeyExchange::X25519 { public_key, .. } => public_key,
|
||||
EcdhKeyExchange::P256 { public_key, .. } => public_key,
|
||||
EcdhKeyExchange::P384 { public_key, .. } => public_key,
|
||||
}
|
||||
}
|
||||
|
||||
fn complete(self: Box<Self>, peer_pub: &[u8], out: &mut Buf) -> Result<(), CryptoError> {
|
||||
match *self {
|
||||
EcdhKeyExchange::X25519 { secret, .. } => {
|
||||
let peer_bytes: [u8; 32] = peer_pub
|
||||
.try_into()
|
||||
.map_err(|_| CryptoError::InvalidPublicKey(NamedGroup::X25519))?;
|
||||
let peer_key = x25519_dalek::PublicKey::from(peer_bytes);
|
||||
let shared_secret = secret.diffie_hellman(&peer_key);
|
||||
// RFC 7748 §6.1: check the shared secret is not zero (low-order point)
|
||||
if !shared_secret.was_contributory() {
|
||||
return Err(CryptoError::InvalidPublicKey(NamedGroup::X25519));
|
||||
}
|
||||
out.clear();
|
||||
out.extend_from_slice(shared_secret.as_bytes());
|
||||
Ok(())
|
||||
}
|
||||
EcdhKeyExchange::P256 { secret, .. } => {
|
||||
let peer_key = P256PublicKey::from_sec1_bytes(peer_pub)
|
||||
.map_err(|_| CryptoError::InvalidPublicKey(NamedGroup::Secp256r1))?;
|
||||
let shared_secret = secret.diffie_hellman(&peer_key);
|
||||
out.clear();
|
||||
out.extend_from_slice(shared_secret.raw_secret_bytes().as_slice());
|
||||
Ok(())
|
||||
}
|
||||
EcdhKeyExchange::P384 { secret, .. } => {
|
||||
let peer_key = P384PublicKey::from_sec1_bytes(peer_pub)
|
||||
.map_err(|_| CryptoError::InvalidPublicKey(NamedGroup::Secp384r1))?;
|
||||
let shared_secret = secret.diffie_hellman(&peer_key);
|
||||
out.clear();
|
||||
out.extend_from_slice(shared_secret.raw_secret_bytes().as_slice());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn group(&self) -> NamedGroup {
|
||||
match self {
|
||||
EcdhKeyExchange::X25519 { .. } => NamedGroup::X25519,
|
||||
EcdhKeyExchange::P256 { .. } => NamedGroup::Secp256r1,
|
||||
EcdhKeyExchange::P384 { .. } => NamedGroup::Secp384r1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// X25519 key exchange group.
|
||||
#[derive(Debug)]
|
||||
struct X25519Kx;
|
||||
|
||||
impl SupportedKxGroup for X25519Kx {
|
||||
fn name(&self) -> NamedGroup {
|
||||
NamedGroup::X25519
|
||||
}
|
||||
|
||||
fn start_exchange(&self, buf: Buf) -> Result<Box<dyn ActiveKeyExchange>, CryptoError> {
|
||||
Ok(Box::new(EcdhKeyExchange::new(NamedGroup::X25519, buf)?))
|
||||
}
|
||||
}
|
||||
|
||||
/// P-256 (secp256r1) key exchange group.
|
||||
#[derive(Debug)]
|
||||
struct P256;
|
||||
|
||||
impl SupportedKxGroup for P256 {
|
||||
fn name(&self) -> NamedGroup {
|
||||
NamedGroup::Secp256r1
|
||||
}
|
||||
|
||||
fn start_exchange(&self, buf: Buf) -> Result<Box<dyn ActiveKeyExchange>, CryptoError> {
|
||||
Ok(Box::new(EcdhKeyExchange::new(NamedGroup::Secp256r1, buf)?))
|
||||
}
|
||||
}
|
||||
|
||||
/// P-384 (secp384r1) key exchange group.
|
||||
#[derive(Debug)]
|
||||
struct P384;
|
||||
|
||||
impl SupportedKxGroup for P384 {
|
||||
fn name(&self) -> NamedGroup {
|
||||
NamedGroup::Secp384r1
|
||||
}
|
||||
|
||||
fn start_exchange(&self, buf: Buf) -> Result<Box<dyn ActiveKeyExchange>, CryptoError> {
|
||||
Ok(Box::new(EcdhKeyExchange::new(NamedGroup::Secp384r1, buf)?))
|
||||
}
|
||||
}
|
||||
|
||||
/// Static instances of supported key exchange groups.
|
||||
static KX_GROUP_X25519: X25519Kx = X25519Kx;
|
||||
static KX_GROUP_P256: P256 = P256;
|
||||
static KX_GROUP_P384: P384 = P384;
|
||||
|
||||
/// All supported key exchange groups.
|
||||
pub(super) static ALL_KX_GROUPS: &[&dyn SupportedKxGroup] =
|
||||
&[&KX_GROUP_X25519, &KX_GROUP_P256, &KX_GROUP_P384];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn x25519_non_contributory_peer_key_returns_invalid_public_key() {
|
||||
let exchange = X25519Kx
|
||||
.start_exchange(Buf::new())
|
||||
.expect("start key exchange");
|
||||
let mut out = Buf::new();
|
||||
|
||||
assert_eq!(
|
||||
exchange.complete(&[0; 32], &mut out),
|
||||
Err(CryptoError::InvalidPublicKey(NamedGroup::X25519))
|
||||
);
|
||||
}
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
//! RustCrypto cryptographic provider implementation for dimpl.
|
||||
//!
|
||||
//! This module provides a pure Rust cryptographic backend for dimpl using
|
||||
//! crates from the [RustCrypto](https://github.com/RustCrypto) organization.
|
||||
//!
|
||||
//! # Feature Flag
|
||||
//!
|
||||
//! This module is only available when the `rust-crypto` feature is enabled. The `rust-crypto`
|
||||
//! feature is included in the default features, so it's enabled by default. To use
|
||||
//! dimpl without this module, disable default features:
|
||||
//!
|
||||
//! ```toml
|
||||
//! dimpl = { version = "...", default-features = false }
|
||||
//! ```
|
||||
//!
|
||||
//! # Usage
|
||||
//!
|
||||
//! The rust-crypto provider is used automatically as a fallback when aws-lc-rs is not available
|
||||
//! or when explicitly specified:
|
||||
//!
|
||||
//! ```
|
||||
//! # #[cfg(feature = "rcgen")]
|
||||
//! # fn main() {
|
||||
//! use std::sync::Arc;
|
||||
//! use std::time::Instant;
|
||||
//! use dimpl::{Config, Dtls, certificate};
|
||||
//! use dimpl::crypto::rust_crypto;
|
||||
//!
|
||||
//! let cert = certificate::generate_self_signed_certificate().unwrap();
|
||||
//! let config = Arc::new(
|
||||
//! Config::builder()
|
||||
//! .with_crypto_provider(rust_crypto::default_provider())
|
||||
//! .build()
|
||||
//! .unwrap()
|
||||
//! );
|
||||
//! let dtls = Dtls::new_12(config, cert, Instant::now());
|
||||
//! # }
|
||||
//! # #[cfg(not(feature = "rcgen"))]
|
||||
//! # fn main() {}
|
||||
//! ```
|
||||
|
||||
mod cipher_suite;
|
||||
mod hash;
|
||||
pub(crate) mod hmac;
|
||||
mod kx_group;
|
||||
mod random;
|
||||
mod sign;
|
||||
|
||||
use super::CryptoProvider;
|
||||
|
||||
/// Get the default RustCrypto-based crypto provider.
|
||||
///
|
||||
/// This provider implements all cryptographic operations required for DTLS 1.2
|
||||
/// using pure Rust crates from the RustCrypto organization.
|
||||
///
|
||||
/// # Supported Cipher Suites
|
||||
///
|
||||
/// - `TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256` (0xC02B)
|
||||
/// - `TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384` (0xC02C)
|
||||
/// - `TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256` (0xCCA9)
|
||||
///
|
||||
/// # Supported Key Exchange Groups
|
||||
///
|
||||
/// - `x25519` (X25519 / Curve25519)
|
||||
/// - `secp256r1` (P-256, NIST Curve)
|
||||
/// - `secp384r1` (P-384, NIST Curve)
|
||||
///
|
||||
/// # Supported Signature Algorithms
|
||||
///
|
||||
/// - ECDSA with P-256 and SHA-256
|
||||
/// - ECDSA with P-384 and SHA-384
|
||||
///
|
||||
/// # Supported Hash Algorithms
|
||||
///
|
||||
/// - SHA-256
|
||||
/// - SHA-384
|
||||
///
|
||||
/// # Key Formats
|
||||
///
|
||||
/// The key provider supports loading private keys in:
|
||||
/// - PKCS#8 DER format (most common)
|
||||
/// - SEC1 DER format (OpenSSL EC private key format)
|
||||
/// - PEM encoded versions of the above
|
||||
///
|
||||
/// # Random Number Generation
|
||||
///
|
||||
/// Uses `OsRng` from the `rand` crate for cryptographically secure random number generation.
|
||||
pub fn default_provider() -> CryptoProvider {
|
||||
CryptoProvider {
|
||||
// Shared components
|
||||
kx_groups: kx_group::ALL_KX_GROUPS,
|
||||
signature_verification: &sign::SIGNATURE_VERIFIER,
|
||||
key_provider: &sign::KEY_PROVIDER,
|
||||
secure_random: &random::SECURE_RANDOM,
|
||||
hash_provider: &hash::HASH_PROVIDER,
|
||||
hmac_provider: &hmac::HMAC_PROVIDER,
|
||||
// DTLS 1.2 components
|
||||
cipher_suites: cipher_suite::ALL_CIPHER_SUITES,
|
||||
// DTLS 1.3 components
|
||||
dtls13_cipher_suites: cipher_suite::ALL_DTLS13_CIPHER_SUITES,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
//! Secure random number generation using RustCrypto.
|
||||
|
||||
use super::super::SecureRandom;
|
||||
use crate::CryptoError;
|
||||
|
||||
/// Secure random number generator implementation.
|
||||
#[derive(Debug)]
|
||||
pub(super) struct RustCryptoSecureRandom;
|
||||
|
||||
impl SecureRandom for RustCryptoSecureRandom {
|
||||
fn fill(&self, buf: &mut [u8]) -> Result<(), CryptoError> {
|
||||
use rand_core::OsRng;
|
||||
use rand_core::RngCore;
|
||||
OsRng.fill_bytes(buf);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Static instance of the secure random generator.
|
||||
pub(super) static SECURE_RANDOM: RustCryptoSecureRandom = RustCryptoSecureRandom;
|
||||
+329
@@ -0,0 +1,329 @@
|
||||
//! Signing and key loading implementations using RustCrypto.
|
||||
|
||||
use std::str;
|
||||
|
||||
use der::{Decode, Encode};
|
||||
use ecdsa::{Signature, SigningKey, VerifyingKey};
|
||||
use p256::NistP256;
|
||||
use p384::NistP384;
|
||||
use pkcs8::DecodePrivateKey;
|
||||
use spki::ObjectIdentifier;
|
||||
use x509_cert::Certificate as X509Certificate;
|
||||
|
||||
use super::super::check_verify_scheme;
|
||||
use super::super::{KeyProvider, SignatureVerifier, SigningKey as SigningKeyTrait};
|
||||
use super::super::{OID_P256, OID_P384};
|
||||
use crate::buffer::Buf;
|
||||
use crate::types::{HashAlgorithm, NamedGroup, SignatureAlgorithm};
|
||||
use crate::{CryptoError, CryptoOperation};
|
||||
|
||||
/// ECDSA signing key implementation.
|
||||
enum EcdsaSigningKey {
|
||||
P256(SigningKey<NistP256>),
|
||||
P384(SigningKey<NistP384>),
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for EcdsaSigningKey {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
EcdsaSigningKey::P256(_) => f.debug_tuple("EcdsaSigningKey::P256").finish(),
|
||||
EcdsaSigningKey::P384(_) => f.debug_tuple("EcdsaSigningKey::P384").finish(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SigningKeyTrait for EcdsaSigningKey {
|
||||
fn sign(
|
||||
&mut self,
|
||||
data: &[u8],
|
||||
hash_alg: HashAlgorithm,
|
||||
out: &mut Buf,
|
||||
) -> Result<(), CryptoError> {
|
||||
use ecdsa::signature::hazmat::PrehashSigner;
|
||||
use sha2::Digest;
|
||||
|
||||
match self {
|
||||
EcdsaSigningKey::P256(key) => {
|
||||
let signature: Signature<NistP256> = match hash_alg {
|
||||
HashAlgorithm::SHA256 => {
|
||||
let hash = sha2::Sha256::digest(data);
|
||||
key.sign_prehash(&hash)
|
||||
}
|
||||
HashAlgorithm::SHA384 => {
|
||||
let hash = sha2::Sha384::digest(data);
|
||||
key.sign_prehash(&hash)
|
||||
}
|
||||
_ => {
|
||||
return Err(CryptoError::SigningKeyUnsupportedHash {
|
||||
group: NamedGroup::Secp256r1,
|
||||
hash: hash_alg,
|
||||
});
|
||||
}
|
||||
}
|
||||
.map_err(|_| CryptoError::OperationFailed(CryptoOperation::Sign))?;
|
||||
out.clear();
|
||||
out.extend_from_slice(signature.to_der().as_bytes());
|
||||
Ok(())
|
||||
}
|
||||
EcdsaSigningKey::P384(key) => {
|
||||
let signature: Signature<NistP384> = match hash_alg {
|
||||
HashAlgorithm::SHA256 => {
|
||||
let hash = sha2::Sha256::digest(data);
|
||||
key.sign_prehash(&hash)
|
||||
}
|
||||
HashAlgorithm::SHA384 => {
|
||||
let hash = sha2::Sha384::digest(data);
|
||||
key.sign_prehash(&hash)
|
||||
}
|
||||
_ => {
|
||||
return Err(CryptoError::SigningKeyUnsupportedHash {
|
||||
group: NamedGroup::Secp384r1,
|
||||
hash: hash_alg,
|
||||
});
|
||||
}
|
||||
}
|
||||
.map_err(|_| CryptoError::OperationFailed(CryptoOperation::Sign))?;
|
||||
out.clear();
|
||||
out.extend_from_slice(signature.to_der().as_bytes());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn algorithm(&self) -> SignatureAlgorithm {
|
||||
SignatureAlgorithm::ECDSA
|
||||
}
|
||||
|
||||
fn hash_algorithm(&self) -> HashAlgorithm {
|
||||
match self {
|
||||
EcdsaSigningKey::P256(_) => HashAlgorithm::SHA256,
|
||||
EcdsaSigningKey::P384(_) => HashAlgorithm::SHA384,
|
||||
}
|
||||
}
|
||||
|
||||
fn supported_hash_algorithms(&self) -> &[HashAlgorithm] {
|
||||
// PrehashSigner accepts any hash digest, so both work for either curve.
|
||||
&[HashAlgorithm::SHA256, HashAlgorithm::SHA384]
|
||||
}
|
||||
}
|
||||
|
||||
/// Key provider implementation.
|
||||
#[derive(Debug)]
|
||||
pub(super) struct RustCryptoKeyProvider;
|
||||
|
||||
impl KeyProvider for RustCryptoKeyProvider {
|
||||
fn load_private_key(&self, key_der: &[u8]) -> Result<Box<dyn SigningKeyTrait>, CryptoError> {
|
||||
// Try PKCS#8 DER format first (most common)
|
||||
if let Ok(key) = SigningKey::<NistP256>::from_pkcs8_der(key_der) {
|
||||
return Ok(Box::new(EcdsaSigningKey::P256(key)));
|
||||
}
|
||||
if let Ok(key) = SigningKey::<NistP384>::from_pkcs8_der(key_der) {
|
||||
return Ok(Box::new(EcdsaSigningKey::P384(key)));
|
||||
}
|
||||
|
||||
// Try parsing as SEC1 DER format (OpenSSL EC private key format)
|
||||
if let Ok(ec_key) = sec1::EcPrivateKey::try_from(key_der) {
|
||||
let private_key_len = ec_key.private_key.len();
|
||||
|
||||
let curve_oid = if let Some(params) = &ec_key.parameters {
|
||||
match params {
|
||||
sec1::EcParameters::NamedCurve(oid) => Some(*oid),
|
||||
}
|
||||
} else if private_key_len == 32 {
|
||||
Some(ObjectIdentifier::new_unwrap("1.2.840.10045.3.1.7")) // P-256
|
||||
} else if private_key_len == 48 {
|
||||
Some(ObjectIdentifier::new_unwrap("1.3.132.0.34")) // P-384
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if let Some(curve_oid) = curve_oid {
|
||||
let ec_alg_oid = ObjectIdentifier::new_unwrap("1.2.840.10045.2.1");
|
||||
let curve_params_der = curve_oid
|
||||
.to_der()
|
||||
.map_err(|_| CryptoError::OperationFailed(CryptoOperation::EncodeKey))?;
|
||||
let curve_params_any = der::asn1::AnyRef::try_from(curve_params_der.as_slice())
|
||||
.map_err(|_| CryptoError::OperationFailed(CryptoOperation::EncodeKey))?;
|
||||
|
||||
let algorithm = spki::AlgorithmIdentifierRef {
|
||||
oid: ec_alg_oid,
|
||||
parameters: Some(curve_params_any),
|
||||
};
|
||||
|
||||
let pkcs8 = pkcs8::PrivateKeyInfo {
|
||||
algorithm,
|
||||
private_key: key_der,
|
||||
public_key: None,
|
||||
};
|
||||
|
||||
let pkcs8_der = pkcs8
|
||||
.to_der()
|
||||
.map_err(|_| CryptoError::OperationFailed(CryptoOperation::EncodeKey))?;
|
||||
|
||||
let p256_curve = ObjectIdentifier::new_unwrap("1.2.840.10045.3.1.7");
|
||||
if curve_oid == p256_curve {
|
||||
if let Ok(key) = SigningKey::<NistP256>::from_pkcs8_der(pkcs8_der.as_slice()) {
|
||||
return Ok(Box::new(EcdsaSigningKey::P256(key)));
|
||||
}
|
||||
}
|
||||
|
||||
let p384_curve = ObjectIdentifier::new_unwrap("1.3.132.0.34");
|
||||
if curve_oid == p384_curve {
|
||||
if let Ok(key) = SigningKey::<NistP384>::from_pkcs8_der(pkcs8_der.as_slice()) {
|
||||
return Ok(Box::new(EcdsaSigningKey::P384(key)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check if it's a PEM encoded key
|
||||
if let Ok(pem_str) = str::from_utf8(key_der) {
|
||||
if pem_str.contains("-----BEGIN") {
|
||||
if let Ok((_label, doc)) = pkcs8::Document::from_pem(pem_str) {
|
||||
return self.load_private_key(doc.as_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Err(CryptoError::InvalidPrivateKey)
|
||||
}
|
||||
}
|
||||
|
||||
/// Signature verifier implementation.
|
||||
#[derive(Debug)]
|
||||
pub(super) struct RustCryptoSignatureVerifier;
|
||||
|
||||
impl SignatureVerifier for RustCryptoSignatureVerifier {
|
||||
fn verify_signature(
|
||||
&self,
|
||||
cert_der: &[u8],
|
||||
data: &[u8],
|
||||
signature: &[u8],
|
||||
hash_alg: HashAlgorithm,
|
||||
sig_alg: SignatureAlgorithm,
|
||||
) -> Result<(), CryptoError> {
|
||||
if sig_alg != SignatureAlgorithm::ECDSA {
|
||||
return Err(CryptoError::UnsupportedSignatureAlgorithm(sig_alg));
|
||||
}
|
||||
|
||||
let cert =
|
||||
X509Certificate::from_der(cert_der).map_err(|_| CryptoError::CertificateParseFailed)?;
|
||||
let spki = &cert.tbs_certificate.subject_public_key_info;
|
||||
|
||||
const OID_EC_PUBLIC_KEY: ObjectIdentifier =
|
||||
ObjectIdentifier::new_unwrap("1.2.840.10045.2.1");
|
||||
|
||||
if spki.algorithm.oid != OID_EC_PUBLIC_KEY {
|
||||
return Err(CryptoError::UnsupportedPublicKeyAlgorithm);
|
||||
}
|
||||
|
||||
let pubkey_bytes = spki
|
||||
.subject_public_key
|
||||
.as_bytes()
|
||||
.ok_or(CryptoError::InvalidSubjectPublicKey)?;
|
||||
|
||||
let curve_oid: ObjectIdentifier = spki
|
||||
.algorithm
|
||||
.parameters
|
||||
.as_ref()
|
||||
.ok_or(CryptoError::MissingEcCurveParameter)?
|
||||
.decode_as()
|
||||
.map_err(|_| CryptoError::InvalidEcCurveParameter)?;
|
||||
|
||||
let group = match curve_oid {
|
||||
OID_P256 => NamedGroup::Secp256r1,
|
||||
OID_P384 => NamedGroup::Secp384r1,
|
||||
_ => return Err(CryptoError::UnsupportedEcCurve),
|
||||
};
|
||||
|
||||
check_verify_scheme(sig_alg, hash_alg, group)?;
|
||||
|
||||
use ecdsa::signature::hazmat::PrehashVerifier;
|
||||
use sha2::Digest;
|
||||
|
||||
// Hash the data before verification (PrehashVerifier expects a hash digest)
|
||||
let hash: Box<[u8]> = match hash_alg {
|
||||
HashAlgorithm::SHA256 => Box::from(sha2::Sha256::digest(data).as_slice()),
|
||||
HashAlgorithm::SHA384 => Box::from(sha2::Sha384::digest(data).as_slice()),
|
||||
// unreachable: check_verify_scheme already validated
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
match group {
|
||||
NamedGroup::Secp256r1 => {
|
||||
let verifying_key = VerifyingKey::<NistP256>::from_sec1_bytes(pubkey_bytes)
|
||||
.map_err(|_| CryptoError::InvalidPublicKey(NamedGroup::Secp256r1))?;
|
||||
let sig = Signature::<NistP256>::from_der(signature)
|
||||
.map_err(|_| CryptoError::InvalidSignatureFormat)?;
|
||||
verifying_key.verify_prehash(&hash, &sig).map_err(|_| {
|
||||
CryptoError::SignatureVerificationFailed {
|
||||
signature: sig_alg,
|
||||
hash: hash_alg,
|
||||
group,
|
||||
}
|
||||
})
|
||||
}
|
||||
NamedGroup::Secp384r1 => {
|
||||
let verifying_key = VerifyingKey::<NistP384>::from_sec1_bytes(pubkey_bytes)
|
||||
.map_err(|_| CryptoError::InvalidPublicKey(NamedGroup::Secp384r1))?;
|
||||
let sig = Signature::<NistP384>::from_der(signature)
|
||||
.map_err(|_| CryptoError::InvalidSignatureFormat)?;
|
||||
verifying_key.verify_prehash(&hash, &sig).map_err(|_| {
|
||||
CryptoError::SignatureVerificationFailed {
|
||||
signature: sig_alg,
|
||||
hash: hash_alg,
|
||||
group,
|
||||
}
|
||||
})
|
||||
}
|
||||
// unreachable: OID match above only produces Secp256r1/Secp384r1
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Static instance of the key provider.
|
||||
pub(super) static KEY_PROVIDER: RustCryptoKeyProvider = RustCryptoKeyProvider;
|
||||
|
||||
/// Static instance of the signature verifier.
|
||||
pub(super) static SIGNATURE_VERIFIER: RustCryptoSignatureVerifier = RustCryptoSignatureVerifier;
|
||||
|
||||
#[cfg(all(test, feature = "rcgen"))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::certificate::generate_self_signed_certificate;
|
||||
|
||||
#[test]
|
||||
fn invalid_signature_returns_structured_verification_error() {
|
||||
let cert = generate_self_signed_certificate().expect("generate cert");
|
||||
let mut key = KEY_PROVIDER
|
||||
.load_private_key(&cert.private_key)
|
||||
.expect("load private key");
|
||||
let data = b"signed data";
|
||||
let mut signature = Buf::new();
|
||||
key.sign(data, HashAlgorithm::SHA256, &mut signature)
|
||||
.expect("sign data");
|
||||
|
||||
let last = signature.len() - 1;
|
||||
signature[last] ^= 0x01;
|
||||
|
||||
let err = SIGNATURE_VERIFIER
|
||||
.verify_signature(
|
||||
&cert.certificate,
|
||||
data,
|
||||
&signature,
|
||||
HashAlgorithm::SHA256,
|
||||
SignatureAlgorithm::ECDSA,
|
||||
)
|
||||
.expect_err("corrupt signature should fail");
|
||||
|
||||
assert_eq!(
|
||||
err,
|
||||
CryptoError::SignatureVerificationFailed {
|
||||
signature: SignatureAlgorithm::ECDSA,
|
||||
hash: HashAlgorithm::SHA256,
|
||||
group: NamedGroup::Secp256r1,
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
+761
@@ -0,0 +1,761 @@
|
||||
//! Validation and filtering for crypto providers.
|
||||
//!
|
||||
//! This module defines the validation rules for crypto providers used with dimpl,
|
||||
//! based on the documented support in lib.rs.
|
||||
|
||||
use arrayvec::ArrayVec;
|
||||
|
||||
use super::{Aad, CryptoProvider, Nonce, SupportedDtls12CipherSuite, SupportedKxGroup};
|
||||
use crate::buffer::{Buf, TmpBuf};
|
||||
use crate::types::{Dtls13CipherSuite, HashAlgorithm, NamedGroup, SignatureAlgorithm};
|
||||
use crate::{ConfigError, CryptoProviderValidationError, Error};
|
||||
|
||||
fn provider_error(error: CryptoProviderValidationError) -> Error {
|
||||
Error::ConfigError(ConfigError::CryptoProvider(error))
|
||||
}
|
||||
|
||||
impl CryptoProvider {
|
||||
/// Returns an iterator over validated cipher suites supported by dimpl.
|
||||
///
|
||||
/// Only cipher suites documented in lib.rs are returned:
|
||||
/// - `TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256`
|
||||
/// - `TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384`
|
||||
/// - `TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256`
|
||||
pub fn supported_cipher_suites(
|
||||
&self,
|
||||
) -> impl Iterator<Item = &'static dyn SupportedDtls12CipherSuite> {
|
||||
self.cipher_suites
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|cs| cs.suite().is_supported())
|
||||
}
|
||||
|
||||
/// Returns an iterator over validated key exchange groups supported by dimpl.
|
||||
///
|
||||
/// Only key exchange groups documented in lib.rs are returned:
|
||||
/// - X25519
|
||||
/// - P-256 (secp256r1)
|
||||
/// - P-384 (secp384r1)
|
||||
pub fn supported_kx_groups(&self) -> impl Iterator<Item = &'static dyn SupportedKxGroup> {
|
||||
self.kx_groups.iter().copied().filter(|kx| {
|
||||
matches!(
|
||||
kx.name(),
|
||||
NamedGroup::X25519 | NamedGroup::Secp256r1 | NamedGroup::Secp384r1
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
///
|
||||
/// Combines provider filtering with signature algorithm compatibility.
|
||||
pub fn supported_cipher_suites_for_signature_algorithm(
|
||||
&self,
|
||||
sig_alg: SignatureAlgorithm,
|
||||
) -> impl Iterator<Item = &'static dyn SupportedDtls12CipherSuite> {
|
||||
self.supported_cipher_suites()
|
||||
.filter(move |cs| cs.suite().signature_algorithm() == Some(sig_alg))
|
||||
}
|
||||
|
||||
/// Check if provider supports ECDH-based cipher suites.
|
||||
///
|
||||
/// Returns true if any supported cipher suite uses ECDH key exchange.
|
||||
pub fn has_ecdh(&self) -> bool {
|
||||
self.supported_cipher_suites()
|
||||
.any(|cs| cs.suite().has_ecc())
|
||||
}
|
||||
|
||||
/// Validates the provider configuration for use with dimpl.
|
||||
///
|
||||
/// This ensures the provider meets dimpl's requirements:
|
||||
/// - At least one supported cipher suite
|
||||
/// - ECDH cipher suites have matching key exchange groups
|
||||
/// - Hash providers support required algorithms
|
||||
/// - HMAC provider supports required operations
|
||||
///
|
||||
/// Returns `Error::ConfigError` if validation fails.
|
||||
pub fn validate(&self) -> Result<(), Error> {
|
||||
self.validate_cipher_suites()?;
|
||||
self.validate_kx_groups()?;
|
||||
let validated_hashes = self.validate_hash_providers()?;
|
||||
self.validate_prf(&validated_hashes)?;
|
||||
self.validate_signature_verifier(&validated_hashes)?;
|
||||
self.validate_hmac_provider()?;
|
||||
self.validate_dtls13_cipher_suites()?;
|
||||
self.validate_dtls13_aead()?;
|
||||
self.validate_dtls13_encrypt_sn()?;
|
||||
self.validate_kx_exchange()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validate that at least one cipher suite is supported.
|
||||
fn validate_cipher_suites(&self) -> Result<(), Error> {
|
||||
let cipher_count = self.supported_cipher_suites().count();
|
||||
if cipher_count == 0 {
|
||||
return Err(provider_error(
|
||||
CryptoProviderValidationError::NoCipherSuites,
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validate that ECDH cipher suites have matching key exchange groups.
|
||||
fn validate_kx_groups(&self) -> Result<(), Error> {
|
||||
if self.has_ecdh() {
|
||||
let kx_count = self.supported_kx_groups().count();
|
||||
if kx_count == 0 {
|
||||
return Err(provider_error(
|
||||
CryptoProviderValidationError::EcdhCipherSuitesWithoutKeyExchangeGroups,
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validate that hash providers support required algorithms.
|
||||
/// Returns the list of validated hash algorithms.
|
||||
fn validate_hash_providers(&self) -> Result<Vec<HashAlgorithm>, Error> {
|
||||
// Collect unique hash algorithms from supported cipher suites
|
||||
let required_hashes: Vec<HashAlgorithm> = self
|
||||
.cipher_suites
|
||||
.iter()
|
||||
.map(|cs| cs.suite().hash_algorithm())
|
||||
.collect();
|
||||
|
||||
// Test each required hash algorithm with known test vectors
|
||||
for hash_alg in &required_hashes {
|
||||
let mut hasher = self.hash_provider.create_hash(*hash_alg);
|
||||
|
||||
// Test with empty input - use known hash values
|
||||
hasher.update(&[]);
|
||||
let mut result = Buf::new();
|
||||
hasher.clone_and_finalize(&mut result);
|
||||
|
||||
let maybe_expected = HASH_TEST_VECTORS
|
||||
.iter()
|
||||
.find(|(h, _)| *h == *hash_alg)
|
||||
.map(|(_, v)| v);
|
||||
|
||||
let Some(expected) = maybe_expected else {
|
||||
return Err(provider_error(
|
||||
CryptoProviderValidationError::MissingHashTestVector(*hash_alg),
|
||||
));
|
||||
};
|
||||
|
||||
if result.as_ref() != *expected {
|
||||
return Err(provider_error(
|
||||
CryptoProviderValidationError::HashProviderIncorrect(*hash_alg),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(required_hashes)
|
||||
}
|
||||
|
||||
/// Validate that PRF (via HMAC) works for every supported hash algorithm.
|
||||
fn validate_prf(&self, validated_hashes: &[HashAlgorithm]) -> Result<(), Error> {
|
||||
let secret = b"test_secret";
|
||||
let label = "test label";
|
||||
let seed = b"test_seed";
|
||||
let output_len = 32;
|
||||
|
||||
for &hash_alg in validated_hashes {
|
||||
let mut result = Buf::new();
|
||||
let mut scratch = Buf::new();
|
||||
super::prf_hkdf::prf_tls12(
|
||||
self.hmac_provider,
|
||||
secret,
|
||||
label,
|
||||
seed,
|
||||
&mut result,
|
||||
output_len,
|
||||
&mut scratch,
|
||||
hash_alg,
|
||||
)
|
||||
.map_err(|e| {
|
||||
provider_error(CryptoProviderValidationError::PrfFailed {
|
||||
hash: hash_alg,
|
||||
source: e,
|
||||
})
|
||||
})?;
|
||||
|
||||
let maybe_expected = PRF_TEST_VECTORS
|
||||
.iter()
|
||||
.find(|(h, _)| *h == hash_alg)
|
||||
.map(|(_, v)| v);
|
||||
|
||||
let Some(expected) = maybe_expected else {
|
||||
return Err(provider_error(
|
||||
CryptoProviderValidationError::MissingPrfTestVector(hash_alg),
|
||||
));
|
||||
};
|
||||
|
||||
if result.as_ref() != *expected {
|
||||
return Err(provider_error(CryptoProviderValidationError::PrfIncorrect(
|
||||
hash_alg,
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validate that signature verifier works for every supported cipher suite.
|
||||
fn validate_signature_verifier(
|
||||
&self,
|
||||
_validated_hashes: &[HashAlgorithm],
|
||||
) -> Result<(), Error> {
|
||||
// Test signature verification for each supported cipher suite
|
||||
for cs in self.supported_cipher_suites() {
|
||||
let hash_alg = cs.suite().hash_algorithm();
|
||||
let sig_alg = match cs.suite().signature_algorithm() {
|
||||
Some(alg) => alg,
|
||||
// PSK suites have no signature — skip validation
|
||||
None => continue,
|
||||
};
|
||||
|
||||
let (cert_der, signature, test_data) = match (hash_alg, sig_alg) {
|
||||
(HashAlgorithm::SHA256, SignatureAlgorithm::ECDSA) => (
|
||||
VALIDATION_P256_CERT,
|
||||
VALIDATION_P256_SHA256_SIG,
|
||||
VALIDATION_TEST_DATA,
|
||||
),
|
||||
(HashAlgorithm::SHA384, SignatureAlgorithm::ECDSA) => (
|
||||
VALIDATION_P384_CERT,
|
||||
VALIDATION_P384_SHA384_SIG,
|
||||
VALIDATION_TEST_DATA,
|
||||
),
|
||||
_ => {
|
||||
return Err(provider_error(
|
||||
CryptoProviderValidationError::NoSignatureValidationVector {
|
||||
hash: hash_alg,
|
||||
signature: sig_alg,
|
||||
},
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
// Verify the signature
|
||||
self.signature_verification
|
||||
.verify_signature(cert_der, test_data, signature, hash_alg, sig_alg)
|
||||
.map_err(|e| {
|
||||
provider_error(CryptoProviderValidationError::SignatureVerificationFailed {
|
||||
hash: hash_alg,
|
||||
signature: sig_alg,
|
||||
source: e,
|
||||
})
|
||||
})?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validate that DTLS 1.3 cipher suites and HKDF provider are configured.
|
||||
fn validate_dtls13_cipher_suites(&self) -> Result<(), Error> {
|
||||
if self.dtls13_cipher_suites.is_empty() {
|
||||
return Err(provider_error(
|
||||
CryptoProviderValidationError::NoDtls13CipherSuites,
|
||||
));
|
||||
}
|
||||
|
||||
// Verify HKDF (via HMAC) works for each DTLS 1.3 cipher suite's hash algorithm
|
||||
for cs in self.dtls13_cipher_suites {
|
||||
let hash = cs.suite().hash_algorithm();
|
||||
let hash_len = hash.output_len();
|
||||
let zeros = [0u8; 48];
|
||||
let zeros = &zeros[..hash_len];
|
||||
let mut out = Buf::new();
|
||||
super::prf_hkdf::hkdf_extract(self.hmac_provider, hash, zeros, zeros, &mut out)
|
||||
.map_err(|e| {
|
||||
provider_error(CryptoProviderValidationError::HkdfFailed {
|
||||
suite: cs.suite(),
|
||||
source: e,
|
||||
})
|
||||
})?;
|
||||
if out.is_empty() {
|
||||
return Err(provider_error(
|
||||
CryptoProviderValidationError::HkdfEmptyOutput(cs.suite()),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validate AEAD encrypt/decrypt for each DTLS 1.3 cipher suite.
|
||||
fn validate_dtls13_aead(&self) -> Result<(), Error> {
|
||||
for cs in self.dtls13_cipher_suites {
|
||||
let suite = cs.suite();
|
||||
let tv = AEAD_TEST_VECTORS
|
||||
.iter()
|
||||
.find(|tv| tv.suite == suite)
|
||||
.ok_or_else(|| {
|
||||
provider_error(CryptoProviderValidationError::NoAeadTestVector(suite))
|
||||
})?;
|
||||
|
||||
let nonce = Nonce(tv.nonce);
|
||||
let mut aad_vec = ArrayVec::new();
|
||||
// unwrap: AAD is at most 12 bytes, well within capacity 13
|
||||
aad_vec.try_extend_from_slice(tv.aad).unwrap();
|
||||
let aad = Aad(aad_vec);
|
||||
|
||||
// Encrypt
|
||||
let mut cipher = cs.create_cipher(tv.key).map_err(|e| {
|
||||
provider_error(CryptoProviderValidationError::AeadCreateFailed { suite, source: e })
|
||||
})?;
|
||||
let mut buf = Buf::new();
|
||||
buf.extend_from_slice(tv.plaintext);
|
||||
cipher.encrypt(&mut buf, aad.clone(), nonce).map_err(|e| {
|
||||
provider_error(CryptoProviderValidationError::AeadEncryptFailed {
|
||||
suite,
|
||||
source: e,
|
||||
})
|
||||
})?;
|
||||
if buf.as_ref() != tv.ciphertext_tag {
|
||||
return Err(provider_error(
|
||||
CryptoProviderValidationError::AeadEncryptWrongOutput(suite),
|
||||
));
|
||||
}
|
||||
|
||||
// Decrypt with a fresh cipher instance
|
||||
let mut cipher = cs.create_cipher(tv.key).map_err(|e| {
|
||||
provider_error(CryptoProviderValidationError::AeadCreateFailed { suite, source: e })
|
||||
})?;
|
||||
let mut ct = Vec::from(tv.ciphertext_tag);
|
||||
let mut tmp = TmpBuf::new(&mut ct);
|
||||
cipher.decrypt(&mut tmp, aad, nonce).map_err(|e| {
|
||||
provider_error(CryptoProviderValidationError::AeadDecryptFailed {
|
||||
suite,
|
||||
source: e,
|
||||
})
|
||||
})?;
|
||||
if tmp.as_ref() != tv.plaintext {
|
||||
return Err(provider_error(
|
||||
CryptoProviderValidationError::AeadDecryptWrongOutput(suite),
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validate record number encryption for each DTLS 1.3 cipher suite.
|
||||
fn validate_dtls13_encrypt_sn(&self) -> Result<(), Error> {
|
||||
for cs in self.dtls13_cipher_suites {
|
||||
let suite = cs.suite();
|
||||
let tv = SN_TEST_VECTORS
|
||||
.iter()
|
||||
.find(|tv| tv.suite == suite)
|
||||
.ok_or_else(|| {
|
||||
provider_error(
|
||||
CryptoProviderValidationError::NoRecordNumberEncryptionTestVector(suite),
|
||||
)
|
||||
})?;
|
||||
|
||||
let mask = cs.encrypt_sn(tv.sn_key, &tv.sample);
|
||||
if mask[..tv.check_len] != tv.expected_mask[..tv.check_len] {
|
||||
return Err(provider_error(
|
||||
CryptoProviderValidationError::RecordNumberEncryptionWrongMask(suite),
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validate key exchange round-trip for each supported group.
|
||||
fn validate_kx_exchange(&self) -> Result<(), Error> {
|
||||
for kx in self.supported_kx_groups() {
|
||||
let group = kx.name();
|
||||
|
||||
let alice = kx.start_exchange(Buf::new()).map_err(|e| {
|
||||
provider_error(CryptoProviderValidationError::KeyExchangeStartFailed {
|
||||
group,
|
||||
source: e,
|
||||
})
|
||||
})?;
|
||||
let bob = kx.start_exchange(Buf::new()).map_err(|e| {
|
||||
provider_error(CryptoProviderValidationError::KeyExchangeStartFailed {
|
||||
group,
|
||||
source: e,
|
||||
})
|
||||
})?;
|
||||
|
||||
let alice_pub = alice.pub_key().to_vec();
|
||||
let bob_pub = bob.pub_key().to_vec();
|
||||
|
||||
let mut alice_secret = Buf::new();
|
||||
alice.complete(&bob_pub, &mut alice_secret).map_err(|e| {
|
||||
provider_error(CryptoProviderValidationError::KeyExchangeCompleteFailed {
|
||||
group,
|
||||
source: e,
|
||||
})
|
||||
})?;
|
||||
|
||||
let mut bob_secret = Buf::new();
|
||||
bob.complete(&alice_pub, &mut bob_secret).map_err(|e| {
|
||||
provider_error(CryptoProviderValidationError::KeyExchangeCompleteFailed {
|
||||
group,
|
||||
source: e,
|
||||
})
|
||||
})?;
|
||||
|
||||
if alice_secret.as_ref() != bob_secret.as_ref() {
|
||||
return Err(provider_error(
|
||||
CryptoProviderValidationError::KeyExchangeMismatchedSharedSecret(group),
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validate that HMAC provider supports required operations.
|
||||
///
|
||||
/// We require HMAC-SHA256 for DTLS cookie computation.
|
||||
fn validate_hmac_provider(&self) -> Result<(), Error> {
|
||||
// Test HMAC-SHA256 with known test vector (RFC 2104 test case)
|
||||
// HMAC-SHA256(key="key", data="The quick brown fox jumps over the lazy dog")
|
||||
let key = b"key";
|
||||
let data = b"The quick brown fox jumps over the lazy dog";
|
||||
|
||||
let result = self
|
||||
.hmac_provider
|
||||
.hmac_sha256(key, data)
|
||||
.map_err(|e| provider_error(CryptoProviderValidationError::HmacFailed(e)))?;
|
||||
|
||||
// Verify against known HMAC-SHA256 test vector
|
||||
if result.as_slice() != HMAC_SHA256_TEST_VECTOR {
|
||||
return Err(provider_error(CryptoProviderValidationError::HmacIncorrect));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
const HASH_TEST_VECTORS: &[(HashAlgorithm, &[u8])] = &[
|
||||
(
|
||||
HashAlgorithm::SHA256,
|
||||
&[
|
||||
0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f,
|
||||
0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b,
|
||||
0x78, 0x52, 0xb8, 0x55,
|
||||
],
|
||||
),
|
||||
(
|
||||
HashAlgorithm::SHA384,
|
||||
&[
|
||||
0x38, 0xb0, 0x60, 0xa7, 0x51, 0xac, 0x96, 0x38, 0x4c, 0xd9, 0x32, 0x7e, 0xb1, 0xb1,
|
||||
0xe3, 0x6a, 0x21, 0xfd, 0xb7, 0x11, 0x14, 0xbe, 0x07, 0x43, 0x4c, 0x0c, 0xc7, 0xbf,
|
||||
0x63, 0xf6, 0xe1, 0xda, 0x27, 0x4e, 0xde, 0xbf, 0xe7, 0x6f, 0x65, 0xfb, 0xd5, 0x1a,
|
||||
0xd2, 0xf1, 0x48, 0x98, 0xb9, 0x5b,
|
||||
],
|
||||
),
|
||||
];
|
||||
|
||||
// Test vectors for TLS 1.2 PRF
|
||||
// Generated using: PRF(secret="test_secret", label="test label", seed="test_seed", output_len=32)
|
||||
const PRF_TEST_VECTORS: &[(HashAlgorithm, &[u8])] = &[
|
||||
(
|
||||
HashAlgorithm::SHA256,
|
||||
&[
|
||||
0xc7, 0x49, 0xce, 0xdf, 0xad, 0xaf, 0x3d, 0xf1, 0x18, 0x2c, 0xa2, 0x25, 0xab, 0xe9,
|
||||
0x4e, 0x0c, 0x19, 0xc3, 0x81, 0x49, 0x57, 0xbd, 0xdc, 0x28, 0x55, 0x78, 0x73, 0xdb,
|
||||
0xb7, 0x9f, 0xce, 0x29,
|
||||
],
|
||||
),
|
||||
(
|
||||
HashAlgorithm::SHA384,
|
||||
&[
|
||||
0x74, 0x9a, 0xf3, 0x03, 0x23, 0x9e, 0x3f, 0x65, 0x4e, 0x9a, 0xd1, 0xb1, 0xd1, 0x22,
|
||||
0x31, 0x02, 0x1a, 0xd2, 0x17, 0x26, 0x04, 0x75, 0x21, 0xf4, 0x66, 0xad, 0xcd, 0x37,
|
||||
0x2b, 0xe4, 0x7e, 0x8b,
|
||||
],
|
||||
),
|
||||
];
|
||||
|
||||
// Test vector for HMAC-SHA256
|
||||
// HMAC-SHA256(key="key", data="The quick brown fox jumps over the lazy dog")
|
||||
// Computed using standard HMAC-SHA256 implementation
|
||||
const HMAC_SHA256_TEST_VECTOR: &[u8] = &[
|
||||
0xf7, 0xbc, 0x83, 0xf4, 0x30, 0x53, 0x84, 0x24, 0xb1, 0x32, 0x98, 0xe6, 0xaa, 0x6f, 0xb1, 0x43,
|
||||
0xef, 0x4d, 0x59, 0xa1, 0x49, 0x46, 0x17, 0x59, 0x97, 0x47, 0x9d, 0xbc, 0x2d, 0x1a, 0x3c, 0xd8,
|
||||
];
|
||||
|
||||
// Test certificates and signatures for signature verification validation
|
||||
const VALIDATION_TEST_DATA: &[u8] = include_bytes!("test_data.bin");
|
||||
const VALIDATION_P256_CERT: &[u8] = include_bytes!("p256_cert.der");
|
||||
const VALIDATION_P256_SHA256_SIG: &[u8] = include_bytes!("p256_sha256_sig.der");
|
||||
const VALIDATION_P384_CERT: &[u8] = include_bytes!("p384_cert.der");
|
||||
const VALIDATION_P384_SHA384_SIG: &[u8] = include_bytes!("p384_sha384_sig.der");
|
||||
|
||||
// AEAD test vectors for DTLS 1.3 cipher suites
|
||||
struct AeadTestVector {
|
||||
suite: Dtls13CipherSuite,
|
||||
key: &'static [u8],
|
||||
nonce: [u8; 12],
|
||||
plaintext: &'static [u8],
|
||||
aad: &'static [u8],
|
||||
ciphertext_tag: &'static [u8], // ciphertext || tag
|
||||
}
|
||||
|
||||
// NIST SP 800-38D Test Case 3 plaintext (shared by AES-128 and AES-256)
|
||||
const GCM_PLAINTEXT: &[u8] = &[
|
||||
0xd9, 0x31, 0x32, 0x25, 0xf8, 0x84, 0x06, 0xe5, 0xa5, 0x59, 0x09, 0xc5, 0xaf, 0xf5, 0x26, 0x9a,
|
||||
0x86, 0xa7, 0xa9, 0x53, 0x15, 0x34, 0xf7, 0xda, 0x2e, 0x4c, 0x30, 0x3d, 0x8a, 0x31, 0x8a, 0x72,
|
||||
0x1c, 0x3c, 0x0c, 0x95, 0x95, 0x68, 0x09, 0x53, 0x2f, 0xcf, 0x0e, 0x24, 0x49, 0xa6, 0xb5, 0x25,
|
||||
0xb1, 0x6a, 0xed, 0xf5, 0xaa, 0x0d, 0xe6, 0x57, 0xba, 0x63, 0x7b, 0x39, 0x1a, 0xaf, 0xd2, 0x55,
|
||||
];
|
||||
|
||||
const AEAD_TEST_VECTORS: &[AeadTestVector] = &[
|
||||
// NIST SP 800-38D Test Case 3: AES-128-GCM, empty AAD
|
||||
AeadTestVector {
|
||||
suite: Dtls13CipherSuite::AES_128_GCM_SHA256,
|
||||
key: &[
|
||||
0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c, 0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30,
|
||||
0x83, 0x08,
|
||||
],
|
||||
nonce: [
|
||||
0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad, 0xde, 0xca, 0xf8, 0x88,
|
||||
],
|
||||
plaintext: GCM_PLAINTEXT,
|
||||
aad: &[],
|
||||
ciphertext_tag: &[
|
||||
// Ciphertext
|
||||
0x42, 0x83, 0x1e, 0xc2, 0x21, 0x77, 0x74, 0x24, 0x4b, 0x72, 0x21, 0xb7, 0x84, 0xd0,
|
||||
0xd4, 0x9c, 0xe3, 0xaa, 0x21, 0x2f, 0x2c, 0x02, 0xa4, 0xe0, 0x35, 0xc1, 0x7e, 0x23,
|
||||
0x29, 0xac, 0xa1, 0x2e, 0x21, 0xd5, 0x14, 0xb2, 0x54, 0x66, 0x93, 0x1c, 0x7d, 0x8f,
|
||||
0x6a, 0x5a, 0xac, 0x84, 0xaa, 0x05, 0x1b, 0xa3, 0x0b, 0x39, 0x6a, 0x0a, 0xac, 0x97,
|
||||
0x3d, 0x58, 0xe0, 0x91, 0x47, 0x3f, 0x59, 0x85, // Tag
|
||||
0x4d, 0x5c, 0x2a, 0xf3, 0x27, 0xcd, 0x64, 0xa6, 0x2c, 0xf3, 0x5a, 0xbd, 0x2b, 0xa6,
|
||||
0xfa, 0xb4,
|
||||
],
|
||||
},
|
||||
// NIST SP 800-38D Test Case 15: AES-256-GCM, empty AAD
|
||||
AeadTestVector {
|
||||
suite: Dtls13CipherSuite::AES_256_GCM_SHA384,
|
||||
key: &[
|
||||
0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c, 0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30,
|
||||
0x83, 0x08, 0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c, 0x6d, 0x6a, 0x8f, 0x94,
|
||||
0x67, 0x30, 0x83, 0x08,
|
||||
],
|
||||
nonce: [
|
||||
0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad, 0xde, 0xca, 0xf8, 0x88,
|
||||
],
|
||||
plaintext: GCM_PLAINTEXT,
|
||||
aad: &[],
|
||||
ciphertext_tag: &[
|
||||
// Ciphertext
|
||||
0x52, 0x2d, 0xc1, 0xf0, 0x99, 0x56, 0x7d, 0x07, 0xf4, 0x7f, 0x37, 0xa3, 0x2a, 0x84,
|
||||
0x42, 0x7d, 0x64, 0x3a, 0x8c, 0xdc, 0xbf, 0xe5, 0xc0, 0xc9, 0x75, 0x98, 0xa2, 0xbd,
|
||||
0x25, 0x55, 0xd1, 0xaa, 0x8c, 0xb0, 0x8e, 0x48, 0x59, 0x0d, 0xbb, 0x3d, 0xa7, 0xb0,
|
||||
0x8b, 0x10, 0x56, 0x82, 0x88, 0x38, 0xc5, 0xf6, 0x1e, 0x63, 0x93, 0xba, 0x7a, 0x0a,
|
||||
0xbc, 0xc9, 0xf6, 0x62, 0x89, 0x80, 0x15, 0xad, // Tag
|
||||
0xb0, 0x94, 0xda, 0xc5, 0xd9, 0x34, 0x71, 0xbd, 0xec, 0x1a, 0x50, 0x22, 0x70, 0xe3,
|
||||
0xcc, 0x6c,
|
||||
],
|
||||
},
|
||||
// RFC 7539 §2.8.2: ChaCha20-Poly1305
|
||||
AeadTestVector {
|
||||
suite: Dtls13CipherSuite::CHACHA20_POLY1305_SHA256,
|
||||
key: &[
|
||||
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d,
|
||||
0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b,
|
||||
0x9c, 0x9d, 0x9e, 0x9f,
|
||||
],
|
||||
nonce: [
|
||||
0x07, 0x00, 0x00, 0x00, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
|
||||
],
|
||||
plaintext: &[
|
||||
// "Ladies and Gentlemen of the class of '99: If I could offer you
|
||||
// only one tip for the future, sunscreen would be it."
|
||||
0x4c, 0x61, 0x64, 0x69, 0x65, 0x73, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x47, 0x65, 0x6e,
|
||||
0x74, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20,
|
||||
0x63, 0x6c, 0x61, 0x73, 0x73, 0x20, 0x6f, 0x66, 0x20, 0x27, 0x39, 0x39, 0x3a, 0x20,
|
||||
0x49, 0x66, 0x20, 0x49, 0x20, 0x63, 0x6f, 0x75, 0x6c, 0x64, 0x20, 0x6f, 0x66, 0x66,
|
||||
0x65, 0x72, 0x20, 0x79, 0x6f, 0x75, 0x20, 0x6f, 0x6e, 0x6c, 0x79, 0x20, 0x6f, 0x6e,
|
||||
0x65, 0x20, 0x74, 0x69, 0x70, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x74, 0x68, 0x65, 0x20,
|
||||
0x66, 0x75, 0x74, 0x75, 0x72, 0x65, 0x2c, 0x20, 0x73, 0x75, 0x6e, 0x73, 0x63, 0x72,
|
||||
0x65, 0x65, 0x6e, 0x20, 0x77, 0x6f, 0x75, 0x6c, 0x64, 0x20, 0x62, 0x65, 0x20, 0x69,
|
||||
0x74, 0x2e,
|
||||
],
|
||||
aad: &[
|
||||
0x50, 0x51, 0x52, 0x53, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
|
||||
],
|
||||
ciphertext_tag: &[
|
||||
// Ciphertext
|
||||
0xd3, 0x1a, 0x8d, 0x34, 0x64, 0x8e, 0x60, 0xdb, 0x7b, 0x86, 0xaf, 0xbc, 0x53, 0xef,
|
||||
0x7e, 0xc2, 0xa4, 0xad, 0xed, 0x51, 0x29, 0x6e, 0x08, 0xfe, 0xa9, 0xe2, 0xb5, 0xa7,
|
||||
0x36, 0xee, 0x62, 0xd6, 0x3d, 0xbe, 0xa4, 0x5e, 0x8c, 0xa9, 0x67, 0x12, 0x82, 0xfa,
|
||||
0xfb, 0x69, 0xda, 0x92, 0x72, 0x8b, 0x1a, 0x71, 0xde, 0x0a, 0x9e, 0x06, 0x0b, 0x29,
|
||||
0x05, 0xd6, 0xa5, 0xb6, 0x7e, 0xcd, 0x3b, 0x36, 0x92, 0xdd, 0xbd, 0x7f, 0x2d, 0x77,
|
||||
0x8b, 0x8c, 0x98, 0x03, 0xae, 0xe3, 0x28, 0x09, 0x1b, 0x58, 0xfa, 0xb3, 0x24, 0xe4,
|
||||
0xfa, 0xd6, 0x75, 0x94, 0x55, 0x85, 0x80, 0x8b, 0x48, 0x31, 0xd7, 0xbc, 0x3f, 0xf4,
|
||||
0xde, 0xf0, 0x8e, 0x4b, 0x7a, 0x9d, 0xe5, 0x76, 0xd2, 0x65, 0x86, 0xce, 0xc6, 0x4b,
|
||||
0x61, 0x16, // Tag
|
||||
0x1a, 0xe1, 0x0b, 0x59, 0x4f, 0x09, 0xe2, 0x6a, 0x7e, 0x90, 0x2e, 0xcb, 0xd0, 0x60,
|
||||
0x06, 0x91,
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
// Record number encryption (encrypt_sn) test vectors
|
||||
struct SnTestVector {
|
||||
suite: Dtls13CipherSuite,
|
||||
sn_key: &'static [u8],
|
||||
sample: [u8; 16],
|
||||
expected_mask: [u8; 16],
|
||||
check_len: usize, // number of leading bytes to verify
|
||||
}
|
||||
|
||||
const SN_TEST_VECTORS: &[SnTestVector] = &[
|
||||
// NIST FIPS 197 Appendix B: AES-128-ECB
|
||||
SnTestVector {
|
||||
suite: Dtls13CipherSuite::AES_128_GCM_SHA256,
|
||||
sn_key: &[
|
||||
0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf,
|
||||
0x4f, 0x3c,
|
||||
],
|
||||
sample: [
|
||||
0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d, 0x31, 0x31, 0x98, 0xa2, 0xe0, 0x37,
|
||||
0x07, 0x34,
|
||||
],
|
||||
expected_mask: [
|
||||
0x39, 0x25, 0x84, 0x1d, 0x02, 0xdc, 0x09, 0xfb, 0xdc, 0x11, 0x85, 0x97, 0x19, 0x6a,
|
||||
0x0b, 0x32,
|
||||
],
|
||||
check_len: 16,
|
||||
},
|
||||
// NIST FIPS 197 Appendix C.3: AES-256-ECB
|
||||
SnTestVector {
|
||||
suite: Dtls13CipherSuite::AES_256_GCM_SHA384,
|
||||
sn_key: &[
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
|
||||
0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b,
|
||||
0x1c, 0x1d, 0x1e, 0x1f,
|
||||
],
|
||||
sample: [
|
||||
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd,
|
||||
0xee, 0xff,
|
||||
],
|
||||
expected_mask: [
|
||||
0x8e, 0xa2, 0xb7, 0xca, 0x51, 0x67, 0x45, 0xbf, 0xea, 0xfc, 0x49, 0x90, 0x4b, 0x49,
|
||||
0x60, 0x89,
|
||||
],
|
||||
check_len: 16,
|
||||
},
|
||||
// RFC 9001 §A.5: ChaCha20 header protection
|
||||
// Only first 5 bytes are checked (aws-lc-rs zeros bytes 5-15, rust_crypto fills all 16)
|
||||
SnTestVector {
|
||||
suite: Dtls13CipherSuite::CHACHA20_POLY1305_SHA256,
|
||||
sn_key: &[
|
||||
0x25, 0xa2, 0x82, 0xb9, 0xe8, 0x2f, 0x06, 0xf2, 0x1f, 0x48, 0x89, 0x17, 0xa4, 0xfc,
|
||||
0x8f, 0x1b, 0x73, 0x57, 0x36, 0x85, 0x60, 0x85, 0x97, 0xd0, 0xef, 0xcb, 0x07, 0x6b,
|
||||
0x0a, 0xb7, 0xa7, 0xa4,
|
||||
],
|
||||
sample: [
|
||||
0x5e, 0x5c, 0xd5, 0x5c, 0x41, 0xf6, 0x90, 0x80, 0x57, 0x5d, 0x79, 0x99, 0xc2, 0x5a,
|
||||
0x5b, 0xfb,
|
||||
],
|
||||
expected_mask: [
|
||||
0xae, 0xfe, 0xfe, 0x7d, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00,
|
||||
],
|
||||
check_len: 5,
|
||||
},
|
||||
];
|
||||
|
||||
#[cfg(test)]
|
||||
#[cfg(feature = "aws-lc-rs")]
|
||||
mod tests_aws_lc_rs {
|
||||
use super::*;
|
||||
use crate::crypto::aws_lc_rs;
|
||||
use crate::dtls12::message::Dtls12CipherSuite;
|
||||
|
||||
#[test]
|
||||
fn test_default_provider_validates() {
|
||||
let provider = aws_lc_rs::default_provider();
|
||||
assert!(provider.validate().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_default_provider_has_cipher_suites() {
|
||||
let provider = aws_lc_rs::default_provider();
|
||||
let count = provider.supported_cipher_suites().count();
|
||||
// ECDHE: AES-128, AES-256, ChaCha20
|
||||
// PSK: CCM-8
|
||||
assert_eq!(count, 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_default_provider_has_kx_groups() {
|
||||
let provider = aws_lc_rs::default_provider();
|
||||
let count = provider.supported_kx_groups().count();
|
||||
assert_eq!(count, 3); // X25519, P-256, and P-384
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_default_provider_has_ecdh() {
|
||||
let provider = aws_lc_rs::default_provider();
|
||||
assert!(provider.has_ecdh());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_supported_cipher_suites_for_signature_algorithm() {
|
||||
let provider = aws_lc_rs::default_provider();
|
||||
let ecdsa_suites: Vec<_> = provider
|
||||
.supported_cipher_suites_for_signature_algorithm(SignatureAlgorithm::ECDSA)
|
||||
.map(|cs| cs.suite())
|
||||
.collect();
|
||||
|
||||
assert_eq!(ecdsa_suites.len(), 3);
|
||||
assert!(ecdsa_suites.contains(&Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256));
|
||||
assert!(ecdsa_suites.contains(&Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384));
|
||||
assert!(ecdsa_suites.contains(&Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[cfg(feature = "rust-crypto")]
|
||||
mod tests_rust_crypto {
|
||||
use super::*;
|
||||
use crate::crypto::rust_crypto;
|
||||
use crate::dtls12::message::Dtls12CipherSuite;
|
||||
|
||||
#[test]
|
||||
fn test_default_provider_validates() {
|
||||
let provider = rust_crypto::default_provider();
|
||||
assert!(provider.validate().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_default_provider_has_cipher_suites() {
|
||||
let provider = rust_crypto::default_provider();
|
||||
let count = provider.supported_cipher_suites().count();
|
||||
// ECDHE: AES-128, AES-256, ChaCha20
|
||||
// PSK: CCM-8
|
||||
assert_eq!(count, 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_default_provider_has_kx_groups() {
|
||||
let provider = rust_crypto::default_provider();
|
||||
let count = provider.supported_kx_groups().count();
|
||||
assert_eq!(count, 3); // X25519, P-256, and P-384
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_default_provider_has_ecdh() {
|
||||
let provider = rust_crypto::default_provider();
|
||||
assert!(provider.has_ecdh());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_supported_cipher_suites_for_signature_algorithm() {
|
||||
let provider = rust_crypto::default_provider();
|
||||
let ecdsa_suites: Vec<_> = provider
|
||||
.supported_cipher_suites_for_signature_algorithm(SignatureAlgorithm::ECDSA)
|
||||
.map(|cs| cs.suite())
|
||||
.collect();
|
||||
|
||||
assert_eq!(ecdsa_suites.len(), 3);
|
||||
assert!(ecdsa_suites.contains(&Dtls12CipherSuite::ECDHE_ECDSA_AES128_GCM_SHA256));
|
||||
assert!(ecdsa_suites.contains(&Dtls12CipherSuite::ECDHE_ECDSA_AES256_GCM_SHA384));
|
||||
assert!(ecdsa_suites.contains(&Dtls12CipherSuite::ECDHE_ECDSA_CHACHA20_POLY1305_SHA256));
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1 @@
|
||||
0d0uçhI¶»Û³I‚Ôà)<ݽм�ò#¼ºšzu¹•Ö|™)¤ýëh¦ÏÛØã^djÒE08{ Aõ™ôÙ Ñìíé½Ìíðì¹]²™e¦=î(HºzDl‚�¢«„J␍hó
|
||||
@@ -0,0 +1 @@
|
||||
test data for signature validation
|
||||
Reference in new issue
Block a user