Network and computeService 11 of 139 controls
Amazon EC2 security hardening
Harden Amazon EC2: require IMDSv2, replace SSH with Session Manager, encrypt EBS by default, block public snapshots and AMIs, and scan with Inspector.
On this page
Amazon EC2 is where AWS security meets classic server security: virtual machines with attached EBS volumes, an instance role whose temporary credentials are served by the Instance Metadata Service, and AMIs and snapshots that can be shared with other accounts or with everyone. The account can have perfect IAM and logging and still lose data through an instance. In the 2019 Capital One breach, a server-side request forgery (SSRF) against a misconfigured web application firewall on EC2 reached IMDSv1, retrieved the instance role's credentials, and used them to read S3 buckets. Other recurring patterns are SSH and RDP open to the internet and brute forced within hours, publicly shared EBS snapshots and AMIs that contain database dumps, keys and configuration files, broad instance roles that turn one compromised web server into account-wide access, and stolen keys used to launch cryptomining fleets. Most of these are defaults or one-click mistakes, and all of them have an account-level setting that fixes them. This page covers those AWS-side controls; operating system hardening inside the instance (SSH configuration, kernel parameters, auditd) is a separate topic, and network controls (security groups, NACLs, flow logs, endpoints) are on the Amazon VPC page.
Baseline controls
- 0101IMDSv2 required on every instance and template
IMDSv1 hands role credentials to any SSRF bug that can make a plain GET request.
How to check:aws ec2 describe-instances --filters Name=metadata-options.http-tokens,Values=optionalMapping: EC2.8, EC2.170, CIS 6.7 - 0202Account IMDS default set to required in every Region
New instances get IMDSv2 even when the launch request does not ask for it.
How to check:aws ec2 get-instance-metadata-defaults --region eu-west-1 - 0303Instances managed by Systems Manager, no SSH or RDP
Removes inbound admin ports and shared key pairs, and ties every session to an IAM identity.
How to check:aws ssm describe-instance-information --query 'InstanceInformationList[].InstanceId'Mapping: SSM.1, EC2.53, EC2.54, CIS 6.3, CIS 6.4, CIS AWS Compute 2.0.0 2.9 - 0404Session Manager activity logged and encrypted
Shell sessions are the activity you most need to replay after an incident.
How to check:aws ssm get-document --name SSM-SessionManagerRunShell - 0505EBS encryption by default in every Region
New volumes and snapshot copies are encrypted without relying on each launch request.
How to check:aws ec2 get-ebs-encryption-by-default --region eu-west-1Mapping: EC2.7, CIS 6.1.1 - 0606Snapshot and AMI block public access enabled
A public snapshot or AMI is a full disk copy, secrets included, that anyone can mount.
How to check:aws ec2 get-snapshot-block-public-access-stateMapping: EC2.182, CIS Compute 2.1.5, CIS Compute 2.2.2 - 0707Only AMIs from trusted providers can be launched
Stops launches from look-alike community AMIs published by attackers.
How to check:aws ec2 get-allowed-images-settingsMapping: CIS Compute 2.1.3 - 0808One least privilege instance role per workload
Limits what an attacker gets when instance credentials are stolen through SSRF or a shell.
How to check:aws ec2 describe-iam-instance-profile-associationsMapping: CIS 2.16 - 0909Inspector EC2 scanning enabled organization wide
Finds exploitable packages and network exposure before an attacker does.
How to check:aws inspector2 batch-get-account-statusMapping: Inspector.1
Require IMDSv2 everywhere
The Instance Metadata Service at 169.254.169.254 serves temporary credentials for the instance role. IMDSv1 answers any plain GET request, which is why SSRF bugs in web applications have been used to steal role credentials. IMDSv2 requires a session token obtained with a PUT request carrying a TTL header, which most SSRF primitives cannot send, and the token response is not forwarded beyond the configured hop limit.
CIS requires that the metadata service only allows IMDSv2, and Security Hub CSPM checks instances with EC2.8 and launch templates with EC2.170. Newer AMIs such as Amazon Linux 2023 already default to IMDSv2, but instances launched from older images, many third-party AMIs, and launch templates written years ago still allow IMDSv1.
Set the account default
Each Region has an account-level default for the metadata options of new instances:
aws ec2 modify-instance-metadata-defaults \
--region eu-west-1 \
--http-tokens required \
--http-put-response-hop-limit 2
aws ec2 get-instance-metadata-defaults --region eu-west-1
A hop limit of 1 stops the token from leaving the instance. Use 2 if you run containers on the instance that need metadata through a bridge network (the default for many container hosts); otherwise keep 1. The default only applies when the launch request does not specify metadata options, so pair it with the SCP below. AWS Organizations declarative policies for EC2 can also set these IMDS defaults for every account and Region in an OU.
Migrate existing instances
# Find instances still allowing IMDSv1
aws ec2 describe-instances \
--filters Name=metadata-options.http-tokens,Values=optional \
--query 'Reservations[].Instances[].[InstanceId,Tags[?Key==`Name`]|[0].Value]' \
--output table
# Enforce IMDSv2 on one instance
aws ec2 modify-instance-metadata-options \
--instance-id i-0123456789abcdef0 \
--http-tokens required \
--http-endpoint enabled
Before flipping production instances, check the MetadataNoToken CloudWatch metric for each instance. A non-zero value means something on the box still calls IMDSv1 (old SDKs and agents are the usual culprits). Update them first. The change takes effect without a reboot.
Prevent regressions with an SCP
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "RequireImdsv2OnLaunch",
"Effect": "Deny",
"Action": "ec2:RunInstances",
"Resource": "arn:aws:ec2:*:*:instance/*",
"Condition": {
"StringNotEquals": { "ec2:MetadataHttpTokens": "required" }
}
},
{
"Sid": "DenyHopLimitAbove2",
"Effect": "Deny",
"Action": "ec2:RunInstances",
"Resource": "arn:aws:ec2:*:*:instance/*",
"Condition": {
"NumericGreaterThan": { "ec2:MetadataHttpPutResponseHopLimit": "2" }
}
},
{
"Sid": "DenyMetadataOptionChanges",
"Effect": "Deny",
"Action": "ec2:ModifyInstanceMetadataOptions",
"Resource": "*",
"Condition": {
"ArnNotLike": { "aws:PrincipalArn": "arn:aws:iam::*:role/PlatformAdmin" }
}
}
]
}
See the AWS Organizations page for how to roll guardrails out through OUs without breaking existing workloads.
Replace SSH and RDP with Session Manager
Open port 22 or 3389 is the most common EC2 finding, and key pairs shared across a team are hard to rotate and impossible to attribute. AWS Systems Manager Session Manager gives shell (and RDP via Fleet Manager) access through the SSM Agent's outbound connection. No inbound ports, no bastion hosts, no SSH keys, and every session is authorized by IAM and logged.
Prerequisites
- SSM Agent installed (preinstalled on Amazon Linux, Ubuntu Server and Windows Server AMIs from AWS).
- Outbound HTTPS to the
ssm,ssmmessagesandec2messagesendpoints, either through a NAT gateway or through interface VPC endpoints (see the Amazon VPC page). - An instance role with the AWS managed policy
AmazonSSMManagedInstanceCore, or the Default Host Management Configuration enabled so Systems Manager manages instances without changing their roles.
Security Hub CSPM control SSM.1 reports instances that are not managed by Systems Manager.
Start a session
aws ssm start-session --target i-0123456789abcdef0
# Port forwarding to a database behind the instance, no inbound rules needed
aws ssm start-session --target i-0123456789abcdef0 \
--document-name AWS-StartPortForwardingSessionToRemoteHost \
--parameters '{"host":["mydb.cluster-abc.eu-west-1.rds.amazonaws.com"],"portNumber":["5432"],"localPortNumber":["5432"]}'
Log every session
Session preferences live in the SSM-SessionManagerRunShell document. Configure encrypted logging to S3 and CloudWatch Logs:
{
"schemaVersion": "1.0",
"description": "Session Manager preferences",
"sessionType": "Standard_Stream",
"inputs": {
"s3BucketName": "org-ssm-session-logs-111122223333",
"s3EncryptionEnabled": true,
"cloudWatchLogGroupName": "/ssm/sessions",
"cloudWatchEncryptionEnabled": true,
"cloudWatchStreamingEnabled": true,
"kmsKeyId": "arn:aws:kms:eu-west-1:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
"idleSessionTimeout": "20",
"runAsEnabled": false
}
}
aws ssm update-document \
--name SSM-SessionManagerRunShell \
--content file://session-prefs.json \
--document-version '$LATEST'
The kmsKeyId setting also encrypts the session data stream end to end. The key policy must let the instance role and the users starting sessions call kms:Decrypt and kms:GenerateDataKey; the AWS KMS page shows how to scope that. Port forwarding sessions are not captured by session logging, only the fact that they were started, so limit who can use the port forwarding documents.
Close the ports and stop creating key pairs
Remove inbound 22 and 3389 rules from every security group (EC2.53 and EC2.54) and stop creating key pairs. To enforce the second part, deny ec2:CreateKeyPair and ec2:ImportKeyPair with an SCP in workload OUs. Control who can open sessions with IAM conditions on ssm:StartSession, for example limiting it to instances tagged with the caller's team using ssm:resourceTag/Team and aws:PrincipalTag/Team. Keep the EC2 serial console disabled at the account level (aws ec2 get-serial-console-access-status) unless you have a documented break-glass need for it.
Encrypt EBS by default
CIS requires EBS volume encryption in all Regions, and Security Hub CSPM checks it as EC2.7 ("EBS default encryption should be enabled"). The setting is per Region and affects new volumes and snapshot copies:
for r in $(aws ec2 describe-regions --query 'Regions[].RegionName' --output text); do
aws ec2 enable-ebs-encryption-by-default --region "$r"
aws ec2 get-ebs-encryption-by-default --region "$r" --query EbsEncryptionByDefault
done
# Use a customer managed key instead of aws/ebs
aws ec2 modify-ebs-default-kms-key-id \
--region eu-west-1 \
--kms-key-id alias/ebs-default
A customer managed key is needed if you plan to share encrypted snapshots or AMIs across accounts, because the AWS managed aws/ebs key cannot be shared. It also lets you revoke access to every volume by changing one key policy. Existing unencrypted volumes are not converted: create an encrypted snapshot copy and replace the volume. Launch templates should also set encryption explicitly for their block devices (EC2.181).
To stop anyone turning the setting off, deny ec2:DisableEbsEncryptionByDefault in an SCP for every principal except your platform role.
Block public snapshots and AMIs
A public EBS snapshot is a full copy of a disk that anyone can mount in their own account. Public AMIs carry the same risk, plus they can be launched by others. Two Region-level settings prevent this:
# EBS snapshots: block all public sharing
aws ec2 enable-snapshot-block-public-access --state block-all-sharing
aws ec2 get-snapshot-block-public-access-state
# AMIs: block new public sharing
aws ec2 enable-image-block-public-access \
--image-block-public-access-state block-new-sharing
aws ec2 get-image-block-public-access-state
Security Hub CSPM checks the snapshot setting with EC2.182. Both settings can be enforced across the organization with AWS Organizations declarative policies for EC2, which also cover the IMDS defaults, Allowed AMIs and VPC Block Public Access.
Find anything already exposed
aws ec2 describe-snapshots --owner-ids self \
--restorable-by-user-ids all --query 'Snapshots[].SnapshotId'
aws ec2 describe-images --owners self \
--filters Name=is-public,Values=true --query 'Images[].ImageId'
The AMI setting in block-new-sharing mode does not make AMIs that are already public private, so remove public launch permissions from anything this query returns. Treat any snapshot or AMI that was public as a leak: rotate every secret that was on that disk.
Allow only trusted AMIs
The opposite risk is launching someone else's image. Datadog Security Labs' "whoAMI" research showed that automation which searches for an AMI by name without filtering on the owner can pick up a look-alike public AMI published by an attacker. Allowed AMIs is an account-level, per-Region setting that restricts which public and shared AMIs can be discovered and launched, by provider (amazon, aws-marketplace or specific account IDs), name, age or Inspector scan result. AMIs owned by your own account are always allowed.
# Start in audit mode to see what would be blocked
aws ec2 enable-allowed-images-settings --allowed-images-settings-state audit-mode
# Allow Amazon and your golden image account only
aws ec2 replace-image-criteria-in-allowed-images-settings \
--cli-input-json file://allowed-images.json
aws ec2 get-allowed-images-settings
# After reviewing, enforce
aws ec2 enable-allowed-images-settings --allowed-images-settings-state enabled
{
"ImageCriteria": [
{ "ImageProviders": ["amazon", "111122223333"] }
]
}
In audit mode, describe-images returns ImageAllowed for each AMI, and the AWS Config rule ec2-instance-launched-with-allowed-ami flags running instances launched from images outside the criteria. Managed services such as Amazon EKS and Amazon ECS depend on Amazon-published AMIs, so keep the amazon alias. Enforce the setting across accounts with a declarative policy, which also prevents local changes.
Scope instance profiles tightly
CIS recommends using IAM instance roles for AWS access from instances rather than embedded access keys, and that is the easy part. The common mistake is one broad role (often with AmazonS3FullAccess or worse) attached to every instance. Each workload should have its own role, with permissions generated from actual usage. IAM Access Analyzer policy generation, described on the AWS IAM page, builds that policy from CloudTrail activity.
# Which role is attached to which instance
aws ec2 describe-iam-instance-profile-associations \
--query 'IamInstanceProfileAssociations[].[InstanceId,IamInstanceProfile.Arn]' \
--output table
Limit where instance credentials work
Two sets of condition keys limit what stolen instance credentials can do:
aws:EC2InstanceSourceVPCandaws:EC2InstanceSourcePrivateIPv4are added to requests made with instance role credentials, so a policy can deny use of those credentials from outside the instance's VPC.ec2:RoleDeliverylets you require that role credentials were delivered through IMDSv2 ("NumericLessThan": {"ec2:RoleDelivery": "2.0"}in a deny statement).
This SCP statement, adapted from the AWS Security Blog, denies any request made with EC2 instance credentials unless it arrives through a VPC endpoint in the instance's own VPC:
{
"Sid": "DenyInstanceCredsOutsideTheirVpc",
"Effect": "Deny",
"Action": "*",
"Resource": "*",
"Condition": {
"StringNotEquals": { "aws:ec2InstanceSourceVPC": "${aws:SourceVpc}" },
"Null": { "ec2:SourceInstanceARN": "false" },
"BoolIfExists": { "aws:ViaAWSService": "false" },
"ArnNotLike": { "aws:PrincipalArn": "arn:aws:iam::*:role/aws:ec2-infrastructure" }
}
}
Because aws:SourceVpc is only present on requests that pass through a VPC endpoint, this statement also denies calls that go to public service endpoints through a NAT gateway, so it fits VPCs where every service the workload uses has an endpoint. The Null check limits it to EC2 instance role credentials, and the aws:ec2-infrastructure exception lets EC2 itself use KMS when attaching encrypted volumes. Test it in a sandbox OU first. GuardDuty also detects instance credentials used from outside AWS or from another account (see the Amazon GuardDuty page).
Scan for vulnerabilities and patch
Amazon Inspector continuously scans EC2 instances for software vulnerabilities and unintended network exposure. It can use the SSM Agent or an agentless snapshot-based scan. Security Hub CSPM checks that EC2 scanning is enabled with Inspector.1.
aws inspector2 enable --resource-types EC2 ECR
aws inspector2 batch-get-account-status
aws inspector2 list-findings \
--filter-criteria '{"severity":[{"comparison":"EQUALS","value":"CRITICAL"}]}' \
--max-results 20
In an organization, designate a delegated administrator for Inspector and enable it for all members, the same pattern as for GuardDuty and Security Hub CSPM. Close the loop with Systems Manager Patch Manager and a patch baseline per operating system (SSM.2 checks patch compliance), and avoid public IPv4 addresses on instances that do not need them (EC2.9).
Logging and detection
What to log:
- CloudTrail management events for EC2 and Systems Manager. The ones that matter most:
ModifyInstanceMetadataOptions,ModifySnapshotAttribute,ModifyImageAttribute,DisableEbsEncryptionByDefault,DisableSnapshotBlockPublicAccess,DisableImageBlockPublicAccess,CreateKeyPair,ImportKeyPair,RunInstancesandssm:StartSession. See the AWS CloudTrail page. - Session Manager logs to S3 and CloudWatch Logs, as configured above.
- The
MetadataNoTokenCloudWatch metric, which tells you an instance is still making IMDSv1 calls.
What to alert on:
- A snapshot shared publicly. This EventBridge pattern matches
ModifySnapshotAttributecalls that add theallgroup:
{
"source": ["aws.ec2"],
"detail-type": ["AWS API Call via CloudTrail"],
"detail": {
"eventName": ["ModifySnapshotAttribute"],
"requestParameters": {
"createVolumePermission": {
"add": { "items": { "group": ["all"] } }
}
}
}
}
- Any call that disables a guardrail: the
Disable*events above, andModifyInstanceMetadataOptionswithhttpTokensset tooptional. - GuardDuty findings
UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.OutsideAWSand.InsideAWS(instance role credentials used elsewhere),UnauthorizedAccess:EC2/MetadataDNSRebind,CryptoCurrency:EC2/BitcoinTool.Band the SSH or RDP brute force findings. - Inspector findings of critical severity on internet-reachable instances, routed through Security Hub CSPM.
Common mistakes
- Enforcing IMDSv2 on instances but not templates. Auto Scaling groups relaunch from launch templates, so an old template quietly brings IMDSv1 back. EC2.170 and the SCP close that gap.
- Hop limit too high. Setting the hop limit to 64 "to make containers work" lets the token travel through proxies and undoes part of the protection. Use 2 for container hosts, 1 elsewhere.
- Session Manager next to an open port 22. Adopting Session Manager without removing the inbound rules and key pairs leaves the old path in place. Close the ports and deny key pair creation.
- Sharing snapshots with the aws/ebs key. Snapshots encrypted with the AWS managed key cannot be shared, so teams fall back to unencrypted copies. Use a customer managed key from the start.
- One role for the whole fleet. A shared instance role with broad S3 or IAM permissions turns any single compromised instance into an account compromise.
- Assuming block-new-sharing cleaned up old AMIs. It only stops new public sharing. Search for and remove existing public AMIs separately.
- Looking up AMIs by name only. Automation that filters on
namewithoutowner-idcan launch an attacker's AMI. Always filter on owner, and use Allowed AMIs as the backstop.
References
- Amazon EC2 User Guide: Transition to using IMDSv2
- AWS Security Blog: Get the full benefits of IMDSv2 and disable IMDSv1 across your AWS infrastructure
- AWS Security Blog: How to use policies to restrict where EC2 instance credentials can be used from
- AWS Systems Manager: Logging session activity
- Amazon EBS User Guide: Encryption by default
- Amazon EBS User Guide: Block public access for snapshots
- Amazon EC2 User Guide: Control the discovery and use of AMIs with Allowed AMIs
- AWS Organizations: Declarative policies
- AWS Security Hub CSPM controls for Amazon EC2
- Capital One: 2019 cyber incident, what happened
- Datadog Security Labs: From detection to enforcement, migrating from IMDSv1 to IMDSv2
- Datadog Security Labs: whoAMI, a cloud image name confusion attack
- Pacu: AWS exploitation framework (Rhino Security Labs)
- MITRE ATT&CK T1552.005: Cloud Instance Metadata API
Written by
Florian AmetteSecurity engineer writing practical, benchmark-aligned hardening baselines for AWS services, from the organization and identities to data, networks and workloads.