Crypto Core Security API Documentation
⚠️ FOUNDATIONAL SECURITY MODULE ⚠️
THIS MODULE DEFINES CORE CRYPTOGRAPHIC INTERFACES AND ABSTRACTIONS
- Unified cryptographic trait definitions
- Security parameter validation
- Algorithm registry and versioning
- Cross-language interface specifications
1. Core Interfaces
1.1 CryptoProvider Trait
pub trait CryptoProvider: Send + Sync {
fn algorithm_id(&self) -> &str;
fn version(&self) -> Version;
fn validate_parameters(&self, params: &Parameters) -> Result<()>;
fn is_secure(&self) -> bool;
}
Security Contract:
- MUST validate all parameters before use
- MUST report accurate security status
- MUST be thread-safe (Send + Sync)
- MUST NOT cache sensitive data
1.2 KeyMaterial Trait
pub trait KeyMaterial: Zeroize {
fn as_bytes(&self) -> &[u8];
fn key_size(&self) -> usize;
fn algorithm(&self) -> Algorithm;
fn validate(&self) -> Result<()>;
}
Security Contract:
- MUST implement secure memory clearing (Zeroize)
- MUST validate key material on creation
- MUST protect against memory dumps
- MUST enforce minimum key sizes
1.3 SecureAllocator Trait
pub trait SecureAllocator {
fn allocate(&self, size: usize) -> Result<SecureBuffer>;
fn allocate_aligned(&self, size: usize, align: usize) -> Result<SecureBuffer>;
fn lock_memory(&self, buffer: &mut [u8]) -> Result<()>;
}
Security Contract:
- MUST use mlocked memory when available
- MUST clear memory on deallocation
- MUST handle allocation failures gracefully
- MUST prevent swapping to disk
2. Security Parameter Definitions
2.1 Algorithm Enumeration
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Algorithm {
// Symmetric
Aes128 { mode: AesMode },
Aes256 { mode: AesMode },
ChaCha20Poly1305,
// Asymmetric
Ed25519,
Sr25519,
Secp256k1,
// Post-Quantum
MlKem768,
Dilithium3,
Falcon512,
// Hash
Sha256,
Sha384,
Sha512,
Blake2b,
Blake3,
// KDF
Argon2id { m_cost: u32, t_cost: u32 },
Pbkdf2 { iterations: u32 },
Hkdf,
}
Security Requirements:
- Each algorithm MUST have defined security parameters
- Deprecated algorithms MUST be marked
- Version compatibility MUST be enforced
2.2 Security Level Classification
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum SecurityLevel {
Broken = 0, // MD5, SHA1, DES
Legacy = 1, // RSA-1024, 3DES
Standard = 2, // AES-128, RSA-2048
High = 3, // AES-256, RSA-4096
PostQuantum = 4, // MLKEM, Dilithium
}
Security Contract:
- MUST reject Broken algorithms
- SHOULD warn on Legacy algorithms
- MUST enforce minimum security levels
- MUST provide migration paths
3. Core Security Functions
3.1 Parameter Validation
pub fn validate_algorithm_parameters(
algorithm: Algorithm,
params: &Parameters,
) -> Result<()> {
match algorithm {
Algorithm::Aes256 { mode } => {
validate_key_size(params.key_size, 256)?;
validate_nonce_size(mode, params.nonce_size)?;
}
Algorithm::Ed25519 => {
validate_key_size(params.key_size, 256)?;
ensure!(params.nonce_size == 0, "Ed25519 doesn't use nonces");
}
Algorithm::Argon2id { m_cost, t_cost } => {
ensure!(m_cost >= 65536, "Memory cost too low");
ensure!(t_cost >= 3, "Time cost too low");
}
_ => {}
}
Ok(())
}
3.2 Version Compatibility
pub fn check_version_compatibility(
required: &Version,
provided: &Version,
) -> Result<()> {
// Security: Never allow downgrade attacks
ensure!(
provided.major >= required.major,
"Major version downgrade detected"
);
// Check breaking changes
if provided.major > required.major {
return Err(Error::IncompatibleVersion);
}
Ok(())
}
4. Attack Resistance Matrix
| Attack Vector | Protection Mechanism | Implementation |
|---|---|---|
| Algorithm Confusion | Strong typing | Enum-based algorithms |
| Parameter Tampering | Validation | Pre-operation checks |
| Version Downgrade | Version checks | No downgrades allowed |
| Memory Disclosure | Secure allocation | mlock/VirtualLock |
| Type Confusion | Trait bounds | Compile-time safety |
5. Implementation Examples
Python Core Types
from enum import Enum, auto
from dataclasses import dataclass
from typing import Protocol, Optional
import mlock
class SecurityLevel(Enum):
BROKEN = 0
LEGACY = 1
STANDARD = 2
HIGH = 3
POST_QUANTUM = 4
class Algorithm(Enum):
AES_128_GCM = auto()
AES_256_GCM = auto()
CHACHA20_POLY1305 = auto()
ED25519 = auto()
MLKEM768 = auto()
@dataclass
class AlgorithmParams:
algorithm: Algorithm
key_size: int
nonce_size: Optional[int] = None
additional_params: Optional[dict] = None
def validate(self) -> None:
"""Validate parameters for the algorithm."""
validators = {
Algorithm.AES_256_GCM: self._validate_aes256,
Algorithm.ED25519: self._validate_ed25519,
Algorithm.MLKEM768: self._validate_mlkem,
}
validator = validators.get(self.algorithm)
if validator:
validator()
def _validate_aes256(self):
assert self.key_size == 256, "AES-256 requires 256-bit key"
assert self.nonce_size == 96, "GCM requires 96-bit nonce"
class CryptoProvider(Protocol):
"""Core cryptographic provider interface."""
def algorithm_id(self) -> str:
...
def get_security_level(self) -> SecurityLevel:
...
def validate_parameters(self, params: AlgorithmParams) -> None:
...
Rust Core Implementation
use zeroize::Zeroize;
use std::sync::Arc;
pub struct CryptoCore {
providers: HashMap<Algorithm, Arc<dyn CryptoProvider>>,
security_policy: SecurityPolicy,
}
impl CryptoCore {
pub fn new(policy: SecurityPolicy) -> Self {
Self {
providers: HashMap::new(),
security_policy: policy,
}
}
pub fn register_provider(
&mut self,
algorithm: Algorithm,
provider: Arc<dyn CryptoProvider>,
) -> Result<()> {
// Validate provider meets security requirements
let level = provider.get_security_level();
if level < self.security_policy.minimum_level {
return Err(Error::InsufficientSecurity);
}
// Verify provider implementation
provider.self_test()?;
self.providers.insert(algorithm, provider);
Ok(())
}
pub fn get_provider(&self, algorithm: Algorithm) -> Result<Arc<dyn CryptoProvider>> {
self.providers
.get(&algorithm)
.cloned()
.ok_or(Error::AlgorithmNotSupported)
}
}
pub struct SecureBuffer {
data: Vec<u8>,
locked: bool,
}
impl SecureBuffer {
pub fn new(size: usize) -> Result<Self> {
let mut data = vec![0u8; size];
// Attempt to lock memory
let locked = unsafe {
#[cfg(unix)]
{
libc::mlock(data.as_ptr() as *const _, size) == 0
}
#[cfg(windows)]
{
winapi::VirtualLock(data.as_ptr() as *mut _, size) != 0
}
};
Ok(Self { data, locked })
}
}
impl Drop for SecureBuffer {
fn drop(&mut self) {
self.data.zeroize();
if self.locked {
unsafe {
#[cfg(unix)]
libc::munlock(self.data.as_ptr() as *const _, self.data.len());
#[cfg(windows)]
winapi::VirtualUnlock(self.data.as_ptr() as *mut _, self.data.len());
}
}
}
}
6. Common Vulnerabilities
6.1 Algorithm Confusion
# VULNERABLE - String-based algorithm selection
def encrypt(algorithm: str, key: bytes, data: bytes):
if algorithm == "AES": # Which AES? What mode?
# ...
# SECURE - Type-safe algorithm selection
def encrypt(algorithm: Algorithm, key: bytes, data: bytes):
if algorithm == Algorithm.AES_256_GCM:
# Explicit algorithm and mode
6.2 Missing Parameter Validation
// VULNERABLE - No validation
impl CryptoProvider for AesProvider {
fn encrypt(&self, key: &[u8], data: &[u8]) -> Result<Vec<u8>> {
// Direct use without validation
aes::encrypt(key, data)
}
}
// SECURE - Comprehensive validation
impl CryptoProvider for AesProvider {
fn encrypt(&self, key: &[u8], data: &[u8]) -> Result<Vec<u8>> {
// Validate key size
validate_key_size(key.len(), 256)?;
// Validate data alignment
validate_block_alignment(data)?;
// Check for weak keys
check_weak_keys(key)?;
aes::encrypt(key, data)
}
}
7. Security Checklist
- All algorithms strongly typed
- Parameter validation enforced
- Version compatibility checked
- Security levels enforced
- Memory protection enabled
- Thread safety guaranteed
- Self-tests implemented
- Deprecation warnings active
- Audit logging enabled
- Error handling secure
8. Performance Considerations
| Component | Impact | Mitigation |
|---|---|---|
| Parameter validation | ~1-5% overhead | Cache validation results |
| Memory locking | Platform dependent | Fallback gracefully |
| Version checking | Negligible | Compile-time where possible |
| Type safety | Zero runtime cost | Rust/TypeScript generics |
9. References
Security Analysis
Threat Model: Crypto Core Infrastructure Threat Model
This component provides critical security infrastructure. For comprehensive security analysis including:
- Infrastructure security considerations
- Cross-algorithm implications
- Implementation best practices
- Deployment recommendations
See the dedicated threat model documentation for complete details.