Sub topic 7
Security groups: stateful instance-level firewalls
This chapter assumes you have a VPC with public and private subnets (covered earlier), can run AWS CLI commands, and know how TCP ports and firewall rules work. It covers how security groups evaluate traffic, how to chain them across tiers, and the mistakes that most often cause outages or open holes.
What a security group is
A security group is a virtual firewall attached to an elastic network interface (ENI). An instance's primary ENI carries its security groups, and so do the ENIs of load balancers, RDS databases, Lambda functions in a VPC, and VPC interface endpoints. The group does not sit on a subnet. Two instances in the same subnet can have different security groups, and an instance can use several groups at once.
Four properties define how security groups behave:
- Allow rules only. You cannot write a deny rule. Traffic is permitted if at least one rule in any attached group matches, and dropped otherwise.
- Stateful. If an inbound request is allowed, the reply is allowed automatically, whatever the outbound rules say. The same holds for outbound requests and their replies.
- Scoped to one VPC. A group belongs to the VPC where you created it and cannot be moved.
- Applied immediately. A rule change takes effect on existing connections' new packets with no restart.
The default for a new group is no inbound rules and one outbound rule allowing all traffic. The default security group that comes with every VPC differs: it allows inbound traffic from members of itself and all outbound traffic. Avoid using the default group for real workloads, because anything you attach to it can talk to everything else attached to it.
How rules are evaluated
AWS takes the union of all rules across all groups attached to an ENI. There is no ordering, priority, or "first match wins". If one group allows TCP 22 from your office and another allows TCP 22 from anywhere, the effective rule is TCP 22 from anywhere.
Each rule has a protocol, a port range (or ICMP type and code), and a source (for inbound) or destination (for outbound). The source or destination can be:
| Type | Example | Use it for |
|---|---|---|
| IPv4 CIDR | `203.0.113.0/24` | Known external ranges such as an office or partner |
| IPv6 CIDR | `2001:db8::/32` | The same, for IPv6 traffic |
| Another security group | `sg-0abc...` | Traffic between tiers inside your VPC |
| Managed prefix list | `pl-0123...` | A maintained set of CIDRs, such as the S3 gateway endpoint ranges |
Statefulness and connection tracking
Security groups track connections. When a packet is allowed in, the group records the flow and permits the matching reply. Two consequences matter in practice.
First, you do not open ephemeral ports (1024–65535) for return traffic, which you must do in a network ACL. Second, a rule that allows all traffic in both directions (protocol -1 to and from 0.0.0.0/0) is not tracked. Replies to a flow that is no longer covered by a rule can then be handled differently after you tighten the rules. If you remove a broad rule while a long-lived connection is open, a tracked connection can survive for a while, while an untracked one stops at once. After tightening rules, test with new connections instead of relying on existing sessions.
Referencing groups instead of IP addresses
Referencing a group as a source is the most useful security group feature. A rule such as "allow TCP 5432 from app-sg" means "allow from any ENI that has app-sg attached". It follows instances as they scale in and out, and you never maintain a list of IPs.
The following commands build on the VPC from earlier chapters, where $VPC_ID is set. They create an app group and a database group, and let only app members reach PostgreSQL.
APP_SG=$(aws ec2 create-security-group --group-name app-sg --description "App tier" --vpc-id "$VPC_ID" --query GroupId --output text)
DB_SG=$(aws ec2 create-security-group --group-name db-sg --description "Database tier" --vpc-id "$VPC_ID" --query GroupId --output text)
aws ec2 authorize-security-group-ingress --group-id "$DB_SG" --protocol tcp --port 5432 --source-group "$APP_SG"Details to know about group references:
- The match is on the private IP of the ENI. Traffic sent to or from a public or Elastic IP address does not match a group reference, because the packet's source address is not the private address.
- You can reference a group in a peered VPC in the same Region. This is not possible across Regions.
- You cannot delete a group while another group's rule references it, or while any ENI uses it. Delete the rules first.
- A group can reference itself, which is how you let cluster members talk to each other.
A three-tier example
A common layout uses one group per tier, each trusting only the tier in front of it.
The commands below create the load balancer group and wire it to the app group. The app group's own rules use the $APP_SG variable created above.
ALB_SG=$(aws ec2 create-security-group --group-name alb-sg --description "Load balancer" --vpc-id "$VPC_ID" --query GroupId --output text)
aws ec2 authorize-security-group-ingress --group-id "$ALB_SG" --protocol tcp --port 443 --cidr 0.0.0.0/0
aws ec2 authorize-security-group-ingress --group-id "$APP_SG" --protocol tcp --port 8080 --source-group "$ALB_SG"An attacker who compromises a host in the public tier still cannot reach the database directly, because db-sg accepts nothing from alb-sg.
Restricting outbound traffic
Every new group starts with an allow-all outbound rule. For most workloads that is acceptable, but a database tier or a regulated workload often should not initiate arbitrary connections. To restrict outbound traffic, remove the default rule and add only what the tier needs.
aws ec2 revoke-security-group-egress \
--group-id "$DB_SG" \
--ip-permissions '[{"IpProtocol":"-1","IpRanges":[{"CidrIp":"0.0.0.0/0"}]}]'
aws ec2 authorize-security-group-egress \
--group-id "$APP_SG" \
--ip-permissions '[{"IpProtocol":"tcp","FromPort":5432,"ToPort":5432,"UserIdGroupPairs":[{"GroupId":"'"$DB_SG"'"}]}]'Before you do this, list what the instance actually needs. Package repositories, DNS resolution through the VPC resolver (the Amazon-provided resolver is not subject to security group rules), the instance metadata service, and AWS API calls through a NAT gateway or endpoint all affect which egress rules you need. Instance-level DNS to the VPC resolver works without a rule, but DNS to a custom server in your VPC does need one.
Inspecting rules
Each rule has an ID, which makes review and automation easier than parsing nested structures.
aws ec2 describe-security-group-rules \
--filters Name=group-id,Values="$DB_SG" \
--query 'SecurityGroupRules[].{Id:SecurityGroupRuleId,Egress:IsEgress,Proto:IpProtocol,From:FromPort,To:ToPort,Group:ReferencedGroupInfo.GroupId,Cidr:CidrIpv4}' \
--output tableTo find which network interfaces use a group, which you should check before deleting it or changing a rule, run:
aws ec2 describe-network-interfaces \
--filters Name=group-id,Values="$APP_SG" \
--query 'NetworkInterfaces[].{Eni:NetworkInterfaceId,Ip:PrivateIpAddress,Desc:Description}' \
--output tableQuotas and limits
The defaults below can be raised through Service Quotas, but they are a useful guide for design.
- 60 inbound and 60 outbound rules per group.
- 5 groups per network interface.
- Rules per interface is the product of those two values, and the interface-group quota combined with the rules-per-group quota cannot exceed 1,000.
- 2,500 groups per Region per VPC.
When a group approaches its rule limit, replace lists of CIDRs with a managed prefix list. A prefix list counts as one rule per its maximum size, so size it deliberately.
Common errors
- Timeouts instead of refusals. A blocked packet is silently dropped, so a missing rule appears as a hang. A connection refused error means the packet arrived and nothing listens on the port, which is not a security group problem.
- Using the wrong address. A rule that references a group does not match traffic arriving through a public IP. Connect over private addresses, or reference a CIDR for the translated source.
- Opening SSH to the world.
0.0.0.0/0on port 22 or 3389 is the most frequently flagged finding in AWS audits. Prefer AWS Systems Manager Session Manager, which needs no inbound rule, or restrict the source. - Forgetting the rule is a union. A permissive extra group attached to an instance overrides every restrictive group on it.
- Reusing one group everywhere. A single shared group makes rule changes affect unrelated workloads. Create one group per role.
- Editing a group that is in use. Removing a rule applies at once. Check the attached ENIs first.
Exercise
An app instance has two security groups. sg-a allows inbound TCP 22 only from 10.0.0.0/16. sg-b allows inbound TCP 22 from 0.0.0.0/0. A client at 198.51.100.7 tries to connect over SSH. Is the connection allowed, and why?
Show answer
Yes. The rules from all attached groups are combined, and sg-b matches the client's address. Security groups have no deny rules and no precedence, so the more restrictive sg-a does not limit sg-b. To block the client, remove or tighten the rule in sg-b.
Exercise
You allow inbound TCP 5432 on db-sg from app-sg. An app instance connects to the database's private IP and it works. The same instance then connects to an Elastic IP associated with the database ENI and times out. What explains this, and how do you fix it?
Show answer
A group reference matches the private IP of the source ENI. When the connection goes through the Elastic IP, the source does not match the reference, so the packet is dropped. Connect using the database's private IP or private DNS name, which resolves to the private address from inside the VPC.
Exercise
After you revoke the default allow-all egress rule on a database group, replies to the application's queries still arrive. Why?
Show answer
Security groups are stateful. The inbound connection from the app was allowed, so its reply traffic is allowed regardless of the outbound rules. The egress restriction only affects connections the database itself initiates.