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

+482
View File
@@ -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()
);
}
}
+69
View File
@@ -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;
+47
View File
@@ -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;
+209
View File
@@ -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
View File
@@ -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,
}
}
+20
View File
@@ -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
View File
@@ -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,
}
);
}
}