Cloud networking & security
The Networking topic showed what a VPC looks like: public and private subnets, an internet gateway, a NAT gateway, security groups. This chapter builds one step by step, compares the two AWS firewalls properly, and then covers the other half of cloud security: IAM permissions, secrets and encryption.
A VPC, piece by piece
A VPC belongs to one region and has an IPv4 range such as 10.0.0.0/16 (65,536 addresses). You split it into subnets, and each subnet lives in exactly one availability zone, so a highly available design has at least one public and one private subnet in each of two or more AZs. AWS reserves five addresses in every subnet (the first four and the last), so a /24 gives 251 usable IPs, not 256. Every region also has a default VPC (172.31.0.0/16) with a public subnet in each AZ: fine for experiments, but real setups create their own.
What makes a subnet "public" is nothing more than its route table. Each subnet is associated with one; the local route (traffic inside the VPC) is always there:
| Route table | Destination | Target |
|---|---|---|
| Public | 10.0.0.0/16 | local |
0.0.0.0/0 | Internet gateway (igw-…) | |
| Private | 10.0.0.0/16 | local |
0.0.0.0/0 | NAT gateway (nat-…), or no default route at all |
An instance in a public subnet also needs a public IP to be reachable. Building a VPC with the CLI shows every piece (in practice you'd write this in Terraform):
$ aws ec2 create-vpc --cidr-block 10.0.0.0/16 --query 'Vpc.VpcId' --output text
vpc-0a1b2c3d4e5f67890
$ aws ec2 create-subnet --vpc-id vpc-0a1b2c3d4e5f67890 --cidr-block 10.0.1.0/24 \
--availability-zone eu-central-1a --query 'Subnet.SubnetId' --output text
subnet-0aaa1111bbbb22223
$ aws ec2 create-internet-gateway --query 'InternetGateway.InternetGatewayId' --output text
igw-0fedcba9876543210
$ aws ec2 attach-internet-gateway --internet-gateway-id igw-0fedcba9876543210 \
--vpc-id vpc-0a1b2c3d4e5f67890
$ aws ec2 create-route-table --vpc-id vpc-0a1b2c3d4e5f67890 --query 'RouteTable.RouteTableId' --output text
rtb-0123abcd4567ef890
$ aws ec2 create-route --route-table-id rtb-0123abcd4567ef890 \
--destination-cidr-block 0.0.0.0/0 --gateway-id igw-0fedcba9876543210
$ aws ec2 associate-route-table --route-table-id rtb-0123abcd4567ef890 \
--subnet-id subnet-0aaa1111bbbb22223
$ aws ec2 modify-subnet-attribute --subnet-id subnet-0aaa1111bbbb22223 --map-public-ip-on-launch
Internet gateway, NAT gateway and VPC endpoints
- An internet gateway is attached to the VPC and allows traffic both ways for resources that have public IPs. It has no charge of its own.
- A NAT gateway lets private resources start connections out (to download updates or call an external API) while nothing on the internet can connect in. The classic zonal NAT gateway lives in a public subnet of one AZ with an Elastic IP, so for high availability you create one per AZ. Since late 2025 there's also a regional mode: one NAT gateway that spreads across the AZs where you have workloads and needs no public subnet. Either way, NAT gateways are billed per hour and per GB processed, a classic source of surprise bills.
- VPC endpoints let private subnets reach AWS services without going through NAT or the internet. Gateway endpoints exist for S3 and DynamoDB and have no extra charge; interface endpoints (PrivateLink) cover most other services and cost per hour per AZ.
Security groups vs network ACLs
| Security group | Network ACL | |
|---|---|---|
| Attached to | A network interface (an instance, load balancer, database…) | A subnet: applies to everything in it |
| State | Stateful: if a request is allowed in, its reply is allowed out automatically | Stateless: replies must be allowed separately, usually by opening ephemeral ports 1024-65535 |
| Rule types | Allow only | Allow and deny |
| Evaluation | All rules are considered together | Rules in number order, lowest first; the first match wins |
| Default | A new group: no inbound, all outbound allowed | The default NACL allows everything; a new custom NACL denies everything until you add rules |
| Can reference | IP ranges and other security groups | IP ranges only |
| Typical use | The main firewall for every resource | A coarse extra layer, for example blocking an abusive IP range |
Referencing security groups is the key idea for layered apps. "The database accepts PostgreSQL only from members of the app servers' group" keeps working however many app servers come and go:
$ aws ec2 authorize-security-group-ingress --group-id sg-0d1e2f3a4b5c6d7e8 \
--protocol tcp --port 5432 --source-group sg-0a1b2c3d4e5f6a7b8 # db group, app group
IAM: who can do what
Every AWS API call, from the console, the CLI or code, is checked by IAM (Identity and Access Management). The pieces:
- Root user: the email address that created the account. It can do everything, including closing the account, and can't be restricted by IAM policies.
- IAM users: long-term identities with a password and/or access keys. For people, AWS now recommends IAM Identity Center (single sign-on with short-lived credentials) over IAM users where possible.
- Groups: collections of users that share policies ("developers", "admins"). Attach permissions to groups, not to individual users.
- Roles: identities with no password or keys of their own. Someone or something assumes a role and gets temporary credentials. EC2 instances, Lambda functions, ECS tasks, CI pipelines and users from other accounts all use roles.
- Policies: JSON documents listing what is allowed or denied. Identity-based policies attach to users, groups and roles; resource-based policies attach to a resource, such as an S3 bucket policy.
A policy that lets an app read and write objects in one bucket, and nothing else:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ListTheBucket",
"Effect": "Allow",
"Action": "s3:ListBucket",
"Resource": "arn:aws:s3:::demee-practice-assets"
},
{
"Sid": "ReadWriteObjects",
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject"],
"Resource": "arn:aws:s3:::demee-practice-assets/*"
}
]
}
"Version": "2012-10-17"is the policy language version, not today's date. Always use exactly this value.- Each statement has an
Effect(Allow or Deny),Actions in the formservice:Operation, and theResources they apply to, as ARNs (Amazon Resource Names).Sidis just a label. - Listing is an action on the bucket (
arn:aws:s3:::bucket), while reading and writing are actions on objects (arn:aws:s3:::bucket/*). Mixing these two up is the most common reason an S3 policy "doesn't work".
How AWS decides: everything is denied by default; an Allow in any applicable policy permits the action; an explicit Deny anywhere always wins over any Allow. A role also has a trust policy saying who may assume it. This one lets EC2 instances use the role:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": { "Service": "ec2.amazonaws.com" },
"Action": "sts:AssumeRole"
}
]
}
Least privilege, MFA and the root account
Least privilege means every identity gets only the actions and resources it needs. Start with AWS managed policies while learning, then narrow them down; IAM Access Analyzer can generate a policy from the actions a role actually used. Protect the root user above everything else: turn on MFA (AWS now requires it for root users on all account types), never create access keys for it, and use it only for the few tasks that need it, such as changing account settings or closing the account. Day to day, sign in as an admin user or Identity Center user that also has MFA. If root is compromised, everything is.
Access keys vs roles
An access key (an ID starting AKIA plus a secret) is a long-lived password for the API. It works from anywhere until someone deletes it, so a key pasted into code and pushed to a public GitHub repository can be found and abused within minutes, typically to launch crypto-mining instances on your bill. A role hands out temporary credentials (IDs starting ASIA, plus a session token) that expire on their own. The rule: code running in AWS uses a role (EC2 instance profile, Lambda execution role, ECS task role), and CI pipelines use OIDC (for example GitHub Actions assuming a role) instead of stored keys. Creating a role for EC2 from the trust policy above:
$ aws iam create-role --role-name web-server-role --assume-role-policy-document file://trust.json
$ aws iam attach-role-policy --role-name web-server-role \
--policy-arn arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore
EC2 receives a role through an instance profile, a wrapper the console creates for you when you pick the role at launch (with the CLI: create-instance-profile, add-role-to-instance-profile, then aws ec2 associate-iam-instance-profile).
Secrets: Secrets Manager and Parameter Store
Database passwords and API tokens don't belong in code, AMIs, user data or environment variables baked into images. AWS has two places for them, and your app reads them at start-up using its role:
- Systems Manager Parameter Store: key-value configuration in a path hierarchy; the
SecureStringtype is encrypted with KMS. Standard parameters have no extra charge. Good for config and simple secrets. - Secrets Manager: built for secrets, with automatic rotation (for example changing an RDS password on a schedule) and cross-account sharing. Charged per secret per month and per API call.
$ aws ssm put-parameter --name /practice/db/password --type SecureString --value 'S3cure-Example'
$ aws ssm get-parameter --name /practice/db/password --with-decryption \
--query 'Parameter.Value' --output text
$ aws secretsmanager get-secret-value --secret-id practice/db \
--query 'SecretString' --output text
Values typed on the command line end up in your shell history; for real secrets, use --value file://secret.txt or let the service generate them (RDS can keep its master password in Secrets Manager for you).
Encryption at rest and in transit
At rest means stored data is encrypted on disk. AWS services use KMS (Key Management Service) keys for this: either AWS managed keys (named like aws/s3, aws/ebs) or customer managed keys you create, which let you control who may use the key, see its use in CloudTrail and disable it. S3 encrypts every new object by default. EBS encryption can be switched on by default per region (aws ec2 enable-ebs-encryption-by-default). RDS encryption has to be chosen when the database is created. In transit means TLS on every connection (see the TLS chapter in Networking): HTTPS on load balancers with free certificates from ACM (AWS Certificate Manager), TLS to databases, and S3 bucket policies that deny requests where aws:SecureTransport is false.
A typical three-tier layout
Picture a VPC spread over two AZs, each with three subnets. The public tier holds only an Application Load Balancer (and zonal NAT gateways, if used); its security group accepts 80 and 443 from the internet. The app tier sits in private subnets: EC2 instances in an Auto Scaling group, or ECS tasks, whose security group accepts traffic only from the load balancer's group; they reach the internet outbound through NAT and reach S3 through a gateway endpoint. The data tier is a further set of private subnets with no route to the internet at all, holding a Multi-AZ RDS database whose security group accepts port 5432 only from the app tier's group. Nothing but the load balancer has a public IP; admins connect with Session Manager instead of SSH through a bastion; the app reads its database password from Secrets Manager using its role; and every tier keeps working if one AZ fails.
Common mistakes
- SSH or databases open to
0.0.0.0/0. Bots scan the whole internet constantly. Restrict to your IP, use security-group references, or use Session Manager. - Private instances can't install packages: the private route table has no
0.0.0.0/0route to a NAT gateway (or the NAT gateway itself sits in a private subnet). - A custom network ACL breaks everything: it's stateless, so without an outbound rule for ports 1024-65535 the replies never leave.
AccessDenied/UnauthorizedOperation"is not authorized to perform": read the message; it names the identity, the action and the resource. Check for an explicit Deny, bucket vs object ARNs, and the region.- Access keys in code,
.envfiles committed to Git, or on EC2 instances. Use roles; if a key leaks, deactivate and delete it immediately, then check CloudTrail and your bill in every region.