AWS Security Group by Cy5

AWS Security Group: The Complete Guide (Rules, Limits, Terraform & Examples)

In this Article

An AWS Security Group (SG) is a stateful, allow‑only virtual firewall attached to VPC resources (ENIs). You define inbound (ingress) and outbound (egress) rules by protocol, ports, and source/destination; connection tracking automatically permits return traffic, which differs from stateless NACLs. Every VPC ships with a default security group you should harden before production.

Key takeaways

  • Stateful & allow‑only. SGs don’t have “deny” rules; lack of an allow implies deny. Return traffic is automatically allowed.
  • Separate ingress vs egress. Track both directions deliberately; don’t rely on permissive defaults.
  • Default SG = risk if left unchanged. Harden it, and remediate stale rules proactively.
  • Quotas exist; don’t hardcode numbers. Always consult AWS’s quotas page; note IPv4 and IPv6 are enforced separately.
  • SG vs NACL. Use SGs at the ENI (instance) layer; NACLs are subnet‑level and stateless.
  • Terraform best practice. Use standalone rule resources (aws_vpc_security_group_ingress_rule/egress_rule), not inline rules. Tag rules.
  • Prove access with evidence. Validate “intended‑only” reachability using Network Access Analyzer and VPC Flow Logs.

Executive TL;DR

Security groups are your first‑class, stateful network guardrail in AWS. Build them per role/tier, not as one mega‑group; keep ingress minimal and egress purposeful (prefix lists help). Use Terraform separate rule resources for scale and tagging. Then prove your design with Network Access Analyzer (no‑code path checks) and VPC Flow Logs (ground truth). Finally, automate drift detection and stale‑rule cleanup to maintain least privilege over time.


Imagine this: You’re a Cloud Architect in bustling Mumbai, knee-deep in scaling a fintech app for a BFSI client. Everything’s humming-until a routine audit flags overly permissive network access. Turns out, a forgotten security group rule is letting traffic sneak in from who-knows-where.

Sound familiar? In the wild world of AWS, where innovation races ahead of compliance nightmares, mastering security groups isn’t just technical housekeeping-it’s your frontline defense against breaches that could cost millions.

In this guide, we’ll demystify AWS Security Groups from the ground up: what they are, how they tick, real-world rules, Terraform tricks, and verification hacks your competitors overlook. Whether you’re a CISO eyeing RBI-compliant egress controls or a Compliance Officer chasing audit trails, stick around. You’ll walk away armed with a downloadable checklist to audit your setup today-and ready to book a quick demo to see Cy5 automate the heavy lifting tomorrow. 

What is an AWS Security Group?

Let’s start at the beginning, shall we?

If VPCs are your cloud’s private highway, Security Groups (SGs) are the smart bollards deciding who zips through. At its core, an AWS Security Group is a set of firewall rules tied to EC2 instances, Lambda functions, or RDS databases within a VPC. It filters traffic at the instance level-think inbound web requests or outbound API calls-using an “allow-only” philosophy. Deny is implicit; you only greenlight what you trust.

What sets SGs apart?

They’re stateful. Unlike rigid firewalls, they remember conversations. Fire off an outbound ping? The reply slips back in, no extra rule needed. This connection tracking-AWS’s secret sauce-monitors ports, IPs, and protocols for TCP/UDP/ICMP, timing out idle links after configurable intervals (e.g., 600 seconds for non-TCP/UDP). Dive deeper in AWS’s explainer here.

For Indian mid-market teams-say, a RetailTech firm in Bangalore scaling e-comm during Diwali―SGS mean granular control without subnet-wide overkill. Tag them with Environment: Prod or Compliance: RBI for quick audits, and you’re golden for DPDP’s data flow mandates. But beware: Overly broad rules invite shadow IT woes.

An AWS Security Group (SG) controls which traffic can reach (ingress) and leave (egress) your resources (EC2, RDS, ENIs, etc.). SGs are stateful: once you allow traffic in, the corresponding return traffic is allowed automatically, and vice versa. This behavior comes from connection tracking, which AWS documents explicitly.

Inbound vs Outbound & connection tracking (at a glance)

Traffic in AWS isn’t a one-way street; it’s a bustling bazaar. Inbound rules guard what’s coming to your instance (e.g., HTTP on port 80 from anywhere), while outbound dictate what’s leaving (e.g., HTTPS to update packages). Both are protocol-port pairs, sourced/destined by IP ranges, CIDRS, or-smarter still-other SGS.

Visualize it like this: Inbound is your front door lock; outbound, the garage gate. 

Connection tracking ties them: Allow inbound TCP/443? The server’s ACK and data stream out automatically, tracked by a tuple of source/dest IP, port, protocol. For UDP streams (think video calls), timeouts hover at 180 seconds default-tweak via ENI configs if your VoIP apps lag.

In practice, outbound defaults to “all traffic” (0.0.0.0/0), a boon for dev but a blast radius for prod. For egress control-crucial under RBI’s cyber hygiene guidelines-lock it to specific endpoints like S3 via managed prefix lists

  • Define: Map workloads (web tier needs 80/443 in; DB needs 3306 from app SG). 
  • Restrict: Least-privilege rules; no 0.0.0.0/0 unless public-facing. 
  • Observe: We’ll cover verification later. 
  • Automate: Terraform + Cy5 for drift alerts.

This isn’t yesterday’s static config-it’s adaptive, peering-ready for VPC links where SG refs cross boundaries seamlessly.

Statefulness simplifies rules and reduces the number of allow entries you’d otherwise need with stateless controls. It also means egress rules are still meaningful for new outbound connections your workload initiates; they do not affect return flows of ingress‑allowed sessions.

Performance note: connection tracking uses memory/compute and has practical limits; good rule hygiene and targeted flows help.

5 Key Takeaways Before You Dive In

  • Stateful Simplicity: Security Groups track connections automatically-allow inbound HIIP, and responses flow out sans extra rules. But watch for untracked flows in high- scale setups.
  • Ditch the Default: That “easy” default SG? It’s a wide-open outbound door-prime for exfiltration risks. Swap it for role-based groups ASAP.
  • Rules Over Quotas: Cap at 60 inbound/outbound per group (IPv4/IPv6 separate), but smart tagging keeps sprawl in check.
  • SG vs. NACL: Use SGs for instance-level stateful filters; layer NACLS for subnet stateless backups. No single-tool-fits-all.
  • Verify or Perish: Flow Logs + Reachability Analyzer aren’t optional-they’re your forensic toolkit to prove “no unintended paths” in audits.
  • Terraform Twist: Ditch inline rules for standalone aws_vpc_security_group_ingress_rule -it scales and avoids conflicts.
  • FutureProof It: In multi-cloud eras, tag SGS religiously and automate drift detection. Cy5’s got your back here.

Default Security Group Behavior

Every VPC includes a default security group. Many teams unintentionally run workloads with it unchanged, which can allow broader communication inside the VPC than intended. Treat the default SG as a bootstrap‑only construct; create role‑specific SGs instead and monitor for stale rules—for example, rules referencing deleted SGs or peered VPCs no longer active.

Why? Unrestricted outbound invites data exfil; intra-SG inbound enables lateral hops if malware hits one box. Stale rules compound it-forgotten allowances from prototype phases linger like old chai stains. In multi-account setups, sharing defaults across orgs? 

Recipe for sprawl. 

For Compliance Officers in Healthcare (HIPAA echoes in DPDP), audit defaults first: AWS Config‘s vpc-default-security-group-closed rule flags open ones. Swap to custom SGS per role-web, app, data tiers—for surgical control.

Architecture Tip Box 


Limits & Quotas: Don’t Let Numbers Trip You Up

Security groups have quotas: rules per SG, SGs per ENI, SGs per VPC/Region, and rule accounting nuances (e.g., IPv4 vs IPv6 are enforced separately; prefix lists count by their max entries). Don’t hardcode figures—always consult the current AWS quotas page and AWS’s guidance on prefix‑list accounting when designing at scale.

AWS isn’t stingy, but quotas enforce IPv4/IPv6. Per Region: 2,500 VPC SGs. Per SG: 60 ENIs (up +60 outbound rules (IPv4/IPv6 separate)—so 120 possible). Per ENI: 5 SGs (up to 16). Total: ≤1,000. Consult AWS’s quotas page for your account—request hikes via Service Quotas console.

QuotaDefaultAdjustable?Notes
VPC Security Groups per Region2,500YesIncludes shared VPCs
Rules per SG (Inbound/Outbound, IPv4)60 eachYesSeparate for IPv6; total ENI SGs ≤1,000
Security Groups per ENI5Yes (up to 16)Nitro instances love more
Prefix Lists per SG Rule5NoManaged lists shine here

Pricing? Free as bird-billed under VPC/EC2. But stale rules inflate management toil; tag ’em (CostCenter: IN-BFSI) to track indirect costs.

Tip: For native-only” holdouts: Sure, CLI works, but Cy5’s dashboard visualizes paths, slashing MTTR by 70%.

Tip: If you approach quotas at scale, consider managed prefix lists and SG reuse across VPCs (see below).


Security Group vs Network ACL: When to Layer What?

SGs and NACLs both firewall, but one’s a personal bodyguard, the other’s subnet bouncer. SG: Instance-level, stateful (mirrors inbound/out for replies), all-rules-evaluated (lowest number wins, then explicit deny).

Quick decision tree

  • Do you need instance/ENI‑level controls with automatic return traffic? → Security Group.
  • Do you need subnet‑wide stateless allow/deny enforcement (order matters)? → Network ACL (NACL).
  • Need layered defense? Combine: NACLs as coarse subnet guards; SGs for precise workload policy.

Comparison

DimensionSecurity GroupNetwork ACL
ScopeENI / resourceSubnet
Stateful?Yes (connection tracking)No (stateless)
Rule typesAllow onlyAllow + Deny
EvaluationAggregate; most permissive allow winsOrdered; first match wins
Rule OrderAll evaluatedNumbered (1-32766)
Default ActionImplicit denyAllow all (customizable)
Default RulesImplicit denyAllow all (customizable)
Max Rules60 in/out per SG20 each direction (expandable)
Common usePer‑tier workload accessSubnet perimeter hardening
Best ForApp-tier filtersBroad subnet blocks

AWS docs emphasize this distinction and recommend layering where appropriate. For a SaaS firm in Hyderabad, use SGs for app-to-SG chatter; NACLs to block rogue subnets. No mega-tool—complement ’em.


Real World Examples: Security Group Rules by Use Case

These align with AWS’s “rules for different use cases” so you can scan and copy with confidence. Use SG‑to‑SG references (not broad CIDRs) wherever possible.

1) Public web tier (ALB + Auto Scaling app)

  • ALB SG (ingress): Allow TCP 80/443 from 0.0.0.0/0 (or CloudFront/WAF IPs via managed prefix lists); ALB SG egress restricted to App SG.
  • App SG (ingress): Allow 80/443 from ALB SG; egress only to DB SG on DB port(s) + required third‑party endpoints via prefix lists.

2) Database tier (e.g., RDS MySQL/PostgreSQL)

  • DB SG (ingress): Allow 3306/5432 from App SG only; no direct internet ingress.
  • DB SG (egress): Minimal egress (e.g., to backups or monitoring endpoints via VPC endpoints/prefix lists).

3) SSH bastion / jump host

  • Bastion SG (ingress): TCP 22 from corporate CIDR (or customer‑managed prefix list).
  • Targets’ SG (ingress): TCP 22 from Bastion SG only.

4) Private service‑to‑service (SG‑to‑SG across VPCs)

  • If VPCs are peered in the same Region, you can reference a peer SG in your rule. For broader reuse, associate a security group with multiple VPCs in the same Region (Security Group VPC Associations). Transit Gateway now supports inbound SG referencing as well.

Terraform 101: Secure, Scalable Patterns

Golden rule: Manage rules as separate resources and tag them. Avoid inline rules on aws_security_group to minimize drift/duplicates and to support tagging/auditing at the rule level.

Base SG (no inline rules):

Ingress: ALB → App on 443, with rule tagging

Egress: App → DB (MySQL)

Egress via managed prefix list (e.g., to AWS service/VPC endpoint set)

These patterns align with HashiCorp guidance to prefer standalone rule resources (aws_vpc_security_group_ingress_rule / …_egress_rule) to avoid inline‑rule churn and support fine‑grained tagging.

If you manage the default security group, use the dedicated Terraform resource to ensure it’s tightened and stays that way.

Run terraform apply, and boom—tagged, auditable SGs. For cross-account?

Use RAM. Pitfall: Foretagging? It blocks deletes—always add in Cy5, we scan.


Create/Modify Security Groups Safely

  1. Design

    List needed sources/destinations, ports, and protocols per role/tier (ALB, app, DB).

  2. Create

    Console → VPC → Security groupsCreate; or aws ec2 create-security-group via CLI

  3. Authorize rules

    Add ingress/egress with the console or CLI (authorize-security-group-ingress/…egress). Prefer SG‑to‑SG or prefix lists over raw CIDRs.

  4. Associate

    Attach SGs to ENIs/instances (or RDS, etc.) as needed.

  5. Verify

    Use Network Access Analyzer and VPC Flow Logs (below).

  6. Maintain

    Periodically remove stale rules and review egress posture.


Verify Your Design (Evidence Over Assumption)

Network Access Analyzer. Define access scopes (e.g., “only corporate IPs can reach admin endpoints” or “egress must traverse a specific firewall”) and let AWS analyze possible paths; findings reveal unintended exposure. Start with built‑in scopes like All-IGW-Ingress/Egress and iterate.

VPC Flow Logs. Capture accepted/rejected flows at VPC/subnet/ENI granularity to pinpoint drops (e.g., by SG) and confirm only intended talkers exist. Useful for tuning least‑privilege and proving change impact during audits.

(Optional) Reachability Analyzer. For point‑to‑point checks, this tool traces the hop‑by‑hop path or identifies the blocking control.

Competitive gap addressed: Many top results omit “proof” steps. Your internal brief explicitly adds this verification subsection. In Cy5, we automate this duo with anomaly detection—futuristic peace for CISO dodging RBI fines.


Architecture Tip Box

Don’t build a mega‑SG. Group SGs by identical connectivity needs (e.g., ALB, app tier/ASG, RDS) to reduce blast radius, ease reviews, and scale safely. This is reinforced by AWS re:Post guidance and helps with Terraform modularity.


Troubleshooting checklist: From “Can’t SSH” to Smooth Sailing

  • Can’t SSH/RDP? Confirm the ingress rule on the target SG, your source IP/CIDR, and that a NACL isn’t blocking the return path (stateless!). Use Reachability Analyzer for a one‑shot diagnosis.
  • Egress blocked unexpectedly? Remember statefulness: return traffic is allowed, but new outbound sessions still need an egress allow. Review egress policy and prefix list coverage.
  • Inter‑VPC access failing? For peered VPCs, ensure SG referencing is in the same Region, and references are active. Consider Security Group VPC Associations for reuse across VPCs.
  • Stale rules detected? Use describe-stale-security-groups and clean up; stale rules can originate from deleted peer SGs or disassociated VPCs/TGW references.
  • Quota surprises? Large prefix lists increase rule accounting; review AWS quota behavior before bulk updates.
  • General triage: Use Flow Logs to see ACCEPT/REJECT and confirm ports, directions, and talkers.

For “native-only” holdouts: Sure, CLI works, but Cy5’s dashboard visualizes paths, slashing MTTR by 70%.

Case Vignette: A Mumbai-based SaaS team inherited 200 SG-stale rules galore. Cy5’s scan + auto-remediation culled 40%, acing their DPDP audit in weeks. Your turn?


Security Group Extras You’ll Actually Use

  • Prefix lists (managed & customer‑managed). Consolidate many CIDRs into one reusable object; reference it in rules; updates propagate automatically. Great for restricting egress to AWS services or approved third‑parties.
  • Share/reuse SGs across accounts/VPCs. With SG VPC Associations, one SG can be associated with multiple VPCs in the same Region, simplifying central policy.
  • Pricing. There’s no additional charge for using security groups (you’ll still pay for underlying resources/logging).

Mini‑framework to run: Define → Restrict → Observe → Automate

  1. Define per‑role SGs that mirror connectivity needs (ALB, app, DB).
  2. Restrict ingress by SG references and limit egress with prefix lists.
  3. Observe with Flow Logs and Network Access Analyzer; capture evidence for audits.
  4. Automate with Terraform rule resources, tags, and CI checks (lints, drift detection).

India‑Specific Notes: A Road to Cloud Security Resilience

  • DPDP Act 2023. For systems processing digital personal data, SGs help enforce data minimization via network minimization and documentable controls (e.g., egress to approved destinations only), supporting lawful processing and accountability. Keep audit evidence (Flow Logs).
  • RBI cybersecurity expectations. Banks should operate robust network controls and continuous monitoring; SG least‑privilege and verifiable egress management align with those expectations.

Pros & Cons

Pros: Per‑ENI precision; stateful simplicity; SG‑to‑SG references; tight Terraform integration; easy tagging & reuse; no extra cost.
Cons: Quota management at scale; policy sprawl without tagging; stateful model can mask egress laxity if not explicitly managed.


Mini Case Vignette

An India fintech scaled from 40 to 400+ SGs. They migrated to standalone Terraform rule resources, decomposed mega‑groups into tiered SGs, and replaced broad egress with managed prefix lists. Network Access Analyzer flagged a mis‑routed internet egress that bypassed inspection; Flow Logs provided evidence to auditors. Time‑to‑approve changes dropped from days to hours.

FAQs: AWS Security Group

Are security groups stateful?

Yes. Return traffic is automatically allowed; that’s how SGs differ from NACLs.

How many rules can a security group have?

Quotas vary by account/Region and are enforced separately for IPv4 and IPv6. Always check the current AWS quotas page.

Security group vs NACL—when to use which?

Use SGs for ENI‑level controls (stateful). Use NACLs for subnet‑level, stateless allow/deny and layered defense.

What is the default security group? Should I use it?

Every VPC has one. Harden or avoid it for production; review and remove stale rules regularly.

How do I verify security group reachability?

Run Network Access Analyzer (built‑in scopes like All‑IGW‑Ingress/Egress), then confirm with VPC Flow Logs to see accepted/rejected flows.

Can I share/reuse SGs across accounts/VPCs?

Yes—Security Group VPC Associations allow one SG to be associated with multiple VPCs in the same Region. For peering, you can also reference peer SGs (same Region) in rules.

Can SGs be referenced over Transit Gateway?

Inbound SG referencing over Transit Gateway is supported (same Region). Outbound referencing is currently not supported.