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:
Claude committed 2026-09-26 23:27:21 +00:00
1 parent fd36372243
commit d1c4424789
152 files changed
+56138 -5

No files matched your search

+458
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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,
}
}
+20
View File
@@ -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
View File
@@ -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,
}
);
}
}