Harden your AWS VPC in layers: subnets, Security Groups, NACLs, Flow Logs, endpoints, and IAM conditions, with CLI examples for production.
Picture a fast-growing fintech in Bengaluru that opens port 3306 to 0.0.0.0/0 on its RDS Security Group. Not the EC2 tier. The database itself. Internet-wide scanners find an exposed MySQL port within minutes, and brute-forcing starts right after. By the time anyone notices odd CloudTrail activity, millions of user records are already gone. This is an illustrative scenario, but the pattern is one of the most common in real incident reports.
VPC security is not a one-time setup. It is a layered design where each layer catches what the previous one misses. This guide walks through every layer, from subnet design to IAM conditions, using the CLI commands you would run in a real ap-south-1 production account.
The AWS Shared Responsibility Model puts network configuration entirely in your hands. AWS secures the physical infrastructure and the hypervisor. You decide which resources are reachable, from where, and on which ports.
The mistakes that show up again and again:
0.0.0.0/0 on sensitive ports (22, 3306, 5432, 6379).None of these are hard to fix. All of them are regularly found in production accounts.
Use three tiers: public subnets for load balancers and NAT Gateways only, private app subnets for compute, and private data subnets for databases and caches. Application servers and databases must never sit in a public subnet.
A typical CIDR plan for a VPC of 10.0.0.0/16 across two AZs looks like this:
## Public (ALB, NAT Gateway)10.0.1.0/24 ap-south-1a10.0.2.0/24 ap-south-1b ## Private app (EC2, ECS)10.0.10.0/24 ap-south-1a10.0.11.0/24 ap-south-1b ## Private data (RDS, ElastiCache)10.0.20.0/24 ap-south-1a10.0.21.0/24 ap-south-1bSeparate tiers give you defence in depth. Even if an attacker reaches the application layer, the data layer sits behind different Security Groups, different subnets, and different route tables. Disable auto-assign public IP on every private subnet so a misconfigured launch cannot hand out an internet-facing address:
## Never auto-assign public IPs in private subnetsaws ec2 modify-subnet-attribute \ --subnet-id subnet-xxxxxxxx \ --no-map-public-ip-on-launch \ --region ap-south-1š” Tip: Skip Bastion Hosts entirely if you can. AWS Systems Manager Session Manager gives you shell access to private instances with no inbound port 22, no SSH keys, and a full audit trail in CloudTrail. It needs the ssm, ssmmessages, and ec2messages interface endpoints (or a NAT route).
Security Groups are stateful, allow-only firewalls attached to individual network interfaces. Because they are stateful, return traffic is allowed automatically. They are also the most frequently misconfigured control in AWS, so enforce one pattern everywhere: each tier accepts traffic only from the Security Group of the tier above it.
The source of each rule is a Security Group ID, never an IP or CIDR. IPs change when instances restart. Security Group IDs do not, so your rules stay correct as the fleet scales.
## Correct: RDS accepts MySQL only from the app tieraws ec2 authorize-security-group-ingress \ --group-id sg-rds-prod \ --protocol tcp --port 3306 \ --source-group sg-app-prod \ --region ap-south-1The rule that must never exist in production is the same command with --cidr 0.0.0.0/0. Find any that already do:
## List groups that allow the whole internet inaws ec2 describe-security-groups \ --filters Name=ip-permission.cidr,Values=0.0.0.0/0 \ --query "SecurityGroups[].[GroupId,GroupName]" \ --output table --region ap-south-1Also lock down the default Security Group of every VPC by removing all its rules. Anything launched without an explicit group then has no network access instead of inheriting a permissive default.
Use Network ACLs when you need an explicit deny. They are stateless, subnet-level firewalls that support both allow and deny rules, evaluated in rule-number order with the lowest number winning. Security Groups cannot deny anything, so NACLs are the right tool for blocking a known-malicious range at once.
## Block a malicious range at the subnet edgeaws ec2 create-network-acl-entry \ --network-acl-id acl-xxxxxxxx \ --rule-number 10 \ --protocol -1 \ --rule-action deny \ --cidr-block 198.51.100.0/24 \ --ingress \ --region ap-south-1Put deny rules at low numbers (10, 20, 30) and leave gaps so you can insert new ones later. The default limit is 20 rules per direction, so keep the list for emergencies and not for routine allow-listing.
Because NACLs are stateless, you must allow return traffic yourself. When a client connects to your server on port 443, the server replies to a client-chosen ephemeral port in the 1024-65535 range. If your egress rules do not allow that range, the response is dropped even though the Security Group accepted the request.
## Allow inbound HTTPS to the public subnetaws ec2 create-network-acl-entry \ --network-acl-id acl-xxxxxxxx \ --rule-number 100 --protocol tcp \ --port-range From=443,To=443 \ --rule-action allow --cidr-block 0.0.0.0/0 \ --ingress ## Allow responses back to clients (ephemeral ports)aws ec2 create-network-acl-entry \ --network-acl-id acl-xxxxxxxx \ --rule-number 100 --protocol tcp \ --port-range From=1024,To=65535 \ --rule-action allow --cidr-block 0.0.0.0/0 \ --egressThe mirror image applies to outbound calls. If instances in the subnet call external APIs on 443, add an egress rule for 443 and an ingress rule for 1024-65535 so the replies can return.
VPC Flow Logs record every accepted and rejected connection with source, destination, port, protocol, and action. Without them you are debugging network issues blind, and you have no evidence trail after an incident. Storage cost is small compared to the hours they save.
## Enable Flow Logs for the whole VPCaws ec2 create-flow-logs \ --resource-type VPC \ --resource-ids vpc-xxxxxxxx \ --traffic-type ALL \ --log-destination-type cloud-watch-logs \ --log-group-name /vpc/prod-flow-logs \ --deliver-logs-permission-arn \ arn:aws:iam::123456789012:role/FlowLogsRole \ --region ap-south-1Use these patterns to triage a mysterious connection failure:
| Pattern | Likely cause |
|---|---|
| REJECT inbound | Security Group or NACL blocks the request |
| REJECT outbound | Security Group or NACL blocks the reply |
| ACCEPT in, REJECT out | Stateless NACL missing ephemeral ports |
| ACCEPT both, app fails | Application issue, not the network |
For detection, run a CloudWatch Logs Insights query to find the noisiest rejected sources. A single address with thousands of rejects per minute is the first sign of a port scan or brute-force attempt, and a natural trigger for an alarm.
fields srcAddr, dstPort| filter action = "REJECT"| stats count(*) as rejects by srcAddr| sort rejects desc| limit 20High-volume payment platforms such as Razorpay or Stripe typically alert on exactly this signal, because the cost of an unnoticed scan is far higher than the cost of a noisy alarm. For long-term retention and cheap querying, send logs to S3 and query them with Athena instead of keeping everything in CloudWatch.
You need one NAT Gateway per Availability Zone, never one in total. A single NAT Gateway is a single point of failure for internet access, and instances in other AZs pay cross-AZ data transfer fees on every outbound request.
## NAT Gateway in ap-south-1aaws ec2 allocate-address --domain vpc --region ap-south-1aws ec2 create-nat-gateway \ --subnet-id subnet-public-1a \ --allocation-id eipalloc-xxxxxxxx \ --region ap-south-1 ## Repeat for ap-south-1b with its own Elastic IPaws ec2 create-nat-gateway \ --subnet-id subnet-public-1b \ --allocation-id eipalloc-yyyyyyyy \ --region ap-south-1Then point each private route table at the NAT Gateway in its own AZ. AZ-1a instances use NAT A, AZ-1b instances use NAT B, and neither depends on the other.
Create S3 and DynamoDB Gateway Endpoints in every VPC on day one. They route traffic over the AWS private network, they cost nothing, and they remove that traffic from your NAT Gateway bill.
## Free S3 Gateway Endpointaws ec2 create-vpc-endpoint \ --vpc-id vpc-xxxxxxxx \ --service-name com.amazonaws.ap-south-1.s3 \ --route-table-ids rtb-private-1a rtb-private-1b \ --region ap-south-1 ## Free DynamoDB Gateway Endpointaws ec2 create-vpc-endpoint \ --vpc-id vpc-xxxxxxxx \ --service-name com.amazonaws.ap-south-1.dynamodb \ --route-table-ids rtb-private-1a rtb-private-1b \ --region ap-south-1A team reading 10 TB per month from S3 through a NAT Gateway pays about $450 in processing fees at $0.045 per GB (us-east-1 list price, so check your region). The endpoint removes that line item. For other services such as ECR, Secrets Manager, and SSM, use Interface Endpoints (PrivateLink). They are billed per hour per AZ plus data, so create them for the services your private workloads actually call.
IAM conditions can deny access based on where a request comes from, which turns a stolen credential into a much less useful one. Even if traffic reaches an S3 bucket from inside your VPC, IAM still decides whether that caller may touch that object.
A bucket policy can deny every request that does not arrive through your VPC endpoint. The example below is a CloudFormation resource, with an admin role exempted so you cannot lock yourself out:
Resources: DataBucketPolicy: Type: AWS::S3::BucketPolicy Properties: Bucket: !Ref DataBucket PolicyDocument: Version: "2012-10-17" Statement: - Sid: DenyOutsideVpcEndpoint Effect: Deny Principal: "*" Action: "s3:*" Resource: - !GetAtt DataBucket.Arn - !Sub "${DataBucket.Arn}/*" Condition: StringNotEquals: aws:SourceVpce: vpce-0abc1234example ArnNotLike: aws:PrincipalArn: arn:aws:iam::123456789012:role/AdminWith this in place, valid credentials used from a laptop, another AWS account, or any external system are refused. Remember that aws:SourceVpce and aws:SourceVpc only exist for traffic that flows through a VPC endpoint, so create the S3 Gateway Endpoint first and test with a non-admin role before enforcing.
A second pattern is a deny policy using BoolIfExists on aws:MultiFactorAuthPresent for network-changing actions such as ec2:AuthorizeSecurityGroupIngress. A thief with stolen access keys then cannot open ports without the physical MFA device. Scope it to human users, because service roles never present MFA.
GuardDuty analyses VPC Flow Logs, CloudTrail, and DNS logs automatically and flags threats that static rules miss. Enable it in every region and every account, since attackers deliberately use regions you do not watch.
| Finding | What it means |
|---|---|
UnauthorizedAccess:EC2/SSHBruteForce |
SSH brute force in progress |
Recon:EC2/PortProbeUnprotectedPort |
Port scanning detected |
CryptoCurrency:EC2/BitcoinTool.B |
Instance mining crypto |
UnauthorizedAccess:IAMUser/TorIPCaller |
Credentials used via Tor |
Wire findings to EventBridge and a Lambda function to automate the first response:
The whole loop finishes in seconds, far faster than a human paging in at 3 AM. Keep a human in the approval path for anything that touches production routing, and remember the NACL rule limit: expire automated deny entries after a set time so the table never fills up.
No single control is enough. Each one covers a gap the others leave open.
| Control | Best for | Limit |
|---|---|---|
| Security Groups | Per-resource allow rules | No deny rules |
| NACLs | Blocking bad CIDRs fast | Stateless, 20 rule default |
| VPC Endpoints | Private AWS API traffic | Interface types cost money |
| IAM conditions | Stopping stolen credentials | Needs endpoint-based traffic |
| GuardDuty | Detecting unknown threats | Detects, does not prevent |
For centralised enforcement across many accounts, consider AWS Network Firewall or a Gateway Load Balancer with an inspection VPC. They add deep packet inspection and domain filtering, at the cost of more moving parts and a per-hour bill.
Implement these in order, because each step builds on the previous one.
restricted-ssh, vpc-default-security-group-closed, and rds-instance-public-access-check.š Remember: Do not use this approach as a substitute for patching and least-privilege IAM. Network layers limit the blast radius of a mistake, they do not remove the mistake.
NoteReferences and Further Reading
- AWS VPC Security Best Practices - Official AWS guidance
- AWS GuardDuty finding types - Full catalogue of detected threats
- AWS Config managed rules - Compliance rule library
- VPC endpoints and S3 bucket policies - Condition keys for endpoint-restricted access
IP addresses change whenever instances restart or scale, which silently breaks rules that reference them. A Security Group ID stays fixed regardless of fleet changes, so chaining SG-to-SG references keeps rules correct as instances scale up and down.
This almost always points to a stateless NACL that is missing the ephemeral port range (1024-65535) on egress. The response to an inbound connection leaves on a client-chosen ephemeral port, and the NACL drops it even though the Security Group allowed the original request.
Use both. Security Groups are stateful and attach to resources, while NACLs are stateless and attach to subnets. NACLs are the only one of the two that supports explicit deny rules, which makes them the fastest way to block a known-malicious CIDR without editing every Security Group.
The aws:SourceVpc and aws:SourceVpce condition keys are only populated when traffic reaches S3 through a VPC endpoint. Requests that exit through a NAT Gateway arrive from a public IP and carry neither key, so a deny rule keyed on them blocks that traffic. Create the S3 gateway endpoint first.
A database or cache left in a public subnet with a public IP and a Security Group open to 0.0.0.0/0 on a sensitive port. RDS, ElastiCache, and Redis instances reachable directly from the internet are the recurring pattern behind large exfiltration incidents.
Discussion0