Remove obsolete SSL certificate and private key files, and delete outdated service catalog pickle file.
This commit is contained in:
parent
80fd31a299
commit
7c48bf12a7
|
|
@ -1 +0,0 @@
|
|||
/home/bryan/.gemini/config/projects/0e26cc16-6539-4017-b372-84a9c385725a.json
|
||||
|
|
@ -1,164 +0,0 @@
|
|||
# Incidente 3 — PRIVILEGE_ESCALATION CRITICAL
|
||||
|
||||
**Qué pasa:** Un usuario o identidad ejecuta acciones críticas de IAM que no le corresponden, como adjuntar políticas de administrador (`AttachUserPolicy` con `AdministratorAccess`), crear llaves de acceso (`CreateAccessKey`) o crear usuarios/grupos sin autorización. Es una fase crítica donde un atacante busca consolidar control total del plano de control de AWS.
|
||||
|
||||
┌───────────────────────┬────────────────────────────────────────────────┐
|
||||
│ Acción │ Por qué │
|
||||
├───────────────────────┼────────────────────────────────────────────────┤
|
||||
│ 🔔 notify-alert → │ Alerta de máxima prioridad (CRITICAL). Alguien │
|
||||
│ SNS/email │ está intentando escalar privilegios en IAM. │
|
||||
├───────────────────────┼────────────────────────────────────────────────┤
|
||||
│ 🚫 revoke-credentials │ Invalidación de credenciales en caliente: │
|
||||
│ (Playbook automático) │ Desactiva las Access Keys del usuario y le │
|
||||
│ │ aplica una política EmergencyDenyAll en IAM. │
|
||||
└───────────────────────┴────────────────────────────────────────────────┘
|
||||
|
||||
---
|
||||
|
||||
# Guía de Simulación de Escalada de Privilegios y Respuesta Automatizada
|
||||
|
||||
Ejecuta este flujo paso a paso en tu terminal dentro de `/home/bryan/localstack-tesis/terraform-tesis-ir-secure-portal` o en el directorio raíz según corresponda.
|
||||
|
||||
## 🗑️ PASO PREVIO (Desplegar y Verificar)
|
||||
|
||||
Asegúrate de que la infraestructura esté desplegada con Terraform:
|
||||
```bash
|
||||
terraform apply -auto-approve
|
||||
```
|
||||
*(Esto desplegará la cola SQS `playbook-revoke-credentials-queue`, la Lambda del detector y el playbook de revocación de credenciales)*
|
||||
|
||||
---
|
||||
|
||||
## 🎯 PASO 1 — Simular el Ataque de Escalada de Privilegios
|
||||
|
||||
### 🧠 Fundamento Técnico (Para el jurado)
|
||||
El ataque consiste en que una identidad comprometida abusa de permisos para crear un nuevo usuario de persistencia y adjuntarse políticas administrativas, generando eventos CloudTrail críticos:
|
||||
1. `CreateUser`: Creación de un usuario no autorizado.
|
||||
2. `AttachUserPolicy`: Intento de adjuntar la política de lectura o administración.
|
||||
|
||||
El Detector Lambda monitorea CloudTrail y genera una alerta automática de severidad **CRITICAL** al identificar llamadas a `iam.amazonaws.com` con estos nombres de eventos. Luego, la Lambda despacha el incidente a la cola del playbook `revoke-credentials` para realizar la mitigación inmediata.
|
||||
|
||||
### ⛓️ La Cadena de Eventos
|
||||
```
|
||||
Atacante (API / CLI)
|
||||
│
|
||||
│ 1. CreateUser (tesis-ir-temp-escalation-test)
|
||||
│ 2. AttachUserPolicy (ReadOnlyAccess / AdministratorAccess)
|
||||
▼
|
||||
AWS IAM plano de control
|
||||
│
|
||||
│ Genera eventos CloudTrail ("CreateUser", "AttachUserPolicy")
|
||||
▼
|
||||
CloudWatch Logs ➔ Subscription Filter ➔ Lambda Detector
|
||||
│
|
||||
│ Detecta evento crítico de IAM.
|
||||
│ Envía el incidente a SQS (incident-queue y playbook-revoke-credentials-queue).
|
||||
▼
|
||||
Playbook Automatizado (revoke-credentials):
|
||||
├── IAM: Desactiva todas las Access Keys del usuario de forma inmediata (Active -> Inactive).
|
||||
├── IAM: Adjunta la política inline "EmergencyDenyAll" (Deny * en Resource *).
|
||||
├── S3: Log de auditoría en responses/revoke-credentials/revoked-credentials.json.
|
||||
└── SNS: Envío de alerta crítica por correo electrónico informando la mitigación exitosa.
|
||||
```
|
||||
|
||||
### 💻 Ejecución del Ataque (Simulación)
|
||||
|
||||
Puedes simular el ataque mediante comandos de terminal (Opción A) o directamente desde la consola web (Opción B). Ambas opciones generarán los mismos eventos de CloudTrail e invocarán la automatización de mitigación.
|
||||
|
||||
#### Opción A: Usando AWS CLI (Terminal)
|
||||
```bash
|
||||
# 1. Crear el usuario de prueba
|
||||
aws iam create-user --user-name tesis-ir-temp-escalation-test --region ca-central-1
|
||||
|
||||
# 2. Adjuntar política de lectura (Simula la escalada)
|
||||
aws iam attach-user-policy --user-name tesis-ir-temp-escalation-test --policy-arn arn:aws:iam::aws:policy/ReadOnlyAccess --region ca-central-1
|
||||
```
|
||||
|
||||
#### Opción B: Simulación Visual Segura desde la Consola Web de AWS
|
||||
Para mostrar al jurado el flujo de mitigación en vivo de forma 100% gráfica y segura (evitando que tu usuario administrador principal `desarrollador-cli` se bloquee a sí mismo):
|
||||
|
||||
**Fase 1: Preparación (Como Administrador)**
|
||||
1. Inicia sesión en la **Consola de Administración de AWS** con tu cuenta administradora (`desarrollador-cli`).
|
||||
2. Navega al servicio **IAM** y haz clic en **Users** (Usuarios) en el menú lateral izquierdo.
|
||||
3. Haz clic en el botón **Create user** (Crear usuario):
|
||||
- **User name:** Escribe exactamente `tesis-ir-temp-escalation-test`.
|
||||
- **Console access:** Marca la casilla **Provide user access to the AWS Management Console**.
|
||||
- **Identity Center:** Elige **I want to create an IAM user**.
|
||||
- **Password:** Selecciona **Custom password** e ingresa una contraseña que recuerdes. Desmarca la opción de cambiar contraseña en el primer inicio de sesión.
|
||||
- Haz clic en **Next** (Siguiente).
|
||||
4. En opciones de permisos, selecciona **Attach policies directly** (Asociar políticas directamente), busca y marca la política **`IAMReadOnlyAccess`** (esto le dará permisos mínimos de lectura, pero no de escritura).
|
||||
5. Haz clic en **Next** y luego en **Create user** (Crear usuario).
|
||||
6. Selecciona el usuario recién creado `tesis-ir-temp-escalation-test` de la lista de usuarios:
|
||||
- Ve a la pestaña **Security credentials** (Credenciales de seguridad).
|
||||
- En la sección **Access keys** (Claves de acceso), haz clic en **Create access key** (Crear clave de acceso).
|
||||
- Selecciona **Command Line Interface (CLI)** u **Other**, acepta el checkbox de confirmación, haz clic en **Next** y luego en **Create access key**.
|
||||
- *(Esto creará una clave de acceso en estado **Active** asignada al usuario de prueba, que servirá como blanco de mitigación).*
|
||||
|
||||
**Fase 2: Simulación del Ataque (Como el Atacante)**
|
||||
1. Abre una ventana en **Modo Incógnito** en tu navegador.
|
||||
2. Inicia sesión en la consola de AWS utilizando la URL de inicio de sesión de tu cuenta con el usuario de prueba `tesis-ir-temp-escalation-test` y la contraseña que creaste.
|
||||
3. Una vez dentro de la sesión limitada, ve al servicio **IAM** e intenta realizar un cambio no autorizado (escalada de privilegios):
|
||||
- Intenta crear un nuevo usuario o intenta asociarte a ti mismo la política `AdministratorAccess`.
|
||||
- El sistema te mostrará un mensaje de **Access Denied** (Acceso Denegado) en letras rojas. Esto es normal y generará un evento de auditoría en CloudTrail.
|
||||
|
||||
**Fase 3: Verificación del Bloqueo (Como Administrador)**
|
||||
1. Vuelve a tu ventana del navegador normal (donde tienes la sesión de administrador `desarrollador-cli`).
|
||||
2. Espera de 1 a 2 minutos (tiempo de entrega de logs de CloudTrail) y **actualiza (refresca) la página del navegador** del usuario `tesis-ir-temp-escalation-test`:
|
||||
- Ve a la pestaña **Security credentials**: Verás que el estado de la clave de acceso de prueba cambió automáticamente a **Inactive** (desactivada por la automatización).
|
||||
- Ve a la pestaña **Permissions**: Verás que ahora tiene asociada la política inline de bloqueo llamada **`EmergencyDenyAll`** (quitándole todos los accesos).
|
||||
- En la ventana de Incógnito del atacante, si intentas navegar a cualquier otro recurso, verás que ha sido completamente bloqueado.
|
||||
|
||||
---
|
||||
|
||||
## 🔍 PASO 2 — Demostración de Mitigación y Respuesta Automatizada
|
||||
|
||||
*Espera de 1 a 2 minutos para permitir que CloudTrail registre los eventos de IAM, se envíen a CloudWatch Logs y las Lambdas procesen la alerta y la mitigación.*
|
||||
|
||||
### 🚫 2a — Contención Activa en IAM (Verificación del Bloqueo)
|
||||
Una vez mitigado el incidente, las Access Keys del usuario objetivo deben haber sido desactivadas y su cuenta debe estar bajo una política Deny-All:
|
||||
|
||||
```bash
|
||||
# Verificar que las Access Keys están "Inactive"
|
||||
aws iam list-access-keys --user-name tesis-ir-temp-escalation-test --region ca-central-1 --output table
|
||||
|
||||
# Verificar la política inline de bloqueo "EmergencyDenyAll"
|
||||
aws iam get-user-policy --user-name tesis-ir-temp-escalation-test --policy-name EmergencyDenyAll --region ca-central-1
|
||||
```
|
||||
|
||||
### 📁 2b — Pista de Auditoría en S3
|
||||
Muestra que el log del playbook registrando las acciones de revocación tomadas se archivó en el bucket de evidencias:
|
||||
|
||||
```bash
|
||||
aws s3 cp "s3://$(terraform output -raw evidence_bucket)/responses/revoke-credentials/revoked-credentials.json" - --region ca-central-1
|
||||
```
|
||||
|
||||
### 🗄️ 2c — Registro en Base de Datos (DynamoDB)
|
||||
Consulta la tabla de incidentes. Deberá figurar un incidente de tipo `PRIVILEGE_ESCALATION` con severidad `CRITICAL` y el affectedResource en formato `iam:user/tesis-ir-temp-escalation-test`:
|
||||
|
||||
```bash
|
||||
aws dynamodb scan --table-name tesis-ir_incidents --region ca-central-1 --output table
|
||||
```
|
||||
|
||||
### 📨 2d — Mensaje Normalizado en la Cola SQS
|
||||
Verifica si el mensaje estructurado llegó a la cola del Componente B/C:
|
||||
|
||||
```bash
|
||||
aws sqs receive-message --queue-url $(terraform output -raw incident_queue_url) --region ca-central-1
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🧹 PASO 3 — Limpieza del Entorno de Simulación
|
||||
|
||||
Para restaurar el entorno a su estado original sin dejar residuos de seguridad en IAM:
|
||||
|
||||
```bash
|
||||
# Eliminar política EmergencyDenyAll
|
||||
aws iam delete-user-policy --user-name tesis-ir-temp-escalation-test --policy-name EmergencyDenyAll --region ca-central-1
|
||||
|
||||
# Desasociar política ReadOnlyAccess
|
||||
aws iam detach-user-policy --user-name tesis-ir-temp-escalation-test --policy-arn arn:aws:iam::aws:policy/ReadOnlyAccess --region ca-central-1
|
||||
|
||||
# Eliminar usuario de prueba
|
||||
aws iam delete-user --user-name tesis-ir-temp-escalation-test --region ca-central-1
|
||||
```
|
||||
|
|
@ -1,122 +0,0 @@
|
|||
#!/usr/bin/env bash
|
||||
# ============================================================================
|
||||
# SIMULACIÓN DE ATAQUE — Incidente 3: Escalada de Privilegios IAM
|
||||
# Tesis: Detección y respuesta ante incidentes en AWS (LocalStack / Real AWS)
|
||||
# ============================================================================
|
||||
set -euo pipefail
|
||||
|
||||
# Colores para salida en consola
|
||||
C_GREEN='\033[0;32m'
|
||||
C_CYAN='\033[0;36m'
|
||||
C_YELLOW='\033[1;33m'
|
||||
C_RED='\033[0;31m'
|
||||
C_NC='\033[0m'
|
||||
|
||||
echo -e "${C_CYAN}======================================================================${C_NC}"
|
||||
echo -e "${C_CYAN} Iniciando Simulación: Escalada de Privilegios (PRIVILEGE_ESCALATION) ${C_NC}"
|
||||
echo -e "${C_CYAN}======================================================================${C_NC}"
|
||||
|
||||
# Detectar si usar LocalStack o AWS Real
|
||||
AWS_CMD="aws"
|
||||
REGION="ca-central-1"
|
||||
ENDPOINT_FLAG=""
|
||||
|
||||
if curl -sf http://localhost:4566/_localstack/health >/dev/null 2>&1; then
|
||||
echo -e "${C_GREEN}[*] LocalStack detectado en localhost:4566.${C_NC}"
|
||||
if command -v awslocal >/dev/null 2>&1; then
|
||||
AWS_CMD="awslocal"
|
||||
else
|
||||
AWS_CMD="aws"
|
||||
ENDPOINT_FLAG="--endpoint-url http://localhost:4566"
|
||||
fi
|
||||
else
|
||||
echo -e "${C_YELLOW}[!] LocalStack no detectado. Utilizando AWS CLI global (ca-central-1).${C_NC}"
|
||||
fi
|
||||
|
||||
# Validar identidad
|
||||
echo -e "\n${C_CYAN}[Paso 1] Validando identidad y conexión AWS...${C_NC}"
|
||||
if ! $AWS_CMD sts get-caller-identity $ENDPOINT_FLAG >/dev/null 2>&1; then
|
||||
echo -e "${C_RED}[ERROR] No se pudo verificar la identidad. ¿Están cargadas tus credenciales?${C_NC}"
|
||||
echo -e "Ejecuta: export AWS_ACCESS_KEY_ID=tu_key && export AWS_SECRET_ACCESS_KEY=tu_secret"
|
||||
exit 1
|
||||
fi
|
||||
$AWS_CMD sts get-caller-identity $ENDPOINT_FLAG --output table
|
||||
|
||||
# Inventario de recursos desplegados
|
||||
echo -e "\n${C_CYAN}[Paso 2] Mostrando recursos del sistema en AWS...${C_NC}"
|
||||
echo -e "${C_GREEN}1. Tabla DynamoDB de Incidentes:${C_NC}"
|
||||
DYNAMO_TABLE=$($AWS_CMD dynamodb list-tables $ENDPOINT_FLAG --query "TableNames[?contains(@, 'incidents')]" --output text || echo "tesis-ir_incidents")
|
||||
echo -e " -> Tabla detectada: $DYNAMO_TABLE"
|
||||
|
||||
echo -e "${C_GREEN}2. Buckets S3 de Evidencia/Logs:${C_NC}"
|
||||
EVIDENCE_BUCKET=$($AWS_CMD s3 ls $ENDPOINT_FLAG | awk '{print $3}' | grep -E 'evidence|logs' | head -n1 || echo "tesis-ir-evidence")
|
||||
echo -e " -> Bucket detectado: $EVIDENCE_BUCKET"
|
||||
|
||||
echo -e "${C_GREEN}3. Colas SQS activas:${C_NC}"
|
||||
QUEUE_URL=$($AWS_CMD sqs list-queues $ENDPOINT_FLAG --query "QueueUrls[?contains(@, 'incident')]" --output text 2>/dev/null | awk '{print $1}' || echo "http://localhost:4566/000000000000/tesis-ir-incident-queue")
|
||||
echo -e " -> Cola detectada: $QUEUE_URL"
|
||||
|
||||
# Simulación del ataque
|
||||
USER_NAME="tesis-ir-temp-escalation-test"
|
||||
POLICY_ARN="arn:aws:iam::aws:policy/ReadOnlyAccess"
|
||||
|
||||
echo -e "\n${C_CYAN}[Paso 3] Ejecutando simulación de ataque (IAM)...${C_NC}"
|
||||
echo -e "Creando usuario temporal: ${C_YELLOW}$USER_NAME${C_NC}"
|
||||
$AWS_CMD iam create-user --user-name "$USER_NAME" $ENDPOINT_FLAG --output json
|
||||
|
||||
# Crear una Access Key activa para este usuario para poder demostrar la revocación real
|
||||
echo -e "Generando Access Key activa para el usuario (blanco de mitigación)..."
|
||||
$AWS_CMD iam create-access-key --user-name "$USER_NAME" $ENDPOINT_FLAG --output json
|
||||
|
||||
echo -e "Adjuntando política: ${C_YELLOW}$POLICY_ARN${C_NC}"
|
||||
$AWS_CMD iam attach-user-policy --user-name "$USER_NAME" --policy-arn "$POLICY_ARN" $ENDPOINT_FLAG
|
||||
|
||||
echo -e "${C_GREEN}[✓] Ataque simulado con éxito.${C_NC}"
|
||||
echo -e "\n${C_YELLOW}Se han ejecutado los eventos 'CreateUser' y 'AttachUserPolicy' en IAM.${C_NC}"
|
||||
echo -e "Estos eventos serán detectados por el CloudTrail y enviados al detector Lambda."
|
||||
echo -e "El playbook de mitigación automática 'revoke-credentials' se disparará en breve."
|
||||
|
||||
# Esperar a que la Lambda procese el incidente y realice la revocación
|
||||
echo -e "\n${C_CYAN}[Paso 4] Esperando 10 segundos para verificar la mitigación automática...${C_NC}"
|
||||
sleep 10
|
||||
|
||||
echo -e "\n${C_CYAN}[Paso 5] Verificando la mitigación (Puntos de Cumplimiento / Enforcement):${C_NC}"
|
||||
|
||||
# 1. Verificar estado de las Access Keys del usuario
|
||||
echo -e "${C_GREEN}1. Verificando estado de las Access Keys (deben pasar a INACTIVE):${C_NC}"
|
||||
$AWS_CMD iam list-access-keys --user-name "$USER_NAME" $ENDPOINT_FLAG --output table || echo -e "${C_RED}Error al listar keys o el usuario no existe.${C_NC}"
|
||||
|
||||
# 2. Verificar si se aplicó EmergencyDenyAll
|
||||
echo -e "${C_GREEN}2. Verificando política de contención inline 'EmergencyDenyAll':${C_NC}"
|
||||
$AWS_CMD iam get-user-policy --user-name "$USER_NAME" --policy-name "EmergencyDenyAll" $ENDPOINT_FLAG --output json || echo -e "${C_RED}La política EmergencyDenyAll aún no ha sido aplicada.${C_NC}"
|
||||
|
||||
# 3. Mostrar log de auditoría del playbook en S3
|
||||
echo -e "${C_GREEN}3. Log de auditoría de revocación registrado en S3:${C_NC}"
|
||||
$AWS_CMD s3 cp "s3://$EVIDENCE_BUCKET/responses/revoke-credentials/revoked-credentials.json" - $ENDPOINT_FLAG 2>/dev/null || echo -e "${C_YELLOW}Log en S3 aún no escrito (o tarda en propagar). Consulta de nuevo en un minuto.${C_NC}"
|
||||
|
||||
# 4. Mostrar registro de incidentes en DynamoDB
|
||||
echo -e "${C_GREEN}4. Registro del incidente en DynamoDB:${C_NC}"
|
||||
$AWS_CMD dynamodb scan --table-name "$DYNAMO_TABLE" $ENDPOINT_FLAG --output table
|
||||
|
||||
# Preguntar para limpiar o salir
|
||||
echo -e "\n${C_CYAN}======================================================================${C_NC}"
|
||||
read -rp "Presiona [ENTER] para limpiar el usuario temporal y las políticas de la simulación..."
|
||||
echo -e "${C_CYAN}======================================================================${C_NC}"
|
||||
|
||||
echo -e "\n${C_CYAN}[Paso 6] Limpiando el entorno...${C_NC}"
|
||||
echo -e "Removiendo política EmergencyDenyAll..."
|
||||
$AWS_CMD iam delete-user-policy --user-name "$USER_NAME" --policy-name "EmergencyDenyAll" $ENDPOINT_FLAG || true
|
||||
|
||||
echo -e "Removiendo política ReadOnlyAccess..."
|
||||
$AWS_CMD iam detach-user-policy --user-name "$USER_NAME" --policy-arn "$POLICY_ARN" $ENDPOINT_FLAG || true
|
||||
|
||||
echo -e "Eliminando Access Keys del usuario de prueba..."
|
||||
KEYS=$($AWS_CMD iam list-access-keys --user-name "$USER_NAME" $ENDPOINT_FLAG --query "AccessKeyMetadata[].AccessKeyId" --output text 2>/dev/null || echo "")
|
||||
for kid in $KEYS; do
|
||||
$AWS_CMD iam delete-access-key --user-name "$USER_NAME" --access-key-id "$kid" $ENDPOINT_FLAG || true
|
||||
done
|
||||
|
||||
echo -e "Eliminando usuario temporal..."
|
||||
$AWS_CMD iam delete-user --user-name "$USER_NAME" $ENDPOINT_FLAG || true
|
||||
|
||||
echo -e "${C_GREEN}[✓] Limpieza completada. El entorno está restaurado.${C_NC}"
|
||||
|
|
@ -1,201 +0,0 @@
|
|||
# Incidente 2 — PORT_SCAN MEDIUM
|
||||
|
||||
**Qué pasa:** Alguien enumera la infraestructura (`DescribeInstances`, `DescribeVpcs`, etc.) o intenta conectar a múltiples puertos cerrados. Es el primer paso de reconocimiento antes de un ataque real.
|
||||
|
||||
┌───────────────────────┬────────────────────────────────────────────────┐
|
||||
│ Acción │ Por qué │
|
||||
├───────────────────────┼────────────────────────────────────────────────┤
|
||||
│ 🔔 notify-alert → │ Avisar al equipo: hay alguien mapeando la red │
|
||||
│ SNS/email │ │
|
||||
├───────────────────────┼────────────────────────────────────────────────┤
|
||||
│ 🚫 block-ip → regla │ Cortar el reconocimiento antes de que el │
|
||||
│ DENY en NACL │ atacante pueda actuar. Respuesta proactiva │
|
||||
└───────────────────────┴────────────────────────────────────────────────┘
|
||||
|
||||
---
|
||||
|
||||
# Guía de Escaneo de Puertos y Respuesta Automatizada
|
||||
|
||||
Ejecuta este flujo paso a paso en tu terminal de Zsh dentro de `/home/bryan/localstack-tesis/terraform-tesis-ir-secure-portal`.
|
||||
|
||||
## 🗑️ PASO PREVIO (Hazlo AHORA mismo para borrar todo)
|
||||
|
||||
Deja tu cuenta en cero para que no gaste nada durante el día:
|
||||
|
||||
```bash
|
||||
terraform destroy -auto-approve
|
||||
|
||||
```
|
||||
|
||||
## 🔑 PASO 1 (En la Noche) — Cargar Credenciales
|
||||
|
||||
Abre tu terminal limpia frente al profesor y carga tus llaves de AWS (asegúrate de usar tus credenciales activas y sin comillas extrañas):
|
||||
|
||||
```bash
|
||||
export AWS_ACCESS_KEY_ID=TU_ACCESS_KEY_ACTIVA
|
||||
export AWS_SECRET_ACCESS_KEY=TU_SECRET_KEY_ACTIVA
|
||||
export AWS_DEFAULT_REGION=ca-central-1
|
||||
|
||||
```
|
||||
|
||||
Valida rápido ante el jurado que estás conectado a AWS:
|
||||
|
||||
```bash
|
||||
aws sts get-caller-identity
|
||||
|
||||
```
|
||||
|
||||
## 🚀 PASO 2 — Inicializar y Desplegar (~3-4 min)
|
||||
|
||||
Inicializa los componentes locales de Terraform:
|
||||
|
||||
```bash
|
||||
terraform init
|
||||
|
||||
```
|
||||
|
||||
Lanza la creación automática de tus 103 recursos en Canadá:
|
||||
|
||||
```bash
|
||||
terraform apply -auto-approve
|
||||
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> **Acción en vivo:** Abre tu correo `banobryan1090@gmail.com`. Busca el email de AWS con el asunto "Subscription Confirmation" y dale clic en "Confirm subscription" para que se activen las alertas por correo en vivo.
|
||||
|
||||
---
|
||||
|
||||
## 🎯 PASO 3 — Simular el Ataque de Escaneo de Puertos
|
||||
|
||||
### 🧠 Fundamento Técnico (Para explicar al jurado)
|
||||
|
||||
El comando que vas a ejecutar realiza un escaneo de puertos en paralelo usando loops de shell nativos:
|
||||
|
||||
```bash
|
||||
for port in $(seq 81 92); do
|
||||
nc -zv -w 1 "$ip" "$port" & # Intento de conexión TCP al puerto
|
||||
done
|
||||
|
||||
```
|
||||
|
||||
`nc` (netcat) intenta abrir una conexión TCP real a cada puerto de la EC2. Como esos puertos están cerrados en el Security Group, AWS los rechaza inmediatamente.
|
||||
|
||||
### ⛓️ La Cadena de Eventos
|
||||
|
||||
```
|
||||
Tu PC (IP Pública)
|
||||
│
|
||||
│ SYN → puerto 81
|
||||
│ SYN → puerto 82 (12 intentos en paralelo)
|
||||
│ ...
|
||||
│ SYN → puerto 92
|
||||
▼
|
||||
EC2 en AWS (IP pública)
|
||||
│
|
||||
│ Security Group: solo permite puertos autorizados (ej. 22 y 80)
|
||||
│ → Todos los demás: REJECT
|
||||
▼
|
||||
VPC Flow Logs captura cada rechazo en caliente:
|
||||
"190.9.182.58 → 10.10.1.10 puerto 81 REJECT"
|
||||
"190.9.182.58 → 10.10.1.10 puerto 82 REJECT"
|
||||
...
|
||||
▼
|
||||
CloudWatch Logs ➔ Subscription Filter ➔ Lambda Detector
|
||||
│
|
||||
│ Cuenta: 12 puertos distintos rechazados desde la misma IP en 5 minutos.
|
||||
│ Threshold (Umbral) = 10 ➔ ¡PORT_SCAN detectado con éxito!
|
||||
▼
|
||||
Respuesta Automatizada (Playbooks):
|
||||
├── DynamoDB: Incidente registrado de manera estructurada.
|
||||
├── S3: Evidencia forense y respuestas guardadas de forma inmutable.
|
||||
├── SNS: Email de alerta crítico enviado al equipo SOC.
|
||||
└── NACL: Regla DENY para la IP atacante (Aislamiento perimetral).
|
||||
|
||||
```
|
||||
|
||||
### ⚠️ Consecuencia Importante para la Demo
|
||||
|
||||
Tu PC es el "atacante" en esta simulación. Cuando el sistema responda, **bloqueará tu propia IP pública en la NACL**. Esto significa que tras el bloqueo:
|
||||
|
||||
* ❌ Ya no podrás hacer SSH a la EC2.
|
||||
* ❌ Ya no podrás cargar el portal web desde tu navegador (dará Timeout).
|
||||
* Puedes seguir usando la consola web de AWS (es tráfico HTTPS diferente mediante la API global).
|
||||
* Puedes seguir usando `aws cli` y `terraform` desde tu terminal (también viajan por la API de AWS y no por la red interna atacada).
|
||||
|
||||
> **Consejo de oro:** Explícale esta consecuencia al profesor **antes** de correr el scan. Así entenderá que la pérdida de acceso web posterior es la prueba rotunda de que tu sistema funciona de verdad.
|
||||
|
||||
### 💻 Ejecución del Ataque
|
||||
|
||||
*Espera 2 minutos tras el apply para que la EC2 inicie servicios.* Ejecuta el comando:
|
||||
|
||||
```bash
|
||||
ip=$(terraform output -raw portal_public_ip) && echo "Target IP: $ip" && for port in $(seq 81 92); do nc -zv -w 1 "$ip" "$port" 2>&1 & done && wait && echo "Scan listo"
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔍 PASO 4 — Demostración Forense y de Respuesta Automatizada
|
||||
|
||||
*Espera 2 minutos para dar tiempo a que las funciones Lambda procesen los flujos de red y disparen los playbooks.*
|
||||
|
||||
### 🗄️ 4a — Evidencia en Base de Datos (Éxito de la Lambda de Análisis)
|
||||
|
||||
Muestra la tabla de incidentes para validar que el Port Scan se guardó con su severidad:
|
||||
|
||||
```bash
|
||||
aws dynamodb scan --table-name tesis-ir_incidents --region ca-central-1 --output table
|
||||
|
||||
```
|
||||
|
||||
### 📨 4b — Mensaje Normalizado en la Cola SQS
|
||||
|
||||
Comprueba la existencia del evento en formato estándar dentro de la cola de mensajería:
|
||||
|
||||
```bash
|
||||
aws sqs receive-message --queue-url $(terraform output -raw incident_queue_url) --region ca-central-1
|
||||
|
||||
```
|
||||
|
||||
### 📁 4c — Almacenamiento Forense Inmutable en S3
|
||||
|
||||
Muestra que los artefactos crudos del ataque y las respuestas de mitigación se archivaron en el bucket:
|
||||
|
||||
```bash
|
||||
aws s3 ls "s3://$(terraform output -raw evidence_bucket)/incident-02-port-scan/" --region ca-central-1
|
||||
|
||||
```
|
||||
|
||||
### 🚫 4d — Verificación de Contención Activa en la NACL (Capa de Red)
|
||||
|
||||
Ejecuta esto para auditar la regla perimetral. Deberá aparecer una regla **DENY** apuntando directamente a tu IP de origen:
|
||||
|
||||
```bash
|
||||
aws ec2 describe-network-acls --filters "Name=vpc-id,Values=$(terraform output -raw vpc_id)" --query "NetworkAcls[0].Entries[?Egress==\`false\` && RuleAction==\`deny\`].[RuleNumber,CidrBlock,RuleAction]" --output table --region ca-central-1
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🛠️ PASO 5 — Desbloqueo Manual en Vivo (Opcional para recuperar acceso)
|
||||
|
||||
Si después de verificar la NACL quieres demostrarle al profesor que puedes revertir la mitigación manualmente desde la terminal para recuperar el acceso a la web sin destruir el entorno, corre este comando limpio:
|
||||
|
||||
```bash
|
||||
aws ec2 delete-network-acl-entry --network-acl-id $(terraform output -raw vpc_id | xargs -I {} aws ec2 describe-network-acls --filters "Name=vpc-id,Values={}" --query "NetworkAcls[0].NetworkAclId" --output text --region ca-central-1) --rule-number 1 --ingress --region ca-central-1
|
||||
|
||||
```
|
||||
|
||||
*(Nota: Revisa el número de regla en el paso 4d, usualmente la regla inyectada es la número 1).*
|
||||
|
||||
---
|
||||
|
||||
## 🗑️ PASO 6 — Cierre de la Defensa (Destrucción de Recursos)
|
||||
|
||||
Termina tu ronda de preguntas demostrando que la infraestructura es efímera y se limpia por completo para no generar costos:
|
||||
|
||||
```bash
|
||||
terraform destroy -auto-approve
|
||||
|
||||
```
|
||||
17
activate.sh
17
activate.sh
|
|
@ -1,17 +0,0 @@
|
|||
#!/usr/bin/env bash
|
||||
# Activa el entorno de desarrollo local de la tesis
|
||||
# Uso: source activate.sh
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
|
||||
source "$SCRIPT_DIR/.venv/bin/activate"
|
||||
|
||||
export AWS_ACCESS_KEY_ID=test
|
||||
export AWS_SECRET_ACCESS_KEY=test
|
||||
export AWS_DEFAULT_REGION=us-east-1
|
||||
export AWS_ENDPOINT_URL=http://localhost:4566
|
||||
|
||||
echo "Entorno de tesis activado."
|
||||
echo " awslocal → $(which awslocal)"
|
||||
echo " python3 → $(which python3)"
|
||||
echo " endpoint → $AWS_ENDPOINT_URL"
|
||||
|
|
@ -1,24 +0,0 @@
|
|||
version: "3.8"
|
||||
|
||||
services:
|
||||
localstack:
|
||||
container_name: "${LOCALSTACK_DOCKER_NAME:-localstack-tesis}"
|
||||
image: localstack/localstack:3.8
|
||||
ports:
|
||||
- "127.0.0.1:4566:4566"
|
||||
- "127.0.0.1:4510-4559:4510-4559"
|
||||
environment:
|
||||
- DEBUG=${DEBUG:-0}
|
||||
- SERVICES=s3,sns,sqs,lambda,iam,logs,cloudwatch,events,ec2
|
||||
- DOCKER_HOST=unix:///var/run/docker.sock
|
||||
- LAMBDA_EXECUTOR=docker
|
||||
- LAMBDA_DOCKER_NETWORK=localstack-tesis_default
|
||||
- AWS_DEFAULT_REGION=us-east-1
|
||||
volumes:
|
||||
- "${LOCALSTACK_VOLUME_DIR:-./volume}:/var/lib/localstack"
|
||||
- "/var/run/docker.sock:/var/run/docker.sock"
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-f", "http://localhost:4566/_localstack/health"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
|
@ -1,58 +0,0 @@
|
|||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "S3LogsAccess",
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:GetObject",
|
||||
"s3:PutObject",
|
||||
"s3:ListBucket"
|
||||
],
|
||||
"Resource": [
|
||||
"arn:aws:s3:::tesis-security-logs",
|
||||
"arn:aws:s3:::tesis-security-logs/*"
|
||||
]
|
||||
},
|
||||
{
|
||||
"Sid": "SNSPublish",
|
||||
"Effect": "Allow",
|
||||
"Action": ["sns:Publish"],
|
||||
"Resource": [
|
||||
"arn:aws:sns:us-east-1:000000000000:tesis-security-alerts",
|
||||
"arn:aws:sns:us-east-1:000000000000:tesis-lambda-triggers"
|
||||
]
|
||||
},
|
||||
{
|
||||
"Sid": "SQSConsume",
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"sqs:ReceiveMessage",
|
||||
"sqs:DeleteMessage",
|
||||
"sqs:GetQueueAttributes"
|
||||
],
|
||||
"Resource": "arn:aws:sqs:us-east-1:000000000000:tesis-incident-queue"
|
||||
},
|
||||
{
|
||||
"Sid": "CloudWatchLogs",
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"logs:CreateLogStream",
|
||||
"logs:PutLogEvents",
|
||||
"logs:DescribeLogStreams"
|
||||
],
|
||||
"Resource": "arn:aws:logs:us-east-1:000000000000:log-group:/tesis/*:*"
|
||||
},
|
||||
{
|
||||
"Sid": "EC2NetworkAclEnforcement",
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"ec2:DescribeVpcs",
|
||||
"ec2:DescribeNetworkAcls",
|
||||
"ec2:CreateNetworkAclEntry",
|
||||
"ec2:DeleteNetworkAclEntry"
|
||||
],
|
||||
"Resource": "*"
|
||||
}
|
||||
]
|
||||
}
|
||||
142
infra/setup.sh
142
infra/setup.sh
|
|
@ -1,142 +0,0 @@
|
|||
#!/usr/bin/env bash
|
||||
# Bootstrap de recursos AWS locales para el Componente C — Automatización de Respuesta
|
||||
# Requiere: LocalStack corriendo en localhost:4566 y awslocal instalado
|
||||
set -euo pipefail
|
||||
|
||||
ENDPOINT="http://localhost:4566"
|
||||
REGION="us-east-1"
|
||||
ACCOUNT_ID="000000000000" # LocalStack usa este account ID ficticio
|
||||
|
||||
# Colores para output
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
RED='\033[0;31m'
|
||||
NC='\033[0m'
|
||||
|
||||
log() { echo -e "${GREEN}[OK]${NC} $1"; }
|
||||
warn() { echo -e "${YELLOW}[--]${NC} $1"; }
|
||||
fail() { echo -e "${RED}[ERR]${NC} $1"; exit 1; }
|
||||
|
||||
echo "========================================"
|
||||
echo " Bootstrap Componente C — Tesis"
|
||||
echo " LocalStack: $ENDPOINT"
|
||||
echo "========================================"
|
||||
|
||||
# Verificar que LocalStack está corriendo
|
||||
curl -sf "$ENDPOINT/_localstack/health" > /dev/null || fail "LocalStack no está corriendo. Ejecuta: docker compose up -d"
|
||||
|
||||
# ── S3 ────────────────────────────────────────────────────────────────────────
|
||||
warn "Creando bucket S3..."
|
||||
awslocal s3 mb s3://tesis-security-logs --region $REGION 2>/dev/null || warn "Bucket ya existe"
|
||||
# Crear prefijos vacíos (objetos vacíos actúan como carpetas)
|
||||
for prefix in cloudtrail vpc-flow guardduty responses; do
|
||||
awslocal s3api put-object --bucket tesis-security-logs --key "$prefix/" > /dev/null
|
||||
done
|
||||
log "S3: s3://tesis-security-logs [cloudtrail/, vpc-flow/, guardduty/, responses/]"
|
||||
|
||||
# ── SNS ───────────────────────────────────────────────────────────────────────
|
||||
warn "Creando tópicos SNS..."
|
||||
ALERTS_ARN=$(awslocal sns create-topic --name tesis-security-alerts --query 'TopicArn' --output text)
|
||||
TRIGGERS_ARN=$(awslocal sns create-topic --name tesis-lambda-triggers --query 'TopicArn' --output text)
|
||||
log "SNS alerts: $ALERTS_ARN"
|
||||
log "SNS triggers: $TRIGGERS_ARN"
|
||||
|
||||
# ── SQS ───────────────────────────────────────────────────────────────────────
|
||||
warn "Creando colas SQS..."
|
||||
DLQ_URL=$(awslocal sqs create-queue --queue-name tesis-incident-queue-dlq --query 'QueueUrl' --output text)
|
||||
DLQ_ARN="arn:aws:sqs:$REGION:$ACCOUNT_ID:tesis-incident-queue-dlq"
|
||||
|
||||
# Cola principal con DLQ configurada
|
||||
QUEUE_URL=$(awslocal sqs create-queue \
|
||||
--queue-name tesis-incident-queue \
|
||||
--attributes "{\"RedrivePolicy\":\"{\\\"deadLetterTargetArn\\\":\\\"$DLQ_ARN\\\",\\\"maxReceiveCount\\\":\\\"3\\\"}\"}" \
|
||||
--query 'QueueUrl' --output text)
|
||||
log "SQS queue: $QUEUE_URL"
|
||||
log "SQS DLQ: $DLQ_URL"
|
||||
|
||||
# ── CloudWatch Logs ───────────────────────────────────────────────────────────
|
||||
warn "Creando grupos de logs CloudWatch..."
|
||||
awslocal logs create-log-group --log-group-name /tesis/security-events 2>/dev/null || warn "Log group ya existe"
|
||||
awslocal logs create-log-group --log-group-name /tesis/lambda-responses 2>/dev/null || warn "Log group ya existe"
|
||||
log "CloudWatch: /tesis/security-events"
|
||||
log "CloudWatch: /tesis/lambda-responses"
|
||||
|
||||
# ── IAM ───────────────────────────────────────────────────────────────────────
|
||||
warn "Creando rol IAM para Lambdas de respuesta..."
|
||||
TRUST_POLICY='{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [{
|
||||
"Effect": "Allow",
|
||||
"Principal": {"Service": "lambda.amazonaws.com"},
|
||||
"Action": "sts:AssumeRole"
|
||||
}]
|
||||
}'
|
||||
ROLE_ARN=$(awslocal iam create-role \
|
||||
--role-name tesis-lambda-response-role \
|
||||
--assume-role-policy-document "$TRUST_POLICY" \
|
||||
--query 'Role.Arn' --output text 2>/dev/null) || {
|
||||
ROLE_ARN=$(awslocal iam get-role --role-name tesis-lambda-response-role --query 'Role.Arn' --output text)
|
||||
warn "Rol ya existe"
|
||||
}
|
||||
|
||||
# Adjuntar política de acceso a los recursos del proyecto
|
||||
awslocal iam put-role-policy \
|
||||
--role-name tesis-lambda-response-role \
|
||||
--policy-name tesis-lambda-base-policy \
|
||||
--policy-document file://$(dirname "$0")/lambda-policies/base-policy.json 2>/dev/null || true
|
||||
log "IAM Role: $ROLE_ARN"
|
||||
|
||||
# ── EC2 / Network ACL (punto de cumplimiento de block-ip) ─────────────────────
|
||||
warn "Verificando VPC y Network ACL objetivo para block-ip..."
|
||||
# LocalStack crea una VPC por defecto automáticamente al usar EC2.
|
||||
VPC_ID=$(awslocal ec2 describe-vpcs --filters "Name=isDefault,Values=true" \
|
||||
--query 'Vpcs[0].VpcId' --output text 2>/dev/null) || VPC_ID="None"
|
||||
if [ "$VPC_ID" = "None" ] || [ -z "$VPC_ID" ]; then
|
||||
VPC_ID=$(awslocal ec2 create-vpc --cidr-block 10.0.0.0/16 \
|
||||
--query 'Vpc.VpcId' --output text)
|
||||
warn "VPC por defecto no existía; creada $VPC_ID"
|
||||
fi
|
||||
NACL_ID=$(awslocal ec2 describe-network-acls \
|
||||
--filters "Name=vpc-id,Values=$VPC_ID" "Name=default,Values=true" \
|
||||
--query 'NetworkAcls[0].NetworkAclId' --output text 2>/dev/null)
|
||||
log "EC2 VPC objetivo: $VPC_ID"
|
||||
log "EC2 Network ACL: $NACL_ID (aquí block-ip añade reglas DENY)"
|
||||
|
||||
# ── IAM usuarios de prueba (para demo revoke-credentials) ────────────────────
|
||||
warn "Creando usuarios IAM de prueba para demos de incidentes..."
|
||||
for user in admin dev-operator ci-runner readonly-audit external-contractor; do
|
||||
awslocal iam create-user --user-name "$user" > /dev/null 2>&1 || true
|
||||
# Crear access key solo si el usuario no tiene ninguna
|
||||
key_count=$(awslocal iam list-access-keys --user-name "$user" \
|
||||
--query 'length(AccessKeyMetadata)' --output text 2>/dev/null || echo "0")
|
||||
if [ "$key_count" = "0" ]; then
|
||||
awslocal iam create-access-key --user-name "$user" > /dev/null 2>/dev/null || true
|
||||
log "IAM user $user: access key Active creada"
|
||||
else
|
||||
log "IAM user $user: ya tiene key(s)"
|
||||
fi
|
||||
done
|
||||
|
||||
# ── S3 prod-data-bucket (para demo exfiltración) ──────────────────────────────
|
||||
warn "Creando bucket prod-data-bucket con datos de prueba..."
|
||||
awslocal s3 mb s3://prod-data-bucket --region $REGION 2>/dev/null || warn "Bucket ya existe"
|
||||
for i in $(seq 0 9); do
|
||||
awslocal s3api put-object \
|
||||
--bucket prod-data-bucket \
|
||||
--key "data/record_$(printf '%04d' $i).json" \
|
||||
--body <(echo "{\"record\": $i, \"data\": \"sensitive-value-$i\", \"pii\": true}") \
|
||||
> /dev/null 2>&1 || true
|
||||
done
|
||||
log "S3: s3://prod-data-bucket [10 archivos sensibles de prueba]"
|
||||
|
||||
# ── Resumen ───────────────────────────────────────────────────────────────────
|
||||
echo ""
|
||||
echo "========================================"
|
||||
echo " Recursos creados exitosamente"
|
||||
echo "========================================"
|
||||
echo ""
|
||||
awslocal s3 ls
|
||||
echo ""
|
||||
awslocal sns list-topics --query 'Topics[].TopicArn' --output table
|
||||
echo ""
|
||||
awslocal sqs list-queues --output table
|
||||
|
|
@ -1,199 +0,0 @@
|
|||
"""
|
||||
Playbook: block-ip
|
||||
Acción de contención REAL ante una IP atacante.
|
||||
|
||||
Punto de cumplimiento (enforcement point):
|
||||
Se añade una regla DENY a la Network ACL de la VPC mediante
|
||||
ec2.create_network_acl_entry(). Esa es la línea donde el tráfico
|
||||
de la IP del atacante queda efectivamente denegado a nivel de red.
|
||||
|
||||
Detalle AWS clave: una NACL evalúa reglas por número, de menor a mayor,
|
||||
y la primera coincidencia gana. La NACL por defecto trae una regla
|
||||
ALLOW (nº 100). Por eso la regla DENY debe llevar un número MENOR a 100
|
||||
(rango 1-99); si fuera mayor, el ALLOW 100 ganaría y el bloqueo no surtiría
|
||||
efecto. Esto es lo que demuestra que el bloqueo es real y no cosmético.
|
||||
|
||||
El registro en S3 (responses/blocked-ips.json) se mantiene como PISTA DE
|
||||
AUDITORÍA / evidencia de mitigación, alineado con el prefijo `responses/`
|
||||
del esquema de almacenamiento del Componente A.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import boto3
|
||||
from datetime import datetime, timezone
|
||||
|
||||
_ls_host = os.environ.get("LOCALSTACK_HOSTNAME", "localhost")
|
||||
ENDPOINT = os.environ.get("AWS_ENDPOINT_URL", f"http://{_ls_host}:4566")
|
||||
REGION = os.environ.get("AWS_DEFAULT_REGION", "us-east-1")
|
||||
BUCKET = os.environ.get("S3_BUCKET", "tesis-security-logs")
|
||||
SNS_ARN = os.environ.get("SNS_ALERTS_ARN", "arn:aws:sns:us-east-1:000000000000:tesis-security-alerts")
|
||||
# Permite forzar una NACL concreta; si no, se usa la NACL por defecto de la VPC por defecto.
|
||||
TARGET_NACL_ID = os.environ.get("TARGET_NACL_ID", "")
|
||||
|
||||
# Rango de números de regla reservado para los bloqueos de este playbook.
|
||||
# Debe quedar por DEBAJO de la regla ALLOW por defecto (nº 100) para que el
|
||||
# DENY se evalúe primero y el bloqueo sea efectivo.
|
||||
RULE_MIN = 1
|
||||
RULE_MAX = 99
|
||||
|
||||
s3 = boto3.client("s3", endpoint_url=ENDPOINT, region_name=REGION)
|
||||
sns = boto3.client("sns", endpoint_url=ENDPOINT, region_name=REGION)
|
||||
ec2 = boto3.client("ec2", endpoint_url=ENDPOINT, region_name=REGION)
|
||||
|
||||
|
||||
def _load_blocklist() -> list:
|
||||
try:
|
||||
obj = s3.get_object(Bucket=BUCKET, Key="responses/blocked-ips.json")
|
||||
return json.loads(obj["Body"].read())
|
||||
except s3.exceptions.NoSuchKey:
|
||||
return []
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
def _resolve_target_nacl() -> str:
|
||||
"""Devuelve el Network ACL ID donde se aplicará el bloqueo."""
|
||||
if TARGET_NACL_ID:
|
||||
return TARGET_NACL_ID
|
||||
vpcs = ec2.describe_vpcs(Filters=[{"Name": "isDefault", "Values": ["true"]}]).get("Vpcs", [])
|
||||
if not vpcs:
|
||||
vpcs = ec2.describe_vpcs().get("Vpcs", [])
|
||||
if not vpcs:
|
||||
raise RuntimeError("No hay ninguna VPC disponible para aplicar la NACL")
|
||||
vpc_id = vpcs[0]["VpcId"]
|
||||
acls = ec2.describe_network_acls(
|
||||
Filters=[{"Name": "vpc-id", "Values": [vpc_id]}, {"Name": "default", "Values": ["true"]}]
|
||||
).get("NetworkAcls", [])
|
||||
if not acls:
|
||||
acls = ec2.describe_network_acls(
|
||||
Filters=[{"Name": "vpc-id", "Values": [vpc_id]}]
|
||||
).get("NetworkAcls", [])
|
||||
if not acls:
|
||||
raise RuntimeError(f"La VPC {vpc_id} no tiene Network ACLs")
|
||||
return acls[0]["NetworkAclId"]
|
||||
|
||||
|
||||
def _next_rule_number(nacl_id: str) -> int:
|
||||
"""Calcula el siguiente número de regla libre en el rango DENY (1-99)."""
|
||||
acls = ec2.describe_network_acls(NetworkAclIds=[nacl_id]).get("NetworkAcls", [])
|
||||
used = set()
|
||||
if acls:
|
||||
for entry in acls[0].get("Entries", []):
|
||||
if not entry["Egress"]:
|
||||
used.add(entry["RuleNumber"])
|
||||
for n in range(RULE_MIN, RULE_MAX + 1):
|
||||
if n not in used:
|
||||
return n
|
||||
raise RuntimeError("No quedan números de regla libres en el rango DENY (1-99)")
|
||||
|
||||
|
||||
def _block_ip_on_network(ip: str) -> dict:
|
||||
"""
|
||||
PUNTO DE CUMPLIMIENTO REAL.
|
||||
Añade una regla DENY de entrada para la IP del atacante en la NACL.
|
||||
"""
|
||||
cidr = f"{ip}/32"
|
||||
nacl_id = _resolve_target_nacl()
|
||||
|
||||
# Idempotencia: ¿ya existe el DENY para este CIDR?
|
||||
acls = ec2.describe_network_acls(NetworkAclIds=[nacl_id]).get("NetworkAcls", [])
|
||||
for entry in (acls[0].get("Entries", []) if acls else []):
|
||||
if (not entry["Egress"]
|
||||
and entry.get("CidrBlock") == cidr
|
||||
and entry.get("RuleAction") == "deny"):
|
||||
return {
|
||||
"enforced": True,
|
||||
"already_present": True,
|
||||
"network_acl_id": nacl_id,
|
||||
"rule_number": entry["RuleNumber"],
|
||||
"cidr": cidr,
|
||||
}
|
||||
|
||||
rule_number = _next_rule_number(nacl_id)
|
||||
# ── Línea exacta donde la IP del atacante queda bloqueada a nivel de red ──
|
||||
ec2.create_network_acl_entry(
|
||||
NetworkAclId=nacl_id,
|
||||
RuleNumber=rule_number,
|
||||
Protocol="-1", # -1 = todos los protocolos
|
||||
RuleAction="deny",
|
||||
Egress=False, # tráfico de ENTRADA (desde el atacante)
|
||||
CidrBlock=cidr,
|
||||
)
|
||||
print(f"[block-ip] NACL {nacl_id}: regla DENY #{rule_number} creada para {cidr}")
|
||||
return {
|
||||
"enforced": True,
|
||||
"already_present": False,
|
||||
"network_acl_id": nacl_id,
|
||||
"rule_number": rule_number,
|
||||
"cidr": cidr,
|
||||
}
|
||||
|
||||
|
||||
def lambda_handler(event, context):
|
||||
results = []
|
||||
|
||||
for record in event.get("Records", []):
|
||||
try:
|
||||
body = json.loads(record["body"])
|
||||
except (KeyError, json.JSONDecodeError) as e:
|
||||
return {"status": "error", "detail": f"Payload inválido: {e}"}
|
||||
|
||||
ip = body.get("sourceIPAddress", "0.0.0.0")
|
||||
incident_type = body.get("incident_type", "UNKNOWN")
|
||||
severity = body.get("severity", "MEDIUM")
|
||||
timestamp = datetime.now(timezone.utc).isoformat()
|
||||
|
||||
# 1. CUMPLIMIENTO REAL: bloquear la IP en la red (Network ACL DENY)
|
||||
try:
|
||||
enforcement = _block_ip_on_network(ip)
|
||||
except Exception as e:
|
||||
enforcement = {"enforced": False, "error": str(e)}
|
||||
print(f"[block-ip] ERROR aplicando bloqueo de red para {ip}: {e}")
|
||||
|
||||
# 2. AUDITORÍA: registrar la evidencia de mitigación en S3 (prefijo responses/)
|
||||
blocklist = _load_blocklist()
|
||||
entry = {
|
||||
"ip": ip,
|
||||
"blocked_at": timestamp,
|
||||
"reason": incident_type,
|
||||
"severity": severity,
|
||||
"affectedResource": body.get("affectedResource", ""),
|
||||
"enforcement": enforcement,
|
||||
}
|
||||
if not any(e["ip"] == ip for e in blocklist):
|
||||
blocklist.append(entry)
|
||||
action = "ip_blocked" if enforcement.get("enforced") else "ip_block_failed"
|
||||
else:
|
||||
action = "ip_already_blocked"
|
||||
print(f"[block-ip] IP {ip} ya estaba en el blocklist de auditoría")
|
||||
s3.put_object(
|
||||
Bucket=BUCKET,
|
||||
Key="responses/blocked-ips.json",
|
||||
Body=json.dumps(blocklist, indent=2).encode(),
|
||||
ContentType="application/json",
|
||||
)
|
||||
|
||||
# 3. Notificar al equipo
|
||||
status = "BLOCKED" if enforcement.get("enforced") else "BLOCK_FAILED"
|
||||
result = {
|
||||
"playbook": "block-ip",
|
||||
"action": action,
|
||||
"ip": ip,
|
||||
"status": status,
|
||||
"enforcement": enforcement,
|
||||
"timestamp": timestamp,
|
||||
}
|
||||
sns.publish(
|
||||
TopicArn=SNS_ARN,
|
||||
Subject=f"[{severity}] IP bloqueada: {ip}"[:100],
|
||||
Message=json.dumps(result, indent=2),
|
||||
)
|
||||
|
||||
results.append({"status": "success", "action": action, "details": result})
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"processed": len(results),
|
||||
"results": results,
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
|
@ -1,23 +0,0 @@
|
|||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "S3Blocklist",
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:GetObject", "s3:PutObject"],
|
||||
"Resource": "arn:aws:s3:::tesis-security-logs/responses/*"
|
||||
},
|
||||
{
|
||||
"Sid": "PublishAlert",
|
||||
"Effect": "Allow",
|
||||
"Action": ["sns:Publish"],
|
||||
"Resource": "arn:aws:sns:us-east-1:000000000000:tesis-security-alerts"
|
||||
},
|
||||
{
|
||||
"Sid": "CloudWatchLogs",
|
||||
"Effect": "Allow",
|
||||
"Action": ["logs:CreateLogStream", "logs:PutLogEvents"],
|
||||
"Resource": "arn:aws:logs:us-east-1:000000000000:log-group:/tesis/lambda-responses:*"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -1,12 +0,0 @@
|
|||
{
|
||||
"Records": [
|
||||
{
|
||||
"messageId": "test-msg-block-001",
|
||||
"receiptHandle": "test-handle",
|
||||
"body": "{\"incident_type\": \"BRUTE_FORCE\", \"severity\": \"HIGH\", \"sourceIPAddress\": \"185.220.101.5\", \"affectedResource\": \"iam:user/admin\", \"timestamp\": \"2026-04-20T23:42:35Z\"}",
|
||||
"eventSource": "aws:sqs",
|
||||
"eventSourceARN": "arn:aws:sqs:us-east-1:000000000000:tesis-incident-queue",
|
||||
"awsRegion": "us-east-1"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -1,89 +0,0 @@
|
|||
"""
|
||||
Playbook: dispatcher
|
||||
Lambda central de enrutamiento. Recibe eventos de SQS y decide qué
|
||||
playbooks ejecutar según el tipo de incidente.
|
||||
|
||||
Tabla de enrutamiento:
|
||||
BRUTE_FORCE → notify-alert + block-ip
|
||||
CREDENTIAL_LEAK → notify-alert + revoke-credentials
|
||||
PRIVILEGE_ESCALATION → notify-alert + revoke-credentials
|
||||
EXFILTRATION → notify-alert + isolate-instance
|
||||
PORT_SCAN → notify-alert + block-ip
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import boto3
|
||||
from datetime import datetime, timezone
|
||||
|
||||
_ls_host = os.environ.get("LOCALSTACK_HOSTNAME", "localhost")
|
||||
ENDPOINT = os.environ.get("AWS_ENDPOINT_URL", f"http://{_ls_host}:4566")
|
||||
REGION = os.environ.get("AWS_DEFAULT_REGION", "us-east-1")
|
||||
|
||||
lmb = boto3.client("lambda", endpoint_url=ENDPOINT, region_name=REGION)
|
||||
|
||||
ROUTING_TABLE = {
|
||||
"BRUTE_FORCE": ["tesis-notify-alert", "tesis-block-ip"],
|
||||
"CREDENTIAL_LEAK": ["tesis-notify-alert", "tesis-revoke-credentials"],
|
||||
"PRIVILEGE_ESCALATION": ["tesis-notify-alert", "tesis-revoke-credentials"],
|
||||
"EXFILTRATION": ["tesis-notify-alert", "tesis-isolate-instance"],
|
||||
"PORT_SCAN": ["tesis-notify-alert", "tesis-block-ip"],
|
||||
}
|
||||
|
||||
|
||||
def _invoke_playbook(function_name: str, payload: dict) -> dict:
|
||||
"""Invoca un playbook Lambda con el mismo formato de evento SQS."""
|
||||
sqs_event = {
|
||||
"Records": [{
|
||||
"messageId": "dispatcher-fwd",
|
||||
"receiptHandle": "dispatcher-fwd",
|
||||
"body": json.dumps(payload),
|
||||
"eventSource": "aws:sqs",
|
||||
"eventSourceARN": "arn:aws:sqs:us-east-1:000000000000:tesis-incident-queue",
|
||||
"awsRegion": REGION,
|
||||
}]
|
||||
}
|
||||
response = lmb.invoke(
|
||||
FunctionName=function_name,
|
||||
InvocationType="RequestResponse",
|
||||
Payload=json.dumps(sqs_event).encode(),
|
||||
)
|
||||
result_payload = json.loads(response["Payload"].read())
|
||||
status = "success" if response.get("FunctionError") is None else "error"
|
||||
print(f"[dispatcher] {function_name} → {status}")
|
||||
return {"function": function_name, "status": status, "response": result_payload}
|
||||
|
||||
|
||||
def lambda_handler(event, context):
|
||||
dispatch_results = []
|
||||
|
||||
for record in event.get("Records", []):
|
||||
try:
|
||||
body = json.loads(record["body"])
|
||||
except (KeyError, json.JSONDecodeError) as e:
|
||||
return {"status": "error", "detail": f"Payload inválido: {e}"}
|
||||
|
||||
incident_type = body.get("incident_type", "UNKNOWN")
|
||||
severity = body.get("severity", "MEDIUM")
|
||||
playbooks = ROUTING_TABLE.get(incident_type, ["tesis-notify-alert"])
|
||||
|
||||
print(f"[dispatcher] Incidente: {incident_type} ({severity}) → playbooks: {playbooks}")
|
||||
|
||||
invocations = []
|
||||
for fn in playbooks:
|
||||
result = _invoke_playbook(fn, body)
|
||||
invocations.append(result)
|
||||
|
||||
dispatch_results.append({
|
||||
"incident_type": incident_type,
|
||||
"severity": severity,
|
||||
"playbooks_run": playbooks,
|
||||
"invocations": invocations,
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
})
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"processed": len(dispatch_results),
|
||||
"results": dispatch_results,
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
|
@ -1,32 +0,0 @@
|
|||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "InvokePlaybooks",
|
||||
"Effect": "Allow",
|
||||
"Action": ["lambda:InvokeFunction"],
|
||||
"Resource": [
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:tesis-notify-alert",
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:tesis-block-ip",
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:tesis-revoke-credentials",
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:tesis-isolate-instance"
|
||||
]
|
||||
},
|
||||
{
|
||||
"Sid": "ConsumeSQS",
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"sqs:ReceiveMessage",
|
||||
"sqs:DeleteMessage",
|
||||
"sqs:GetQueueAttributes"
|
||||
],
|
||||
"Resource": "arn:aws:sqs:us-east-1:000000000000:tesis-incident-queue"
|
||||
},
|
||||
{
|
||||
"Sid": "CloudWatchLogs",
|
||||
"Effect": "Allow",
|
||||
"Action": ["logs:CreateLogStream", "logs:PutLogEvents"],
|
||||
"Resource": "arn:aws:logs:us-east-1:000000000000:log-group:/tesis/lambda-responses:*"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -1,12 +0,0 @@
|
|||
{
|
||||
"Records": [
|
||||
{
|
||||
"messageId": "test-msg-dispatch-001",
|
||||
"receiptHandle": "test-handle",
|
||||
"body": "{\"incident_type\": \"BRUTE_FORCE\", \"severity\": \"HIGH\", \"sourceIPAddress\": \"185.220.101.5\", \"affectedResource\": \"iam:user/admin\", \"timestamp\": \"2026-04-20T23:42:35Z\"}",
|
||||
"eventSource": "aws:sqs",
|
||||
"eventSourceARN": "arn:aws:sqs:us-east-1:000000000000:tesis-incident-queue",
|
||||
"awsRegion": "us-east-1"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -1,192 +0,0 @@
|
|||
"""
|
||||
Playbook: isolate-instance
|
||||
Contención ante acceso masivo no autorizado a datos (exfiltración u otro).
|
||||
|
||||
Punto de cumplimiento (enforcement point) según tipo de recurso:
|
||||
|
||||
▶ Recurso S3 (prefijo "s3:bucket/<nombre>") — EXFILTRACIÓN
|
||||
s3.put_bucket_policy() con Deny GetObject+ListBucket para la IP atacante.
|
||||
Esa es la línea donde la exfiltración queda bloqueada a nivel de datos:
|
||||
cualquier intento de GetObject desde esa IP recibirá AccessDenied.
|
||||
|
||||
▶ Recurso EC2 (prefijo "ec2:instance/<id>") — otro incidente
|
||||
Registra la instancia en la lista de cuarentena en S3 y simula las
|
||||
acciones de aislamiento de red (security group removal, policy, snapshot).
|
||||
En producción real reemplazaría el SG de la instancia por uno vacío.
|
||||
|
||||
El registro en S3 (responses/quarantine-instances.json) actúa como
|
||||
PISTA DE AUDITORÍA / evidencia de mitigación, alineado con el prefijo
|
||||
`responses/` del esquema del Componente A.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import boto3
|
||||
from datetime import datetime, timezone
|
||||
|
||||
_ls_host = os.environ.get("LOCALSTACK_HOSTNAME", "localhost")
|
||||
ENDPOINT = os.environ.get("AWS_ENDPOINT_URL", f"http://{_ls_host}:4566")
|
||||
REGION = os.environ.get("AWS_DEFAULT_REGION", "us-east-1")
|
||||
BUCKET = os.environ.get("S3_BUCKET", "tesis-security-logs")
|
||||
SNS_ARN = os.environ.get("SNS_ALERTS_ARN",
|
||||
"arn:aws:sns:us-east-1:000000000000:tesis-security-alerts")
|
||||
|
||||
s3 = boto3.client("s3", endpoint_url=ENDPOINT, region_name=REGION)
|
||||
sns = boto3.client("sns", endpoint_url=ENDPOINT, region_name=REGION)
|
||||
|
||||
|
||||
def _load_quarantine() -> list:
|
||||
try:
|
||||
obj = s3.get_object(Bucket=BUCKET, Key="responses/quarantine-instances.json")
|
||||
return json.loads(obj["Body"].read())
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
def _block_s3_exfiltration(bucket_name: str, source_ip: str) -> dict:
|
||||
"""
|
||||
PUNTO DE CUMPLIMIENTO REAL para exfiltración de datos S3.
|
||||
Aplica una política de bucket que deniega GetObject y ListBucket
|
||||
desde la IP atacante — la exfiltración queda cortada a nivel de datos.
|
||||
"""
|
||||
cidr = f"{source_ip}/32"
|
||||
stmt_id = f"DenyExfiltrationIP-{source_ip.replace('.', '-')}"
|
||||
|
||||
# Cargar política existente o inicializar con estructura vacía
|
||||
try:
|
||||
existing = json.loads(s3.get_bucket_policy(Bucket=bucket_name)["Policy"])
|
||||
statements = existing.get("Statement", [])
|
||||
except Exception:
|
||||
statements = []
|
||||
|
||||
# Idempotencia: ¿ya existe el Deny para este CIDR?
|
||||
for stmt in statements:
|
||||
condition_ips = (stmt.get("Condition", {})
|
||||
.get("IpAddress", {})
|
||||
.get("aws:SourceIp", []))
|
||||
if stmt.get("Effect") == "Deny" and cidr in condition_ips:
|
||||
return {
|
||||
"enforced": True,
|
||||
"already_present": True,
|
||||
"bucket": bucket_name,
|
||||
"denied_ip": cidr,
|
||||
}
|
||||
|
||||
# ← ENFORCEMENT POINT: línea donde la exfiltración queda bloqueada
|
||||
statements.append({
|
||||
"Sid": stmt_id,
|
||||
"Effect": "Deny",
|
||||
"Principal": "*",
|
||||
"Action": ["s3:GetObject", "s3:ListBucket"],
|
||||
"Resource": [
|
||||
f"arn:aws:s3:::{bucket_name}",
|
||||
f"arn:aws:s3:::{bucket_name}/*",
|
||||
],
|
||||
"Condition": {
|
||||
"IpAddress": {
|
||||
"aws:SourceIp": [cidr]
|
||||
}
|
||||
}
|
||||
})
|
||||
new_policy = {"Version": "2012-10-17", "Statement": statements}
|
||||
s3.put_bucket_policy(Bucket=bucket_name, Policy=json.dumps(new_policy))
|
||||
|
||||
print(f"[isolate-instance] S3 bucket {bucket_name}: "
|
||||
f"Deny GetObject/ListBucket para {cidr} → exfiltración bloqueada")
|
||||
return {
|
||||
"enforced": True,
|
||||
"already_present": False,
|
||||
"bucket": bucket_name,
|
||||
"denied_ip": cidr,
|
||||
"blocked_actions": ["s3:GetObject", "s3:ListBucket"],
|
||||
}
|
||||
|
||||
|
||||
def lambda_handler(event, context):
|
||||
results = []
|
||||
|
||||
for record in event.get("Records", []):
|
||||
try:
|
||||
body = json.loads(record["body"])
|
||||
except (KeyError, json.JSONDecodeError) as e:
|
||||
return {"status": "error", "detail": f"Payload inválido: {e}"}
|
||||
|
||||
resource = body.get("affectedResource", "ec2:instance/unknown")
|
||||
incident_type = body.get("incident_type", "UNKNOWN")
|
||||
severity = body.get("severity", "HIGH")
|
||||
source_ip = body.get("sourceIPAddress", "0.0.0.0")
|
||||
timestamp = datetime.now(timezone.utc).isoformat()
|
||||
|
||||
actions_applied = []
|
||||
enforcement = {}
|
||||
|
||||
# ── Enforcement real según tipo de recurso ────────────────────────────
|
||||
if resource.startswith("s3:bucket/"):
|
||||
bucket_name = resource.replace("s3:bucket/", "")
|
||||
try:
|
||||
enforcement = _block_s3_exfiltration(bucket_name, source_ip)
|
||||
action = "s3_exfiltration_blocked"
|
||||
actions_applied.extend([
|
||||
f"s3_deny_policy_applied:{bucket_name}",
|
||||
f"attacker_ip_blocked:{source_ip}/32",
|
||||
"s3:GetObject_denied",
|
||||
"s3:ListBucket_denied",
|
||||
])
|
||||
except Exception as e:
|
||||
enforcement = {"enforced": False, "error": str(e)}
|
||||
action = "s3_block_failed"
|
||||
print(f"[isolate-instance] ERROR bloqueando bucket {bucket_name}: {e}")
|
||||
|
||||
else:
|
||||
# EC2 u otro recurso: registro en cuarentena + acciones simuladas
|
||||
action = "instance_isolated"
|
||||
actions_applied = [
|
||||
"security_group_removed", # En prod: reemplazar por SG vacío
|
||||
"deny_all_policy_applied", # En prod: IAM policy de cuarentena
|
||||
"snapshot_triggered", # En prod: EBS snapshot forense
|
||||
]
|
||||
enforcement = {"enforced": True, "mode": "simulated"}
|
||||
|
||||
# ── Auditoría: lista de cuarentena en S3 (prefijo responses/) ─────────
|
||||
quarantine = _load_quarantine()
|
||||
entry = {
|
||||
"resource": resource,
|
||||
"isolated_at": timestamp,
|
||||
"reason": incident_type,
|
||||
"severity": severity,
|
||||
"sourceIPAddress": source_ip,
|
||||
"actions_applied": actions_applied,
|
||||
"enforcement": enforcement,
|
||||
}
|
||||
quarantine.append(entry)
|
||||
s3.put_object(
|
||||
Bucket=BUCKET,
|
||||
Key="responses/quarantine-instances.json",
|
||||
Body=json.dumps(quarantine, indent=2).encode(),
|
||||
ContentType="application/json",
|
||||
)
|
||||
print(f"[isolate-instance] Recurso {resource} registrado en cuarentena")
|
||||
|
||||
# ── Notificar al equipo vía SNS ────────────────────────────────────────
|
||||
status = "QUARANTINED" if enforcement.get("enforced") else "QUARANTINE_FAILED"
|
||||
result = {
|
||||
"playbook": "isolate-instance",
|
||||
"action": action,
|
||||
"resource": resource,
|
||||
"status": status,
|
||||
"enforcement": enforcement,
|
||||
"timestamp": timestamp,
|
||||
}
|
||||
sns.publish(
|
||||
TopicArn=SNS_ARN,
|
||||
Subject=f"[{severity}] Recurso aislado: {resource}"[:100],
|
||||
Message=json.dumps(result, indent=2),
|
||||
)
|
||||
|
||||
results.append({"status": "success", "action": action, "details": result})
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"processed": len(results),
|
||||
"results": results,
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
|
@ -1,23 +0,0 @@
|
|||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "S3Quarantine",
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:GetObject", "s3:PutObject"],
|
||||
"Resource": "arn:aws:s3:::tesis-security-logs/responses/*"
|
||||
},
|
||||
{
|
||||
"Sid": "PublishAlert",
|
||||
"Effect": "Allow",
|
||||
"Action": ["sns:Publish"],
|
||||
"Resource": "arn:aws:sns:us-east-1:000000000000:tesis-security-alerts"
|
||||
},
|
||||
{
|
||||
"Sid": "CloudWatchLogs",
|
||||
"Effect": "Allow",
|
||||
"Action": ["logs:CreateLogStream", "logs:PutLogEvents"],
|
||||
"Resource": "arn:aws:logs:us-east-1:000000000000:log-group:/tesis/lambda-responses:*"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -1,12 +0,0 @@
|
|||
{
|
||||
"Records": [
|
||||
{
|
||||
"messageId": "test-msg-isolate-001",
|
||||
"receiptHandle": "test-handle",
|
||||
"body": "{\"incident_type\": \"EXFILTRATION\", \"severity\": \"HIGH\", \"sourceIPAddress\": \"10.0.1.55\", \"affectedResource\": \"ec2:instance/i-0abc123def456\", \"timestamp\": \"2026-04-20T23:50:00Z\"}",
|
||||
"eventSource": "aws:sqs",
|
||||
"eventSourceARN": "arn:aws:sqs:us-east-1:000000000000:tesis-incident-queue",
|
||||
"awsRegion": "us-east-1"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -1,65 +0,0 @@
|
|||
"""
|
||||
Playbook: notify-alert
|
||||
Recibe un evento de incidente desde SQS y publica una notificación
|
||||
estructurada al tópico SNS de alertas.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import boto3
|
||||
from datetime import datetime, timezone
|
||||
|
||||
# LOCALSTACK_HOSTNAME es inyectada por LocalStack en contenedores Lambda (Docker executor)
|
||||
# Permite que la Lambda alcance LocalStack sin hardcodear IPs que cambian entre reinicios
|
||||
_ls_host = os.environ.get("LOCALSTACK_HOSTNAME", "localhost")
|
||||
ENDPOINT = os.environ.get("AWS_ENDPOINT_URL", f"http://{_ls_host}:4566")
|
||||
REGION = os.environ.get("AWS_DEFAULT_REGION", "us-east-1")
|
||||
SNS_ARN = os.environ.get("SNS_ALERTS_ARN", "arn:aws:sns:us-east-1:000000000000:tesis-security-alerts")
|
||||
|
||||
sns = boto3.client("sns", endpoint_url=ENDPOINT, region_name=REGION)
|
||||
|
||||
|
||||
def lambda_handler(event, context):
|
||||
results = []
|
||||
|
||||
for record in event.get("Records", []):
|
||||
# Parsear mensaje SQS
|
||||
try:
|
||||
body = json.loads(record["body"])
|
||||
except (KeyError, json.JSONDecodeError) as e:
|
||||
return {"status": "error", "detail": f"Payload inválido: {e}"}
|
||||
|
||||
incident_type = body.get("incident_type", "UNKNOWN")
|
||||
severity = body.get("severity", "MEDIUM")
|
||||
source_ip = body.get("sourceIPAddress", "0.0.0.0")
|
||||
resource = body.get("affectedResource", "unknown")
|
||||
timestamp = body.get("timestamp", datetime.now(timezone.utc).isoformat())
|
||||
|
||||
# Construir mensaje de alerta
|
||||
alert = {
|
||||
"alert_type": "SECURITY_INCIDENT",
|
||||
"incident_type": incident_type,
|
||||
"severity": severity,
|
||||
"sourceIPAddress": source_ip,
|
||||
"affectedResource": resource,
|
||||
"detectedAt": timestamp,
|
||||
"respondedAt": datetime.now(timezone.utc).isoformat(),
|
||||
"playbook": "notify-alert",
|
||||
"status": "NOTIFIED"
|
||||
}
|
||||
|
||||
subject = f"[{severity}] Incidente detectado: {incident_type}"
|
||||
sns.publish(
|
||||
TopicArn=SNS_ARN,
|
||||
Subject=subject[:100], # SNS limita el subject a 100 chars
|
||||
Message=json.dumps(alert, indent=2)
|
||||
)
|
||||
|
||||
print(f"[notify-alert] Alerta publicada: {incident_type} desde {source_ip}")
|
||||
results.append({"status": "success", "action": "sns_published", "details": alert})
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"processed": len(results),
|
||||
"results": results,
|
||||
"timestamp": datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "PublishAlertOnly",
|
||||
"Effect": "Allow",
|
||||
"Action": ["sns:Publish"],
|
||||
"Resource": "arn:aws:sns:us-east-1:000000000000:tesis-security-alerts"
|
||||
},
|
||||
{
|
||||
"Sid": "CloudWatchLogs",
|
||||
"Effect": "Allow",
|
||||
"Action": ["logs:CreateLogStream", "logs:PutLogEvents"],
|
||||
"Resource": "arn:aws:logs:us-east-1:000000000000:log-group:/tesis/lambda-responses:*"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -1,15 +0,0 @@
|
|||
{
|
||||
"Records": [
|
||||
{
|
||||
"messageId": "test-msg-001",
|
||||
"receiptHandle": "test-handle",
|
||||
"body": "{\"incident_type\": \"BRUTE_FORCE\", \"severity\": \"HIGH\", \"sourceIPAddress\": \"203.0.113.42\", \"affectedResource\": \"iam:user/admin\", \"timestamp\": \"2024-01-15T10:30:00Z\"}",
|
||||
"attributes": {},
|
||||
"messageAttributes": {},
|
||||
"md5OfBody": "",
|
||||
"eventSource": "aws:sqs",
|
||||
"eventSourceARN": "arn:aws:sqs:us-east-1:000000000000:tesis-incident-queue",
|
||||
"awsRegion": "us-east-1"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -1,160 +0,0 @@
|
|||
"""
|
||||
Playbook: revoke-credentials
|
||||
Revoca (desactiva) las access keys de un usuario IAM comprometido
|
||||
y adjunta una política de denegación explícita para bloqueo inmediato.
|
||||
|
||||
Punto de cumplimiento (enforcement point):
|
||||
1. iam.update_access_key(Status="Inactive") ← línea exacta donde las
|
||||
credenciales del atacante quedan invalidadas. Cada key existente
|
||||
del usuario pasa de Active → Inactive en IAM.
|
||||
2. iam.put_user_policy("EmergencyDenyAll") ← capa extra: aunque haya
|
||||
keys no listadas o futuros tokens STS, la política Deny-All las bloquea.
|
||||
|
||||
El registro en S3 (responses/revoked-credentials.json) actúa como
|
||||
PISTA DE AUDITORÍA / evidencia de mitigación, alineado con el prefijo
|
||||
`responses/` del esquema del Componente A.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import boto3
|
||||
from datetime import datetime, timezone
|
||||
|
||||
_ls_host = os.environ.get("LOCALSTACK_HOSTNAME", "localhost")
|
||||
ENDPOINT = os.environ.get("AWS_ENDPOINT_URL", f"http://{_ls_host}:4566")
|
||||
REGION = os.environ.get("AWS_DEFAULT_REGION", "us-east-1")
|
||||
BUCKET = os.environ.get("S3_BUCKET", "tesis-security-logs")
|
||||
SNS_ARN = os.environ.get("SNS_ALERTS_ARN",
|
||||
"arn:aws:sns:us-east-1:000000000000:tesis-security-alerts")
|
||||
|
||||
iam = boto3.client("iam", endpoint_url=ENDPOINT, region_name=REGION)
|
||||
s3 = boto3.client("s3", endpoint_url=ENDPOINT, region_name=REGION)
|
||||
sns = boto3.client("sns", endpoint_url=ENDPOINT, region_name=REGION)
|
||||
|
||||
DENY_ALL_POLICY = json.dumps({
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [{
|
||||
"Effect": "Deny",
|
||||
"Action": "*",
|
||||
"Resource": "*"
|
||||
}]
|
||||
})
|
||||
|
||||
|
||||
def _load_revoke_log() -> list:
|
||||
try:
|
||||
obj = s3.get_object(Bucket=BUCKET, Key="responses/revoked-credentials.json")
|
||||
return json.loads(obj["Body"].read())
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
def lambda_handler(event, context):
|
||||
results = []
|
||||
|
||||
for record in event.get("Records", []):
|
||||
try:
|
||||
body = json.loads(record["body"])
|
||||
except (KeyError, json.JSONDecodeError) as e:
|
||||
return {"status": "error", "detail": f"Payload inválido: {e}"}
|
||||
|
||||
username = body.get("affectedResource", "").replace("iam:user/", "")
|
||||
incident_type = body.get("incident_type", "UNKNOWN")
|
||||
severity = body.get("severity", "CRITICAL")
|
||||
source_ip = body.get("sourceIPAddress", "0.0.0.0")
|
||||
timestamp = datetime.now(timezone.utc).isoformat()
|
||||
|
||||
if not username:
|
||||
return {"status": "error", "detail": "affectedResource no contiene usuario IAM"}
|
||||
|
||||
actions_taken = []
|
||||
keys_revoked = []
|
||||
enforcement = {}
|
||||
|
||||
# ── 1. CUMPLIMIENTO REAL: desactivar todas las access keys ───────────
|
||||
# ENFORCEMENT POINT: update_access_key(Status="Inactive")
|
||||
try:
|
||||
keys = iam.list_access_keys(UserName=username).get("AccessKeyMetadata", [])
|
||||
for key in keys:
|
||||
kid = key["AccessKeyId"]
|
||||
if key.get("Status") == "Active":
|
||||
# ← línea exacta donde la credencial queda revocada
|
||||
iam.update_access_key(
|
||||
UserName=username,
|
||||
AccessKeyId=kid,
|
||||
Status="Inactive"
|
||||
)
|
||||
keys_revoked.append(kid)
|
||||
actions_taken.append(f"AccessKey desactivada: {kid}")
|
||||
print(f"[revoke-credentials] Desactivada key {kid} de {username}")
|
||||
else:
|
||||
actions_taken.append(f"AccessKey ya inactiva: {kid}")
|
||||
enforcement["keys_found"] = len(keys)
|
||||
enforcement["keys_deactivated"] = len(keys_revoked)
|
||||
enforcement["key_ids"] = keys_revoked
|
||||
except Exception as e:
|
||||
enforcement["keys_error"] = str(e)
|
||||
print(f"[revoke-credentials] No se pudieron listar/desactivar keys de "
|
||||
f"{username}: {e}")
|
||||
|
||||
# ── 2. CUMPLIMIENTO ADICIONAL: política DenyAll (bloqueo total) ──────
|
||||
try:
|
||||
iam.put_user_policy(
|
||||
UserName=username,
|
||||
PolicyName="EmergencyDenyAll",
|
||||
PolicyDocument=DENY_ALL_POLICY
|
||||
)
|
||||
actions_taken.append("Política EmergencyDenyAll adjuntada")
|
||||
enforcement["deny_all_applied"] = True
|
||||
print(f"[revoke-credentials] EmergencyDenyAll aplicado a {username}")
|
||||
except Exception as e:
|
||||
enforcement["deny_all_error"] = str(e)
|
||||
enforcement["deny_all_applied"] = False
|
||||
print(f"[revoke-credentials] Error aplicando DenyAll a {username}: {e}")
|
||||
|
||||
# ── 3. AUDITORÍA: evidencia de mitigación en S3 (prefijo responses/) ─
|
||||
revoke_log = _load_revoke_log()
|
||||
log_entry = {
|
||||
"username": username,
|
||||
"revoked_at": timestamp,
|
||||
"reason": incident_type,
|
||||
"severity": severity,
|
||||
"sourceIPAddress": source_ip,
|
||||
"enforcement": enforcement,
|
||||
"actions_taken": actions_taken,
|
||||
}
|
||||
if not any(e["username"] == username for e in revoke_log):
|
||||
revoke_log.append(log_entry)
|
||||
s3.put_object(
|
||||
Bucket=BUCKET,
|
||||
Key="responses/revoked-credentials.json",
|
||||
Body=json.dumps(revoke_log, indent=2).encode(),
|
||||
ContentType="application/json",
|
||||
)
|
||||
|
||||
# ── 4. Notificar al equipo vía SNS ───────────────────────────────────
|
||||
result = {
|
||||
"playbook": "revoke-credentials",
|
||||
"username": username,
|
||||
"actions": actions_taken,
|
||||
"status": "CONTAINED",
|
||||
"enforcement": enforcement,
|
||||
"timestamp": timestamp,
|
||||
}
|
||||
sns.publish(
|
||||
TopicArn=SNS_ARN,
|
||||
Subject=f"[{severity}] Credenciales revocadas: {username}"[:100],
|
||||
Message=json.dumps(result, indent=2),
|
||||
)
|
||||
|
||||
results.append({
|
||||
"status": "success",
|
||||
"action": "credentials_revoked",
|
||||
"details": result,
|
||||
})
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"processed": len(results),
|
||||
"results": results,
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
|
|
@ -1,27 +0,0 @@
|
|||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "IAMRevokeOnly",
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"iam:ListAccessKeys",
|
||||
"iam:UpdateAccessKey",
|
||||
"iam:PutUserPolicy"
|
||||
],
|
||||
"Resource": "arn:aws:iam::000000000000:user/*"
|
||||
},
|
||||
{
|
||||
"Sid": "SNSNotify",
|
||||
"Effect": "Allow",
|
||||
"Action": ["sns:Publish"],
|
||||
"Resource": "arn:aws:sns:us-east-1:000000000000:tesis-security-alerts"
|
||||
},
|
||||
{
|
||||
"Sid": "CloudWatchLogs",
|
||||
"Effect": "Allow",
|
||||
"Action": ["logs:CreateLogStream", "logs:PutLogEvents"],
|
||||
"Resource": "arn:aws:logs:us-east-1:000000000000:log-group:/tesis/lambda-responses:*"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -1,12 +0,0 @@
|
|||
{
|
||||
"Records": [
|
||||
{
|
||||
"messageId": "test-msg-002",
|
||||
"receiptHandle": "test-handle",
|
||||
"body": "{\"incident_type\": \"CREDENTIAL_LEAK\", \"severity\": \"CRITICAL\", \"sourceIPAddress\": \"198.51.100.77\", \"affectedResource\": \"iam:user/dev-operator\", \"timestamp\": \"2024-01-15T11:00:00Z\"}",
|
||||
"eventSource": "aws:sqs",
|
||||
"eventSourceARN": "arn:aws:sqs:us-east-1:000000000000:tesis-incident-queue",
|
||||
"awsRegion": "us-east-1"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -1,45 +0,0 @@
|
|||
{
|
||||
"Records": [
|
||||
{
|
||||
"eventVersion": "1.08",
|
||||
"eventTime": "2024-01-15T10:30:00Z",
|
||||
"eventSource": "signin.amazonaws.com",
|
||||
"eventName": "ConsoleLogin",
|
||||
"awsRegion": "us-east-1",
|
||||
"sourceIPAddress": "203.0.113.42",
|
||||
"userAgent": "aws-cli/2.x Python/3.11",
|
||||
"requestID": "a1b2c3d4-0000-0000-0000-000000000001",
|
||||
"eventID": "e1b2c3d4-0000-0000-0000-000000000001",
|
||||
"readOnly": false,
|
||||
"errorCode": "AccessDenied",
|
||||
"errorMessage": "Failed authentication",
|
||||
"responseElements": {"ConsoleLogin": "Failure"},
|
||||
"userIdentity": {
|
||||
"type": "IAMUser",
|
||||
"userName": "admin",
|
||||
"arn": "arn:aws:iam::123456789012:user/admin",
|
||||
"accountId": "123456789012"
|
||||
}
|
||||
},
|
||||
{
|
||||
"eventVersion": "1.08",
|
||||
"eventTime": "2024-01-15T10:30:15Z",
|
||||
"eventSource": "signin.amazonaws.com",
|
||||
"eventName": "ConsoleLogin",
|
||||
"awsRegion": "us-east-1",
|
||||
"sourceIPAddress": "203.0.113.42",
|
||||
"requestID": "a1b2c3d4-0000-0000-0000-000000000002",
|
||||
"eventID": "e1b2c3d4-0000-0000-0000-000000000002",
|
||||
"readOnly": false,
|
||||
"errorCode": "AccessDenied",
|
||||
"errorMessage": "Failed authentication",
|
||||
"responseElements": {"ConsoleLogin": "Failure"},
|
||||
"userIdentity": {
|
||||
"type": "IAMUser",
|
||||
"userName": "admin",
|
||||
"arn": "arn:aws:iam::123456789012:user/admin",
|
||||
"accountId": "123456789012"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -1,20 +0,0 @@
|
|||
-- Detección de Fuerza Bruta
|
||||
-- Busca >5 intentos fallidos de ConsoleLogin desde la misma IP en una ventana de 5 minutos
|
||||
-- Equivalente a una regla Athena sobre la tabla de CloudTrail
|
||||
-- Sintaxis DuckDB: acceso por campo de struct (r.campo), no por operador JSON (->>)
|
||||
|
||||
SELECT
|
||||
r.sourceIPAddress,
|
||||
r.userIdentity.userName AS username,
|
||||
COUNT(*) AS failed_attempts,
|
||||
MIN(r.eventTime) AS first_attempt,
|
||||
MAX(r.eventTime) AS last_attempt
|
||||
FROM (
|
||||
SELECT unnest(Records) AS r
|
||||
FROM read_json_auto('$LOG_PATH')
|
||||
)
|
||||
WHERE r.eventName = 'ConsoleLogin'
|
||||
AND r.errorCode = 'AccessDenied'
|
||||
GROUP BY r.sourceIPAddress, r.userIdentity.userName
|
||||
HAVING COUNT(*) > 5
|
||||
ORDER BY failed_attempts DESC;
|
||||
|
|
@ -1,19 +0,0 @@
|
|||
-- Detección de Exfiltración de Datos
|
||||
-- Busca acceso masivo a S3 GetObject (>50 objetos) desde la misma IP en 1 hora
|
||||
-- Sintaxis DuckDB: acceso por campo de struct (r.campo), no por operador JSON (->>)
|
||||
|
||||
SELECT
|
||||
r.sourceIPAddress,
|
||||
r.userIdentity.userName AS username,
|
||||
COUNT(*) AS total_downloads,
|
||||
MIN(r.eventTime) AS first_access,
|
||||
MAX(r.eventTime) AS last_access
|
||||
FROM (
|
||||
SELECT unnest(Records) AS r
|
||||
FROM read_json_auto('$LOG_PATH')
|
||||
)
|
||||
WHERE r.eventSource = 's3.amazonaws.com'
|
||||
AND r.eventName = 'GetObject'
|
||||
GROUP BY r.sourceIPAddress, r.userIdentity.userName
|
||||
HAVING COUNT(*) > 50
|
||||
ORDER BY total_downloads DESC;
|
||||
|
|
@ -1,25 +0,0 @@
|
|||
-- Detección de Escalada de Privilegios
|
||||
-- Busca eventos IAM sospechosos: adjuntar políticas admin, crear keys, modificar roles
|
||||
-- Sintaxis DuckDB: acceso por campo de struct (r.campo), no por operador JSON (->>)
|
||||
|
||||
SELECT
|
||||
r.userIdentity.userName AS username,
|
||||
r.sourceIPAddress,
|
||||
r.eventName,
|
||||
r.eventTime,
|
||||
r.requestParameters
|
||||
FROM (
|
||||
SELECT unnest(Records) AS r
|
||||
FROM read_json_auto('$LOG_PATH')
|
||||
)
|
||||
WHERE r.eventSource = 'iam.amazonaws.com'
|
||||
AND r.eventName IN (
|
||||
'AttachUserPolicy',
|
||||
'AttachRolePolicy',
|
||||
'CreateAccessKey',
|
||||
'PutUserPolicy',
|
||||
'AddUserToGroup',
|
||||
'CreateLoginProfile',
|
||||
'UpdateLoginProfile'
|
||||
)
|
||||
ORDER BY r.eventTime DESC;
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
boto3>=1.34
|
||||
awscli-local>=0.22
|
||||
duckdb>=0.10
|
||||
Binary file not shown.
|
|
@ -1,159 +0,0 @@
|
|||
"""
|
||||
Generador de eventos CloudTrail simulados.
|
||||
Produce logs JSON con la estructura real de CloudTrail para probar
|
||||
los componentes de Detección (B) y Respuesta (C) sin depender de AWS real.
|
||||
"""
|
||||
import json
|
||||
import random
|
||||
import uuid
|
||||
from datetime import datetime, timezone, timedelta
|
||||
|
||||
|
||||
USERS = ["admin", "dev-operator", "ci-runner", "readonly-audit", "external-contractor"]
|
||||
REGIONS = ["us-east-1", "us-west-2"]
|
||||
IPS_LEGIT = ["10.0.1.15", "10.0.2.30", "192.168.1.100"]
|
||||
IPS_ATTACK = ["203.0.113.42", "198.51.100.77", "185.220.101.5", "45.33.32.156"]
|
||||
|
||||
|
||||
def _base_event(username: str, source_ip: str, event_name: str, event_source: str) -> dict:
|
||||
return {
|
||||
"eventVersion": "1.08",
|
||||
"eventTime": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
|
||||
"eventSource": event_source,
|
||||
"eventName": event_name,
|
||||
"awsRegion": random.choice(REGIONS),
|
||||
"sourceIPAddress": source_ip,
|
||||
"userAgent": "aws-cli/2.x Python/3.11",
|
||||
"requestID": str(uuid.uuid4()),
|
||||
"eventID": str(uuid.uuid4()),
|
||||
"readOnly": False,
|
||||
"userIdentity": {
|
||||
"type": "IAMUser",
|
||||
"userName": username,
|
||||
"arn": f"arn:aws:iam::123456789012:user/{username}",
|
||||
"accountId": "123456789012"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def brute_force(attempts: int = 10, target_user: str = None) -> list[dict]:
|
||||
"""Genera múltiples intentos fallidos de login (simula fuerza bruta)."""
|
||||
user = target_user or random.choice(USERS)
|
||||
ip = random.choice(IPS_ATTACK)
|
||||
events = []
|
||||
base_time = datetime.now(timezone.utc)
|
||||
|
||||
for i in range(attempts):
|
||||
e = _base_event(user, ip, "ConsoleLogin", "signin.amazonaws.com")
|
||||
e["eventTime"] = (base_time + timedelta(seconds=i * 15)).isoformat().replace("+00:00", "Z")
|
||||
e["responseElements"] = {"ConsoleLogin": "Failure"}
|
||||
e["errorCode"] = "AccessDenied"
|
||||
e["errorMessage"] = "Failed authentication"
|
||||
events.append(e)
|
||||
|
||||
return events
|
||||
|
||||
|
||||
def privilege_escalation(username: str = None) -> list[dict]:
|
||||
"""Genera eventos de escalada de privilegios: un usuario adjunta políticas de admin."""
|
||||
user = username or random.choice(USERS)
|
||||
ip = random.choice(IPS_ATTACK)
|
||||
events = []
|
||||
|
||||
# Intento de listar roles (reconocimiento)
|
||||
e = _base_event(user, ip, "ListRoles", "iam.amazonaws.com")
|
||||
e["readOnly"] = True
|
||||
events.append(e)
|
||||
|
||||
# Adjuntar política AdministratorAccess a sí mismo
|
||||
e = _base_event(user, ip, "AttachUserPolicy", "iam.amazonaws.com")
|
||||
e["requestParameters"] = {
|
||||
"userName": user,
|
||||
"policyArn": "arn:aws:iam::aws:policy/AdministratorAccess"
|
||||
}
|
||||
events.append(e)
|
||||
|
||||
# Crear nueva access key para persistencia
|
||||
e = _base_event(user, ip, "CreateAccessKey", "iam.amazonaws.com")
|
||||
e["requestParameters"] = {"userName": user}
|
||||
e["responseElements"] = {
|
||||
"accessKey": {
|
||||
"accessKeyId": f"AKIA{''.join(random.choices('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', k=16))}",
|
||||
"status": "Active",
|
||||
"userName": user
|
||||
}
|
||||
}
|
||||
events.append(e)
|
||||
|
||||
return events
|
||||
|
||||
|
||||
def credential_leak(username: str = None) -> list[dict]:
|
||||
"""Simula uso de credenciales desde IP externa inusual (posible filtración)."""
|
||||
user = username or random.choice(USERS)
|
||||
ip = random.choice(IPS_ATTACK)
|
||||
|
||||
e = _base_event(user, ip, "GetCallerIdentity", "sts.amazonaws.com")
|
||||
e["readOnly"] = True
|
||||
e["requestParameters"] = None
|
||||
e["responseElements"] = {
|
||||
"userId": f"AIDA{''.join(random.choices('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', k=16))}",
|
||||
"account": "123456789012",
|
||||
"arn": f"arn:aws:iam::123456789012:user/{user}"
|
||||
}
|
||||
return [e]
|
||||
|
||||
|
||||
def exfiltration(bucket: str = "prod-data-bucket", files: int = 50) -> list[dict]:
|
||||
"""Genera muchos GetObject consecutivos desde la misma IP (exfiltración de datos)."""
|
||||
user = random.choice(USERS)
|
||||
ip = random.choice(IPS_ATTACK)
|
||||
events = []
|
||||
|
||||
for i in range(files):
|
||||
e = _base_event(user, ip, "GetObject", "s3.amazonaws.com")
|
||||
e["readOnly"] = True
|
||||
e["resources"] = [{
|
||||
"ARN": f"arn:aws:s3:::{bucket}/data/record_{i:04d}.json",
|
||||
"accountId": "123456789012",
|
||||
"type": "AWS::S3::Object"
|
||||
}]
|
||||
events.append(e)
|
||||
|
||||
return events
|
||||
|
||||
|
||||
def port_scan(source_ip: str = None) -> list[dict]:
|
||||
"""Simula un evento de reconocimiento (DescribeSecurityGroups masivo)."""
|
||||
user = random.choice(USERS)
|
||||
ip = source_ip or random.choice(IPS_ATTACK)
|
||||
events = []
|
||||
|
||||
for action in ["DescribeSecurityGroups", "DescribeInstances", "DescribeSubnets",
|
||||
"DescribeVpcs", "DescribeNetworkInterfaces"]:
|
||||
e = _base_event(user, ip, action, "ec2.amazonaws.com")
|
||||
e["readOnly"] = True
|
||||
events.append(e)
|
||||
|
||||
return events
|
||||
|
||||
|
||||
GENERATORS = {
|
||||
"brute-force": brute_force,
|
||||
"privilege-escalation": privilege_escalation,
|
||||
"credential-leak": credential_leak,
|
||||
"exfiltration": exfiltration,
|
||||
"port-scan": port_scan,
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
incident = sys.argv[1] if len(sys.argv) > 1 else "brute-force"
|
||||
gen = GENERATORS.get(incident)
|
||||
if not gen:
|
||||
print(f"Tipos disponibles: {', '.join(GENERATORS)}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
events = gen()
|
||||
print(json.dumps(events, indent=2))
|
||||
|
|
@ -1,105 +0,0 @@
|
|||
"""
|
||||
Inyector de logs simulados hacia LocalStack.
|
||||
Genera eventos con cloudtrail_gen.py y los sube a S3 + SQS para
|
||||
activar el flujo completo del Componente C.
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import os
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import boto3
|
||||
from cloudtrail_gen import GENERATORS
|
||||
|
||||
ENDPOINT = os.environ.get("AWS_ENDPOINT_URL", "http://localhost:4566")
|
||||
REGION = os.environ.get("AWS_DEFAULT_REGION", "us-east-1")
|
||||
BUCKET = os.environ.get("S3_BUCKET", "tesis-security-logs")
|
||||
QUEUE = os.environ.get("SQS_QUEUE", "tesis-incident-queue")
|
||||
QUEUE_URL = f"{ENDPOINT}/000000000000/{QUEUE}"
|
||||
|
||||
_KEY = os.environ.get("AWS_ACCESS_KEY_ID", "test")
|
||||
_SECRET = os.environ.get("AWS_SECRET_ACCESS_KEY", "test")
|
||||
|
||||
s3 = boto3.client("s3", endpoint_url=ENDPOINT, region_name=REGION,
|
||||
aws_access_key_id=_KEY, aws_secret_access_key=_SECRET)
|
||||
sqs = boto3.client("sqs", endpoint_url=ENDPOINT, region_name=REGION,
|
||||
aws_access_key_id=_KEY, aws_secret_access_key=_SECRET)
|
||||
|
||||
SEVERITY_MAP = {
|
||||
"brute-force": "HIGH",
|
||||
"privilege-escalation": "CRITICAL",
|
||||
"credential-leak": "CRITICAL",
|
||||
"exfiltration": "HIGH",
|
||||
"port-scan": "MEDIUM",
|
||||
}
|
||||
|
||||
|
||||
def inject(incident_type: str):
|
||||
gen = GENERATORS.get(incident_type)
|
||||
if not gen:
|
||||
print(f"Tipo desconocido: {incident_type}. Disponibles: {', '.join(GENERATORS)}")
|
||||
sys.exit(1)
|
||||
|
||||
events = gen()
|
||||
print(f"[inject] Generados {len(events)} eventos de tipo '{incident_type}'")
|
||||
|
||||
# 1. Subir a S3 como archivo JSON (simula CloudTrail → S3)
|
||||
timestamp = datetime.now(timezone.utc).strftime("%Y/%m/%d/%H%M%S")
|
||||
s3_key = f"cloudtrail/{timestamp}/{incident_type}-{uuid.uuid4().hex[:8]}.json"
|
||||
s3.put_object(
|
||||
Bucket=BUCKET,
|
||||
Key=s3_key,
|
||||
Body=json.dumps({"Records": events}, indent=2).encode(),
|
||||
ContentType="application/json"
|
||||
)
|
||||
print(f"[inject] Subido a s3://{BUCKET}/{s3_key}")
|
||||
|
||||
# 2. Detectar el evento más relevante para el payload de respuesta
|
||||
first = events[0]
|
||||
|
||||
# El recurso afectado depende del tipo de incidente:
|
||||
# - exfiltration → el bucket S3 que se está extrayendo
|
||||
# - demás → el usuario IAM del atacante
|
||||
if incident_type == "exfiltration":
|
||||
resources = first.get("resources", [])
|
||||
if resources:
|
||||
arn = resources[0].get("ARN", "")
|
||||
# arn:aws:s3:::prod-data-bucket/data/record_0000.json
|
||||
# → s3:bucket/prod-data-bucket
|
||||
bucket_name = arn.split(":::")[1].split("/")[0] if ":::" in arn else "prod-data-bucket"
|
||||
else:
|
||||
bucket_name = "prod-data-bucket"
|
||||
affected_resource = f"s3:bucket/{bucket_name}"
|
||||
else:
|
||||
affected_resource = f"iam:user/{first['userIdentity']['userName']}"
|
||||
|
||||
payload = {
|
||||
"incident_type": incident_type.replace("-", "_").upper(),
|
||||
"severity": SEVERITY_MAP.get(incident_type, "MEDIUM"),
|
||||
"sourceIPAddress": first.get("sourceIPAddress", "0.0.0.0"),
|
||||
"affectedResource": affected_resource,
|
||||
"s3_log_key": s3_key,
|
||||
"event_count": len(events),
|
||||
"timestamp": first.get("eventTime", datetime.now(timezone.utc).isoformat()),
|
||||
}
|
||||
|
||||
# 3. Publicar en SQS para triggear Lambda de respuesta
|
||||
sqs.send_message(
|
||||
QueueUrl=QUEUE_URL,
|
||||
MessageBody=json.dumps(payload),
|
||||
MessageAttributes={
|
||||
"incident_type": {
|
||||
"StringValue": incident_type,
|
||||
"DataType": "String"
|
||||
}
|
||||
}
|
||||
)
|
||||
print(f"[inject] Mensaje SQS enviado a {QUEUE}")
|
||||
print(f"[inject] Payload:\n{json.dumps(payload, indent=2)}")
|
||||
return payload
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
incident = sys.argv[1] if len(sys.argv) > 1 else "brute-force"
|
||||
inject(incident)
|
||||
Loading…
Reference in New Issue