MetaMUI Crypto Primitives Security Procedures
Side-channel claim limit. Nothing on this page claims constant-time behaviour or side-channel resistance for any target: the side-channel harness covers nothing (finding A48) and no measurement exists. The Rust and C cores are designed for constant time and unmeasured; managed runtimes (JIT, GC, bounds checks) make no timing claim. Where this page names constant-time or side-channel techniques, in prose or in code, they are design intent or recommendations, not measured properties.
Table of Contents
- Secure Development Procedures
- Key Management Procedures
- Security Testing Procedures
- Incident Response Procedures
- Audit and Compliance Procedures
- Security Operations Procedures
Secure Development Procedures
Pre-Development Security Review
Procedure SD-001: Security Requirements Analysis
Purpose: Ensure security requirements are identified before development begins.
Steps:
- Review feature requirements for security implications
- Identify cryptographic needs
- Assess regulatory compliance requirements
- Document security constraints
- Get security team approval
Checklist:
- Threat model created/updated
- Cryptographic algorithms selected
- Key management requirements defined
- Compliance requirements identified
- Security tests planned
Secure Coding Procedures
Procedure SD-002: Cryptographic Implementation
Purpose: Ensure cryptographic code is implemented securely.
Steps:
- Use only approved cryptographic libraries
- Implement constant-time operations
- Validate all inputs before processing
- Handle errors without information leakage
- Clear sensitive data after use
Code Example:
// Secure key derivation procedure
pub fn derive_key(
master_key: &[u8; 32],
context: &[u8],
key_id: u64,
) -> Result<[u8; 32], KeyDerivationError> {
// Step 1: Validate inputs
if context.len() > 255 {
return Err(KeyDerivationError::ContextTooLong);
}
// Step 2: Prepare derivation data
let mut data = Vec::with_capacity(8 + 1 + context.len());
data.extend_from_slice(&key_id.to_be_bytes());
data.push(context.len() as u8);
data.extend_from_slice(context);
// Step 3: Derive key using HKDF
let mut derived_key = [0u8; 32];
hkdf_sha256(master_key, &data, b"metamui-key-derive", &mut derived_key)?;
// Step 4: Clear intermediate data
data.zeroize();
Ok(derived_key)
}
Procedure SD-003: Memory Safety
Purpose: Prevent memory-related vulnerabilities.
Steps:
- Avoid unsafe code blocks unless absolutely necessary
- Document and review all unsafe code usage
- Use bounds checking for all array accesses
- Implement Drop trait for sensitive data
- Use memory barriers to prevent optimization
Implementation:
use zeroize::{Zeroize, ZeroizeOnDrop};
#[derive(ZeroizeOnDrop)]
pub struct SecretKey {
#[zeroize(skip)]
algorithm: Algorithm,
key_material: Vec<u8>,
}
impl Drop for SecretKey {
fn drop(&mut self) {
// Explicit zeroization with memory barrier
self.key_material.zeroize();
// Memory barrier to prevent reordering
core::sync::atomic::fence(core::sync::atomic::Ordering::SeqCst);
}
}
Code Review Procedures
Procedure SD-004: Security-Focused Code Review
Purpose: Identify security issues before code merger.
Review Checklist:
- Input Validation
- All external inputs validated
- Buffer sizes checked
- Integer overflow protection
- Cryptography
- Approved algorithms used
- Proper key sizes
- Secure random number generation
- No hardcoded secrets
- Memory Safety
- No uninitialized memory use
- Bounds checking present
- Sensitive data cleared
- Error Handling
- No information leakage in errors
- All errors handled
- Fail-secure behavior
Key Management Procedures
Key Generation Procedures
Procedure KM-001: Master Key Generation
Purpose: Generate cryptographically secure master keys.
Steps:
- Instantiate the HMAC_DRBG (
DrbgRng::new()runs the power-up KATs and start-up health tests) - Reseed from the entropy source
- Generate 256 bits of entropy
- Apply key derivation function
- Store in secure key storage
- Log key generation event
Implementation:
pub fn generate_master_key() -> Result<MasterKey, KeyGenerationError> {
// Step 1: Instantiate the DRBG (power-up KATs and start-up health tests run here)
let mut rng = DrbgRng::new()?;
// Step 2: Reseed from the entropy source
rng.reseed()?;
// Step 3: Generate entropy
let mut entropy = [0u8; 32];
rng.fill_bytes(&mut entropy)?;
// Step 4: Derive master key
let master_key = kdf_sha256(&entropy, b"metamui-master-key", 32)?;
// Step 5: Clear entropy
entropy.zeroize();
// Step 6: Audit log
audit_log(AuditEvent::MasterKeyGenerated {
timestamp: SystemTime::now(),
key_id: master_key.id(),
})?;
Ok(master_key)
}
Procedure KM-002: Key Rotation
Purpose: Rotate keys according to policy.
Steps:
- Generate new key version
- Re-encrypt data with new key
- Verify re-encryption success
- Update key version metadata
- Schedule old key destruction
- Audit log rotation
Key Rotation Schedule:
pub struct KeyRotationSchedule {
key_type: KeyType,
max_age: Duration,
max_operations: u64,
}
const ROTATION_SCHEDULE: &[KeyRotationSchedule] = &[
KeyRotationSchedule {
key_type: KeyType::Master,
max_age: Duration::from_secs(365 * 24 * 60 * 60), // 1 year
max_operations: u64::MAX,
},
KeyRotationSchedule {
key_type: KeyType::DataEncryption,
max_age: Duration::from_secs(30 * 24 * 60 * 60), // 30 days
max_operations: 1 << 32, // 2^32 operations
},
];
Key Storage Procedures
Procedure KM-003: Secure Key Storage
Purpose: Store keys securely at rest.
Steps:
- Encrypt key with Key Encryption Key (KEK)
- Add integrity protection (HMAC)
- Store in secure location
- Set appropriate permissions
- Enable audit logging
Storage Format:
#[derive(Serialize, Deserialize)]
pub struct StoredKey {
version: u32,
key_id: Uuid,
algorithm: Algorithm,
encrypted_key: Vec<u8>,
nonce: [u8; 12],
tag: [u8; 16],
metadata: KeyMetadata,
hmac: [u8; 32],
}
pub fn store_key(key: &SecretKey, kek: &[u8; 32]) -> Result<(), StorageError> {
// Encrypt key material
let (ciphertext, nonce, tag) = aes_256_gcm_encrypt(
kek,
&key.material,
&key.metadata.to_bytes()?,
)?;
// Create storage structure
let stored = StoredKey {
version: 1,
key_id: key.id,
algorithm: key.algorithm,
encrypted_key: ciphertext,
nonce,
tag,
metadata: key.metadata.clone(),
hmac: [0u8; 32],
};
// Compute HMAC over entire structure
let hmac = hmac_sha256(kek, &stored.to_bytes()?);
stored.hmac = hmac;
// Store to secure location
secure_storage::write(&key.id, &stored)?;
Ok(())
}
Security Testing Procedures
Cryptographic Testing
Procedure ST-001: Algorithm Validation
Purpose: Verify cryptographic implementations against test vectors.
Steps:
- Load official test vectors
- Run algorithm with test inputs
- Compare outputs
- Verify timing consistency
- Document results
Test Framework:
#[cfg(test)]
mod crypto_tests {
use super::*;
#[test]
fn test_aes_256_gcm() {
// NIST test vectors
let test_vectors = load_nist_vectors("aes_gcm_256.json");
for vector in test_vectors {
let (ciphertext, tag) = aes_256_gcm_encrypt(
&vector.key,
&vector.nonce,
&vector.plaintext,
&vector.aad,
).expect("Encryption failed");
assert_eq!(ciphertext, vector.expected_ciphertext);
assert_eq!(tag, vector.expected_tag);
// Verify constant time
assert_constant_time(|| {
aes_256_gcm_encrypt(&vector.key, &vector.nonce, &vector.plaintext, &vector.aad)
});
}
}
}
Procedure ST-002: Side-Channel Testing
Purpose: Verify resistance to timing attacks.
Steps:
- Instrument code for timing measurements
- Run operations with different inputs
- Statistical analysis of timings
- Identify timing variations
- Fix any variable-time operations
Testing Code:
pub fn test_constant_time_comparison() {
let iterations = 100_000;
let mut timings = Vec::with_capacity(iterations);
for _ in 0..iterations {
let a = random_bytes(32);
let b = random_bytes(32);
let start = precise_time_ns();
let _ = constant_time_eq(&a, &b);
let end = precise_time_ns();
timings.push(end - start);
}
// Statistical analysis
let mean = statistical::mean(&timings);
let std_dev = statistical::std_dev(&timings);
let max_deviation = statistical::max_deviation(&timings);
// Assert timing is consistent
assert!(std_dev < mean * 0.05); // Less than 5% variation
assert!(max_deviation < mean * 0.10); // Max 10% deviation
}
Penetration Testing
Procedure ST-003: Security Penetration Testing
Purpose: Identify vulnerabilities through active testing.
Test Categories:
- Input Validation
- Fuzzing with AFL++
- Boundary value testing
- Injection attacks
- Memory Safety
- Address sanitizer
- Memory sanitizer
- Undefined behavior sanitizer
- Cryptographic Attacks
- Nonce reuse detection
- Weak randomness testing
- Protocol downgrade attempts
Fuzzing Configuration:
#!/bin/bash
# Fuzz testing script
# Build with fuzzing instrumentation
cargo fuzz build
# Run fuzzer for each target
for target in $(cargo fuzz list); do
echo "Fuzzing $target..."
cargo fuzz run $target -- \
-max_len=65536 \
-timeout=30 \
-max_total_time=3600 \
-print_final_stats=1
done
# Analyze crashes
for crash in fuzz/artifacts/*/crash-*; do
echo "Analyzing crash: $crash"
cargo fuzz reproduce $target $crash
done
Incident Response Procedures
Incident Detection
Procedure IR-001: Security Incident Detection
Purpose: Quickly identify and classify security incidents.
Detection Sources:
- Automated monitoring alerts
- User reports
- Security audit logs
- Vulnerability scanners
- Third-party notifications
Initial Response:
pub async fn handle_security_alert(alert: SecurityAlert) -> Result<(), IncidentError> {
// Step 1: Log incident
let incident_id = log_incident(&alert)?;
// Step 2: Assess severity
let severity = assess_severity(&alert)?;
// Step 3: Notify team
match severity {
Severity::Critical => {
notify_oncall_immediately(&alert).await?;
page_security_team(&alert).await?;
}
Severity::High => {
notify_security_team(&alert).await?;
}
Severity::Medium | Severity::Low => {
create_security_ticket(&alert).await?;
}
}
// Step 4: Begin containment
if severity >= Severity::High {
begin_containment(&alert).await?;
}
Ok(())
}
Incident Containment
Procedure IR-002: Incident Containment
Purpose: Limit damage from security incidents.
Containment Actions:
- Key Compromise
pub async fn contain_key_compromise(key_id: KeyId) -> Result<(), ContainmentError> { // Revoke key immediately key_manager::revoke_key(key_id).await?; // Identify affected systems let affected = identify_key_usage(key_id).await?; // Rotate to new key let new_key = key_manager::emergency_rotation(key_id).await?; // Update affected systems for system in affected { system.update_key(key_id, new_key).await?; } Ok(()) } - Data Breach
pub async fn contain_data_breach(breach: DataBreach) -> Result<(), ContainmentError> { // Isolate affected systems for system in &breach.affected_systems { network::isolate(system).await?; } // Revoke access tokens for token in identify_active_tokens(&breach).await? { auth::revoke_token(token).await?; } // Enable enhanced monitoring monitoring::enable_enhanced_mode(&breach.affected_systems).await?; Ok(()) }
Audit and Compliance Procedures
Security Auditing
Procedure AC-001: Security Audit Logging
Purpose: Maintain comprehensive security audit trail.
Audit Events:
#[derive(Serialize, Deserialize)]
pub enum AuditEvent {
// Key management
KeyGenerated { key_id: KeyId, algorithm: Algorithm },
KeyRotated { old_id: KeyId, new_id: KeyId },
KeyDestroyed { key_id: KeyId },
// Authentication
LoginAttempt { user: UserId, success: bool },
TokenIssued { user: UserId, token_id: TokenId },
TokenRevoked { token_id: TokenId, reason: String },
// Data access
DataEncrypted { data_id: DataId, key_id: KeyId },
DataDecrypted { data_id: DataId, key_id: KeyId },
// Configuration
ConfigChanged { setting: String, old_value: String, new_value: String },
// Security events
SecurityAlert { alert_type: AlertType, severity: Severity },
IncidentCreated { incident_id: IncidentId },
}
pub fn audit_log(event: AuditEvent) -> Result<(), AuditError> {
let entry = AuditEntry {
timestamp: SystemTime::now(),
event,
actor: current_actor()?,
session_id: current_session()?,
correlation_id: Uuid::new_v4(),
};
// Sign entry for integrity
let signature = sign_audit_entry(&entry)?;
// Store in append-only log
audit_store::append(entry, signature)?;
Ok(())
}
Compliance Verification
Procedure AC-002: DRBG health-test review
Purpose: Confirm the HMAC_DRBG (SP 800-90A) and its SP 800-90B-style health tests stay as documented. The project holds no FIPS 140-3 validation.
Verification Steps:
- Algorithm Compliance
pub fn verify_fips_algorithms() -> Result<(), ComplianceError> { // Check only approved algorithms used for algorithm in inventory::list_algorithms()? { if !FIPS_APPROVED_ALGORITHMS.contains(&algorithm) { return Err(ComplianceError::NonApprovedAlgorithm(algorithm)); } } // Verify algorithm parameters verify_key_sizes()?; verify_mode_compliance()?; Ok(()) } - Self-Test Compliance
pub fn run_fips_self_tests() -> Result<(), SelfTestError> { // Power-on self-tests crypto_self_test()?; integrity_self_test()?; // Conditional self-tests if new_key_generated() { key_generation_self_test()?; } if firmware_updated() { firmware_integrity_test()?; } Ok(()) }
Security Operations Procedures
Monitoring Procedures
Procedure SO-001: Continuous Security Monitoring
Purpose: Detect security issues in real-time.
Monitoring Dashboard:
pub struct SecurityMetrics {
// Cryptographic operations
pub encryption_ops_per_sec: f64,
pub decryption_ops_per_sec: f64,
pub key_generation_rate: f64,
// Security events
pub failed_auth_attempts: u64,
pub anomaly_detections: u64,
pub policy_violations: u64,
// System health
pub entropy_pool_level: f64,
pub key_rotation_lag: Duration,
pub audit_log_integrity: bool,
}
pub async fn monitor_security() -> Result<(), MonitoringError> {
loop {
let metrics = collect_security_metrics().await?;
// Check thresholds
if metrics.failed_auth_attempts > 100 {
alert(AlertType::BruteForceAttempt).await?;
}
if metrics.entropy_pool_level < 0.5 {
alert(AlertType::LowEntropy).await?;
}
if !metrics.audit_log_integrity {
alert(AlertType::AuditTamper).await?;
}
// Update dashboard
dashboard::update(metrics).await?;
tokio::time::sleep(Duration::from_secs(60)).await;
}
}
Backup and Recovery
Procedure SO-002: Secure Backup Procedures
Purpose: Enable recovery while maintaining security.
Backup Process:
pub async fn backup_security_data() -> Result<BackupId, BackupError> {
// Step 1: Create backup encryption key
let backup_key = generate_backup_key()?;
// Step 2: Collect security-critical data
let backup_data = BackupData {
master_keys: export_master_keys()?,
key_metadata: export_key_metadata()?,
audit_logs: export_audit_logs()?,
configuration: export_security_config()?,
};
// Step 3: Encrypt backup
let encrypted = encrypt_backup(&backup_data, &backup_key)?;
// Step 4: Split key using Shamir's Secret Sharing
let key_shares = shamir::split_secret(&backup_key, 5, 3)?; // 5 shares, 3 to recover
// Step 5: Store encrypted backup
let backup_id = secure_storage::store_backup(encrypted).await?;
// Step 6: Distribute key shares
for (i, share) in key_shares.iter().enumerate() {
key_custodian::store_share(i, share).await?;
}
Ok(backup_id)
}
Performance Optimization
Procedure SO-003: Security Performance Tuning
Purpose: Optimize security operations without compromising protection.
Optimization Strategies:
- Caching
pub struct SecurityCache { // Cache validated tokens token_cache: LruCache<TokenId, TokenInfo>, // Cache key derivations derived_keys: LruCache<(KeyId, Context), DerivedKey>, // Cache permission checks permissions: LruCache<(UserId, Resource), Permission>, } - Batch Operations
pub async fn batch_encrypt(items: Vec<Data>) -> Result<Vec<EncryptedData>, CryptoError> { // Process in parallel batches let batch_size = 1000; let mut results = Vec::with_capacity(items.len()); for chunk in items.chunks(batch_size) { let batch_results: Vec<_> = chunk .par_iter() .map(|item| encrypt(item)) .collect::<Result<Vec<_>, _>>()?; results.extend(batch_results); } Ok(results) }
Appendices
Appendix A: Security Contacts
| Role | Contact | Availability |
|---|---|---|
| Security Lead | security@metamui.id | 24/7 |
| Incident Response | incident@metamui.id | 24/7 |
| Compliance Officer | compliance@metamui.id | Business hours |
| External Auditor | auditor@security-firm.com | Scheduled |
Appendix B: Tool References
| Tool | Purpose | Documentation |
|---|---|---|
| cargo-fuzz | Fuzzing | Link |
| cargo-audit | Dependency scanning | Link |
| MIRI | Undefined behavior detection | Link |
Appendix C: Compliance Matrices
| Requirement | FIPS 140-3 (informative; not validated) | Common Criteria | Implementation |
|---|---|---|---|
| Crypto Algorithms | Approved only | Validated | ✓ Implemented |
| Key Management | Secure lifecycle | Formal model | ✓ Implemented |
| Audit Logging | Required | Required | ✓ Implemented |
| Self-Tests | Mandatory | Recommended | ✓ Implemented |
Document Version: 1.0 Last Updated: January 2025 Next Review: April 2025