Skip to content

Network and computeService 10 of 139 controls

Amazon VPC security hardening

Harden Amazon VPC: empty default security groups, no SSH or RDP from the internet, flow logs, endpoint policies and VPC Block Public Access.

Published on Updated on 12 min readTags:#network#data-protection#logging
On this page

Amazon VPC is the private network every EC2 instance, RDS database, Lambda function in a VPC and EKS node lives in: subnets, route tables, internet and NAT gateways, security groups, network ACLs and endpoints. Identity is the primary perimeter in AWS, but the network still decides how far a single mistake travels. The defaults work against you: every Region of every account has a default VPC with public subnets and an internet gateway, every VPC has a default security group that lets its members talk freely, and nothing stops a team from opening SSH to 0.0.0.0/0. Exposed RDP and SSH ports are one of the most common ways in for ransomware and cryptomining crews, which brute force or reuse credentials against anything that answers. On the way out, an instance with unrestricted egress can copy data to any S3 bucket on the internet, including one the attacker owns. This page covers the network controls to apply to every VPC, how to verify them and how to enforce them across an organization. Instance level settings (IMDSv2, Session Manager, EBS encryption) are on the Amazon EC2 page.

Baseline controls

9 controlsCIS numbers refer to the CIS AWS Foundations Benchmark v7.1.0 unless another CIS benchmark is named; Security Hub CSPM IDs are listed where a control exists.
  1. 01Default security group has no rules

    Resources launched without a group otherwise talk freely to each other and to the internet.

    How to check: aws ec2 describe-security-groups --filters Name=group-name,Values=default
    Mapping: EC2.2, CIS 6.5
  2. 02Unused default VPCs deleted

    Default VPCs ship with public subnets and an internet gateway in every Region.

    How to check: aws ec2 describe-vpcs --filters Name=is-default,Values=true
  3. 03No SSH or RDP from 0.0.0.0/0 or ::/0 in security groups

    Internet-facing admin ports are scanned within minutes and brute forced continuously.

    How to check: aws ec2 describe-security-groups --filters Name=ip-permission.cidr,Values=0.0.0.0/0
    Mapping: EC2.53, EC2.54, CIS 6.3, CIS 6.4
  4. 04NACLs deny admin ports from anywhere

    A subnet deny holds even when a team opens port 22 in its own security group.

    How to check: aws ec2 describe-network-acls --query 'NetworkAcls[].Entries'
    Mapping: EC2.21, CIS 6.2
  5. 05Flow logs on every VPC to a central archive

    Without flow logs you cannot reconstruct what an attacker reached or exfiltrated.

    How to check: aws ec2 describe-flow-logs --query 'FlowLogs[].[ResourceId,LogDestination]'
    Mapping: EC2.6, CIS 4.7
  6. 06S3 and DynamoDB endpoints limited to org resources

    Stops a compromised workload from copying data to an attacker-owned bucket.

    How to check: aws ec2 describe-vpc-endpoints --query 'VpcEndpoints[].PolicyDocument'
    Mapping: CIS 6.8
  7. 07Internal buckets reachable only from your network

    Stolen credentials become useless against the data when used outside your VPCs.

    How to check: aws s3api get-bucket-policy --bucket prod-internal-data
  8. 08VPC Block Public Access on in every Region

    Overrides routes and security groups so a mistake cannot expose a VPC to the internet.

    How to check: aws ec2 describe-vpc-block-public-access-options
    Mapping: EC2.172
  9. 09Internet reachability analyzed on a schedule

    Proves no path exists from the internet to databases, whatever the individual rules say.

    How to check: aws ec2 describe-network-insights-access-scopes

Security groups and network ACLs

Two layers filter traffic inside a VPC:

Security groupNetwork ACL
Attached toElastic network interfaceSubnet
StateStateful (return traffic allowed automatically)Stateless (return traffic needs its own rule)
RulesAllow onlyAllow and deny, evaluated in rule number order
Typical usePer workload access controlCoarse subnet guardrails, explicit denies

Security groups do the real work. NACLs are a backstop: they let you deny something regardless of what an application team puts in its security groups. The CIS AWS Foundations Benchmark networking section and the Security Hub CSPM EC2 controls check both layers.

Lock down the default security group

Every VPC has a default security group that allows all inbound traffic from members of the same group and all outbound traffic. Resources launched without an explicit group land in it, and they can then reach each other freely and anything on the internet.

CIS requires that the default security group of every VPC restricts all traffic, and Security Hub CSPM checks it as EC2.2 ("VPC default security groups should not allow inbound or outbound traffic"). You cannot delete the default group, so remove its rules:

VPC_ID=vpc-0abc1234def567890
SG_ID=$(aws ec2 describe-security-groups \
  --filters Name=vpc-id,Values=$VPC_ID Name=group-name,Values=default \
  --query 'SecurityGroups[0].GroupId' --output text)

aws ec2 revoke-security-group-ingress --group-id "$SG_ID" \
  --ip-permissions "$(aws ec2 describe-security-groups --group-ids $SG_ID \
  --query 'SecurityGroups[0].IpPermissions' --output json)"

aws ec2 revoke-security-group-egress --group-id "$SG_ID" \
  --ip-permissions "$(aws ec2 describe-security-groups --group-ids $SG_ID \
  --query 'SecurityGroups[0].IpPermissionsEgress' --output json)"

Run it in every Region, including VPCs you do not use. Console: VPC > Security groups, filter on the group name default, then edit inbound and outbound rules.

Delete unused default VPCs

Default VPCs exist in every Region so that a launch "just works", which means a public IP address and a route to an internet gateway by default. If you build your networks with infrastructure as code, delete the default VPC in every Region you do not use:

for r in $(aws ec2 describe-regions --query 'Regions[].RegionName' --output text); do
  aws ec2 describe-vpcs --region "$r" --filters Name=is-default,Values=true \
    --query 'Vpcs[].VpcId' --output text
done

Deleting a VPC requires removing its subnets, internet gateway and any interfaces first; the console's delete action does this in one step for an empty default VPC. If you need a default VPC later, aws ec2 create-default-vpc recreates it. Combine this with an SCP that denies ec2:* outside approved Regions (see the AWS Organizations page) so nobody launches into a Region you are not watching.

Close administration ports to the internet

CIS has three related recommendations: no NACL allowing ingress from 0.0.0.0/0 to remote administration ports, and no security group allowing ingress from 0.0.0.0/0 or ::/0 to those ports. Security Hub CSPM checks them as EC2.21 (NACLs), EC2.53 (security groups, IPv4) and EC2.54 (security groups, IPv6). The ports are 22 (SSH) and 3389 (RDP).

Find offending rules

aws ec2 describe-security-groups \
  --filters Name=ip-permission.cidr,Values=0.0.0.0/0 \
  --query 'SecurityGroups[?IpPermissions[?(FromPort<=`22` && ToPort>=`22`) || (FromPort<=`3389` && ToPort>=`3389`) || IpProtocol==`-1`]].[GroupId,GroupName,VpcId]' \
  --output table

aws ec2 describe-security-groups \
  --filters Name=ip-permission.ipv6-cidr,Values=::/0 \
  --query 'SecurityGroups[].[GroupId,GroupName]' --output table

The fix is not to replace 0.0.0.0/0 with a slightly smaller range. Remove inbound administration ports entirely and use Systems Manager Session Manager, which needs no inbound rule at all. The Amazon EC2 page walks through that setup.

Keep security groups readable

  • Reference other security groups instead of CIDR blocks for east-west traffic (for example, the database group allows 5432 only from the app group).
  • Use managed prefix lists for shared IP sets such as office egress addresses, so one change updates every rule.
  • Restrict egress for sensitive tiers. The default "allow all outbound" rule is what lets a compromised instance reach a command and control server or an attacker's bucket.
  • Use the security group rule Description field. During an incident, "temporary for vendor, ticket 4711" is far more useful than an unexplained /16.

Enforce across the organization

AWS Firewall Manager can apply a common security group policy and audit policies that flag or automatically remediate rules allowing 0.0.0.0/0 to administration ports in every account of the organization. If you do not use Firewall Manager, deploy the AWS Config managed rule restricted-ssh and the restricted-common-ports rule through a conformance pack, as described on the Security Hub CSPM and Config page.

Use network ACLs as subnet guardrails

Because NACLs are stateless, outbound replies need a rule for the ephemeral port range (1024 to 65535 covers most clients). A minimal public subnet NACL that denies administration ports from anywhere before allowing web traffic:

NACL_ID=acl-0abc1234def567890

aws ec2 create-network-acl-entry --network-acl-id $NACL_ID --ingress \
  --rule-number 50 --protocol tcp --port-range From=22,To=22 \
  --cidr-block 0.0.0.0/0 --rule-action deny

aws ec2 create-network-acl-entry --network-acl-id $NACL_ID --ingress \
  --rule-number 60 --protocol tcp --port-range From=3389,To=3389 \
  --cidr-block 0.0.0.0/0 --rule-action deny

aws ec2 create-network-acl-entry --network-acl-id $NACL_ID --ingress \
  --rule-number 100 --protocol tcp --port-range From=443,To=443 \
  --cidr-block 0.0.0.0/0 --rule-action allow

aws ec2 create-network-acl-entry --network-acl-id $NACL_ID --ingress \
  --rule-number 200 --protocol tcp --port-range From=1024,To=65535 \
  --cidr-block 0.0.0.0/0 --rule-action allow

Rules are evaluated lowest number first, and the first match wins, so put denies before broad allows. Add equivalent --ipv6-cidr-block ::/0 entries if the subnet has IPv6. Keep NACLs simple: complex stateless rule sets break things in ways that are painful to debug, and the security group is where fine-grained policy belongs. Every new VPC also comes with a default NACL that allows everything in and out, so subnets you forget to associate with a custom NACL get no guardrail at all.

Enable VPC Flow Logs everywhere

Flow logs record accepted and rejected IP traffic metadata at the VPC, subnet or interface level. CIS requires flow logging in all VPCs, and Security Hub CSPM checks it as EC2.6. They are essential for incident response: they tell you which hosts an attacker scanned, which ones answered, and how many bytes left through which interface. GuardDuty analyzes flow log data independently of whether you enable them (see the Amazon GuardDuty page), but GuardDuty's copy is not available to you for investigations.

Send them to a central S3 bucket in the log archive account:

aws ec2 create-flow-logs \
  --resource-type VPC \
  --resource-ids vpc-0abc1234def567890 \
  --traffic-type ALL \
  --log-destination-type s3 \
  --log-destination arn:aws:s3:::org-vpc-flow-logs-111122223333/ \
  --log-format '${version} ${account-id} ${vpc-id} ${subnet-id} ${instance-id} ${interface-id} ${srcaddr} ${dstaddr} ${srcport} ${dstport} ${protocol} ${packets} ${bytes} ${start} ${end} ${action} ${tcp-flags} ${pkt-srcaddr} ${pkt-dstaddr} ${flow-direction} ${traffic-path}' \
  --max-aggregation-interval 60

The custom format adds fields such as pkt-srcaddr and flow-direction that the default format omits and that you will want during an investigation behind NAT gateways or load balancers. Protect the bucket like any other log archive: Object Lock or at least a bucket policy that denies deletes, and no write access from workload accounts beyond the log delivery service.

Verify and enforce

# VPCs in this Region without a flow log
comm -23 \
  <(aws ec2 describe-vpcs --query 'Vpcs[].VpcId' --output text | tr '\t' '\n' | sort) \
  <(aws ec2 describe-flow-logs --query 'FlowLogs[].ResourceId' --output text | tr '\t' '\n' | sort)

At scale, enforce flow logs with the AWS Config rule vpc-flow-logs-enabled in a conformance pack and an infrastructure as code module that creates the flow log with the VPC, rather than per-VPC commands.

Keep AWS API traffic private with VPC endpoints

Without endpoints, an instance in a private subnet reaches S3 or Secrets Manager through a NAT gateway and the public service endpoint. VPC endpoints keep that traffic on the AWS network and, more importantly, let you attach a policy that controls what can pass through.

Gateway endpoints exist for S3 and DynamoDB. They are free and work through route table entries:

aws ec2 create-vpc-endpoint \
  --vpc-id vpc-0abc1234def567890 \
  --service-name com.amazonaws.eu-west-1.s3 \
  --vpc-endpoint-type Gateway \
  --route-table-ids rtb-0aaa1111bbbb2222c

Interface endpoints (AWS PrivateLink) exist for most other services. They create network interfaces in your subnets with private DNS. Common ones for a hardened workload VPC are ssm, ssmmessages and ec2messages (for Session Manager without internet access), kms, secretsmanager, logs, sts, and ecr.api plus ecr.dkr for containers. Security Hub CSPM has controls that check for several of these, for example EC2.10 (EC2 service endpoint), EC2.55 and EC2.56 (ECR) and EC2.57 (Systems Manager). Interface endpoints have their own security groups: allow 443 only from the VPC CIDR or the workload groups that need them.

Endpoint policies

An endpoint policy limits which principals and resources can be used through the endpoint. This S3 gateway endpoint policy only allows access to buckets owned by your organization, which blocks data exfiltration to an attacker's bucket from inside the VPC:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "OnlyOrgBuckets",
      "Effect": "Allow",
      "Principal": "*",
      "Action": "s3:*",
      "Resource": "*",
      "Condition": {
        "StringEquals": { "aws:ResourceOrgID": "o-exampleorgid" }
      }
    }
  ]
}

Some AWS-owned buckets are needed for package repositories and service agents (Amazon Linux repositories, SSM agent updates), so test in a non-production VPC and add explicit exceptions where required. An endpoint policy only applies to traffic that uses the endpoint: if the subnet also has a NAT gateway route, a workload can still reach S3 through the public endpoint for buckets in other Regions. Restrict egress, or route all S3 traffic through endpoints, for the policy to mean anything.

Lock resources to the endpoint with aws:SourceVpce

The other direction is to make a resource reachable only through your endpoint. A bucket policy that denies any request not coming through a specific VPC endpoint:

{
  "Sid": "DenyOutsideVpce",
  "Effect": "Deny",
  "Principal": "*",
  "Action": "s3:*",
  "Resource": [
    "arn:aws:s3:::prod-internal-data",
    "arn:aws:s3:::prod-internal-data/*"
  ],
  "Condition": {
    "StringNotEquals": { "aws:SourceVpce": "vpce-0123456789abcdef0" }
  }
}

Be careful: this also denies console access and access from administrators outside the VPC. Use aws:SourceVpc to allow any endpoint in a VPC, or add an exception for a break-glass role with aws:PrincipalArn. Applying these "data perimeter" conditions at organization scale is easier with resource control policies, covered on the AWS Organizations page, and the bucket side is detailed on the Amazon S3 page. The AWS data perimeter guidance also pairs this with an SCP using aws:SourceIp and aws:SourceVpc so that your own credentials only work from your expected networks.

Turn on VPC Block Public Access

VPC Block Public Access (BPA) is a Region-level account setting that blocks traffic through internet gateways and egress-only internet gateways for every VPC, overriding route tables and security groups. It is the network equivalent of S3 Block Public Access.

# Block all internet gateway traffic in both directions in this Region
aws ec2 modify-vpc-block-public-access-options \
  --internet-gateway-block-mode block-bidirectional

# Or block only inbound, keeping outbound via NAT
aws ec2 modify-vpc-block-public-access-options \
  --internet-gateway-block-mode block-ingress

aws ec2 describe-vpc-block-public-access-options

Workloads that legitimately need internet access (a public load balancer subnet, a NAT gateway subnet) get an exclusion with aws ec2 create-vpc-block-public-access-exclusion. Security Hub CSPM checks the setting as EC2.172 ("EC2 VPC Block Public Access settings should block internet gateway traffic"). For accounts that should never have internet facing workloads, such as data or shared services accounts, bidirectional mode with no exclusions is a strong default.

Enforce across the organization

AWS Organizations declarative policies for EC2 can set VPC Block Public Access for every account and Region in an OU. While a declarative policy is attached, account administrators cannot change the setting locally, which is exactly what you want for a data account. Roll it out in a sandbox OU first, since a block mode applied to an account with a public load balancer takes that service offline.

Verify reachability with Network Access Analyzer

Rule-by-rule review does not tell you whether a path actually exists from the internet to a database. Network Access Analyzer reasons over route tables, security groups, NACLs, gateways and load balancers to find paths that match a scope you define. AWS provides built-in scopes, including one for internet access to resources.

aws ec2 describe-network-insights-access-scopes \
  --query 'NetworkInsightsAccessScopes[].[NetworkInsightsAccessScopeId,Tags]'

aws ec2 start-network-insights-access-scope-analysis \
  --network-insights-access-scope-id nis-0123456789abcdef0

aws ec2 get-network-insights-access-scope-analysis-findings \
  --network-insights-access-scope-analysis-id nisa-0123456789abcdef0

For a single path question ("can this instance reach that RDS endpoint on 5432?"), use Reachability Analyzer instead. Amazon Inspector also reports network reachability findings for EC2 instances. Run the access scope analysis on a schedule (an EventBridge Scheduler rule calling the API is enough) and treat a new finding like any other security alert.

Logging and detection

What to log:

  • CloudTrail management events for the EC2 API cover every network change: AuthorizeSecurityGroupIngress, AuthorizeSecurityGroupEgress, CreateNetworkAclEntry, ReplaceNetworkAclEntry, CreateRoute, AttachInternetGateway, CreateVpcPeeringConnection, ModifyVpcBlockPublicAccessOptions and DeleteFlowLogs. Make sure the organization trail captures them (see the AWS CloudTrail page).
  • VPC Flow Logs for every VPC, in the custom format above.
  • Route 53 Resolver query logs for the DNS side. DNS is a common exfiltration and command and control channel that flow logs only show as port 53 traffic to the resolver.

What to alert on:

  • An EventBridge rule on security group changes that open a port to the world:
{
  "source": ["aws.ec2"],
  "detail-type": ["AWS API Call via CloudTrail"],
  "detail": {
    "eventName": ["AuthorizeSecurityGroupIngress"],
    "requestParameters": {
      "ipPermissions": {
        "items": { "ipRanges": { "items": { "cidrIp": ["0.0.0.0/0"] } } }
      }
    }
  }
}
  • Disabling of controls: DeleteFlowLogs, ModifyVpcBlockPublicAccessOptions, DeleteVpcEndpoints and endpoint policy changes (ModifyVpcEndpoint).
  • GuardDuty finding types that point at the network layer: Recon:EC2/PortProbeUnprotectedPort (an open port is being probed), UnauthorizedAccess:EC2/SSHBruteForce and UnauthorizedAccess:EC2/RDPBruteForce, Backdoor:EC2/C&CActivity.B, CryptoCurrency:EC2/BitcoinTool.B and Trojan:EC2/DNSDataExfiltration.
  • Security Hub CSPM controls CloudWatch.10 to CloudWatch.14, which check for metric filters and alarms on security group, NACL, network gateway, route table and VPC changes. If you already route the EventBridge events above to your alerting pipeline, you can document that as the compensating control.

Common mistakes

  • Narrowing instead of closing. Replacing 0.0.0.0/0 on port 22 with a large corporate range still leaves SSH keys, bastions and exposure. Remove the port and use Session Manager.
  • Forgetting IPv6. A security group or NACL that blocks 0.0.0.0/0 but allows ::/0 is just as exposed once the subnet has an IPv6 CIDR, which is why EC2.54 exists.
  • Endpoint policy with a NAT bypass. An S3 gateway endpoint with an org-only policy does nothing if the same subnet can reach S3 through a NAT gateway for other Regions. Control egress too.
  • Default VPCs left in unused Regions. Attackers with stolen keys launch cryptomining instances in Regions nobody looks at, into the default VPC that is ready and waiting.
  • Flow logs to a bucket the workload can delete. Logs stored in the same account, writable by the same administrators, are the first thing an intruder removes. Centralize them in the log archive account.
  • Complex NACLs. Long stateless rule sets that try to replicate security groups cause outages and get disabled. Keep NACLs to a handful of explicit denies.
  • SourceVpce locks without a break-glass path. A bucket policy that denies everything outside one endpoint also locks out incident responders. Add a tightly controlled exception for a break-glass role.

References

Written by

Florian Amette

Security engineer writing practical, benchmark-aligned hardening baselines for AWS services, from the organization and identities to data, networks and workloads.

Related services

All services