Entorno base docker configuracion stack local
This commit is contained in:
commit
1336631a22
|
|
@ -0,0 +1,232 @@
|
||||||
|
# Entorno de Desarrollo Local — Tesis: Sistema de Detección y Respuesta ante Incidentes en AWS
|
||||||
|
|
||||||
|
## Contexto del Proyecto
|
||||||
|
|
||||||
|
Este documento describe el entorno local emulado para desarrollar el **Componente C: Automatización de Respuesta**, parte del Trabajo de Integración Curricular sobre diseño e implementación de un sistema de detección y respuesta ante incidentes de seguridad en entornos cloud (AWS).
|
||||||
|
|
||||||
|
| Componente | Responsable | Descripción |
|
||||||
|
|------------|-------------|-------------|
|
||||||
|
| A — Arquitectura y Logs | Melany | CloudTrail, VPC Flow Logs, GuardDuty, S3, Glue |
|
||||||
|
| B — Detección de Incidentes | Aarón | Reglas SQL/Athena, CloudWatch Alarms, DuckDB local |
|
||||||
|
| **C — Automatización de Respuesta** | **Bryan** | **Lambda Playbooks, IAM, SNS, respuesta automatizada** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ¿Por qué un entorno local?
|
||||||
|
|
||||||
|
Probar directamente en AWS real durante el desarrollo tiene dos problemas críticos:
|
||||||
|
|
||||||
|
1. **Costos descontrolados**: errores en bucles Lambda o mala configuración de triggers pueden generar cargos exponenciales.
|
||||||
|
2. **Lentitud de iteración**: cada prueba requiere despliegue real, latencia de red y permisos de cuenta.
|
||||||
|
|
||||||
|
El entorno local permite iterar en segundos, sin internet y sin tarjeta de crédito.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Arquitectura de Emulación Local
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────────────────────────┐
|
||||||
|
│ Docker Compose Stack │
|
||||||
|
│ │
|
||||||
|
│ ┌──────────────────────────────────────────────────────┐ │
|
||||||
|
│ │ LocalStack 3.8 (community) │ │
|
||||||
|
│ │ ┌──────┐ ┌──────┐ ┌────────┐ ┌───┐ ┌───────┐ │ │
|
||||||
|
│ │ │ S3 │ │ SNS │ │ Lambda │ │IAM│ │ SQS │ │ │
|
||||||
|
│ │ └──────┘ └──────┘ └────────┘ └───┘ └───────┘ │ │
|
||||||
|
│ │ ┌──────────────────────────────────────────────┐ │ │
|
||||||
|
│ │ │ CloudWatch Logs / Events │ │ │
|
||||||
|
│ │ └──────────────────────────────────────────────┘ │ │
|
||||||
|
│ └──────────────────────────────────────────────────────┘ │
|
||||||
|
│ localhost:4566 │
|
||||||
|
│ │
|
||||||
|
│ ┌──────────────────────────────────────────────────────┐ │
|
||||||
|
│ │ DuckDB (reemplaza Amazon Athena) │ │
|
||||||
|
│ │ Consulta directa de archivos JSON de logs │ │
|
||||||
|
│ └──────────────────────────────────────────────────────┘ │
|
||||||
|
└─────────────────────────────────────────────────────────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
awslocal → .venv/bin/awslocal → apunta a localhost:4566
|
||||||
|
aws CLI → perfil "local" con credenciales ficticias
|
||||||
|
```
|
||||||
|
|
||||||
|
### Mapeo: AWS Real → Emulación Local
|
||||||
|
|
||||||
|
| Servicio AWS Real | Emulación Local | Propósito en el Proyecto |
|
||||||
|
|---|---|---|
|
||||||
|
| Amazon S3 | LocalStack S3 | Almacenamiento de logs JSON |
|
||||||
|
| AWS Lambda | LocalStack Lambda | Playbooks de respuesta automatizada |
|
||||||
|
| Amazon SNS | LocalStack SNS | Notificaciones de alertas al equipo |
|
||||||
|
| Amazon SQS | LocalStack SQS | Cola de eventos para triggear Lambdas |
|
||||||
|
| AWS IAM | LocalStack IAM | Roles y políticas de mínimo privilegio |
|
||||||
|
| CloudWatch Logs | LocalStack CloudWatch | Centralización de logs |
|
||||||
|
| Amazon Athena | **DuckDB local** | Consultas SQL sobre logs JSON |
|
||||||
|
| AWS GuardDuty | **Scripts Python** | Simulación de hallazgos de seguridad |
|
||||||
|
| AWS CloudTrail | **cloudtrail_gen.py** | Generación de eventos de API simulados |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Stack Tecnológico Instalado
|
||||||
|
|
||||||
|
| Herramienta | Versión | Rol |
|
||||||
|
|---|---|---|
|
||||||
|
| Docker Engine | 29.3.0 | Motor de contenedores |
|
||||||
|
| Docker Compose | 5.1.0 | Orquestación del stack |
|
||||||
|
| LocalStack | 3.8.1 community | Emulador de servicios AWS |
|
||||||
|
| Python | 3.14.3 | Scripts de simulación y Lambdas |
|
||||||
|
| aws-cli-v2 | 2.34.24 | Interfaz de comandos (perfil `local`) |
|
||||||
|
| awscli-local | 0.22.2 | Wrapper `awslocal` para LocalStack |
|
||||||
|
| boto3 | 1.42.88 | SDK Python para AWS / LocalStack |
|
||||||
|
| DuckDB | 1.5.1 | Motor SQL local (reemplaza Athena) |
|
||||||
|
|
||||||
|
> Las dependencias Python están aisladas en `.venv/` dentro del proyecto.
|
||||||
|
> `awslocal` se encuentra en `.venv/bin/awslocal`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Estructura de Archivos
|
||||||
|
|
||||||
|
```
|
||||||
|
localstack-tesis/
|
||||||
|
├── ENTORNO_LOCAL.md ← Este documento
|
||||||
|
├── docker-compose.yml ← Stack de LocalStack (imagen 3.8)
|
||||||
|
├── .env ← Variables de entorno del proyecto
|
||||||
|
├── activate.sh ← Activa el venv y exporta variables
|
||||||
|
├── requirements.txt ← Dependencias Python del proyecto
|
||||||
|
│
|
||||||
|
├── .venv/ ← Entorno virtual Python (no commitear)
|
||||||
|
│
|
||||||
|
├── .claude/
|
||||||
|
│ └── commands/ ← Skills de Claude Code (ver sección Skills)
|
||||||
|
│
|
||||||
|
├── infra/
|
||||||
|
│ ├── setup.sh ← Bootstrap de recursos AWS locales
|
||||||
|
│ └── lambda-policies/
|
||||||
|
│ └── base-policy.json ← Política IAM base para Lambdas
|
||||||
|
│
|
||||||
|
├── lambdas/ ← Playbooks de respuesta automatizada
|
||||||
|
│ ├── notify-alert/ ← Publica alerta a SNS
|
||||||
|
│ │ ├── handler.py
|
||||||
|
│ │ ├── policy.json
|
||||||
|
│ │ └── test_event.json
|
||||||
|
│ └── revoke-credentials/ ← Desactiva keys IAM comprometidas
|
||||||
|
│ ├── handler.py
|
||||||
|
│ ├── policy.json
|
||||||
|
│ └── test_event.json
|
||||||
|
│
|
||||||
|
├── simulators/
|
||||||
|
│ ├── cloudtrail_gen.py ← Genera eventos CloudTrail por tipo de incidente
|
||||||
|
│ └── inject_logs.py ← Sube eventos a S3 y envía mensaje a SQS
|
||||||
|
│
|
||||||
|
├── queries/ ← SQL para DuckDB (equivalente a Athena)
|
||||||
|
│ ├── detect_brute_force.sql
|
||||||
|
│ ├── detect_privilege_esc.sql
|
||||||
|
│ └── detect_exfiltration.sql
|
||||||
|
│
|
||||||
|
└── logs/
|
||||||
|
└── sample_cloudtrail.json ← Log de referencia para pruebas sin LocalStack
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Recursos AWS Locales Creados
|
||||||
|
|
||||||
|
Estos recursos ya existen en LocalStack y se recrean con `bash infra/setup.sh` si se pierde el estado (LocalStack no persiste entre reinicios por defecto).
|
||||||
|
|
||||||
|
| Tipo | Nombre | ARN / URL |
|
||||||
|
|---|---|---|
|
||||||
|
| S3 | `tesis-security-logs` | prefijos: `cloudtrail/`, `vpc-flow/`, `guardduty/`, `responses/` |
|
||||||
|
| SNS | `tesis-security-alerts` | `arn:aws:sns:us-east-1:000000000000:tesis-security-alerts` |
|
||||||
|
| SNS | `tesis-lambda-triggers` | `arn:aws:sns:us-east-1:000000000000:tesis-lambda-triggers` |
|
||||||
|
| SQS | `tesis-incident-queue` | cola principal de eventos de incidentes |
|
||||||
|
| SQS | `tesis-incident-queue-dlq` | dead letter queue para mensajes fallidos |
|
||||||
|
| CloudWatch | `/tesis/security-events` | log group de eventos de seguridad |
|
||||||
|
| CloudWatch | `/tesis/lambda-responses` | log group de respuestas de Lambdas |
|
||||||
|
| IAM | `tesis-lambda-response-role` | `arn:aws:iam::000000000000:role/tesis-lambda-response-role` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Cómo iniciar el entorno
|
||||||
|
|
||||||
|
Estos son los pasos para tener el entorno operativo al comenzar cada sesión de trabajo.
|
||||||
|
|
||||||
|
### Paso 1 — Activar el entorno Python
|
||||||
|
|
||||||
|
Desde el directorio del proyecto:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
source activate.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
Esto activa el venv y exporta las variables de entorno necesarias (`AWS_ENDPOINT_URL`, `AWS_DEFAULT_REGION`, etc.). Solo dura la sesión de terminal actual.
|
||||||
|
|
||||||
|
### Paso 2 — Levantar LocalStack
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
Espera unos segundos y verifica que esté healthy:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -s http://localhost:4566/_localstack/health | python3 -m json.tool
|
||||||
|
```
|
||||||
|
|
||||||
|
Los servicios relevantes deben aparecer como `"available"`: `s3`, `sns`, `sqs`, `lambda`, `iam`, `logs`.
|
||||||
|
|
||||||
|
### Paso 3 — Recrear los recursos AWS locales
|
||||||
|
|
||||||
|
LocalStack **no persiste** su estado entre reinicios. Cada vez que se levanta de cero hay que recrear los recursos:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bash infra/setup.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
> Si el venv no está activo, usa la ruta completa: `.venv/bin/awslocal` en lugar de `awslocal`.
|
||||||
|
|
||||||
|
### Resumen de comandos por sesión
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd ~/localstack-tesis
|
||||||
|
source activate.sh
|
||||||
|
docker compose up -d
|
||||||
|
bash infra/setup.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Skills de Claude Code
|
||||||
|
|
||||||
|
Los skills están en `.claude/commands/` y solo están disponibles cuando Claude Code está abierto en este directorio. Se invocan escribiendo el nombre en el chat.
|
||||||
|
|
||||||
|
| Skill | Descripción |
|
||||||
|
|---|---|
|
||||||
|
| `/localstack-up` | Verifica si LocalStack está corriendo y lo levanta si no. Muestra el estado de cada servicio relevante para el Componente C. |
|
||||||
|
| `/bootstrap-resources` | Crea todos los recursos AWS locales del proyecto (S3, SNS, SQS, IAM, CloudWatch). Equivale a correr `bash infra/setup.sh`. |
|
||||||
|
| `/simulate-incident [tipo]` | Genera un evento de incidente de seguridad sintético, lo sube a S3 y envía el mensaje a SQS para activar el flujo completo. Tipos: `brute-force`, `privilege-escalation`, `credential-leak`, `exfiltration`, `port-scan`. |
|
||||||
|
| `/deploy-lambda [playbook]` | Empaqueta y despliega un Lambda Playbook en LocalStack. Lo invoca con su `test_event.json` y muestra el resultado. Playbooks: `notify-alert`, `revoke-credentials`, `block-ip`, `isolate-instance`. |
|
||||||
|
| `/query-logs [tipo]` | Descarga logs de S3 y ejecuta una consulta DuckDB sobre ellos (equivalente a Athena). Tipos: `brute-force`, `privilege-escalation`, `exfiltration`, `summary`, `recent`. |
|
||||||
|
| `/new-playbook [descripción]` | Crea la estructura completa de un nuevo Lambda Playbook: `handler.py`, `policy.json` (mínimo privilegio) y `test_event.json`. |
|
||||||
|
|
||||||
|
### Flujo de trabajo típico
|
||||||
|
|
||||||
|
```
|
||||||
|
/localstack-up
|
||||||
|
→ /bootstrap-resources (si es primera vez o LocalStack fue reiniciado)
|
||||||
|
→ /simulate-incident brute-force
|
||||||
|
→ /query-logs brute-force
|
||||||
|
→ /deploy-lambda notify-alert
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Restricciones del Entorno
|
||||||
|
|
||||||
|
1. **No usar la consola web de AWS real** ni credenciales reales en ningún archivo.
|
||||||
|
2. **No usar SIEMs comerciales** (Splunk, Datadog, Elastic). Solo servicios AWS nativos emulados.
|
||||||
|
3. **Athena → DuckDB**: todas las consultas SQL sobre logs se hacen con DuckDB.
|
||||||
|
4. **GuardDuty → Scripts Python**: los hallazgos se simulan con `simulators/cloudtrail_gen.py`.
|
||||||
|
5. Cada Lambda debe tener su `policy.json` con permisos de mínimo privilegio.
|
||||||
|
6. Los archivos en `logs/` son datos sintéticos, nunca logs reales de producción.
|
||||||
|
7. LocalStack Community **no persiste** estado entre reinicios: siempre correr `setup.sh` al levantar.
|
||||||
|
|
@ -0,0 +1,17 @@
|
||||||
|
#!/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"
|
||||||
|
|
@ -0,0 +1,23 @@
|
||||||
|
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
|
||||||
|
- DOCKER_HOST=unix:///var/run/docker.sock
|
||||||
|
- LAMBDA_EXECUTOR=docker
|
||||||
|
- 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
|
||||||
|
|
@ -0,0 +1,47 @@
|
||||||
|
{
|
||||||
|
"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/*:*"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,99 @@
|
||||||
|
#!/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"
|
||||||
|
|
||||||
|
# ── 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
|
||||||
|
|
@ -0,0 +1,62 @@
|
||||||
|
"""
|
||||||
|
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
|
||||||
|
|
||||||
|
ENDPOINT = os.environ.get("AWS_ENDPOINT_URL", "http://localhost: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()
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,17 @@
|
||||||
|
{
|
||||||
|
"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:*"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,15 @@
|
||||||
|
{
|
||||||
|
"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"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,73 @@
|
||||||
|
"""
|
||||||
|
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.
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import boto3
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
ENDPOINT = os.environ.get("AWS_ENDPOINT_URL", "http://localhost:4566")
|
||||||
|
REGION = os.environ.get("AWS_DEFAULT_REGION", "us-east-1")
|
||||||
|
|
||||||
|
iam = boto3.client("iam", endpoint_url=ENDPOINT, region_name=REGION)
|
||||||
|
sns = boto3.client("sns", endpoint_url=ENDPOINT, region_name=REGION)
|
||||||
|
SNS_ARN = os.environ.get("SNS_ALERTS_ARN", "arn:aws:sns:us-east-1:000000000000:tesis-security-alerts")
|
||||||
|
|
||||||
|
DENY_ALL_POLICY = json.dumps({
|
||||||
|
"Version": "2012-10-17",
|
||||||
|
"Statement": [{
|
||||||
|
"Effect": "Deny",
|
||||||
|
"Action": "*",
|
||||||
|
"Resource": "*"
|
||||||
|
}]
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
def lambda_handler(event, context):
|
||||||
|
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/", "")
|
||||||
|
if not username:
|
||||||
|
return {"status": "error", "detail": "affectedResource no contiene usuario IAM"}
|
||||||
|
|
||||||
|
actions_taken = []
|
||||||
|
|
||||||
|
# 1. Listar y desactivar todas las access keys del usuario
|
||||||
|
keys = iam.list_access_keys(UserName=username).get("AccessKeyMetadata", [])
|
||||||
|
for key in keys:
|
||||||
|
kid = key["AccessKeyId"]
|
||||||
|
iam.update_access_key(UserName=username, AccessKeyId=kid, Status="Inactive")
|
||||||
|
actions_taken.append(f"AccessKey desactivada: {kid}")
|
||||||
|
print(f"[revoke-credentials] Desactivada key {kid} de usuario {username}")
|
||||||
|
|
||||||
|
# 2. Adjuntar política de Deny-All como medida de contención
|
||||||
|
iam.put_user_policy(
|
||||||
|
UserName=username,
|
||||||
|
PolicyName="EmergencyDenyAll",
|
||||||
|
PolicyDocument=DENY_ALL_POLICY
|
||||||
|
)
|
||||||
|
actions_taken.append("Política EmergencyDenyAll adjuntada")
|
||||||
|
print(f"[revoke-credentials] DenyAll aplicado al usuario {username}")
|
||||||
|
|
||||||
|
# 3. Notificar al equipo
|
||||||
|
result = {
|
||||||
|
"playbook": "revoke-credentials",
|
||||||
|
"username": username,
|
||||||
|
"actions": actions_taken,
|
||||||
|
"status": "CONTAINED",
|
||||||
|
"timestamp": datetime.now(timezone.utc).isoformat()
|
||||||
|
}
|
||||||
|
sns.publish(
|
||||||
|
TopicArn=SNS_ARN,
|
||||||
|
Subject=f"[RESPUESTA] Credenciales revocadas: {username}",
|
||||||
|
Message=json.dumps(result, indent=2)
|
||||||
|
)
|
||||||
|
|
||||||
|
return {"status": "success", "action": "credentials_revoked", "details": result,
|
||||||
|
"timestamp": datetime.now(timezone.utc).isoformat()}
|
||||||
|
|
@ -0,0 +1,27 @@
|
||||||
|
{
|
||||||
|
"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:*"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,12 @@
|
||||||
|
{
|
||||||
|
"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"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,45 @@
|
||||||
|
{
|
||||||
|
"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"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,18 @@
|
||||||
|
-- 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
|
||||||
|
|
||||||
|
SELECT
|
||||||
|
sourceIPAddress,
|
||||||
|
userIdentity.userName AS username,
|
||||||
|
COUNT(*) AS failed_attempts,
|
||||||
|
MIN(eventTime) AS first_attempt,
|
||||||
|
MAX(eventTime) AS last_attempt,
|
||||||
|
epoch_ms(MAX(epoch_ms(last_attempt)) - MIN(epoch_ms(first_attempt))) AS window_seconds
|
||||||
|
FROM read_json_auto('$LOG_PATH', format='array')
|
||||||
|
WHERE eventName = 'ConsoleLogin'
|
||||||
|
AND errorCode = 'AccessDenied'
|
||||||
|
AND epoch_ms(eventTime) >= now() - INTERVAL '1 hour'
|
||||||
|
GROUP BY sourceIPAddress, userIdentity.userName
|
||||||
|
HAVING COUNT(*) > 5
|
||||||
|
ORDER BY failed_attempts DESC;
|
||||||
|
|
@ -0,0 +1,16 @@
|
||||||
|
-- Detección de Exfiltración de Datos
|
||||||
|
-- Busca acceso masivo a S3 GetObject (>50 objetos) desde la misma IP en 1 hora
|
||||||
|
|
||||||
|
SELECT
|
||||||
|
sourceIPAddress,
|
||||||
|
userIdentity.userName AS username,
|
||||||
|
COUNT(*) AS total_downloads,
|
||||||
|
MIN(eventTime) AS first_access,
|
||||||
|
MAX(eventTime) AS last_access
|
||||||
|
FROM read_json_auto('$LOG_PATH', format='array')
|
||||||
|
WHERE eventSource = 's3.amazonaws.com'
|
||||||
|
AND eventName = 'GetObject'
|
||||||
|
AND epoch_ms(eventTime) >= now() - INTERVAL '1 hour'
|
||||||
|
GROUP BY sourceIPAddress, userIdentity.userName
|
||||||
|
HAVING COUNT(*) > 50
|
||||||
|
ORDER BY total_downloads DESC;
|
||||||
|
|
@ -0,0 +1,22 @@
|
||||||
|
-- Detección de Escalada de Privilegios
|
||||||
|
-- Busca eventos IAM sospechosos: adjuntar políticas admin, crear keys, modificar roles
|
||||||
|
|
||||||
|
SELECT
|
||||||
|
userIdentity.userName AS username,
|
||||||
|
sourceIPAddress,
|
||||||
|
eventName,
|
||||||
|
eventTime,
|
||||||
|
requestParameters
|
||||||
|
FROM read_json_auto('$LOG_PATH', format='array')
|
||||||
|
WHERE eventSource = 'iam.amazonaws.com'
|
||||||
|
AND eventName IN (
|
||||||
|
'AttachUserPolicy',
|
||||||
|
'AttachRolePolicy',
|
||||||
|
'CreateAccessKey',
|
||||||
|
'PutUserPolicy',
|
||||||
|
'AddUserToGroup',
|
||||||
|
'CreateLoginProfile',
|
||||||
|
'UpdateLoginProfile'
|
||||||
|
)
|
||||||
|
AND epoch_ms(eventTime) >= now() - INTERVAL '24 hours'
|
||||||
|
ORDER BY eventTime DESC;
|
||||||
|
|
@ -0,0 +1,3 @@
|
||||||
|
boto3>=1.34
|
||||||
|
awscli-local>=0.22
|
||||||
|
duckdb>=0.10
|
||||||
|
|
@ -0,0 +1,159 @@
|
||||||
|
"""
|
||||||
|
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))
|
||||||
|
|
@ -0,0 +1,83 @@
|
||||||
|
"""
|
||||||
|
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}"
|
||||||
|
|
||||||
|
s3 = boto3.client("s3", endpoint_url=ENDPOINT, region_name=REGION)
|
||||||
|
sqs = boto3.client("sqs", endpoint_url=ENDPOINT, region_name=REGION)
|
||||||
|
|
||||||
|
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]
|
||||||
|
payload = {
|
||||||
|
"incident_type": incident_type.replace("-", "_").upper(),
|
||||||
|
"severity": SEVERITY_MAP.get(incident_type, "MEDIUM"),
|
||||||
|
"sourceIPAddress": first.get("sourceIPAddress", "0.0.0.0"),
|
||||||
|
"affectedResource": f"iam:user/{first['userIdentity']['userName']}",
|
||||||
|
"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