Security Remediation Strategies
This document provides comprehensive remediation strategies for common security vulnerabilities, organized by vulnerability category.
Buffer Overflow Vulnerabilities
CWE-120: Buffer Copy without Checking Size of Input
Unsafe Patterns:
strcpy(),strcat(),sprintf(),gets()- Fixed-size buffers with unchecked input
Remediation Strategies:
Use Safe String Functions
- Replace
strcpy()withstrncpy()orstrlcpy() - Replace
strcat()withstrncat()orstrlcat() - Replace
sprintf()withsnprintf() - Never use
gets()- usefgets()instead
- Replace
Bounds Checking
- Always validate input length before copying
- Use
sizeof()to determine buffer capacity - Leave room for null terminator
Modern Language Features
- Use
std::stringin C++ instead of char arrays - Use safe string libraries (SafeStr, Bstrlib)
- Use
Trade-offs:
- Performance: Minimal overhead for bounds checking
- Compatibility: May require refactoring existing code
- Complexity: Slightly more verbose code
CWE-121: Stack-based Buffer Overflow
Remediation Strategies:
Stack Canaries
- Enable compiler protections (
-fstack-protector-all) - Use Address Space Layout Randomization (ASLR)
- Enable compiler protections (
Input Validation
- Validate all external input sizes
- Use length-prefixed strings
- Implement maximum size limits
Safe Alternatives
- Use dynamic allocation with size tracking
- Implement custom safe buffer types
Injection Vulnerabilities
CWE-89: SQL Injection
Unsafe Patterns:
- String concatenation for SQL queries
- Unescaped user input in queries
- Dynamic query construction
Remediation Strategies:
Parameterized Queries (Preferred)
- Use prepared statements with bound parameters
- Separates SQL logic from data
- Prevents injection by design
ORM Frameworks
- Use Object-Relational Mapping tools
- Abstracts SQL generation
- Built-in injection protection
Input Validation
- Whitelist allowed characters
- Validate data types and formats
- Reject suspicious patterns
Stored Procedures
- Encapsulate SQL logic
- Parameterized by default
- Centralized security control
Trade-offs:
- Parameterized queries: Best security, minimal performance impact
- ORMs: Easier development, potential performance overhead
- Stored procedures: Centralized logic, less flexible
CWE-78: OS Command Injection
Unsafe Patterns:
system(),exec(),popen()with user input- Shell metacharacters in commands
- Unvalidated command arguments
Remediation Strategies:
Avoid Shell Execution
- Use language-specific APIs instead of shell commands
- Direct system calls (e.g.,
os.remove()vsrm) - Library functions for file operations
Parameterized Execution
- Use
subprocesswith argument lists (Python) - Use
execve()family instead ofsystem() - Pass arguments as array, not concatenated string
- Use
Input Sanitization
- Whitelist allowed characters
- Escape shell metacharacters
- Validate against expected patterns
Sandboxing
- Run commands in restricted environment
- Use containers or VMs
- Apply principle of least privilege
Trade-offs:
- API alternatives: Best security, may require code restructuring
- Sanitization: Defense in depth, but error-prone
- Sandboxing: Strong isolation, operational complexity
CWE-79: Cross-Site Scripting (XSS)
Remediation Strategies:
Output Encoding
- HTML entity encoding for HTML context
- JavaScript encoding for JS context
- URL encoding for URL parameters
- CSS encoding for style attributes
Content Security Policy (CSP)
- Restrict script sources
- Disable inline scripts
- Use nonces or hashes for trusted scripts
Input Validation
- Whitelist allowed HTML tags (if needed)
- Sanitize user input
- Reject dangerous patterns
Framework Protection
- Use auto-escaping templates
- React/Vue/Angular built-in XSS protection
- Avoid
dangerouslySetInnerHTMLorv-html
Trade-offs:
- Output encoding: Essential, minimal overhead
- CSP: Strong protection, may break legacy code
- Framework protection: Easiest, requires framework adoption
Insecure Deserialization
CWE-502: Deserialization of Untrusted Data
Unsafe Patterns:
- Deserializing user-controlled data
- Using
pickle,marshal,eval()on untrusted input - Accepting serialized objects from network
Remediation Strategies:
Avoid Deserialization
- Use data-only formats (JSON, XML)
- Avoid object serialization for untrusted data
- Use simple data structures
Integrity Checks
- Sign serialized data with HMAC
- Verify signatures before deserialization
- Use authenticated encryption
Type Validation
- Whitelist allowed classes
- Implement custom deserializers
- Validate object types before use
Sandboxing
- Deserialize in isolated environment
- Restrict class loading
- Use security managers
Trade-offs:
- JSON/XML: Safest, limited to data structures
- Integrity checks: Good protection, key management overhead
- Sandboxing: Strong isolation, performance impact
Authentication & Authorization
CWE-287: Improper Authentication
Remediation Strategies:
Multi-Factor Authentication
- Implement 2FA/MFA
- Use TOTP or hardware tokens
- SMS as fallback only
Strong Password Policies
- Minimum length requirements
- Complexity requirements
- Password strength meters
- Breach detection (HaveIBeenPwned)
Secure Session Management
- Generate cryptographically random session IDs
- Implement session timeout
- Regenerate session ID after login
- Secure cookie flags (HttpOnly, Secure, SameSite)
Account Lockout
- Rate limiting on login attempts
- Progressive delays
- CAPTCHA after failures
- Account lockout with recovery
Trade-offs:
- MFA: Best security, user friction
- Password policies: Improved security, user annoyance
- Rate limiting: Prevents brute force, potential DoS
CWE-862: Missing Authorization
Remediation Strategies:
Centralized Authorization
- Implement authorization middleware
- Check permissions on every request
- Use role-based access control (RBAC)
Principle of Least Privilege
- Grant minimum necessary permissions
- Default deny policy
- Explicit permission checks
Resource-Level Checks
- Verify user owns resource
- Check permissions before operations
- Validate indirect object references
Authorization Frameworks
- Use established libraries (Casbin, Spring Security)
- Policy-based access control
- Attribute-based access control (ABAC)
Trade-offs:
- Centralized authorization: Consistent enforcement, single point of failure
- Fine-grained checks: Better security, more code
- Frameworks: Robust features, learning curve
Cryptographic Issues
CWE-327: Use of Broken Cryptography
Unsafe Patterns:
- MD5, SHA1 for security purposes
- DES, 3DES, RC4 encryption
- ECB mode for block ciphers
- Custom crypto implementations
Remediation Strategies:
Modern Algorithms
- Use SHA-256 or SHA-3 for hashing
- Use AES-256 for symmetric encryption
- Use RSA-2048+ or ECC for asymmetric crypto
- Use Argon2, bcrypt, or scrypt for passwords
Proper Modes
- Use GCM or CCM for authenticated encryption
- Use CBC with HMAC if GCM unavailable
- Never use ECB mode
- Use random IVs for each encryption
Established Libraries
- Use libsodium, OpenSSL, or platform crypto APIs
- Avoid implementing crypto primitives
- Keep libraries updated
Key Management
- Generate keys with CSPRNG
- Store keys securely (HSM, key vault)
- Rotate keys regularly
- Use key derivation functions
Trade-offs:
- Modern algorithms: Better security, may break compatibility
- Authenticated encryption: Prevents tampering, slightly larger output
- Library updates: Security patches, potential breaking changes
CWE-330: Insufficient Randomness
Remediation Strategies:
Cryptographically Secure RNG
- Use
/dev/urandom(Linux) - Use
CryptGenRandom(Windows) - Use
secretsmodule (Python) - Use
crypto.randomBytes()(Node.js)
- Use
Avoid Weak RNGs
- Never use
rand(),srand()for security - Don't use
Math.random()for tokens - Avoid predictable seeds
- Never use
Sufficient Entropy
- Use at least 128 bits for session tokens
- Use 256 bits for cryptographic keys
- Don't truncate random values
Trade-offs:
- CSPRNG: Essential for security, slightly slower
- Entropy requirements: Better security, larger tokens
Memory Safety
CWE-416: Use After Free
Remediation Strategies:
Nullify Pointers
- Set pointers to NULL after free
- Check for NULL before dereferencing
- Use defensive programming
Smart Pointers
- Use
std::unique_ptr,std::shared_ptr(C++) - Automatic memory management
- RAII pattern
- Use
Memory-Safe Languages
- Use Rust for memory safety guarantees
- Use garbage-collected languages
- Consider language migration
Static Analysis
- Use AddressSanitizer (ASan)
- Use Valgrind for memory debugging
- Enable compiler warnings
Trade-offs:
- Smart pointers: Prevents many issues, slight overhead
- Language migration: Best long-term solution, high cost
- Static analysis: Catches bugs early, CI/CD integration needed
CWE-476: NULL Pointer Dereference
Remediation Strategies:
Null Checks
- Check return values before use
- Validate pointers before dereferencing
- Use assertions in debug builds
Error Handling
- Return error codes or exceptions
- Use Option/Maybe types
- Fail fast on invalid state
Defensive Programming
- Initialize pointers to NULL
- Use const correctness
- Validate function parameters
Trade-offs:
- Null checks: Prevents crashes, verbose code
- Option types: Type-safe, requires language support
- Defensive programming: Robust code, more boilerplate
Configuration & Deployment
CWE-798: Hard-coded Credentials
Remediation Strategies:
Environment Variables
- Store secrets in environment
- Use
.envfiles (not in version control) - Access via
os.getenv()or similar
Secret Management
- Use HashiCorp Vault
- Use AWS Secrets Manager
- Use Azure Key Vault
- Use Kubernetes Secrets
Configuration Files
- External config files (not in repo)
- Encrypted configuration
- File permissions (600)
Credential Rotation
- Regular password changes
- Automated rotation
- Revoke old credentials
Trade-offs:
- Environment variables: Simple, limited features
- Secret management: Enterprise-grade, operational complexity
- Rotation: Better security, coordination overhead
CWE-732: Incorrect Permission Assignment
Remediation Strategies:
Principle of Least Privilege
- Minimum necessary permissions
- Restrict file permissions (644 for files, 755 for dirs)
- Use umask appropriately
Access Control Lists
- Fine-grained permissions
- Group-based access
- Regular audits
Secure Defaults
- Restrictive default permissions
- Explicit permission grants
- Deny by default
Trade-offs:
- Restrictive permissions: Better security, may break functionality
- ACLs: Fine-grained control, complexity
- Regular audits: Catches drift, requires automation