Security Utils Security API Documentation
⚠️ CRITICAL SECURITY MODULE ⚠️
THIS MODULE PROVIDES FOUNDATIONAL SECURITY UTILITIES
- Secure memory management
- Constant-time operations
- Random number generation
- Security validation utilities
1. API Functions
1.1 Secure Memory Operations
secure_zero_memory(buffer: &mut [u8])
Security Contract:
- MUST overwrite memory with zeros
- MUST prevent compiler optimizations from removing the operation
- MUST handle all memory sizes without timing variations
- MUST be called before freeing sensitive data
Critical Requirements:
- Use compiler barriers to prevent optimization
- Verify zeroing with memory inspection in debug builds
- Never skip this operation for performance
secure_compare(a: &[u8], b: &[u8]) -> bool
Security Contract:
- MUST execute in constant time regardless of input
- MUST compare all bytes even after mismatch found
- MUST NOT leak information through timing
- MUST handle different-length inputs safely
Attack Resistance:
- Timing attacks: Full resistance through constant-time implementation
- Cache attacks: No data-dependent memory access patterns
1.2 Random Number Generation
secure_random_bytes(length: usize) -> Result<Vec<u8>>
Security Contract:
- MUST use cryptographically secure RNG
- MUST never return predictable values
- MUST fail safely if entropy unavailable
- MUST NOT cache or reuse random values
Critical Requirements:
- Use OS-provided CSPRNG (getrandom/CryptGenRandom)
- Implement proper error handling for entropy exhaustion
- Never fallback to insecure RNG
secure_random_u32() -> Result<u32>
Security Contract:
- MUST provide uniform distribution
- MUST use secure_random_bytes internally
- MUST handle endianness correctly
1.3 Validation Utilities
validate_key_size(algorithm: &str, key_size: usize) -> Result<()>
Security Contract:
- MUST reject weak key sizes
- MUST enforce algorithm-specific requirements
- MUST provide clear error messages
Key Size Requirements:
AES: 128, 192, 256 bits only
RSA: >= 2048 bits
ECC: >= 256 bits
Ed25519: exactly 256 bits
validate_nonce_uniqueness(nonce: &[u8], cache: &NonceCache) -> Result<()>
Security Contract:
- MUST detect nonce reuse within cache window
- MUST handle cache overflow safely
- MUST be thread-safe
1.4 Constant-Time Operations
ct_select(condition: bool, a: u8, b: u8) -> u8
Security Contract:
- MUST NOT branch based on condition
- MUST use bitwise operations only
- MUST resist compiler optimizations
ct_copy(condition: bool, dest: &mut [u8], src: &[u8])
Security Contract:
- MUST copy in constant time
- MUST handle overlapping buffers
- MUST NOT leak condition through timing
2. Attack Resistance Matrix
| Attack Vector | Protection Mechanism | Implementation |
|---|---|---|
| Timing Attacks | Constant-time operations | Bitwise ops, no branches |
| Memory Disclosure | Secure zeroing | Compiler barriers |
| RNG Prediction | CSPRNG usage | OS entropy sources |
| Compiler Optimization | Volatile operations | Memory barriers |
| Side Channels | Constant memory access | No secret-dependent indexing |
3. Implementation Examples
Python Example
import os
import ctypes
from typing import Union
class SecurityUtils:
@staticmethod
def secure_zero_memory(data: Union[bytes, bytearray, memoryview]) -> None:
"""Securely zero memory, preventing optimization."""
if isinstance(data, bytes):
raise TypeError("Cannot modify immutable bytes")
# Use ctypes to ensure memory is actually zeroed
size = len(data)
if size > 0:
ctypes.memset(ctypes.addressof(ctypes.c_char.from_buffer(data)), 0, size)
@staticmethod
def secure_compare(a: bytes, b: bytes) -> bool:
"""Constant-time comparison."""
if len(a) != len(b):
return False
result = 0
for x, y in zip(a, b):
result |= x ^ y
return result == 0
@staticmethod
def secure_random_bytes(length: int) -> bytes:
"""Generate cryptographically secure random bytes."""
if length < 0:
raise ValueError("Length must be non-negative")
return os.urandom(length)
Rust Example
use std::sync::atomic::{AtomicPtr, Ordering};
use getrandom::getrandom;
pub struct SecurityUtils;
impl SecurityUtils {
pub fn secure_zero_memory(buffer: &mut [u8]) {
unsafe {
// Use volatile write to prevent optimization
let ptr = buffer.as_mut_ptr();
let len = buffer.len();
for i in 0..len {
std::ptr::write_volatile(ptr.add(i), 0);
}
// Compiler barrier
std::sync::atomic::compiler_fence(Ordering::SeqCst);
}
}
pub fn secure_compare(a: &[u8], b: &[u8]) -> bool {
if a.len() != b.len() {
return false;
}
let mut result = 0u8;
for (x, y) in a.iter().zip(b.iter()) {
result |= x ^ y;
}
result == 0
}
pub fn secure_random_bytes(length: usize) -> Result<Vec<u8>, Error> {
let mut buffer = vec![0u8; length];
getrandom(&mut buffer)?;
Ok(buffer)
}
}
4. Common Vulnerabilities
4.1 Optimization Removal
// VULNERABLE - Compiler may optimize out
fn bad_zero_memory(buffer: &mut [u8]) {
for b in buffer {
*b = 0; // May be removed if buffer not used after
}
}
// SECURE - Uses volatile operations
fn secure_zero_memory(buffer: &mut [u8]) {
unsafe {
let ptr = buffer.as_mut_ptr();
for i in 0..buffer.len() {
std::ptr::write_volatile(ptr.add(i), 0);
}
}
}
4.2 Timing Leaks
# VULNERABLE - Early return leaks timing
def bad_compare(a: bytes, b: bytes) -> bool:
if len(a) != len(b):
return False
for i in range(len(a)):
if a[i] != b[i]:
return False # Timing leak!
return True
# SECURE - Constant time
def secure_compare(a: bytes, b: bytes) -> bool:
if len(a) != len(b):
return False
result = 0
for x, y in zip(a, b):
result |= x ^ y
return result == 0
5. Performance Considerations
| Operation | Time Complexity | Security Impact |
|---|---|---|
| secure_zero_memory | O(n) | Must not be optimized |
| secure_compare | O(n) | Always full comparison |
| secure_random_bytes | O(n) | May block for entropy |
| ct_select | O(1) | No branching allowed |
6. Security Checklist
- All sensitive data zeroed before deallocation
- No timing variations in comparisons
- CSPRNG used for all randomness
- Compiler barriers in place
- No secret-dependent branches
- Thread-safe implementations
- Proper error handling
- No optimization vulnerabilities
- Memory protection enabled
- Debug assertions for security properties
7. References
Security Analysis
Threat Model: Security Utilities 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.