Security groups vs network ACLs
Filter traffic in a VPC with stateful security groups that reference each other and stateless network ACLs as a subnet guardrail, know exactly which one to use when, and audit both with a C# tool.
Assumes: AWS CLI v2 ยท AWS SDK for .NET v4 (AWSSDK.EC2 4.1.4) ยท .NET 10 LTS ยท CDK v2 (Amazon.CDK.Lib 2.277.0) ยท Terraform AWS provider v6 ยท Region us-east-1. Verified against official sources on 2026-11-18.
Learning objectives
By the end of this lesson you can:
- Explain stateful versus stateless filtering and predict what happens to reply traffic in each.
- Write security group rules that reference other security groups (ALB โ app โ database) instead of IP ranges.
- Write a network ACL for a data tier, including the ephemeral-port rules that stateless filtering needs.
- Decide when a network ACL adds value and when it only adds risk.
- Run a C# auditor that finds internet-open rules, unused groups, a non-empty default security group and over-permissive NACLs.
Prerequisites
- Public, private and isolated subnets and route tables โ routing decides whether a path exists; this lesson decides whether traffic may use it.
- Networking refresher โ ports, TCP handshakes and ephemeral ports.
- Tools: AWS CLI v2 (
learn-sandbox), .NET 10 SDK.
Why this matters in banking
The most frequent network finding in cloud security reviews is a security group rule like "TCP 1433 from 0.0.0.0/0" or "all traffic from 10.0.0.0/8" added during a late-night fix and never removed. Each such rule is an open door that every penetration tester and every attacker scans for. Banks have lost real money and customer data through exposed database and remote-desktop ports.
The opposite failure is just as real: a carefully written network ACL that forgets the ephemeral port range, so replies are dropped and a payment run fails at 02:00 with timeouts nobody can explain.
Harbourline's standard is therefore precise: security groups are the primary control, written as references between tiers, never wide CIDRs; network ACLs are a coarse guardrail on the data tier only, generated from code and tested. This lesson teaches you to work to that standard and to prove it.
The idea in plain language
Both are firewalls built into the VPC, but they sit in different places and remember different things.
- A security group (SG) is attached to a network interface (an EC2 instance, an ECS task, an RDS database, a load balancer, a Lambda function in a VPC, an interface endpoint). It is stateful: if a connection is allowed in one direction, the replies are automatically allowed back. It has allow rules only.
- A network ACL (NACL) is attached to a subnet. It is stateless: it checks every packet on its own, in each direction, with no memory of connections. It has numbered allow and deny rules, evaluated lowest number first; the first match wins.
Analogy: a security group is the keycard reader on each office door. Once your card lets you in, you can walk back out through the same door without swiping again. A network ACL is the security desk at the entrance of each floor. The desk has a printed list and checks everyone going in and everyone coming out, against the list, every time โ it does not remember that you came in five minutes ago.
Side by side
| Security group | Network ACL | |
|---|---|---|
| Attached to | Network interface (ENI) | Subnet |
| State | Stateful โ replies allowed automatically | Stateless โ replies need their own rule |
| Rule types | Allow only | Allow and deny |
| Evaluation | All rules together; any match allows | Numbered order, lowest first; first match decides |
| Sources | CIDR, prefix list, another security group | CIDR only |
| Default for new ones | No inbound, all outbound allowed | Custom NACL: deny everything both ways |
| VPC default object | Default SG: inbound from members of itself, all outbound | Default NACL: allow everything both ways |
| Quotas (default, checked 2026-11-18) | 60 inbound and 60 outbound rules per SG; 5 SGs per ENI (up to 16; rules ร SGs โค 1,000) | 20 inbound and 20 outbound rules (up to 40 each) |
| Typical use | Precise, per-application rules | Coarse tier guardrail; emergency "deny this range" |
Security group referencing
The most powerful SG feature: a rule's source can be another security group. "Allow TCP 5432 from hl-m02-app-sg" means "from any network interface that has hl-m02-app-sg attached", whatever its IP address. When ECS starts a new task with a new IP in a new subnet, the rule still works, and nothing else in the VPC can reach the database, even from the same subnet.
References work within a VPC, across peered VPCs in the same Region, and within shared VPCs. They do not work across Transit Gateway by default โ VERIFY current support for security group referencing over Transit Gateway in your Region, so cross-VPC rules over Transit Gateway usually use CIDRs or prefix lists.
Stateful in practice: connection tracking
Security groups track connections. Two consequences:
- Changing a rule does not cut existing tracked connections immediately. Removing an allow rule stops new connections; established ones can continue until they close or time out. In an incident, a NACL deny (stateless) cuts traffic at once.
- Some flows are untracked (for example when both directions are fully open for that protocol), and very high connection counts can hit per-instance tracking limits on some instance types. This matters for high-throughput NLB targets, not for a typical banking API.
Stateless in practice: ephemeral ports
When a client connects to your database on port 5432, the client side uses a random ephemeral port (Linux typically 32768โ60999, Windows 49152โ65535, AWS load balancers and NAT gateways 1024โ65535). A NACL therefore needs:
- Inbound: allow TCP 5432 from the app subnets.
- Outbound: allow TCP 1024โ65535 to the app subnets โ the replies.
Forget the second rule and the TCP handshake never completes.
What neither one filters
Traffic to and from some link-local services is not filtered by security groups or NACLs: the Amazon DNS resolver (.2 address), the instance metadata service (169.254.169.254), Amazon Time Sync, DHCP, and Windows license activation for AWS-provided Windows AMIs. Use Route 53 Resolver DNS Firewall to control DNS, and IMDSv2 settings to protect metadata.
Also: a NACL only sees traffic that crosses the subnet boundary. Two instances in the same subnet talk without the NACL being involved. Security groups apply to every ENI regardless.
What problem these controls solve
Routing makes a path possible; filters decide who may use it. Security groups let you express application intent โ "the ALB may call the app on 8080; the app may call the database on 5432" โ independent of addresses. NACLs let a central team put a coarse, independent fence around a tier that application teams cannot loosen, because NACLs live with the subnet (often in a separate network account) while SGs live with the application.
Limits and sharp edges:
- Rule quotas multiply. A prefix list referenced in a rule counts as its maximum entries. A rule with a 50-entry prefix list uses 50 of your 60 rules.
- NACLs are capped at 20 rules per direction by default (40 maximum, with a performance warning). They are not designed to hold long allow-lists.
- You cannot "deny" in a security group. To block one address inside an allowed range, use a NACL deny rule (lower number than the allow).
- The default security group is attached to anything launched without an explicit SG. Remove all its rules so mistakes fail closed (the lab's Terraform does this with
aws_default_security_group).
Microsoft / Azure comparison
| You know (Microsoft/Azure) | AWS equivalent | What's different |
|---|---|---|
| Network security group (NSG) on a NIC | Security group on an ENI | NSGs have allow and deny with priorities; SGs are allow-only, unordered |
| NSG on a subnet | Network ACL | NSGs are stateful; NACLs are stateless and need return-traffic rules |
| Application security groups (ASGs) | Security group references | Same idea โ group by role, not IP; AWS SG references also work across same-Region peering |
Service tags (Storage, Sql) | AWS-managed prefix lists (e.g. S3, CloudFront origin-facing) | Prefix lists count against rule quotas at their max size |
| NSG default rules (allow VNet, allow LB, deny all) | Default SG (self-referencing) and default NACL (allow all) | Neither AWS default is a good baseline; restrict them |
| NSG flow logs | VPC Flow Logs (ACCEPT/REJECT) | Flow Logs show whether SGs/NACLs rejected traffic, not which rule |
| Azure Firewall Manager policies | AWS Firewall Manager security group policies | Central audit and enforcement across accounts |
Architecture
Security-boundary view: each arrow is one security group rule whose source is the previous tier's security group โ no IP ranges appear anywhere inside the VPC. The data subnets carry a second, independent fence: the NACL allows 5432 only from the app subnets' CIDRs and replies back to them, and denies everything else, so even a mistaken db-sg rule (for example "from 10.20.0.0/16") would still not let the public-tier probe in. VPC Flow Logs record the probe's attempts as REJECT, which is your evidence.
Step-by-step implementation
Lock down the default security group
Remove every inbound and outbound rule from the VPC's default SG. Anything launched without an explicit SG now cannot talk to anything โ a safe failure.
Create one security group per tier
hl-m02-alb-sg, hl-m02-app-sg, hl-m02-db-sg. New groups start with no inbound rules and an "all outbound" rule; remove the outbound rule from each so you add only what is needed.
Add rules as references
ALB: inbound 80 (lab) / 443 (production) from the internet; outbound 8080 to app-sg. App: inbound 8080 from alb-sg; outbound 5432 to db-sg (plus 443 to the endpoints' SG, later). DB: inbound 5432 from app-sg; no outbound rules.
Add the data-tier NACL
Create hl-m02-data-nacl, associate it with the two data subnets, and add: inbound 5432 from each app subnet CIDR (rules 100, 110), outbound 1024โ65535 to each app subnet CIDR (rules 100, 110). Everything else falls through to the implicit * deny.
Audit
Run the C# auditor. Expect one finding at most: the ALB's internet rule on port 80 (allowed by the auditor's list, flagged as "plain HTTP").
AWS Console instructions
- VPC โ Security groups โ Create security group. Name
hl-m02-app-sg, description "App tier: reachable only from the ALB", VPChl-m02-vpc. Inbound rule: Custom TCP, port8080, Source Custom โ start typingsg-and pickhl-m02-alb-sg. Delete the default outbound rule; add Custom TCP 5432 โ destinationhl-m02-db-sg. Add tags โ Create. - Default SG: select the group named
defaultfor the VPC โ Inbound rules โ Edit โ Delete each โ Save; repeat for Outbound rules. - VPC โ Network ACLs โ Create network ACL โ name
hl-m02-data-nacl, VPC โ Create. Then Inbound rules โ Edit: rule100, Custom TCP, port5432, source10.20.64.0/20, Allow; rule110for10.20.80.0/20. Outbound rules โ Edit: rule100, Custom TCP, ports1024-65535, destination10.20.64.0/20, Allow; rule110for10.20.80.0/20. Subnet associations โ Edit โ tick both data subnets. - To see what applies to a resource: EC2 โ Network interfaces โ select ENI โ Security groups; for a subnet: VPC โ Subnets โ Network ACL tab.
AWS CLI
$p = "--profile", "learn-sandbox", "--region", "us-east-1"
$tags = "{Key=Project,Value=cea-lab},{Key=Lab,Value=m02-secure-vpc},{Key=Environment,Value=learn},{Key=Owner,Value=alex}"
$vpcId = aws ec2 describe-vpcs --filters Name=tag:Name,Values=hl-m02-vpc @p --query "Vpcs[0].VpcId" --output text
function New-TierSg([string]$name, [string]$description) {
$id = aws ec2 create-security-group --group-name $name --description $description --vpc-id $vpcId @p `
--tag-specifications "ResourceType=security-group,Tags=[{Key=Name,Value=$name},$tags]" --query GroupId --output text
# Remove the default "all outbound" rule so egress is explicit too
aws ec2 revoke-security-group-egress --group-id $id --ip-permissions "IpProtocol=-1,IpRanges=[{CidrIp=0.0.0.0/0}]" @p | Out-Null
return $id
}
$albSg = New-TierSg "hl-m02-alb-sg" "Internet-facing ALB"
$appSg = New-TierSg "hl-m02-app-sg" "App tier: reachable only from the ALB"
$dbSg = New-TierSg "hl-m02-db-sg" "Data tier: PostgreSQL from the app tier only"
# ALB: HTTP from the internet (learning shortcut; production is 443), and to the app on 8080
aws ec2 authorize-security-group-ingress --group-id $albSg @p `
--ip-permissions "IpProtocol=tcp,FromPort=80,ToPort=80,IpRanges=[{CidrIp=0.0.0.0/0,Description=HTTP from internet (lab only)}]"
aws ec2 authorize-security-group-egress --group-id $albSg @p `
--ip-permissions "IpProtocol=tcp,FromPort=8080,ToPort=8080,UserIdGroupPairs=[{GroupId=$appSg,Description=ALB to app}]"
# App: 8080 from the ALB's SG only; 5432 out to the DB's SG only
aws ec2 authorize-security-group-ingress --group-id $appSg @p `
--ip-permissions "IpProtocol=tcp,FromPort=8080,ToPort=8080,UserIdGroupPairs=[{GroupId=$albSg,Description=From ALB only}]"
aws ec2 authorize-security-group-egress --group-id $appSg @p `
--ip-permissions "IpProtocol=tcp,FromPort=5432,ToPort=5432,UserIdGroupPairs=[{GroupId=$dbSg,Description=App to database}]"
# DB: 5432 from the app SG only, and no outbound rules at all
aws ec2 authorize-security-group-ingress --group-id $dbSg @p `
--ip-permissions "IpProtocol=tcp,FromPort=5432,ToPort=5432,UserIdGroupPairs=[{GroupId=$appSg,Description=PostgreSQL from app tier}]"
# Lock down the default security group (remove its self-referencing inbound and all-outbound rules)
$defaultSg = aws ec2 describe-security-groups @p --filters Name=vpc-id,Values=$vpcId Name=group-name,Values=default --query "SecurityGroups[0].GroupId" --output text
$ruleIds = aws ec2 describe-security-group-rules @p --filters Name=group-id,Values=$defaultSg --query "SecurityGroupRules[].[SecurityGroupRuleId,IsEgress]" --output text
foreach ($line in $ruleIds -split "`n") {
$id, $egress = $line -split "\s+"
if ($egress -eq "True") { aws ec2 revoke-security-group-egress --group-id $defaultSg --security-group-rule-ids $id @p | Out-Null }
else { aws ec2 revoke-security-group-ingress --group-id $defaultSg --security-group-rule-ids $id @p | Out-Null }
}
# Data-tier NACL: 5432 in from app subnets, ephemeral ports back out to them
$nacl = aws ec2 create-network-acl --vpc-id $vpcId @p `
--tag-specifications "ResourceType=network-acl,Tags=[{Key=Name,Value=hl-m02-data-nacl},$tags]" --query NetworkAcl.NetworkAclId --output text
$rule = 100
foreach ($cidr in "10.20.64.0/20", "10.20.80.0/20") {
aws ec2 create-network-acl-entry --network-acl-id $nacl --ingress --rule-number $rule --protocol tcp --port-range From=5432,To=5432 --cidr-block $cidr --rule-action allow @p
aws ec2 create-network-acl-entry --network-acl-id $nacl --egress --rule-number $rule --protocol tcp --port-range From=1024,To=65535 --cidr-block $cidr --rule-action allow @p
$rule += 10
}
# Associate the NACL with each data subnet (replace-network-acl-association moves a subnet to a new NACL)
$dataSubnets = aws ec2 describe-subnets @p --filters Name=vpc-id,Values=$vpcId Name=tag:Tier,Values=data --query "Subnets[].SubnetId" --output text
foreach ($s in $dataSubnets -split "\s+") {
$assoc = aws ec2 describe-network-acls @p --filters Name=association.subnet-id,Values=$s `
--query "NetworkAcls[0].Associations[?SubnetId=='$s'].NetworkAclAssociationId | [0]" --output text
aws ec2 replace-network-acl-association --association-id $assoc --network-acl-id $nacl @p | Out-Null
}
# Review every rule in the VPC's tier groups
aws ec2 describe-security-group-rules @p --filters Name=group-id,Values=$albSg,$appSg,$dbSg `
--query "SecurityGroupRules[].[GroupId,IsEgress,IpProtocol,FromPort,CidrIpv4,ReferencedGroupInfo.GroupId,Description]" --output tableThere is no "associate NACL" call: every subnet always has exactly one NACL, so you replace the existing association.
Infrastructure as Code
using Amazon.CDK;
using Amazon.CDK.AWS.EC2;
using Constructs;
namespace Harbourline.Networking.Examples;
public sealed class TierSecurityStack : Stack
{
public TierSecurityStack(Construct scope, string id, IVpc vpc, IStackProps? props = null)
: base(scope, id, props)
{
var albSg = new SecurityGroup(this, "AlbSg", new SecurityGroupProps
{
Vpc = vpc, SecurityGroupName = "hl-m02-alb-sg", Description = "Internet-facing ALB", AllowAllOutbound = false,
});
var appSg = new SecurityGroup(this, "AppSg", new SecurityGroupProps
{
Vpc = vpc, SecurityGroupName = "hl-m02-app-sg", Description = "App tier: reachable only from the ALB", AllowAllOutbound = false,
});
var dbSg = new SecurityGroup(this, "DbSg", new SecurityGroupProps
{
Vpc = vpc, SecurityGroupName = "hl-m02-db-sg", Description = "Data tier: PostgreSQL from the app tier only", AllowAllOutbound = false,
});
// LEARNING SHORTCUT: plain HTTP. Production: Port.Tcp(443) with an ACM certificate on the listener.
albSg.AddIngressRule(Peer.AnyIpv4(), Port.Tcp(80), "HTTP from the internet (lab only)");
// Connections.AllowTo/AllowFrom write the matching egress AND ingress rules on both groups.
albSg.Connections.AllowTo(appSg, Port.Tcp(8080), "ALB to app");
appSg.Connections.AllowTo(dbSg, Port.Tcp(5432), "App to PostgreSQL");
// Stateless guardrail on the data subnets.
var nacl = new NetworkAcl(this, "DataNacl", new NetworkAclProps
{
Vpc = vpc,
NetworkAclName = "hl-m02-data-nacl",
SubnetSelection = new SubnetSelection { SubnetGroupName = "data" },
});
var appSubnets = vpc.SelectSubnets(new SubnetSelection { SubnetGroupName = "app" }).Subnets;
for (var i = 0; i < appSubnets.Length; i++)
{
nacl.AddEntry($"InPostgres{i}", new CommonNetworkAclEntryOptions
{
RuleNumber = 100 + i * 10,
Cidr = AclCidr.Ipv4(appSubnets[i].Ipv4CidrBlock),
Traffic = AclTraffic.TcpPort(5432),
Direction = TrafficDirection.INGRESS,
RuleAction = Amazon.CDK.AWS.EC2.Action.ALLOW,
});
nacl.AddEntry($"OutEphemeral{i}", new CommonNetworkAclEntryOptions
{
RuleNumber = 100 + i * 10,
Cidr = AclCidr.Ipv4(appSubnets[i].Ipv4CidrBlock),
Traffic = AclTraffic.TcpPortRange(1024, 65535),
Direction = TrafficDirection.EGRESS,
RuleAction = Amazon.CDK.AWS.EC2.Action.ALLOW,
});
}
}
}Amazon.CDK.AWS.EC2.Action is written in full because Action alone clashes with System.Action. Connections.AllowTo is the idiomatic CDK way to express "A may call B on port X": it adds the egress rule on A and the matching ingress rule on B, both as group references.
Complete code
A network-filter auditor for a VPC. It reports security group rules open to the internet on unexpected ports, all-protocol rules, rules without descriptions, a default SG that still has rules, security groups attached to nothing, and NACL rules that allow all traffic from anywhere.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AWSSDK.EC2" Version="4.1.4" />
<PackageReference Include="AWSSDK.SSO" Version="4.1.0.2" />
<PackageReference Include="AWSSDK.SSOOIDC" Version="4.1.0.2" />
</ItemGroup>
</Project>using Amazon;
using Amazon.EC2;
using Amazon.EC2.Model;
// Usage: $env:AWS_PROFILE = "learn-sandbox"; dotnet run -- vpc-0123456789abcdef0
if (args.Length != 1)
{
Console.Error.WriteLine("Usage: FilterAudit <vpc-id>");
return 2;
}
var vpcId = args[0];
using var ec2 = new AmazonEC2Client(RegionEndpoint.USEast1);
var vpcFilter = new Filter { Name = "vpc-id", Values = [vpcId] };
var findings = new List<string>();
// Ports that may legitimately face the internet, and only on load balancers.
int[] internetPorts = [443, 80];
// 1. Security groups and their rules
var groups = new List<SecurityGroup>();
await foreach (var g in ec2.Paginators.DescribeSecurityGroups(new DescribeSecurityGroupsRequest { Filters = [vpcFilter] }).SecurityGroups)
{
groups.Add(g);
}
var groupIds = groups.Select(g => g.GroupId).ToList();
var rules = new List<SecurityGroupRule>();
if (groupIds.Count > 0)
{
await foreach (var r in ec2.Paginators.DescribeSecurityGroupRules(new DescribeSecurityGroupRulesRequest
{
Filters = [new Filter { Name = "group-id", Values = groupIds }],
}).SecurityGroupRules)
{
rules.Add(r);
}
}
// 2. Which groups are attached to at least one network interface?
var inUse = new HashSet<string>();
await foreach (var eni in ec2.Paginators.DescribeNetworkInterfaces(new DescribeNetworkInterfacesRequest { Filters = [vpcFilter] }).NetworkInterfaces)
{
foreach (var g in eni.Groups ?? [])
{
inUse.Add(g.GroupId);
}
}
foreach (var group in groups)
{
var label = $"{group.GroupId} ({group.GroupName})";
var groupRules = rules.Where(r => r.GroupId == group.GroupId).ToList();
if (group.GroupName == "default" && groupRules.Count > 0)
{
findings.Add($"{label}: default security group still has {groupRules.Count} rule(s) โ remove them all");
}
else if (group.GroupName != "default" && !inUse.Contains(group.GroupId))
{
findings.Add($"{label}: not attached to any network interface โ delete it or explain it");
}
foreach (var rule in groupRules)
{
var direction = rule.IsEgress == true ? "egress" : "ingress";
var anywhere = rule.CidrIpv4 == "0.0.0.0/0" || rule.CidrIpv6 == "::/0";
var allProtocols = rule.IpProtocol == "-1";
var ports = allProtocols ? "all" : rule.FromPort == rule.ToPort ? $"{rule.FromPort}" : $"{rule.FromPort}-{rule.ToPort}";
if (rule.IsEgress != true && anywhere && (allProtocols || !internetPorts.Contains(rule.FromPort ?? -1) || rule.FromPort != rule.ToPort))
{
findings.Add($"{label}: {direction} {rule.IpProtocol}/{ports} from the INTERNET");
}
else if (rule.IsEgress != true && anywhere && rule.FromPort == 80)
{
findings.Add($"{label}: plain HTTP (80) from the internet โ redirect to 443 at the load balancer");
}
if (rule.IsEgress != true && allProtocols && rule.ReferencedGroupInfo is null && rule.PrefixListId is null && !anywhere)
{
findings.Add($"{label}: {direction} ALL traffic from {rule.CidrIpv4 ?? rule.CidrIpv6} โ use specific ports or an SG reference");
}
if (string.IsNullOrWhiteSpace(rule.Description))
{
findings.Add($"{label}: {direction} rule {rule.SecurityGroupRuleId} has no description");
}
}
}
// 3. Network ACLs: flag "allow everything from anywhere" rules on custom NACLs
await foreach (var acl in ec2.Paginators.DescribeNetworkAcls(new DescribeNetworkAclsRequest { Filters = [vpcFilter] }).NetworkAcls)
{
var subnets = string.Join(",", (acl.Associations ?? []).Select(a => a.SubnetId));
foreach (var entry in acl.Entries ?? [])
{
var allowAll = entry.RuleAction == RuleAction.Allow && entry.Protocol == "-1" &&
(entry.CidrBlock == "0.0.0.0/0" || entry.Ipv6CidrBlock == "::/0") && entry.RuleNumber != 32767;
if (allowAll && acl.IsDefault != true)
{
findings.Add($"{acl.NetworkAclId}: rule {entry.RuleNumber} ({(entry.Egress == true ? "egress" : "ingress")}) allows ALL traffic from anywhere; subnets: {subnets}");
}
}
if (acl.IsDefault == true && (acl.Associations ?? []).Count > 0)
{
Console.WriteLine($"info: default NACL {acl.NetworkAclId} (allow all) protects subnets {subnets}");
}
}
foreach (var f in findings)
{
Console.WriteLine($"FINDING: {f}");
}
Console.WriteLine(findings.Count == 0 ? "No findings." : $"{findings.Count} finding(s).");
return findings.Count == 0 ? 0 : 1;Code explained line by line
DescribeSecurityGroupswith avpc-idfilter โ security groups belong to one VPC; this lists them all.DescribeSecurityGroupRulesfiltered bygroup-idโ the newer, rule-level API. Every rule has its own ID (sgr-โฆ), direction (IsEgress), and either a CIDR, a prefix list or aReferencedGroupInfo. It is far easier to audit than the nestedIpPermissionsstructure.DescribeNetworkInterfacesโeni.Groupsโ the only reliable way to know whether an SG is in use is to look at which ENIs carry it. Unused groups are clutter, and clutter hides mistakes.group.GroupName == "default" && groupRules.Count > 0โ the default SG is attached to anything launched without an explicit group; it should have no rules.rule.IpProtocol == "-1"โ "-1" means all protocols and all ports.- The internet check allows only single-port 80/443 rules from
0.0.0.0/0or::/0; everything else (a range, all protocols, 22, 3389, 1433, 5432) is a finding. Port 80 still produces a softer finding โ production listeners should redirect to HTTPS. rule.ReferencedGroupInfo is null && rule.PrefixListId is nullโ wide CIDR rules with all protocols are flagged; SG references are the preferred form.string.IsNullOrWhiteSpace(rule.Description)โ every rule should say why it exists. Auditors ask; descriptions answer.entry.RuleNumber != 32767โ rule*(number 32767) is the implicit final rule; the default NACL's allow-all entries use lower numbers (100) and are reported only as information.RuleAction.Allowโ an SDK v4 constant class, compared with==like an enum.
Security considerations
- Reference, don't enumerate. SG-to-SG references survive scaling and IP changes and stop lateral movement within a subnet. Use CIDRs only for traffic from outside the VPC (on-premises ranges, partners) and prefer managed prefix lists for those.
- Restrict egress too. The default "all outbound" rule lets a compromised workload talk to anything its routes reach. The database SG in the lab has no egress rules.
- No administrative ports from the internet. No 22 or 3389 rules at all โ use AWS Systems Manager Session Manager for shell access, logged in CloudTrail.
- Govern centrally. AWS Firewall Manager can audit and enforce security group policies across accounts; AWS Config managed rules detect unrestricted SSH and other common issues; Security Hub CSPM reports them.
- NACLs for guardrails and emergencies. A deny rule cuts traffic immediately, including established flows that SG changes would not interrupt.
โ Learning shortcut โ not for production
The lab's ALB accepts plain HTTP on port 80 from 0.0.0.0/0. In production the ALB listens on 443 only (with an ACM certificate, HTTP redirected to HTTPS), AWS WAF is attached, and if the API is used only by known partners the source is a managed prefix list of their ranges. NACL rules in production are generated by the network team's pipeline, not written by hand, and changes to them are peer-reviewed like code.
Banking use case
Harbourline's card-authorisation service handles PCI DSS-scoped data (fictional design):
- Security groups chain
edge-nlb-sg โ auth-app-sg โ auth-db-sgwith references only. The authorisation app may call the tokenisation service on 8443 throughtokeniser-sg, and nothing else in the VPC. - NACL on the cardholder-data subnets allows only the tokeniser and app subnets' CIDRs on the database port and the replies; a deny rule at number 50 blocks the shared-services subnet range outright. The NACL is owned by the network account; application teams cannot edit it.
- Evidence: a nightly job runs the filter auditor against every PCI-scoped VPC and stores the output; Flow Logs show
REJECTrecords for anything else. The QSA receives both, plus the IaC history โ and the security team, not this lesson, decides whether that satisfies the segmentation requirement.
Common mistakes
- Opening a port to
0.0.0.0/0"just to test" โ forgotten, scanned, exploited โ test from a known source SG or use Session Manager port forwarding. - Forgetting the ephemeral-port rule in a NACL โ handshakes fail with timeouts โ always add the return rule, and test from both sides.
- Using the same SG for every tier โ anything can talk to anything โ one SG per role, references between them.
- Expecting a NACL to filter traffic between instances in the same subnet โ it doesn't โ use security groups for that.
- Trying to block one IP with a security group โ SGs cannot deny โ NACL deny rule with a lower number than the allow.
- Assuming removing an SG rule kills an active session โ tracked connections may continue โ use a NACL deny for immediate cut-off during an incident.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Connection times out (no "refused") | SG or NACL dropping packets silently | Flow Logs: REJECT on the target ENI points to SG/NACL; Reachability Analyzer names the blocking component |
| Inbound works, replies never arrive | NACL missing outbound ephemeral rule (or inbound on the other side) | Add 1024โ65535 return rules in both NACLs on the path |
InvalidPermission.Duplicate | Same rule already exists | Describe rules first; make IaC the only writer |
RulesPerSecurityGroupLimitExceeded | 60-rule quota (prefix lists count at max size) | Consolidate with SG references or smaller prefix lists; request a quota increase |
DependencyViolation deleting an SG | Attached to an ENI, or referenced by another SG's rule | Find references: describe-security-group-references / describe-security-group-rules |
| NACL rule seems ignored | A lower-numbered rule matched first | Read rules in ascending order; renumber with gaps of 10 |
Cost and cleanup
Cost: USD 0. Security groups, NACLs and their rules are free. (Flow Logs and Reachability Analyzer, which you may use to test them, have small charges.)
$p = "--profile", "learn-sandbox", "--region", "us-east-1"
# Move data subnets back to the default NACL, then delete the custom NACL
$defaultNacl = aws ec2 describe-network-acls @p --filters Name=vpc-id,Values=$vpcId Name=default,Values=true --query "NetworkAcls[0].NetworkAclId" --output text
aws ec2 describe-network-acls @p --network-acl-ids $nacl --query "NetworkAcls[0].Associations[].NetworkAclAssociationId" --output text |
ForEach-Object { $_ -split "\s+" } | Where-Object { $_ } |
ForEach-Object { aws ec2 replace-network-acl-association --association-id $_ --network-acl-id $defaultNacl @p | Out-Null }
aws ec2 delete-network-acl --network-acl-id $nacl @p
# Security groups reference each other: revoke the referencing rules first, then delete
foreach ($sg in $albSg, $appSg, $dbSg) {
$ids = aws ec2 describe-security-group-rules @p --filters Name=group-id,Values=$sg --query "SecurityGroupRules[].[SecurityGroupRuleId,IsEgress]" --output text
foreach ($line in ($ids -split "`n" | Where-Object { $_ })) {
$id, $egress = $line -split "\s+"
if ($egress -eq "True") { aws ec2 revoke-security-group-egress --group-id $sg --security-group-rule-ids $id @p | Out-Null }
else { aws ec2 revoke-security-group-ingress --group-id $sg --security-group-rule-ids $id @p | Out-Null }
}
}
foreach ($sg in $albSg, $appSg, $dbSg) { aws ec2 delete-security-group --group-id $sg @p }Exercises
- ๐ข Guided: Create the three tier SGs and the data NACL with the CLI, lock down the default SG, and run the auditor. Expect a single port-80 finding. Then add
TCP 5432 from 0.0.0.0/0tohl-m02-db-sg, re-run, see the finding, and remove the rule. - ๐ก Challenge: Extend the auditor to detect NACL rule shadowing: a lower-numbered rule that fully covers a higher-numbered rule with the opposite action (so the later rule can never apply). Write two unit-testable pure functions for "CIDR covers CIDR" and "port range covers port range".
- ๐ด Live problem: "After the network team added a NACL to the data subnets last night, the nightly reconciliation job (ECS task in the app tier) fails at the 'export to S3' step with timeouts. Database queries work." Diagnose without access to the NACL change ticket.
Assignment
Create docs/network-filters.md in your repository: a table of every security group rule in your lab VPC (source, port, purpose), the NACL rules with the reason for each, and a paragraph on why the database SG has no egress. Generate the tables from the auditor's output, not by hand.
Solutions
First run: FINDING: sg-โฆ (hl-m02-alb-sg): plain HTTP (80) from the internet โ redirect to 443 at the load balancer (plus "not attached" findings for all three SGs until an ALB, task and database use them). After adding the rule: FINDING: sg-โฆ (hl-m02-db-sg): ingress tcp/5432 from the INTERNET. Remove it with aws ec2 revoke-security-group-ingress --group-id $dbSg --ip-permissions "IpProtocol=tcp,FromPort=5432,ToPort=5432,IpRanges=[{CidrIp=0.0.0.0/0}]". Why the NACL alone doesn't save you: it would block internet traffic to the data subnets today โ but SGs are the primary control, and the next person to edit the NACL may not know the SG is wide open.
Use System.Net.IPNetwork: rule A covers rule B's CIDR if a.PrefixLength <= b.PrefixLength && a.Contains(b.BaseAddress). Port coverage: a.From <= b.From && a.To >= b.To (with protocol -1 covering all). Sort entries by RuleNumber per direction; for each later rule, check whether any earlier rule with a different action covers both its CIDR and its ports. Why it matters: a "deny the shared-services range" rule numbered 200 after an "allow 10.0.0.0/8" at 100 never applies โ a classic NACL mistake that looks correct in a review.
Database queries work, so the NACL allows app โ data traffic. The failing step goes to S3 โ but the job runs in the app tier, so look at the app subnets' path: did the new NACL go on the app subnets too, or does the app tier reach S3 through a gateway endpoint whose traffic must pass the app subnets' NACL? S3 traffic uses public S3 IP ranges on 443; a NACL that allows only VPC-internal ranges outbound โ or lacks inbound ephemeral ports from S3's ranges โ drops it. Flow Logs on the task ENI will show REJECT for S3 addresses. Fix: in the affected NACL, allow outbound 443 and inbound 1024โ65535 for S3's prefix-list CIDRs (NACLs cannot reference prefix lists, so this needs CIDRs โ another reason NACLs belong only on the data tier). Why: stateless rules must cover every flow crossing the subnet edge, including those to AWS services.
Knowledge check
Answer: Yes. Security groups are stateful: replies to an allowed inbound connection are allowed automatically, regardless of outbound rules.
Answer: Denied. Rules are evaluated in ascending order; rule 90 matches first.
Answer: With a NACL deny rule numbered lower than any matching allow rule. Security groups have no deny rules.
Answer: No. NACLs filter traffic entering and leaving the subnet. Use security groups between instances in the same subnet.
Answer: Replies go back to the client's ephemeral source port. A stateless NACL must allow that reply traffic explicitly.
Interview questions
- "Security groups or NACLs โ which do you use?" โ Security groups as the primary control, written as SG references per tier; NACLs only as a coarse guardrail on sensitive tiers and for emergency denies, because they're stateless and harder to get right.
- "How would you let only the API tier reach the database, even as it scales?" โ An inbound rule on the DB's SG with the API SG as the source; no CIDRs.
- "A user reports intermittent timeouts after a NACL change. What do you check?" โ Ephemeral port rules in both directions, rule order, and both subnets' NACLs on the path; confirm with Flow Logs
REJECTrecords. - "How do you stop someone opening SSH to the world?" โ Don't need SSH (Session Manager); detect with AWS Config / Security Hub CSPM; enforce with Firewall Manager SG policies; restrict who can modify SGs with IAM and SCPs.
Certification practice
A three-tier application runs web servers behind an ALB, application servers in an Auto Scaling group, and Amazon RDS. The database must accept connections only from the application servers, whose IP addresses change frequently. What is the most operationally efficient configuration?
A. A network ACL on the database subnets allowing the application subnets' CIDRs B. An inbound rule on the database security group that references the application servers' security group C. A Lambda function that updates the database security group with current instance IPs D. An inbound rule on the database security group allowing the VPC CIDR
Answer: B. An SG reference follows instances automatically, with no maintenance. A allows everything in those subnets, not just the app servers. C is fragile custom code. D allows every resource in the VPC.
During an incident, a security engineer must immediately stop all traffic from a malicious IP range to instances in a public subnet, including connections already established. Security groups allow 443 from anywhere. What should the engineer do?
A. Remove the 443 rule from the security group B. Add a deny rule for the range to the subnet's network ACL with a rule number lower than the existing allow rules C. Add a deny rule to the security group D. Enable AWS Shield Advanced
Answer: B. A stateless NACL deny takes effect for every packet, including existing flows. A would block every customer and may not cut tracked connections at once. C is impossible. D protects against DDoS but does not immediately block a specific range by itself.
A CloudOps engineer creates a custom network ACL for a private subnet with inbound rule 100 allowing TCP 443 from 10.0.0.0/16 and outbound rule 100 allowing TCP 443 to 10.0.0.0/16. Clients in 10.0.0.0/16 cannot complete HTTPS connections to servers in the subnet. Why?
A. Network ACLs are stateful and the rules are duplicated B. The outbound rule must allow the clients' ephemeral ports (1024โ65535), not 443 C. Custom network ACLs must reference security groups D. Rule numbers must be at least 200
Answer: B. Replies go from server port 443 to the client's ephemeral port, so the outbound rule must allow the ephemeral range. A โ NACLs are stateless. C and D are not real requirements.
A security review finds that several EC2 instances were launched without specifying a security group and can communicate freely with each other. What explains this, and what is the best preventive step?
A. They received the default security group, which allows inbound traffic from members of the same group; remove all rules from the default security group B. The default NACL is stateful; replace it C. Instances without a security group bypass filtering; enable VPC Block Public Access D. The VPC's main route table allows it; delete the local route
Answer: A. Unspecified launches get the default SG, which allows traffic from itself. Emptying it makes mistakes fail closed. B โ NACLs are stateless and not the cause. C โ every ENI has at least one SG. D โ the local route cannot be deleted and isn't a filter.
Completion checklist
- I can explain stateful vs stateless with a reply-traffic example
- I built ALB โ app โ database security groups using references only
- I wrote a data-tier NACL with ephemeral return rules
- I emptied the default security group and ran the auditor
- I deleted the lab SGs and NACL (or kept them for the next lesson)
Key takeaways
- Security groups: on ENIs, stateful, allow-only, can reference other SGs โ your primary control.
- Network ACLs: on subnets, stateless, ordered allow/deny, CIDR-only โ a guardrail, not the main control.
- Stateless means you must allow the return traffic (ephemeral ports) explicitly.
- Reference security groups instead of IP ranges inside the VPC; restrict egress, too; empty the default SG.
- Use a NACL deny for an immediate cut-off; SG changes may not end tracked connections.
Further reading
Independent learning resource โ not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.
NAT gateway and egress
Give private subnets outbound-only internet access with a NAT gateway, calculate exactly what it costs, choose between zonal and regional NAT, and design NAT-free alternatives โ with a C# tool that estimates your NAT bill from CloudWatch.
VPC endpoints and PrivateLink
Reach S3, DynamoDB and other AWS APIs without the internet using gateway and interface endpoints, lock them down with endpoint and bucket policies, publish your own service privately with PrivateLink, and audit endpoint policies with C#.