Security Best Practices
Security Best Practices
Implement comprehensive security measures across all layers of your infrastructure to protect against threats and ensure compliance.
Security Framework
A robust security strategy requires a multi-layered approach addressing people, processes, and technology.
Defense in Depth
- Perimeter Security: Firewalls, IDS/IPS, DDoS protection
- Network Security: Segmentation, encryption, access controls
- Host Security: Hardening, patching, endpoint protection
- Application Security: Secure coding, WAF, input validation
- Data Security: Encryption, classification, DLP
Access Control
Identity and Access Management (IAM)
- Principle of Least Privilege: Grant minimum required permissions
- Role-Based Access Control (RBAC): Assign permissions to roles, not users
- Multi-Factor Authentication (MFA): Require for all privileged access
- Regular Access Reviews: Quarterly audits of user permissions
SSH Key Management
# Generate strong SSH key
ssh-keygen -t ed25519 -C "[email protected]" -f ~/.ssh/id_ed25519
# Restrict permissions
chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_ed25519
chmod 644 ~/.ssh/id_ed25519.pub
# Configure SSH daemon (sshd_config)
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
MaxAuthTries 3
ClientAliveInterval 300
ClientAliveCountMax 2
Privileged Access Management
- Use sudo instead of root login
- Implement just-in-time (JIT) access
- Record and audit privileged sessions
- Rotate privileged credentials regularly
Network Security
Firewall Configuration
Zone | Allowed Inbound | Allowed Outbound |
---|---|---|
Public DMZ | 80/443 from Internet | Specific ports to App tier |
Application | From DMZ and Management | Database ports, External APIs |
Database | From Application tier only | Backup destinations |
Management | SSH/RDP from bastion | All zones for management |
Network Segmentation
# iptables example for application server
# Default policies
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
# Allow established connections
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# Allow from load balancer
iptables -A INPUT -s 10.0.1.0/24 -p tcp --dport 8080 -j ACCEPT
# Allow database responses
iptables -A INPUT -s 10.0.3.0/24 -p tcp --sport 5432 -j ACCEPT
# Allow SSH from bastion
iptables -A INPUT -s 10.0.4.10 -p tcp --dport 22 -j ACCEPT
# Log and drop everything else
iptables -A INPUT -j LOG --log-prefix "DROPPED: "
iptables -A INPUT -j DROP
System Hardening
Linux Hardening Checklist
- ✓ Disable unnecessary services
- ✓ Remove unnecessary packages
- ✓ Configure secure kernel parameters
- ✓ Enable SELinux/AppArmor
- ✓ Configure audit logging
- ✓ Implement file integrity monitoring
Kernel Security Parameters
# /etc/sysctl.d/99-security.conf
# IP Spoofing protection
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
# Ignore ICMP redirects
net.ipv4.conf.all.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
# Ignore send redirects
net.ipv4.conf.all.send_redirects = 0
# Disable source packet routing
net.ipv4.conf.all.accept_source_route = 0
net.ipv6.conf.all.accept_source_route = 0
# Log Martians
net.ipv4.conf.all.log_martians = 1
# Ignore ICMP ping requests
net.ipv4.icmp_echo_ignore_broadcasts = 1
# Apply settings
sysctl -p /etc/sysctl.d/99-security.conf
Service Hardening
# Disable unnecessary services
systemctl disable avahi-daemon
systemctl disable cups
systemctl disable rpcbind
# Mask services to prevent starting
systemctl mask ctrl-alt-del.target
systemctl mask debug-shell.service
Application Security
Secure Coding Practices
- Input Validation: Validate all user input
- Output Encoding: Encode data for the correct context
- Parameterized Queries: Prevent SQL injection
- Session Management: Secure session handling
- Error Handling: Don't expose sensitive information
Web Application Security Headers
# Nginx security headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline';" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
API Security
- Use OAuth 2.0 / JWT for authentication
- Implement rate limiting
- Version your APIs
- Use HTTPS everywhere
- Validate and sanitize all inputs
Data Protection
Encryption at Rest
# LUKS disk encryption
# Create encrypted partition
cryptsetup luksFormat /dev/sdb1
# Open encrypted device
cryptsetup luksOpen /dev/sdb1 encrypted_disk
# Create filesystem
mkfs.ext4 /dev/mapper/encrypted_disk
# Mount
mount /dev/mapper/encrypted_disk /secure_data
Encryption in Transit
- TLS 1.3: Use latest protocols only
- Strong Ciphers: Disable weak algorithms
- Certificate Management: Automate with Let's Encrypt
- Perfect Forward Secrecy: Protect past sessions
Database Security
# PostgreSQL encryption
# Enable SSL
ssl = on
ssl_cert_file = 'server.crt'
ssl_key_file = 'server.key'
ssl_ciphers = 'HIGH:MEDIUM:+3DES:!aNULL'
# Force SSL for connections
# pg_hba.conf
hostssl all all 0.0.0.0/0 md5
# Column-level encryption
CREATE EXTENSION pgcrypto;
INSERT INTO users (email, password)
VALUES ('[email protected]', crypt('password', gen_salt('bf')));
Security Monitoring
Log Collection and Analysis
- Centralized Logging: ELK Stack, Splunk
- Security Information and Event Management (SIEM)
- Real-time Alerting: Suspicious activity detection
- Log Retention: Meet compliance requirements
Intrusion Detection
# Install and configure AIDE
apt-get install aide
# Initialize database
aideinit
# Configure monitoring (/etc/aide/aide.conf)
/bin Binaries
/sbin Binaries
/etc ConfFiles
/var/log Logs
# Run checks
aide --check
Security Metrics
Metric | Target | Measurement |
---|---|---|
Patch Compliance | 100% within 30 days | % systems patched |
Mean Time to Detect | < 24 hours | Hours from breach |
MFA Adoption | 100% privileged users | % users with MFA |
Security Training | 100% annually | % completed training |
Incident Response
Incident Response Plan
- Preparation: Team, tools, and procedures ready
- Detection: Identify potential security incidents
- Analysis: Determine scope and impact
- Containment: Limit damage and prevent spread
- Eradication: Remove threat from environment
- Recovery: Restore normal operations
- Lessons Learned: Document and improve
Incident Response Checklist
- □ Activate incident response team
- □ Document everything
- □ Preserve evidence
- □ Contain the incident
- □ Assess impact and scope
- □ Notify stakeholders
- □ Begin remediation
- □ Conduct post-mortem
Compliance and Governance
Common Compliance Standards
- PCI DSS: Payment card data protection
- HIPAA: Healthcare data privacy
- GDPR: EU data protection
- SOC 2: Service organization controls
- ISO 27001: Information security management
Security Policies
- Information Security Policy
- Acceptable Use Policy
- Data Classification Policy
- Incident Response Policy
- Business Continuity Policy
- Third-Party Security Policy
Best Practices Summary
- Automate: Security scanning, patching, compliance checks
- Monitor: Continuous monitoring of all systems
- Update: Keep all software up to date
- Train: Regular security awareness training
- Test: Regular penetration testing and audits
- Document: Maintain security documentation
Note: This documentation is provided for reference purposes only. It reflects general best practices and industry-aligned guidelines, and any examples, claims, or recommendations are intended as illustrative—not definitive or binding.