AWS Certified Cloud Practitioner

Post 10 of 25

40%

Complete

Cloud Architecture12 min read

AWS Cloud Practitioner #10: Security Groups y NACLs - Firewall en AWS

Comprende la diferencia entre Security Groups (stateful) y Network ACLs (stateless), reglas inbound/outbound, y diseña seguridad de red robusta.

🎯 Lo que Aprenderás Hoy

Al finalizar este post, podrás:

  • Diferenciar entre Security Groups y Network ACLs
  • Explicar stateful vs. stateless firewalls
  • Configurar reglas inbound/outbound
  • Diseñar defense-in-depth con múltiples layers
  • Troubleshoot connectivity issues

El Problema Real

Tienes un web server en EC2. Necesitas:

plaintext
✅ Permitir HTTP (port 80) desde internet
✅ Permitir HTTPS (port 443) desde internet
✅ Permitir SSH (port 22) solo desde tu oficina (IP: 203.0.113.0/24)
❌ Bloquear TODO lo demás
 
Además:
✅ Permitir outbound traffic a internet (para updates)
❌ Bloquear outbound traffic a IPs maliciosas conocidas

Solución: Security Groups + Network ACLs


Security Groups

¿Qué son?

Security Groups son firewalls virtuales que controlan tráfico a nivel de instance (EC2, RDS, etc.).

Info

Analogía: Security Group es como un guardia de seguridad en la puerta de tu oficina.

  • Reglas: Lista de personas permitidas (whitelist)
  • Default: Bloquea TODO (deny all), solo permite lo que explícitamente permites
  • Stateful: Si permites entrada, salida automática permitida

Características Clave

1. Stateful

plaintext
CRITICAL: Security Groups son STATEFUL
 
¿Qué significa?
Si permites inbound traffic, return traffic (response) automáticamente permitido.
 
Ejemplo:
Regla inbound: Allow HTTP (port 80) from 0.0.0.0/0
 
Flujo:
1. User (54.123.45.67) → HTTP request (port 80) → EC2
   ✅ Permitido (matched inbound rule)
 
2. EC2 → HTTP response → User (54.123.45.67)
   ✅ Permitido AUTOMÁTICAMENTE (stateful, tracking connection)
 
NO necesitas regla outbound explícita para responses.

2. Allow Rules Only

plaintext
Security Groups solo tienen ALLOW rules.
NO hay DENY rules.
 
Default:
❌ Deny ALL inbound
✅ Allow ALL outbound
 
Solo agregas lo que quieres permitir.
 
Ejemplo:
Quieres permitir HTTP pero bloquear SSH desde internet:
 
❌ INCORRECTO (no puedes hacer esto):
Deny SSH from 0.0.0.0/0
 
✅ CORRECTO:
Allow HTTP from 0.0.0.0/0
(SSH automáticamente bloqueado porque no está en allow list)

3. Asociado a Instance

plaintext
Security Group se aplica a nivel de ENI (Elastic Network Interface).
 
1 Instance puede tener múltiples Security Groups.
1 Security Group puede aplicar a múltiples instances.
 
Ejemplo:
Instance: web-server-1
Security Groups:
- web-sg (allows HTTP/HTTPS)
- ssh-sg (allows SSH from office IP)
- monitoring-sg (allows monitoring tools)
 
Todo el tráfico debe pasar por TODOS los Security Groups.

Reglas de Security Group

plaintext
Regla components:
- Type: Protocolo (HTTP, HTTPS, SSH, Custom TCP, etc.)
- Protocol: TCP, UDP, ICMP
- Port Range: 80, 443, 22, 1024-65535
- Source (inbound) / Destination (outbound): IP range o otro Security Group
 
Ejemplo inbound rule:
Type: HTTPS
Protocol: TCP
Port: 443
Source: 0.0.0.0/0  (anywhere)
 
Ejemplo outbound rule:
Type: Custom TCP
Protocol: TCP
Port: 3306
Destination: sg-database  (otro Security Group)

Ejemplo: Web Server Security Group

hcl
# Terraform example
 
resource "aws_security_group" "web_sg" {
  name        = "web-server-sg"
  description = "Allow HTTP and HTTPS from internet"
  vpc_id      = aws_vpc.main.id
 
  # Inbound rules
  ingress {
    description = "HTTPS from anywhere"
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
 
  ingress {
    description = "HTTP from anywhere"
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
 
  ingress {
    description = "SSH from office only"
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["203.0.113.0/24"]  # Office IP range
  }
 
  # Outbound rules
  egress {
    description = "Allow all outbound"
    from_port   = 0
    to_port     = 0
    protocol    = "-1"  # All protocols
    cidr_blocks = ["0.0.0.0/0"]
  }
}

Referencing Security Groups

Potente feature: Puedes referenciar otros Security Groups.

plaintext
Problema:
Web servers (múltiples IPs) necesitan acceder database.
Cuando lanzas nuevos web servers, IPs cambian.
 
❌ Solución mala:
Database SG: Allow port 3306 from 10.0.1.10, 10.0.1.11, 10.0.1.12...
(Debes actualizar cada vez que agregas web server)
 
✅ Solución buena:
Database SG: Allow port 3306 from sg-web
(Cualquier instance con sg-web puede acceder)

Ejemplo:

plaintext
Web Server Security Group (sg-web):
Inbound:
- HTTP/HTTPS from 0.0.0.0/0
Outbound:
- MySQL (3306) to sg-database
 
Database Security Group (sg-database):
Inbound:
- MySQL (3306) from sg-web  ← Referencia a Security Group
Outbound:
- All traffic to 0.0.0.0/0
 
Beneficio:
- Lanzas nuevo web server con sg-web → automáticamente puede acceder DB
- No modificas reglas
- Dynamic membership

Network ACLs (NACLs)

¿Qué son?

Network ACLs son firewalls que controlan tráfico a nivel de subnet.

Info

Analogía: NACL es como seguridad en el perímetro del edificio.

Security Group = Guardia en puerta de oficina individual NACL = Guardia en entrada del edificio

Tráfico pasa por:

  1. NACL (subnet level) → permite/bloquea
  2. Security Group (instance level) → permite/bloquea

Defense in depth.

Características Clave

1. Stateless

plaintext
CRITICAL: NACLs son STATELESS
 
¿Qué significa?
Debes configurar reglas inbound Y outbound explícitamente.
 
Ejemplo:
NACL inbound: Allow HTTP (port 80) from 0.0.0.0/0
 
Flujo:
1. User → HTTP request (port 80) → Instance
   ✅ Permitido (inbound rule)
 
2. Instance → HTTP response (source port 80, dest port ephemeral) → User
   ❌ BLOQUEADO si no hay outbound rule
 
NECESITAS regla outbound:
Allow TCP ports 1024-65535 (ephemeral ports) to 0.0.0.0/0
 
Esto es diferente a Security Groups (stateful).

2. Allow AND Deny Rules

plaintext
NACLs tienen BOTH allow y deny rules.
 
Puedes:
✅ Allow HTTP from everyone
❌ Deny access from specific IP malicioso
 
Ejemplo:
Rule 100: DENY TCP port 22 from 203.0.113.50/32
Rule 200: ALLOW TCP port 22 from 203.0.113.0/24
Rule 300: DENY ALL
 
Result:
- 203.0.113.50 → SSH bloqueado (rule 100)
- 203.0.113.51 → SSH permitido (rule 200)
- Todos los demás → bloqueado (rule 300)

3. Processed in Order

plaintext
Reglas se evalúan en orden numérico.
Primera regla que matched → se aplica, stop processing.
 
Ejemplo:
Rule 100: ALLOW HTTP from 0.0.0.0/0
Rule 200: DENY HTTP from 203.0.113.0/24
Rule *: DENY ALL
 
Tráfico desde 203.0.113.50:
- Check rule 100: Match ✓ → ALLOW
- Stop (no check rule 200)
 
Result: 203.0.113.50 PUEDE acceder (rule 100 matched first)
 
Para bloquear subnet específica:
Rule 50: DENY HTTP from 203.0.113.0/24  ← Antes de allow
Rule 100: ALLOW HTTP from 0.0.0.0/0

4. Asociado a Subnet

plaintext
1 NACL por subnet (default or custom)
1 NACL puede asociarse a múltiples subnets
 
Subnet sin NACL explícita → usa Default NACL

Default NACL vs. Custom NACL

Default NACL:

plaintext
Inbound rules:
Rule 100: ALLOW ALL traffic from 0.0.0.0/0
 
Outbound rules:
Rule 100: ALLOW ALL traffic to 0.0.0.0/0
 
Rule *: DENY ALL (implícito)
 
Behavior: PERMITE TODO (sin restricción)
Uso: Default cuando creas subnet, no recommended para producción

Custom NACL:

plaintext
Default cuando creas custom NACL:
 
Inbound rules:
Rule *: DENY ALL
 
Outbound rules:
Rule *: DENY ALL
 
Behavior: BLOQUEA TODO (debes agregar allows explícitos)
Uso: Recommended para seguridad granular

Ejemplo: NACL para Web Subnet

plaintext
Public Subnet NACL:
 
Inbound rules:
Rule #  Type         Protocol  Port      Source         Action
100     HTTP         TCP       80        0.0.0.0/0      ALLOW
110     HTTPS        TCP       443       0.0.0.0/0      ALLOW
120     SSH          TCP       22        203.0.113.0/24 ALLOW
130     Custom TCP   TCP       1024-65535 0.0.0.0/0     ALLOW  ← Ephemeral
*       ALL          ALL       ALL       0.0.0.0/0      DENY
 
Outbound rules:
Rule #  Type         Protocol  Port      Destination    Action
100     HTTP         TCP       80        0.0.0.0/0      ALLOW
110     HTTPS        TCP       443       0.0.0.0/0      ALLOW
120     Custom TCP   TCP       1024-65535 0.0.0.0/0     ALLOW  ← Ephemeral
*       ALL          ALL       ALL       0.0.0.0/0      DENY

Ephemeral Ports explicados:

plaintext
Cuando cliente hace request:
Client:54321 → Server:80
 
Response:
Server:80 → Client:54321

     Ephemeral port (random 1024-65535)
 
NACL (stateless) necesita permitir este rango para responses.
 
Security Groups NO necesitan esto (stateful).

Security Groups vs. NACLs

AspectoSecurity GroupNetwork ACL
LevelInstance (ENI)Subnet
StateStatefulStateless
RulesALLOW onlyALLOW + DENY
EvaluationAll rulesFirst match wins
DefaultDeny inbound, Allow outboundAllow all (default NACL)
Response trafficAuto-allowedMust be explicitly allowed
Use casePrimary securityAdditional layer/blacklist

Defense in Depth

Combina Security Groups + NACLs para defensa por capas.

plaintext
Arquitectura:
 
Internet

NACL (Subnet level)
├─ Allow HTTP/HTTPS from anywhere
├─ Deny traffic from known malicious IPs
└─ Deny SSH from internet

Security Group (Instance level)
├─ Allow HTTP/HTTPS from anywhere
└─ Allow SSH from office IP only

EC2 Instance
 
Ejemplo de ataque:
Malicious IP: 198.51.100.50 tries to access
 
1. NACL check:
   Rule 50: DENY from 198.51.100.50 → ❌ BLOCKED
   (no llega a Security Group ni instance)
 
2. Legit user: 203.0.113.75 tries SSH
 
   NACL check:
   Rule 100: ALLOW SSH from 203.0.113.0/24 → ✅ Pass
 
   Security Group check:
   Rule: ALLOW SSH from 203.0.113.0/24 → ✅ Pass
 
   → Llega a instance
 
Beneficio: Múltiples layers de seguridad

Casos de Uso Comunes

1. Bloquear IP Maliciosa

plaintext
Problema:
IP 198.51.100.50 está hackeando tu web server.
 
Solución:
❌ Security Group: NO puedes (solo ALLOW rules)
✅ NACL: Agrega DENY rule
 
NACL:
Rule 10: DENY ALL from 198.51.100.50/32
Rule 100: ALLOW HTTP from 0.0.0.0/0
 
→ IP maliciosa bloqueada a nivel de subnet

2. Permitir Solo Tráfico de Office

plaintext
Office IP: 203.0.113.0/24
 
Security Group:
Inbound:
- SSH (22) from 203.0.113.0/24
- HTTP (80) from 0.0.0.0/0
 
NACL:
Inbound:
- SSH (22) from 203.0.113.0/24
- HTTP (80) from 0.0.0.0/0
- Ephemeral (1024-65535) from 0.0.0.0/0
- DENY ALL
 
Outbound:
- ALL to 0.0.0.0/0
 
Resultado:
- SSH: Solo desde office
- HTTP: Desde cualquier lugar
- Defense in depth (NACL + SG)

3. Database en Private Subnet

plaintext
Database Security Group:
Inbound:
- PostgreSQL (5432) from sg-app-server
 
Database NACL:
Inbound:
- PostgreSQL (5432) from 10.0.0.0/16 (VPC CIDR)
- Ephemeral ports from 10.0.0.0/16
- DENY ALL
 
Outbound:
- ALL to 10.0.0.0/16
- HTTPS (443) to 0.0.0.0/0 (para updates)
- DENY ALL else
 
Seguridad:
✅ Solo app servers pueden conectar a DB
✅ DB NO accesible desde internet (NACL + SG)
✅ DB puede descargar patches (HTTPS outbound)

Troubleshooting Connectivity

plaintext
Problema: No puedo conectar a EC2 instance via SSH
 
Debug checklist:
 
1. Security Group inbound:
   ✅ Tiene regla SSH (22) desde tu IP?
   ✅ Protocol es TCP?
   ✅ Source IP es correcto?
 
2. NACL inbound (subnet):
   ✅ Permite SSH (22) desde tu IP?
   ✅ Rule number es menor que deny all?
 
3. NACL outbound (subnet):
   ✅ Permite ephemeral ports (1024-65535) a tu IP?
   (Para responses de SSH)
 
4. Route Table:
   ✅ Subnet tiene route a Internet Gateway?
   (Para public subnets)
 
5. Instance:
   ✅ Tiene Public IP?
   ✅ SSH service está corriendo?
   ✅ OS firewall no bloqueando?
 
Herramienta:
VPC Reachability Analyzer:
Simula path entre source y destination
Identifica dónde está el bloqueo

Best Practices

1. Security Groups:

plaintext
✅ Usa nombres descriptivos (web-sg, db-sg, ssh-office-sg)
✅ Principio de least privilege (solo lo necesario)
✅ Referencia otros Security Groups en lugar de IPs
✅ Evita 0.0.0.0/0 para SSH/RDP (restringe a office IP)
✅ Separa concerns (web-sg, db-sg en lugar de all-in-one)
 
❌ NO permitas todo (0.0.0.0/0 port 0-65535)
❌ NO uses Security Groups como único layer de seguridad

2. NACLs:

plaintext
✅ Usa para subnet-level controls
✅ Usa para blacklisting IPs maliciosas
✅ Number rules con gaps (100, 200, 300) para poder insertar después
✅ Documenta reglas (nombres, comments)
 
❌ NO compliques innecesariamente (Security Groups son suficientes para mayoría de casos)
❌ NO olvides ephemeral ports para outbound responses
❌ NO uses rules con rangos muy amplios de puertos

3. Defense in Depth:

plaintext
Layer 1: NACL (subnet level)
- Bloquea IPs maliciosas conocidas
- Reglas generales para subnet
 
Layer 2: Security Group (instance level)
- Reglas específicas por instance type
- Referencias entre Security Groups
 
Layer 3: OS Firewall (opcional)
- iptables, firewalld
- Para casos especiales
 
Layer 4: Application (siempre)
- Input validation
- Authentication/Authorization

📝 Preparación para el Examen

Puntos Clave para Memorizar

Security Groups:

  • 📌 Stateful: Return traffic automáticamente permitido
  • 📌 Allow only: Solo reglas de ALLOW (no DENY)
  • 📌 Instance level: Asociado a ENI/instance
  • 📌 Default: Deny all inbound, allow all outbound
  • 📌 Referencias: Puede referenciar otros Security Groups

NACLs:

  • 📌 Stateless: Debes configurar inbound Y outbound explícitamente
  • 📌 Allow + Deny: Soporta ambas reglas
  • 📌 Subnet level: Asociado a subnet
  • 📌 Ordered: Evalúa reglas en orden numérico, first match wins
  • 📌 Ephemeral ports: Debes permitir 1024-65535 para responses

Comparación:

  • 📌 SG = Primary security, NACL = Additional layer
  • 📌 SG = Stateful, NACL = Stateless
  • 📌 SG = Instance, NACL = Subnet

Preguntas de Práctica

Pregunta 1:

¿Cuál es una diferencia clave entre Security Groups y Network ACLs?

A) Security Groups son stateless, NACLs son stateful B) Security Groups son stateful, NACLs son stateless C) Ambos son stateful D) Ambos son stateless

Success

Respuesta: B) Security Groups son stateful, NACLs son stateless

Stateful (SG): Return traffic automáticamente permitido. Stateless (NACL): Debes configurar inbound y outbound explícitamente.

Pregunta 2:

Una empresa quiere bloquear tráfico de una IP maliciosa específica. ¿Qué deben usar?

A) Security Group con deny rule B) Network ACL con deny rule C) Route Table con blackhole route D) VPC Endpoint

Success

Respuesta: B) Network ACL con deny rule

Security Groups NO soportan deny rules (solo allow). NACLs soportan deny rules, perfecto para blacklisting IPs.

Pregunta 3:

Un web server permite HTTP desde anywhere pero conexiones fallan. Security Group permite HTTP (80) inbound. NACL permite HTTP (80) inbound. ¿Qué falta?

A) Security Group outbound rule para port 80 B) NACL outbound rule para ephemeral ports C) Internet Gateway D) NAT Gateway

Success

Respuesta: B) NACL outbound rule para ephemeral ports

NACLs son stateless. Necesitas:

  • Inbound: port 80 ✓
  • Outbound: ephemeral ports (1024-65535) para responses

Security Groups (stateful) NO necesitan outbound explícito para responses.


🎓 Resumen

Lo que aprendimos:

  1. Security Groups: Stateful, instance-level, allow-only
  2. NACLs: Stateless, subnet-level, allow+deny, ordered rules
  3. Defense in Depth: Combina múltiples layers de seguridad
  4. Troubleshooting: Check SG → NACL → Routes → Instance
plaintext
Decision flow:
 
¿Necesitas bloquear IP específica?
└─ NACL (deny rule)
 
¿Necesitas configuración por instance?
└─ Security Group
 
¿Necesitas subnet-wide rules?
└─ NACL
 
¿Quieres simplicidad?
└─ Security Group (stateful, no ephemeral ports)
 
Best practice:
Security Group (primary) + NACL (additional layer)

⏭️ Próximo Post

En el Post #11 exploraremos CloudFront y Edge Services:

  • Content Delivery Network (CDN)
  • Edge Locations
  • Caching strategies
  • Lambda@Edge

📚 Recursos


Tags: #AWS #CloudPractitioner #SecurityGroups #NACLs #Firewall #NetworkSecurity #Stateful #Stateless #Certification

Written by Jhonny Lorenzo

Researcher at TrautsLab

Related Articles

Recent Articles

Comments