# Security Groups — Cloud Networking: VPCs, Subnets & Peering

Source: https://www.skillbyai.com/en/cloud-networking/cn-security-groups

> Write stateful, allow-only security group rules and reference other groups instead of IP ranges.

## A stateful firewall on every network interface

A **security group (SG)** is a virtual firewall attached to a network interface, such as an EC2 instance, a load balancer or a database. It contains only **allow** rules; anything not allowed is denied. There are separate inbound and outbound rule lists. Security groups are **stateful**: if an inbound request is allowed, the response is automatically allowed out, and vice versa, so you never write rules for return traffic. A rule's source can be a CIDR block or, more powerfully, **another security group**. Saying 'allow port 5432 from the app-tier SG' means any interface carrying that SG may connect, no matter what IP it has today. This survives autoscaling and IP changes, which CIDR-based rules do not. A new security group allows all outbound traffic and no inbound traffic by default. Because rules only allow, the order of rules does not matter: the group is the union of everything it permits.

## Allowing the app tier to reach Postgres

Reference the source security group instead of a CIDR range. IDs are placeholders.

```bash
aws ec2 authorize-security-group-ingress \
  --group-id sg-0db0000000000000a \
  --ip-permissions 'IpProtocol=tcp,FromPort=5432,ToPort=5432,UserIdGroupPairs=[{GroupId=sg-0app000000000000b,Description="app tier"}]'
```

## A guest list, not a blacklist

A wedding security guard holds a guest list. If your name is not on it, you do not get in; there is no need for a list of who is banned. And once you are inside, you can walk back out without being checked again. That is an allow-only, stateful security group.

**Quiz:** An SG allows inbound TCP 443 from 0.0.0.0/0 and has no outbound rules at all. Does the HTTPS response reach the client?

- [ ] No, an outbound rule for 443 is required
- [x] Yes, security groups are stateful, so the response is allowed
- [ ] Only if the NACL also allows it inbound
- [ ] Only for IPv6 clients

*Answer:* Yes, security groups are stateful, so the response is allowed. Return traffic for an allowed connection is tracked and permitted automatically. (Subnet NACLs, being stateless, are evaluated separately.)
