HeliosDB Security Best Practices
HeliosDB Security Best Practices
Document Control
- Version: 1.0
- Last Updated: 2025-01-02
- Audience: Developers, Database Administrators, Security Engineers
- Classification: Public
Table of Contents
- Authentication and Access Control
- Encryption and Key Management
- Network Security
- Secure Development
- Auditing and Monitoring
- Data Protection
- Deployment Security
- Incident Response
1. Authentication and Access Control
1.1 Password Management
DO
- Use strong passwords: Minimum 12 characters with complexity requirements
- Enable password expiration: Force password changes every 90 days
- Implement account lockout: Lock accounts after 5 failed attempts
- Use password hashing: Argon2id with appropriate parameters
- Store password hashes securely: Never store plaintext passwords
use heliosdb_security::vault::password::PasswordPolicy;
let policy = PasswordPolicy { min_length: 12, require_uppercase: true, require_lowercase: true, require_numbers: true, require_special: true, max_age_days: Some(90), prevent_reuse: 5,};❌ DON’T
- Never hardcode passwords in source code
- Don’t transmit passwords over unencrypted connections
- Avoid using weak hashing algorithms (MD5, SHA1)
- Don’t log passwords or password hashes
- Never share passwords between users or systems
1.2 Multi-Factor Authentication
DO
- Enable MFA for privileged accounts: All admin accounts must use MFA
- Support multiple MFA methods: TOTP, SMS, hardware tokens
- Implement backup codes: Provide emergency access codes
- Audit MFA events: Log all MFA authentication attempts
Example Configuration
-- Enable MFA for a userALTER USER admin REQUIRE MFA;
-- Configure TOTP-based MFASELECT configure_mfa('admin', 'totp');1.3 Role-Based Access Control
DO
- Follow principle of least privilege: Grant minimum necessary permissions
- Use role hierarchies: Create role inheritance structures
- Regularly review permissions: Audit user access quarterly
- Separate admin and user accounts: Never use admin for regular operations
-- Create roles with minimal permissionsCREATE ROLE analyst;GRANT SELECT ON TABLE sales TO analyst;
CREATE ROLE developer;GRANT SELECT, INSERT, UPDATE ON TABLE app_data TO developer;
CREATE ROLE admin WITH SUPERUSER;
-- Assign roles to usersGRANT analyst TO alice;GRANT developer TO bob;❌ DON’T
- Don’t grant SUPERUSER to regular users
- Avoid granting ALL PRIVILEGES unnecessarily
- Don’t share role credentials between users
1.4 Row-Level Security (RLS)
DO
- Enable RLS on sensitive tables: Protect PII and confidential data
- Create comprehensive policies: Cover all access patterns
- Test RLS policies thoroughly: Verify policies work as expected
- Document RLS rules: Explain policy logic
-- Enable RLS on sensitive tableALTER TABLE customer_data ENABLE ROW LEVEL SECURITY;
-- Create policy for users to see only their own dataCREATE POLICY customer_isolation ON customer_data FOR ALL USING (user_id = current_user_id()) WITH CHECK (user_id = current_user_id());
-- Create policy for admins to see all dataCREATE POLICY admin_access ON customer_data FOR ALL TO admin_role USING (true);2. Encryption and Key Management
2.1 Transparent Data Encryption (TDE)
DO
- Enable TDE for production databases: Encrypt all data at rest
- Use strong encryption algorithms: AES-256-GCM or ChaCha20-Poly1305
- Implement key rotation: Rotate TEKs annually, MEKs every 2 years
- Use HSM or cloud KMS: Never store MEK on same server as data
use heliosdb_security::tde::{TdeConfig, EncryptionAlgorithm, KmsConfig};use std::path::PathBuf;
let config = TdeConfig { enabled: true, algorithm: EncryptionAlgorithm::Aes256Gcm, key_storage_path: PathBuf::from("/secure/keys"), default_mek_id: "production_mek_001".to_string(), cache_limit: 1000, kms_config: Some(KmsConfig::Aws(AwsKmsConfig { region: "us-east-1".to_string(), key_id: "arn:aws:kms:...".to_string(), ..Default::default() })), hsm_config: None,};❌ DON’T
- Never use ECB mode for encryption
- Don’t reuse initialization vectors (IVs)
- Avoid storing encryption keys in source code
- Don’t disable encryption in production
- Never log encryption keys
2.2 Column-Level Encryption
DO
- Encrypt sensitive columns: SSN, credit cards, PII
- Use deterministic encryption for searchable fields: Where needed
- Implement proper key management: Separate keys per data type
- Document encrypted columns: Maintain encryption inventory
-- Create table with encrypted columnsCREATE TABLE customer ( id SERIAL PRIMARY KEY, name TEXT, email TEXT, ssn TEXT ENCRYPTED DETERMINISTIC, -- Searchable credit_card TEXT ENCRYPTED RANDOM -- Not searchable, more secure);
-- Insert encrypted dataINSERT INTO customer (name, email, ssn, credit_card)VALUES ('Alice', 'alice@example.com', ENCRYPT('123-45-6789'), ENCRYPT('4111-1111-1111-1111'));2.3 Key Rotation
DO
- Rotate keys regularly: Follow key rotation schedule
- Use automated rotation: Implement rotation automation
- Maintain key history: Keep retired keys for data recovery
- Test rotation procedures: Practice rotation in non-production
use heliosdb_security::key_rotation::{KeyRotationManager, RotationConfig};
let config = RotationConfig { rotation_interval_days: 365, retain_old_keys_days: 90, auto_rotation_enabled: true, ..Default::default()};
let rotation_manager = KeyRotationManager::new(config);rotation_manager.schedule_rotation("production_tek").await?;❌ DON’T
- Don’t rotate keys without testing first
- Never delete old keys until all data is re-encrypted
- Don’t rotate all keys simultaneously
- Avoid manual key rotation processes
3. Network Security
3.1 TLS Configuration
DO
- Enforce TLS 1.3: Disable TLS 1.0 and 1.1
- Use strong cipher suites: Only AEAD ciphers
- Enable certificate validation: Verify server certificates
- Implement certificate pinning: For high-security deployments
[tls]min_version = "1.3"cipher_suites = [ "TLS_AES_256_GCM_SHA384", "TLS_CHACHA20_POLY1305_SHA256", "TLS_AES_128_GCM_SHA256"]require_client_cert = falsecert_path = "/etc/heliosdb/certs/server.crt"key_path = "/etc/heliosdb/certs/server.key"❌ DON’T
- Never disable certificate validation
- Don’t use self-signed certificates in production
- Avoid weak cipher suites (RC4, 3DES, MD5)
- Don’t expose database directly to internet
3.2 Network Isolation
DO
- Use private networks: Deploy database in private subnet
- Implement firewall rules: Allow only necessary ports
- Enable connection limits: Prevent connection exhaustion
- Use VPN or bastion hosts: For remote access
# Firewall rules example (iptables)# Allow connections only from application serversiptables -A INPUT -p tcp --dport 5432 -s 10.0.1.0/24 -j ACCEPTiptables -A INPUT -p tcp --dport 5432 -j DROP
# Connection limitsiptables -A INPUT -p tcp --dport 5432 -m connlimit \ --connlimit-above 100 --connlimit-mask 32 -j REJECT4. Secure Development
4.1 SQL Injection Prevention
DO
- Always use parameterized queries: Never concatenate SQL
- Validate all inputs: Whitelist acceptable values
- Use ORM or query builders: Leverage safe abstractions
- Escape special characters: When dynamic SQL is unavoidable
// GOOD: Parameterized querylet result = client .query("SELECT * FROM users WHERE username = $1", &[&username]) .await?;
// ❌ BAD: String concatenationlet query = format!("SELECT * FROM users WHERE username = '{}'", username);let result = client.query(&query, &[]).await?;❌ DON’T
- Never trust user input
- Don’t use string formatting for SQL
- Avoid dynamic table/column names from user input
- Don’t disable SQL injection protection
4.2 Secure Coding Practices
DO
- Validate all inputs: Check type, length, format, range
- Sanitize outputs: Encode data for appropriate context
- Handle errors securely: Don’t leak sensitive information
- Use prepared statements: For all database operations
// Input validation examplefn validate_username(username: &str) -> Result<(), ValidationError> { if username.is_empty() { return Err(ValidationError::Empty); } if username.len() > 50 { return Err(ValidationError::TooLong); } if !username.chars().all(|c| c.is_alphanumeric() || c == '_') { return Err(ValidationError::InvalidCharacters); } Ok(())}❌ DON’T
- Don’t trust client-side validation alone
- Never expose stack traces to users
- Avoid logging sensitive data
- Don’t use
unwrap()on untrusted input
4.3 Dependency Management
DO
- Keep dependencies updated: Regularly update packages
- Audit dependencies: Run
cargo auditregularly - Pin dependency versions: Use exact versions in production
- Review dependency licenses: Ensure compliance
# Check for vulnerable dependenciescargo audit
# Update dependenciescargo update
# Scan for outdated packagescargo outdated5. Auditing and Monitoring
5.1 Audit Logging
DO
- Log security events: Authentication, authorization, configuration changes
- Use structured logging: JSON format for machine parsing
- Ship logs to SIEM: Centralized log management
- Protect audit logs: Prevent unauthorized access or modification
use heliosdb_security::vault::audit::AuditLogger;
let audit_logger = AuditLogger::new(AuditConfig { enabled: true, log_level: AuditLevel::Detailed, destinations: vec![ AuditDestination::File("/var/log/heliosdb/audit.log".into()), AuditDestination::Syslog, AuditDestination::Remote("siem.example.com:514".into()), ],});
// Log security eventaudit_logger.log_auth_success( "alice", "10.0.1.100", AuthMethod::Password,).await;❌ DON’T
- Never log passwords or encryption keys
- Don’t allow users to delete audit logs
- Avoid excessive logging (performance impact)
- Don’t ignore audit log alerts
5.2 Security Monitoring
DO
- Monitor failed authentication: Alert on suspicious patterns
- Track privilege escalations: Alert on role changes
- Monitor query patterns: Detect SQL injection attempts
- Set up alerts: Notify security team of incidents
alerts: - name: Failed_Login_Attempts condition: failed_logins > 10 in 5m severity: high action: email security-team@example.com
- name: Privilege_Escalation condition: role_changed TO admin_role severity: critical action: page security-oncall
- name: SQL_Injection_Detected condition: query contains "' OR '1'='1" severity: critical action: block_ip6. Data Protection
6.1 Data Masking
DO
- Mask PII in non-production: Use realistic but fake data
- Implement dynamic masking: Show masked data to non-privileged users
- Use format-preserving masking: Maintain data format
- Document masking rules: Keep inventory of masked fields
-- Create masking policyCREATE MASKING POLICY ssn_mask AS (val TEXT) RETURNS TEXT -> CASE WHEN current_role() IN ('admin', 'auditor') THEN val ELSE 'XXX-XX-' || RIGHT(val, 4) END;
-- Apply masking policy to columnALTER TABLE customer ALTER COLUMN ssn SET MASKING POLICY ssn_mask;6.2 Data Classification
DO
- Classify all data: Public, Internal, Confidential, Restricted
- Apply appropriate controls: Based on classification
- Label sensitive columns: Use metadata tags
- Regular classification reviews: Update as data changes
-- Tag sensitive columnsCOMMENT ON COLUMN customer.ssn IS 'CLASSIFICATION:RESTRICTED PII:SSN';COMMENT ON COLUMN customer.email IS 'CLASSIFICATION:INTERNAL PII:EMAIL';6.3 Data Retention
DO
- Implement retention policies: Delete old data automatically
- Secure data deletion: Use secure wipe for sensitive data
- Archive before deletion: Keep backups as needed
- Document retention rules: Compliance requirements
-- Create retention policyCREATE RETENTION POLICY logs_retention FOR TABLE access_logs KEEP 90 DAYS ACTION DELETE;
-- Secure deletion of sensitive dataSELECT secure_delete('customer', 'id = 12345');7. Deployment Security
7.1 Configuration Management
DO
- Use environment variables: For secrets and configuration
- Store secrets in vault: HashiCorp Vault, AWS Secrets Manager
- Encrypt configuration files: Sensitive settings
- Version control configurations: Track changes
# Use environment variablesexport HELIOSDB_PASSWORD="$(vault kv get -field=password secret/heliosdb)"export HELIOSDB_ENCRYPTION_KEY="$(aws secretsmanager get-secret-value \ --secret-id heliosdb-mek --query SecretString --output text)"❌ DON’T
- Never commit secrets to git
- Don’t use default passwords
- Avoid world-readable configuration files
- Don’t store credentials in plain text
7.2 System Hardening
DO
- Run as non-root user: Use dedicated service account
- Set minimal file permissions: 600 for sensitive files
- Disable unnecessary features: Reduce attack surface
- Keep system updated: Apply security patches
# Create dedicated useruseradd -r -s /bin/false heliosdb
# Set file permissionschmod 600 /etc/heliosdb/config.tomlchmod 700 /var/lib/heliosdbchown -R heliosdb:heliosdb /var/lib/heliosdb
# Run as service usersudo -u heliosdb heliosdb-server8. Incident Response
8.1 Preparation
DO
- Document incident procedures: Step-by-step response plan
- Maintain contact list: Security team, legal, management
- Regular drills: Practice incident response
- Backup and recovery plans: Test regularly
8.2 Detection and Analysis
DO
- Monitor security alerts: 24/7 monitoring for critical systems
- Investigate anomalies: Don’t ignore unusual patterns
- Preserve evidence: Don’t alter logs or data
- Document everything: Timeline, actions taken, findings
8.3 Containment and Recovery
DO
- Isolate affected systems: Prevent further damage
- Rotate credentials: Change all passwords and keys
- Restore from clean backups: Verify backup integrity
- Conduct post-mortem: Learn from incidents
# Emergency response script#!/bin/bash
# 1. Enable detailed loggingheliosdb-cli set audit_level VERBOSE
# 2. Lock suspicious accountsheliosdb-cli lock-user suspicious_user
# 3. Rotate credentialsheliosdb-cli rotate-all-keys --emergency
# 4. Export audit logsheliosdb-cli export-logs --since="1 hour ago" --output=/secure/incident-logs/
# 5. Notify security teamalert-oncall --severity=critical --message="Potential security incident detected"9. Compliance Checklists
9.1 SOC 2 Requirements
- Encryption at rest (TDE enabled)
- Encryption in transit (TLS 1.3)
- Access controls (RBAC, RLS)
- Audit logging (comprehensive)
- Vulnerability management (scanning, patching)
- Incident response (documented procedures)
- Change management (version control)
- Vendor management (dependency auditing)
9.2 ISO 27001 Requirements
- Information security policy
- Asset management (data classification)
- Access control (authentication, authorization)
- Cryptography (key management)
- Physical security (deployment guidance)
- Operations security (monitoring, logging)
- Communications security (TLS)
- Incident management (response procedures)
9.3 GDPR Compliance
- Data encryption (TDE, column encryption)
- Access controls (RLS, RBAC)
- Audit trails (comprehensive logging)
- Right to erasure (secure deletion)
- Data portability (export capabilities)
- Data minimization (retention policies)
- Pseudonymization (data masking)
10. Quick Reference
Security Commands
# Enable TDEheliosdb-cli tde enable --algorithm=aes256gcm
# Create user with strong passwordheliosdb-cli user create alice --require-strong-password
# Enable RLS on tableheliosdb-cli rls enable --table=customer_data
# Run security auditheliosdb-cli audit run --comprehensive
# Check for vulnerabilitiesheliosdb-cli security scan --include-dependencies
# Rotate encryption keysheliosdb-cli keys rotate --key-type=tekSecurity Configuration Template
[security]mode = "strict"
[security.authentication]require_strong_passwords = truepassword_min_length = 12enable_mfa = truelockout_threshold = 5lockout_duration = "30m"
[security.encryption]tde_enabled = truetde_algorithm = "aes256gcm"enforce_column_encryption = ["ssn", "credit_card"]
[security.network]tls_min_version = "1.3"require_tls = trueallowed_ips = ["10.0.0.0/8"]
[security.auditing]audit_level = "detailed"log_destination = "/var/log/heliosdb/audit.log"remote_siem = "syslog://siem.example.com:514"11. Additional Resources
Document Version: 1.0 Last Updated: 2025-01-02 Next Review: 2025-04-02