Sub topic 6
Controlling traffic with security groups
A security group is a virtual firewall that filters traffic to and from the network interfaces of your EC2 instances. This chapter assumes you know what a VPC and a subnet are, can read CIDR notation such as 203.0.113.0/24, and have the AWS CLI configured with permission to manage EC2.
What a security group is
A security group is a named set of rules that belongs to one VPC. You attach it to an instance's elastic network interface (ENI). Most instances have one ENI, so in practice you attach it to the instance. Three properties define how it behaves:
- Allow rules only. You cannot write a deny rule. Traffic is permitted if at least one rule in at least one attached group matches it. Otherwise it is dropped.
- Stateful. If an inbound request is allowed, the reply is allowed automatically, whatever the outbound rules say. The same holds in reverse for outbound requests. You do not open ephemeral ports (the high, temporary ports clients use) for replies.
- Evaluated together. If an interface has several groups, AWS combines all their rules into one allow list. Order does not matter, and there are no priorities.
A new group has no inbound rules, so all inbound traffic is denied. It has one outbound rule that allows everything. Rule changes take effect almost immediately, with no restart.
The diagram shows a common two-tier layout. The database group accepts traffic from the web group, not from an address range.
Anatomy of a rule
Each rule has four parts:
| Part | Meaning | Example |
|---|---|---|
| Protocol | TCP, UDP, ICMP, or all | `tcp` |
| Port range | One port or a range | `22`, `8000-8100` |
| Source (inbound) or destination (outbound) | A CIDR block, a prefix list, or another security group | `203.0.113.0/24` |
| Description | Optional note for humans | `office SSH` |
A group is scoped to one VPC. You cannot attach a group from one VPC to an instance in another. Group names must be unique within a VPC, but IDs (sg-...) are what the API uses.
Creating a group and opening one port
The following commands create a group and allow SSH from a single example range. Replace the VPC ID and group ID with your own. create-security-group prints the real group ID to use in the second command.
aws ec2 create-security-group \
--group-name web-sg \
--description "Web server access" \
--vpc-id vpc-0123456789abcdef0
aws ec2 authorize-security-group-ingress \
--group-id sg-0123456789abcdef0 \
--protocol tcp \
--port 22 \
--cidr 203.0.113.0/24Until the second command runs, the group allows no inbound traffic at all. To allow web traffic from anywhere, add a rule for port 80:
aws ec2 authorize-security-group-ingress \
--group-id sg-0123456789abcdef0 \
--protocol tcp \
--port 80 \
--cidr 0.0.0.0/0To limit SSH to your current public address, you can look it up and use it as a /32 range:
MY_IP=$(curl -s https://checkip.amazonaws.com)
aws ec2 authorize-security-group-ingress \
--group-id sg-0123456789abcdef0 \
--protocol tcp \
--port 22 \
--cidr "${MY_IP}/32"If your address changes (a home connection, a VPN), you will have to update this rule.
Referencing another security group
Instead of a CIDR, a rule can name another group as its source. The rule then matches traffic from any interface that has that group attached. It matches on the instances' private addresses, so you do not maintain IP lists as instances come and go.
aws ec2 create-security-group \
--group-name db-sg \
--description "Database access from web tier" \
--vpc-id vpc-0123456789abcdef0
aws ec2 authorize-security-group-ingress \
--group-id sg-0fedcba9876543210 \
--protocol tcp \
--port 3306 \
--source-group sg-0123456789abcdef0Here sg-0fedcba9876543210 is the database group and sg-0123456789abcdef0 is the web group. Any instance in web-sg can reach MySQL on the database, and nothing else can. The rule works with the private address, so connect to the database through its private IP or private DNS name. Referencing a group does not make a public address reachable.
Inspecting and removing rules
List the rules of a group in a readable form:
aws ec2 describe-security-groups \
--group-ids sg-0123456789abcdef0 \
--query 'SecurityGroups[].IpPermissions[].[IpProtocol,FromPort,ToPort,IpRanges[].CidrIp]' \
--output jsonRemove a rule by repeating its exact parameters with the revoke command:
aws ec2 revoke-security-group-ingress \
--group-id sg-0123456789abcdef0 \
--protocol tcp \
--port 80 \
--cidr 0.0.0.0/0You can attach or replace groups on a running instance with aws ec2 modify-instance-attribute --instance-id i-0123456789abcdef0 --groups sg-0123456789abcdef0. This command replaces the full list, so include every group you want to keep.
The default group and outbound rules
Every VPC has a default security group. It allows inbound traffic from members of the same group and all outbound traffic. You cannot delete it. If you launch an instance without naming a group, it joins the default group. Create your own groups for each role instead, so that changing one workload's rules does not affect another.
Outbound rules default to allow-all. For tighter control, you can remove that rule and allow only what the instance needs, such as HTTPS to package repositories. Be careful: an instance with no outbound access cannot reach the instance metadata service's neighbors in your VPC, DNS resolvers, or update servers. Test after restricting.
Common errors
- SSH times out. A timeout usually means a packet was dropped, not refused. Check that the group allows port 22 from your current address, that the subnet has a route to an internet gateway, that the instance has a public IPv4 address, and that no network ACL (a stateless subnet-level filter) blocks it. A "connection refused" message means traffic arrived but nothing listens on that port.
- Wrong VPC.
InvalidGroup.NotFoundor a mismatch error often means the group is in a different VPC than the subnet. - Duplicate rule. Adding a rule that already exists returns
InvalidPermission.Duplicate. This is harmless. - Rule removed, connection continues. Existing tracked connections can keep working for a time after you revoke a rule. New connections are blocked. Do not rely on a revoke to cut off a session at once.
- Rule quotas. Each group has a default limit on the number of rules, and each interface has a limit on attached groups. Prefix lists and group references keep rule counts down.
Design habits
- Create one group per role (web, app, database) and chain them by group reference.
- Open only the ports a role serves, and only to the sources that need them.
- Give each rule a description so later readers know why it exists.
- Avoid editing the default group.
Exercise
A database instance in db-sg should accept MySQL (port 3306) connections only from instances in web-sg. Which rule do you add to db-sg, and why is no matching outbound rule needed on web-sg for the replies?
Show answer
Add an inbound rule to db-sg for TCP port 3306 whose source is the web-sg group ID (use --source-group). Security groups are stateful, so replies to an allowed connection are permitted automatically, and the default allow-all outbound rule on web-sg already permits the request itself.
Exercise
You ran the SSH authorize command with your office CIDR, but connecting from home times out. Name two things to check.
Show answer
Check that the group's SSH rule includes your current home public IP (the rule only covers the office range), and that the instance has a public IPv4 address with a route to an internet gateway and no network ACL blocking port 22. A timeout means packets are being dropped, not refused.