
Complete Guide to Hardening Ubuntu EC2 Instances
Essential security measures for AWS Ubuntu servers

Table of Contents
Securing an Ubuntu EC2 instance requires a multi-layered approach that addresses network security, access control, system configuration, and continuous monitoring. This comprehensive guide walks you through essential steps to harden your Ubuntu EC2 instance, making it resilient against common security threats.
Table of Contents
- Pre-deployment Security
- Network Security
- Identity and Access Management
- Operating System Hardening
- Application Security
- Data Protection
- Monitoring and Logging
- Backup and Recovery
- Continuous Security Maintenance
Pre-deployment Security
1. Choose the Right AMI
- Use an official Ubuntu AMI from the AWS Marketplace
- Prefer LTS (Long Term Support) versions for stability and security updates
- Consider using AWS-optimized Ubuntu AMIs
- Verify AMI authenticity by checking AWS account ID (099720109477 for Ubuntu)
2. Plan Your VPC Architecture
- Deploy EC2 instances in private subnets when possible
- Use NAT Gateway for outbound internet access from private subnets
- Segregate workloads into different subnets based on security requirements
- Implement a multi-tier architecture (public, private, and database tiers)
Network Security
1. Configure Security Groups
# Example of a minimal security group for a web server
aws ec2 create-security-group --group-name web-server-sg --description "Security group for web servers"
aws ec2 authorize-security-group-ingress --group-name web-server-sg --protocol tcp --port 443 --cidr 0.0.0.0/0
aws ec2 authorize-security-group-ingress --group-name web-server-sg --protocol tcp --port 80 --cidr 0.0.0.0/0
Best Practices:
- Create separate security groups for different applications
- Allow only necessary inbound ports (e.g., 80, 443 for web servers)
- Restrict SSH access to specific IP ranges or use Systems Manager Session Manager
- Regularly review and audit security group rules
2. Enable VPC Flow Logs
aws ec2 create-flow-logs --resource-type VPC --resource-ids vpc-12345678 --traffic-type ALL --log-group-name VPCFlowLogs --deliver-logs-permission-arn arn:aws:iam::123456789012:role/flowlogsRole
3. Configure Network ACLs
- Implement subnet-level filtering as an additional security layer
- Set up both inbound and outbound rules
- Remember Network ACLs are stateless (unlike Security Groups)
4. Enable AWS WAF for Web Applications
- Configure AWS WAF rules to protect against common web exploits
- Use managed rule groups for OWASP Top 10 protection
- Monitor WAF logs for attack patterns
Identity and Access Management
1. Configure IAM Roles for EC2
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:ListBucket"
],
"Resource": [
"arn:aws:s3:::your-bucket-name/*",
"arn:aws:s3:::your-bucket-name"
]
}
]
}
2. Enable IMDSv2
aws ec2 modify-instance-metadata-options --instance-id i-1234567890abcdef0 --http-tokens required --http-endpoint enabled
3. Implement Key Rotation
- Rotate SSH keys every 90 days
- Use AWS Secrets Manager for secure key storage
- Implement automated key rotation scripts
Operating System Hardening
1. Initial System Updates
# Update the system
sudo apt update && sudo apt upgrade -y
sudo apt dist-upgrade -y
# Enable automatic security updates
sudo apt install unattended-upgrades
sudo dpkg-reconfigure --priority=low unattended-upgrades
2. Configure SSH Security
# Edit /etc/ssh/sshd_config
sudo nano /etc/ssh/sshd_config
# Add or modify these settings:
Protocol 2
PermitRootLogin no
PasswordAuthentication no
PermitEmptyPasswords no
X11Forwarding no
MaxAuthTries 3
ClientAliveInterval 300
ClientAliveCountMax 2
AllowUsers ubuntu yourusername
3. Configure Firewall (UFW)
# Install and enable UFW
sudo apt install ufw -y
# Set default policies
sudo ufw default deny incoming
sudo ufw default allow outgoing
# Allow SSH (adjust port if changed)
sudo ufw allow 22/tcp
# Allow HTTP and HTTPS if needed
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
# Enable UFW
sudo ufw enable
4. Install and Configure Fail2Ban
# Install Fail2Ban
sudo apt install fail2ban -y
# Create local jail configuration
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
sudo nano /etc/fail2ban/jail.local
# Configure SSH jail
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600
5. System Hardening Scripts
# Disable unnecessary services
sudo systemctl disable bluetooth.service
sudo systemctl disable cups.service
# Configure system limits
sudo nano /etc/security/limits.conf
# Add these lines:
* hard core 0
* soft nofile 65535
* hard nofile 65535
# Secure shared memory
echo "tmpfs /run/shm tmpfs defaults,noexec,nosuid 0 0" | sudo tee -a /etc/fstab
6. Install Security Tools
# Install security tools
sudo apt install -y lynis rkhunter clamav auditd apparmor aide
# Initialize AIDE database
sudo aideinit
sudo mv /var/lib/aide/aide.db.new /var/lib/aide/aide.db
Application Security
1. Web Server Hardening (Nginx Example)
# Hide Nginx version information
sudo nano /etc/nginx/nginx.conf
# Add: server_tokens off;
# Configure SSL/TLS
server {
listen 443 ssl http2;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
}
2. Application User Permissions
# Create application user
sudo useradd -r -s /bin/false appuser
# Set proper ownership
sudo chown -R appuser:appuser /var/www/application
# Restrict file permissions
sudo find /var/www/application -type f -exec chmod 644 {} ;
sudo find /var/www/application -type d -exec chmod 755 {} ;
Data Protection
1. Enable EBS Encryption
# Create encrypted EBS volume
aws ec2 create-volume --size 100 --region us-east-1 --availability-zone us-east-1a --encrypted
2. Configure Encryption at Rest
# Install encryption tools
sudo apt install ecryptfs-utils cryptsetup
# Configure encrypted home directories for new users
sudo apt install ecryptfs-utils
sudo ecryptfs-setup-private
3. Secure Sensitive Files
# Set proper permissions for sensitive files
sudo chmod 600 /etc/shadow
sudo chmod 600 /etc/gshadow
sudo chmod 644 /etc/passwd
sudo chmod 644 /etc/group
Monitoring and Logging
1. Configure CloudWatch Agent
# Install CloudWatch agent
wget https://s3.amazonaws.com/amazoncloudwatch-agent/ubuntu/amd64/latest/amazon-cloudwatch-agent.deb
sudo dpkg -i -E ./amazon-cloudwatch-agent.deb
# Configure the agent
sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-config-wizard
2. Set Up Audit Logging
# Configure auditd rules
sudo nano /etc/audit/rules.d/audit.rules
# Add rules for monitoring important files
-w /etc/passwd -p wa -k passwd_changes
-w /etc/shadow -p wa -k shadow_changes
-w /etc/sudoers -p wa -k sudoers_changes
3. Enable AWS Security Services
- AWS GuardDuty for threat detection
- AWS Inspector for vulnerability scanning
- AWS Config for compliance monitoring
- AWS Security Hub for centralized security view
Backup and Recovery
1. Configure Automated Snapshots
# Create snapshot lifecycle policy
aws dlm create-lifecycle-policy --description "Daily EBS snapshots" --state ENABLED --execution-role-arn arn:aws:iam::123456789012:role/AWSDataLifecycleManagerDefaultRole --policy-details file://policy.json
2. Implement Backup Scripts
#!/bin/bash
# Backup script example
DATE=$(date +%Y%m%d)
BACKUP_DIR="/backup"
S3_BUCKET="your-backup-bucket"
# Create backup
tar -czf $BACKUP_DIR/backup-$DATE.tar.gz /var/www /etc
# Upload to S3
aws s3 cp $BACKUP_DIR/backup-$DATE.tar.gz s3://$S3_BUCKET/
# Rotate old backups
find $BACKUP_DIR -type f -mtime +7 -delete
Continuous Security Maintenance
1. Regular Security Assessments
# Run Lynis audit
sudo lynis audit system
# Run ClamAV scan
sudo freshclam
sudo clamscan -r /home
# Check for rootkits
sudo rkhunter --check
2. Patch Management
# Create update script
#!/bin/bash
sudo apt update
sudo apt upgrade -y
sudo apt autoremove -y
sudo reboot
3. Security Monitoring Checklist
- Review CloudWatch logs weekly
- Check Security Hub findings
- Analyze VPC Flow Logs for suspicious traffic
- Review IAM access patterns
- Update OS and applications monthly
- Perform quarterly security assessments
- Test backup restoration procedures
- Review and update security groups
Conclusion
Hardening your Ubuntu EC2 instance is an ongoing process that requires regular attention and maintenance. By following this guide, you'll establish a strong security foundation for your EC2 instances. Remember to:
- Implement the principle of least privilege
- Keep systems updated and patched
- Monitor logs and alerts consistently
- Regularly test your security measures
- Document all security procedures
- Stay informed about new security threats and best practices
Regular security assessments and continuous improvement are key to maintaining a secure EC2 environment.
For more comprehensive cloud security guidance, check out our Cloud Security Best Practices for Australian Businesses guide.
Additional Resources
- AWS Security Best Practices
- Ubuntu Security Guide
- CIS Ubuntu Benchmarks
- AWS CloudTrail Documentation
- AWS Systems Manager
Remember: Security is not a one-time task but an ongoing process. Regular reviews and updates to your security posture are essential for maintaining a secure infrastructure.
Need Expert Help With Your Project?
Our team of specialists is ready to help you implement the strategies discussed in this article and address your specific business challenges.