Home AWSHow to Harden an EC2 Instance on AWS: Security Best Practices

How to Harden an EC2 Instance on AWS: Security Best Practices

by Knowledge Base Linux
How to harden ec2 instance on AWS with SSH keys and security best practices illustration

Launching a server is only the first step. If you do not harden ec2 instance security right after provisioning, that server is exposed to brute-force login attempts, port scans, credential stuffing, and automated bots within minutes of going online. In this guide you will learn how to harden ec2 instance workloads on AWS using practical, proven steps: key-only SSH, least-privilege security groups, IMDSv2, automatic updates, and disabled root login. If you have not launched a server yet, start with our guide on how to launch your first EC2 instance on AWS, then return here and work through every step in order.

Security hardening is not a single setting. It is a series of small, layered decisions that together remove the easiest attack paths. Attackers look for the simplest target first, so the goal when you harden ec2 instance deployments is to make your server boring, quiet, and difficult to exploit, while keeping it easy for you to administer.

Prerequisites to Harden EC2 Instance Deployments

Before you begin, make sure you have the following ready:

  • A running EC2 instance based on Ubuntu, Debian, Amazon Linux, or another common Linux distribution.
  • An SSH key pair that you control, and a local terminal where you can test a second login session.
  • Administrator access to the AWS Management Console or the AWS CLI configured on your workstation.
  • A backup or snapshot of the instance, so you can recover quickly if you lock yourself out.
  • A maintenance window of about thirty minutes, because some changes require reconnecting to the server.

Keep your current SSH session open while you test changes in a second terminal window. That simple habit prevents most lockout accidents. For background reading, the official Amazon EC2 User Guide is the authoritative reference for instance configuration.

Step 1: Harden EC2 Instance Access with Key-Only SSH

Password authentication is the most commonly attacked login method on the public internet. Switching to key-only authentication removes that entire class of attack. First, make sure your public key is installed for your login user, then test it:

ssh -i ~/.ssh/my-key.pem ubuntu@YOUR_INSTANCE_IP
ls -la ~/.ssh/
cat ~/.ssh/authorized_keys

The .ssh directory should be owned by your user with restrictive permissions. Correct the permissions if needed:

chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

Once a key-based login works in a fresh terminal, you can safely disable passwords in the next step. Never disable password login before proving that your key works, because that is the fastest way to lock yourself out of a remote server.

Administrator workspace showing how to harden ec2 instance settings on a Linux server
Layered protection is the core idea behind every hardened Linux server.

Step 2: Disable Password Authentication and Root Login

Edit the SSH daemon configuration and set three important options. On Ubuntu and Debian the main file is /etc/ssh/sshd_config, and many images also read drop-in files from /etc/ssh/sshd_config.d/, so check both locations:

sudo nano /etc/ssh/sshd_config

PasswordAuthentication no
ChallengeResponseAuthentication no
PermitRootLogin no
PubkeyAuthentication yes

Validate the configuration before restarting the service, then reload SSH:

sudo sshd -t
sudo systemctl reload ssh || sudo systemctl reload sshd

Disabling direct root login forces every administrator to log in as a named user and then use sudo. That creates a clear audit trail and means a single compromised account does not immediately give an attacker full control. It is one of the highest-value changes you can make when you harden ec2 instance access.

Step 3: Apply Least Privilege in Security Groups

A security group is the virtual firewall in front of your instance. The most common mistake is opening SSH to the whole internet forever. Instead, allow port 22 only from your own IP address, and open web ports only when the server actually serves web traffic. Explore more AWS topics in our AWS category as you build out your setup.

Review your rules with the AWS CLI:

aws ec2 describe-security-groups --group-ids sg-0123456789abcdef0
aws ec2 authorize-security-group-ingress --group-id sg-0123456789abcdef0 --protocol tcp --port 22 --cidr YOUR_IP/32

Remove broad rules that allow 0.0.0.0/0 on administrative ports such as 22 and 3389. For teams, prefer AWS Systems Manager Session Manager or a bastion host instead of public SSH at all. Fewer open ports means a smaller attack surface, simpler audits, and fewer surprises during security reviews.

Step 4: Harden EC2 Instance Metadata with IMDSv2

The Instance Metadata Service provides temporary credentials to applications running on your server. The older IMDSv1 protocol can be abused through server-side request forgery attacks, so enforce IMDSv2, which requires a session token:

aws ec2 modify-instance-metadata-options --instance-id i-0123456789abcdef0 --http-tokens required --http-endpoint enabled

TOKEN=$(curl -s -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/

After enforcing IMDSv2, test your applications carefully. Older software that calls the metadata endpoint without a token will fail, and it is better to discover that in testing than in production. This single change blocks a well-known credential theft technique, which is why security teams recommend it for every instance.

Step 5: Enable Automatic Security Updates

Most successful intrusions exploit known vulnerabilities for which a patch already exists. On Ubuntu and Debian, install and enable unattended upgrades:

sudo apt update
sudo apt install -y unattended-upgrades
sudo dpkg-reconfigure -plow unattended-upgrades
systemctl status unattended-upgrades

On Amazon Linux, keep the system updated with the package manager and consider a scheduled update job:

sudo dnf update -y
sudo dnf upgrade --security -y

Automatic updates do not remove the need for maintenance. Check in weekly, reboot when a new kernel requires it, and monitor update logs so a failed update does not go unnoticed for months.

Step 6: Add Fail2ban as an Optional Extra Layer

Fail2ban watches log files and temporarily bans IP addresses that show repeated failed login attempts. It is optional once password authentication is disabled, but it still reduces noise and slows down persistent scanners:

sudo apt install -y fail2ban
sudo systemctl enable --now fail2ban
sudo fail2ban-client status sshd

Start with the default jail settings, review the ban list after a few days, and whitelist your own office IP address so you never ban yourself during troubleshooting. Remember that fail2ban is a supporting control, not a replacement for keys, patching, and tight firewall rules.

Troubleshooting Common Hardening Problems

Locked out after disabling passwords: Stop the instance, attach its root volume to another instance, restore the SSH configuration or add your key again, then reattach the volume and start the instance. AWS EC2 Instance Connect and serial console access can also help on supported instance types.

SSH still asks for a password: A drop-in file in /etc/ssh/sshd_config.d/ may be overriding your main configuration. Search that directory, correct the conflicting value, validate with sshd -t, and reload the service.

Application broke after IMDSv2: Update the application SDK or metadata call to request a token first. If you must roll back temporarily, set tokens to optional while you fix the code, and note the exception so it is not forgotten.

Security group change had no effect: Confirm you edited the group actually attached to the instance, and check that no second group adds the broad rule you removed. Network ACLs and local firewalls can also affect traffic independently.

Conclusion

When you harden ec2 instance security in layers, no single mistake becomes a disaster. Use key-only SSH, disable password and root login, restrict security groups to the minimum, enforce IMDSv2, patch automatically, and add fail2ban if it fits your workflow. Work through the checklist on every new server, document any exceptions, and review your rules quarterly. A short hardening routine today prevents the far longer and more expensive job of incident response tomorrow.

You may also like

KbLinux

Typically replies within a day

Hello, Welcome to the site. Please click below button for chatting me through Telegram.