From a294c8daebb495a6ef79bbf4cbd8762d49869871 Mon Sep 17 00:00:00 2001 From: bryancito1090 Date: Mon, 20 Apr 2026 20:03:28 -0500 Subject: [PATCH 1/9] feat: implement automated incident response dispatcher with new block-ip and isolate-instance playbooks and update SQL query parsing --- analisis_flujo1_bruteforce.md | 462 ++++++++++++++++++ analisis_flujo2_automatizacion.md | 328 +++++++++++++ docker-compose.yml | 1 + lambdas/block-ip/handler.py | 90 ++++ lambdas/block-ip/policy.json | 23 + lambdas/block-ip/test_event.json | 12 + lambdas/dispatcher/handler.py | 89 ++++ lambdas/dispatcher/policy.json | 32 ++ lambdas/dispatcher/test_event.json | 12 + lambdas/isolate-instance/handler.py | 89 ++++ lambdas/isolate-instance/policy.json | 23 + lambdas/isolate-instance/test_event.json | 12 + lambdas/notify-alert/handler.py | 5 +- lambdas/revoke-credentials/handler.py | 4 +- queries/detect_brute_force.sql | 24 +- queries/detect_exfiltration.sql | 23 +- queries/detect_privilege_esc.sql | 23 +- .../cloudtrail_gen.cpython-314.pyc | Bin 0 -> 8488 bytes simulators/inject_logs.py | 9 +- 19 files changed, 1226 insertions(+), 35 deletions(-) create mode 100644 analisis_flujo1_bruteforce.md create mode 100644 analisis_flujo2_automatizacion.md create mode 100644 lambdas/block-ip/handler.py create mode 100644 lambdas/block-ip/policy.json create mode 100644 lambdas/block-ip/test_event.json create mode 100644 lambdas/dispatcher/handler.py create mode 100644 lambdas/dispatcher/policy.json create mode 100644 lambdas/dispatcher/test_event.json create mode 100644 lambdas/isolate-instance/handler.py create mode 100644 lambdas/isolate-instance/policy.json create mode 100644 lambdas/isolate-instance/test_event.json create mode 100644 simulators/__pycache__/cloudtrail_gen.cpython-314.pyc diff --git a/analisis_flujo1_bruteforce.md b/analisis_flujo1_bruteforce.md new file mode 100644 index 0000000..cd3e6ec --- /dev/null +++ b/analisis_flujo1_bruteforce.md @@ -0,0 +1,462 @@ +# Análisis de Flujo 1 — Ataque Brute-Force en Entorno Local + +**Proyecto:** Trabajo de Integración Curricular — Sistema de Detección y Respuesta ante Incidentes en AWS +**Componente:** C — Automatización de Respuesta +**Responsable:** Bryan +**Fecha de ejecución:** 2026-04-20 +**Entorno:** LocalStack 3.8.1 Community — localhost:4566 + +--- + +## 1. Descripción del Escenario + +Se simuló un ataque de fuerza bruta contra la consola de AWS, donde un actor externo realizó **10 intentos fallidos de autenticación** (`ConsoleLogin` con `AccessDenied`) contra el usuario IAM `admin` desde la IP `185.220.101.5` en un período de ~2 minutos. + +El flujo completo cubre: generación del incidente → almacenamiento en S3 → detección con DuckDB → notificación vía Lambda + SNS. + +--- + +## 2. Flujo Ejecutado + +``` +PASO 1 /localstack-up LocalStack levantado y verificado +PASO 2 /bootstrap-resources Recursos AWS locales creados en LocalStack +PASO 3 /simulate-incident Evento brute-force generado → S3 + SQS +PASO 4 /query-logs DuckDB detectó el IoC (análisis Athena-equivalente) +PASO 5 /deploy-lambda Lambda notify-alert desplegada y ejecutada +``` + +--- + +## 3. Recursos AWS Locales Utilizados + +| Tipo | Nombre | ARN / URL | +|------|--------|-----------| +| S3 | `tesis-security-logs` | `s3://tesis-security-logs/cloudtrail/` | +| 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` | `http://sqs.us-east-1.localhost.localstack.cloud:4566/000000000000/tesis-incident-queue` | +| 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 | +| CloudWatch | `/aws/lambda/tesis-notify-alert` | logs de ejecución de la Lambda | +| IAM | `tesis-lambda-response-role` | `arn:aws:iam::000000000000:role/tesis-lambda-response-role` | +| Lambda | `tesis-notify-alert` | `arn:aws:lambda:us-east-1:000000000000:function:tesis-notify-alert` | + +--- + +## 4. Paso a Paso con Respuestas del Sistema + +### 4.1 LocalStack UP + +```bash +docker compose -f docker-compose.yml up -d +curl -s http://localhost:4566/_localstack/health | python3 -m json.tool +``` + +**Respuesta:** +``` +LocalStack 3.8.1 community — localhost:4566 +Servicios disponibles: s3, sns, sqs, lambda, iam, logs, cloudwatch, events +``` + +--- + +### 4.2 Bootstrap de Recursos + +```bash +source activate.sh +bash infra/setup.sh +``` + +**Respuesta:** +``` +[OK] S3: s3://tesis-security-logs [cloudtrail/, vpc-flow/, guardduty/, responses/] +[OK] SNS alerts: arn:aws:sns:us-east-1:000000000000:tesis-security-alerts +[OK] SNS triggers: arn:aws:sns:us-east-1:000000000000:tesis-lambda-triggers +[OK] SQS queue: http://...localstack.cloud:4566/.../tesis-incident-queue +[OK] SQS DLQ: http://...localstack.cloud:4566/.../tesis-incident-queue-dlq +[OK] CloudWatch: /tesis/security-events +[OK] CloudWatch: /tesis/lambda-responses +[OK] IAM Role: arn:aws:iam::000000000000:role/tesis-lambda-response-role +``` + +--- + +### 4.3 Simulación del Incidente Brute-Force + +```bash +.venv/bin/python3 simulators/inject_logs.py brute-force +``` + +**Respuesta:** +``` +[inject] Generados 10 eventos de tipo 'brute-force' +[inject] Subido a s3://tesis-security-logs/cloudtrail/2026/04/20/234235/brute-force-51cbb9f1.json +[inject] Mensaje SQS enviado a tesis-incident-queue +``` + +**Payload enviado a SQS (entrada para Lambda):** +```json +{ + "incident_type": "BRUTE_FORCE", + "severity": "HIGH", + "sourceIPAddress": "185.220.101.5", + "affectedResource": "iam:user/admin", + "s3_log_key": "cloudtrail/2026/04/20/234235/brute-force-51cbb9f1.json", + "event_count": 10, + "timestamp": "2026-04-20T23:42:35.606154Z" +} +``` + +**Verificación S3:** +``` +s3://tesis-security-logs/cloudtrail/2026/04/20/234235/brute-force-51cbb9f1.json (7,681 bytes) +``` + +**Verificación SQS:** +``` +ApproximateNumberOfMessages: 1 +``` + +--- + +### 4.4 Detección con DuckDB (equivalente a Amazon Athena) + +```bash +.venv/bin/awslocal s3 sync s3://tesis-security-logs/cloudtrail/ /tmp/tesis-logs/ +# Ejecutar queries/detect_brute_force.sql sobre los archivos descargados +``` + +**Estructura del evento CloudTrail simulado:** +```json +{ + "eventVersion": "1.08", + "eventName": "ConsoleLogin", + "eventSource": "signin.amazonaws.com", + "errorCode": "AccessDenied", + "sourceIPAddress": "185.220.101.5", + "userIdentity": { "type": "IAMUser", "userName": "admin" }, + "responseElements": { "ConsoleLogin": "Failure" } +} +``` + +**Resultado de la consulta DuckDB:** + +| sourceIPAddress | username | failed_attempts | first_attempt | last_attempt | +|-----------------|----------|-----------------|---------------|--------------| +| 185.220.101.5 | admin | **10** | 2026-04-20T23:42:35Z | 2026-04-20T23:44:50Z | + +``` +IoC detectados: 1 +Regla disparada: ConsoleLogin + AccessDenied > 5 intentos +Ventana temporal: ~2 minutos +Acción recomendada: notify-alert → block-ip +``` + +--- + +### 4.5 Despliegue y Ejecución de Lambda Playbook `notify-alert` + +```bash +# Empaquetar +python3 -c "import zipfile; z=zipfile.ZipFile('/tmp/notify-alert.zip','w'); z.write('handler.py'); z.close()" + +# Desplegar +.venv/bin/awslocal lambda create-function \ + --function-name tesis-notify-alert \ + --runtime python3.12 \ + --handler handler.lambda_handler \ + --zip-file fileb:///tmp/notify-alert.zip \ + ... + +# Invocar +.venv/bin/awslocal lambda invoke \ + --function-name tesis-notify-alert \ + --cli-binary-format raw-in-base64-out \ + --payload file://lambdas/notify-alert/test_event.json \ + output.json +``` + +**Respuesta de la Lambda (HTTP 200):** +```json +{ + "status": "success", + "processed": 1, + "results": [{ + "status": "success", + "action": "sns_published", + "details": { + "alert_type": "SECURITY_INCIDENT", + "incident_type": "BRUTE_FORCE", + "severity": "HIGH", + "sourceIPAddress": "203.0.113.42", + "affectedResource": "iam:user/admin", + "detectedAt": "2024-01-15T10:30:00Z", + "respondedAt": "2026-04-21T00:00:45Z", + "playbook": "notify-alert", + "status": "NOTIFIED" + } + }], + "timestamp": "2026-04-21T00:00:45Z" +} +``` + +**Logs de ejecución (CloudWatch):** +``` +START RequestId: 11c6f134-... Version: $LATEST +[notify-alert] Alerta publicada: BRUTE_FORCE desde 203.0.113.42 +END RequestId: 11c6f134-... +REPORT Duration: 7.45 ms Billed Duration: 8 ms Memory: 128 MB +``` + +--- + +## 5. Dónde Ver los Logs (Guía Visual) + +### 5.1 Archivos en disco (más directo) + +```bash +# Ver el JSON del incidente subido a S3 (descargado localmente): +cat /tmp/tesis-logs/2026/04/20/234235/brute-force-51cbb9f1.json | python3 -m json.tool + +# Sincronizar todos los logs de S3 a local: +.venv/bin/awslocal s3 sync s3://tesis-security-logs/cloudtrail/ /tmp/tesis-logs/ + +# Ver todos los archivos de logs en S3: +.venv/bin/awslocal s3 ls s3://tesis-security-logs/ --recursive +``` + +### 5.2 Logs de ejecución de Lambda (CloudWatch) + +```bash +# Ver todos los log groups disponibles: +.venv/bin/awslocal logs describe-log-groups --query 'logGroups[].logGroupName' --output text + +# Ver los streams de la Lambda: +.venv/bin/awslocal logs describe-log-streams \ + --log-group-name /aws/lambda/tesis-notify-alert \ + --query 'logStreams[].logStreamName' --output text + +# Leer los logs de la última ejecución: +.venv/bin/awslocal logs get-log-events \ + --log-group-name /aws/lambda/tesis-notify-alert \ + --log-stream-name "2026/04/21/[\$LATEST]STREAM_ID" \ + --query 'events[].message' --output text +``` + +### 5.3 Mensajes en SQS (cola de incidentes) + +```bash +# Ver cuántos mensajes hay en la cola: +.venv/bin/awslocal sqs get-queue-attributes \ + --queue-url http://localhost:4566/000000000000/tesis-incident-queue \ + --attribute-names ApproximateNumberOfMessages + +# Leer un mensaje de la cola (sin eliminarlo): +.venv/bin/awslocal sqs receive-message \ + --queue-url http://localhost:4566/000000000000/tesis-incident-queue \ + --attribute-names All +``` + +### 5.4 Mensajes publicados en SNS + +```bash +# Listar tópicos SNS: +.venv/bin/awslocal sns list-topics + +# Para ver mensajes SNS publicados, suscribir SQS al tópico primero: +.venv/bin/awslocal sns subscribe \ + --topic-arn arn:aws:sns:us-east-1:000000000000:tesis-security-alerts \ + --protocol sqs \ + --notification-endpoint arn:aws:sqs:us-east-1:000000000000:tesis-incident-queue +``` + +### 5.5 Interfaz Web — LocalStack Web UI (sin instalar nada extra) + +LocalStack Community expone una API REST que puedes consultar desde el navegador: + +| Recurso | URL directa en navegador | +|---------|--------------------------| +| Health general | http://localhost:4566/_localstack/health | +| Listar buckets S3 | http://localhost:4566/tesis-security-logs/ | +| Info de LocalStack | http://localhost:4566/_localstack/info | + +> Para una UI visual completa (tablas, árbol de recursos, gráficos), instala **LocalStack Desktop** (gratuito): https://app.localstack.cloud/download — conecta a `localhost:4566` sin credenciales adicionales. + +--- + +## 6. Hallazgos y Correcciones Aplicadas + +### Hallazgo 1 — Scripts fallaban sin credenciales AWS + +**Síntoma:** `botocore.exceptions.NoCredentialsError` al correr `inject_logs.py` sin activar el venv antes. + +**Causa raíz:** `activate.sh` exporta `AWS_ACCESS_KEY_ID=test` pero solo en el shell que lo ejecuta con `source`. Si se llama el script directamente sin haber hecho `source activate.sh`, boto3 no encuentra credenciales. + +**Corrección aplicada** (`simulators/inject_logs.py`): +```python +_KEY = os.environ.get("AWS_ACCESS_KEY_ID", "test") +_SECRET = os.environ.get("AWS_SECRET_ACCESS_KEY", "test") +s3 = boto3.client("s3", ..., aws_access_key_id=_KEY, aws_secret_access_key=_SECRET) +sqs = boto3.client("sqs", ..., aws_access_key_id=_KEY, aws_secret_access_key=_SECRET) +``` + +**Regla para la tesis:** Siempre hacer `source activate.sh` antes de cualquier comando, o asegurar fallback `"test"` en los clientes boto3 del entorno local. + +--- + +### Hallazgo 2 — Queries SQL incompatibles con DuckDB + +**Síntoma:** `ConversionException: Unimplemented type for cast` al ejecutar las queries `.sql`. + +**Causa raíz:** Los archivos SQL usaban el operador de extracción JSON de PostgreSQL (`->>'campo'`), pero DuckDB trabaja con registros struct y requiere acceso por punto (`r.campo`). Además, `format='array'` no es necesario cuando los Records son un campo dentro del JSON raíz. + +**Corrección aplicada** (los 3 archivos en `queries/`): +```sql +-- ANTES (PostgreSQL/Athena style — no funciona en DuckDB): +FROM read_json_auto('$LOG_PATH', format='array') +WHERE eventName = 'ConsoleLogin' AND userIdentity->>'userName' = 'x' + +-- DESPUÉS (DuckDB struct access): +FROM (SELECT unnest(Records) AS r FROM read_json_auto('$LOG_PATH')) +WHERE r.eventName = 'ConsoleLogin' AND r.userIdentity.userName = 'x' +``` + +**Regla para la tesis:** DuckDB usa acceso por punto para campos de structs anidados. Para JSON complejo con arreglos dentro de objetos, usar `unnest()` para aplanar el array antes de filtrar. + +--- + +### Hallazgo 3 — Lambda no podía alcanzar LocalStack (endpoint `localhost:4566`) + +**Síntoma:** `EndpointConnectionError: Could not connect to http://localhost:4566/` desde dentro de la Lambda. + +**Causa raíz:** Las Lambdas con `LAMBDA_EXECUTOR=docker` se ejecutan en contenedores Docker separados. Dentro de ese contenedor, `localhost` es el propio contenedor Lambda, no el host ni el contenedor LocalStack. + +**Corrección aplicada** (`lambdas/*/handler.py`): +```python +# ANTES — hardcoded, falla dentro del contenedor: +ENDPOINT = os.environ.get("AWS_ENDPOINT_URL", "http://localhost:4566") + +# DESPUÉS — usa LOCALSTACK_HOSTNAME inyectada automáticamente por LocalStack: +_ls_host = os.environ.get("LOCALSTACK_HOSTNAME", "localhost") +ENDPOINT = os.environ.get("AWS_ENDPOINT_URL", f"http://{_ls_host}:4566") +``` + +**Por qué funciona:** LocalStack inyecta automáticamente la variable `LOCALSTACK_HOSTNAME` en cada contenedor Lambda que lanza, apuntando al hostname correcto dentro de la red Docker. + +--- + +### Hallazgo 4 — IP de LocalStack cambia entre reinicios + +**Síntoma:** Workaround manual de usar `172.19.0.2:4566` dejó de funcionar tras reiniciar Docker (la IP puede asignarse distinta). + +**Causa raíz:** Sin una red Docker configurada explícitamente para los contenedores Lambda, cada reinicio puede resultar en IPs distintas para los contenedores. + +**Corrección aplicada** (`docker-compose.yml`): +```yaml +environment: + - LAMBDA_EXECUTOR=docker + - LAMBDA_DOCKER_NETWORK=localstack-tesis_default # ← AÑADIDO +``` + +Esto garantiza que los contenedores Lambda se unan a la misma red Docker que LocalStack (`localstack-tesis_default`), haciendo que `LOCALSTACK_HOSTNAME` sea siempre resoluble por nombre de contenedor, independientemente de la IP asignada. + +--- + +## 7. Archivos Modificados en Esta Sesión + +| Archivo | Cambio | +|---------|--------| +| `simulators/inject_logs.py` | Credenciales boto3 con fallback `"test"` | +| `queries/detect_brute_force.sql` | Sintaxis DuckDB: `r.campo` en lugar de `->>'campo'` | +| `queries/detect_privilege_esc.sql` | Misma corrección de sintaxis | +| `queries/detect_exfiltration.sql` | Misma corrección de sintaxis | +| `docker-compose.yml` | `LAMBDA_DOCKER_NETWORK=localstack-tesis_default` | +| `lambdas/notify-alert/handler.py` | Endpoint via `LOCALSTACK_HOSTNAME` | +| `lambdas/revoke-credentials/handler.py` | Endpoint via `LOCALSTACK_HOSTNAME` | + +--- + +## 8. Diagrama del Flujo Ejecutado + +``` +Atacante externo +185.220.101.5 + │ + │ 10x ConsoleLogin FAILED + ▼ +┌─────────────────────────────────────────────────────────┐ +│ simulators/inject_logs.py │ +│ cloudtrail_gen.py → genera 10 eventos CloudTrail JSON │ +└────────────────────┬────────────────────────────────────┘ + │ + ┌──────────┼──────────┐ + ▼ ▼ +┌─────────────────┐ ┌─────────────────────────┐ +│ S3 LocalStack │ │ SQS LocalStack │ +│ tesis-security- │ │ tesis-incident-queue │ +│ logs/cloudtrail/ │ │ payload BRUTE_FORCE │ +│ (7,681 bytes) │ │ severity: HIGH │ +└────────┬────────┘ └───────────┬─────────────┘ + │ │ + ▼ ▼ +┌─────────────────┐ ┌─────────────────────────┐ +│ DuckDB (Athena) │ │ Lambda: notify-alert │ +│ detect_brute_ │ │ Runtime: python3.12 │ +│ force.sql │ │ Duration: 7.45 ms │ +│ │ │ │ +│ RESULTADO: │ │ → sns.publish() │ +│ 10 intentos │ │ → SNS: tesis-security- │ +│ desde misma IP │ │ alerts │ +│ IoC: CONFIRMADO │ │ → status: NOTIFIED │ +└─────────────────┘ └───────────┬─────────────┘ + │ + ┌──────────▼──────────┐ + │ CloudWatch Logs │ + │ /aws/lambda/tesis- │ + │ notify-alert │ + │ │ + │ [notify-alert] │ + │ Alerta publicada: │ + │ BRUTE_FORCE desde │ + │ 203.0.113.42 │ + └─────────────────────┘ +``` + +--- + +## 9. Verificación Final del Estado + +```bash +# Verificar Lambda activa: +.venv/bin/awslocal lambda get-function --function-name tesis-notify-alert \ + --query 'Configuration.[State,Runtime,Timeout]' --output text +# Active python3.12 30 + +# Ver log de ejecución: +.venv/bin/awslocal logs get-log-events \ + --log-group-name /aws/lambda/tesis-notify-alert \ + --log-stream-name "$(awslocal logs describe-log-streams \ + --log-group-name /aws/lambda/tesis-notify-alert \ + --query 'logStreams[0].logStreamName' --output text)" \ + --query 'events[].message' --output text +``` + +**Salida esperada:** +``` +START RequestId: 11c6f134-... Version: $LATEST +[notify-alert] Alerta publicada: BRUTE_FORCE desde 203.0.113.42 +END RequestId: 11c6f134-... +REPORT Duration: 7.45 ms Billed Duration: 8 ms Memory: 128 MB +``` + +--- + +## 10. Próximos Pasos + +- [ ] Desplegar playbook `block-ip` y encadenarlo tras `notify-alert` +- [ ] Desplegar playbook `revoke-credentials` para escenario `credential-leak` +- [ ] Simular incidente `privilege-escalation` y ejecutar el flujo completo +- [ ] Conectar SQS → Lambda trigger (event source mapping) para respuesta automática sin invocación manual +- [ ] Suscribir un email o cola SQS al tópico SNS para ver notificaciones end-to-end diff --git a/analisis_flujo2_automatizacion.md b/analisis_flujo2_automatizacion.md new file mode 100644 index 0000000..f750e3b --- /dev/null +++ b/analisis_flujo2_automatizacion.md @@ -0,0 +1,328 @@ +# Análisis de Flujo 2 — Automatización Completa del Componente C + +**Proyecto:** Trabajo de Integración Curricular — Sistema de Detección y Respuesta ante Incidentes en AWS +**Componente:** C — Automatización de Respuesta +**Responsable:** Bryan +**Fecha de ejecución:** 2026-04-21 +**Entorno:** LocalStack 3.8.1 Community — localhost:4566 + +--- + +## 1. Objetivo de Este Flujo + +Completar el Componente C de forma que la respuesta ante incidentes sea **totalmente automática**: +un mensaje en SQS dispara el playbook correcto sin ninguna intervención manual. + +--- + +## 2. Estado Antes vs Después + +| Capacidad | Antes (Flujo 1) | Después (Flujo 2) | +|-----------|-----------------|-------------------| +| Simular incidente → S3 + SQS | ✅ | ✅ | +| Detectar con DuckDB (Athena) | ✅ | ✅ | +| Lambda `notify-alert` | ✅ manual | ✅ automático | +| Lambda `block-ip` | ❌ no existía | ✅ automático | +| Lambda `revoke-credentials` | ✅ código, no desplegada | ✅ automático | +| Lambda `isolate-instance` | ❌ no existía | ✅ automático | +| Lambda `dispatcher` (enrutador) | ❌ no existía | ✅ automático | +| SQS → Lambda trigger automático | ❌ invocación manual | ✅ Event Source Mapping | + +--- + +## 3. Arquitectura Final del Componente C + +``` +Atacante externo + │ + ▼ +simulators/inject_logs.py + ├── genera eventos CloudTrail JSON + ├── sube a S3: tesis-security-logs/cloudtrail/ + └── publica en SQS: tesis-incident-queue + │ + │ Event Source Mapping (automático) + │ batch-size: 1 + ▼ + ┌─────────────────────────────┐ + │ Lambda: tesis-dispatcher │ + │ Tabla de enrutamiento: │ + │ │ + │ BRUTE_FORCE → notify-alert + block-ip │ + │ CREDENTIAL_LEAK → notify-alert + revoke-credentials │ + │ PRIVILEGE_ESC → notify-alert + revoke-credentials │ + │ EXFILTRATION → notify-alert + isolate-instance │ + │ PORT_SCAN → notify-alert + block-ip │ + └──────────────┬──────────────┘ + │ lambda.invoke() para cada playbook + ┌──────────────┼──────────────┬────────────────┐ + ▼ ▼ ▼ ▼ + notify-alert block-ip revoke-credentials isolate-instance + sns.publish() S3 blocklist iam.update_access_key S3 quarantine + │ │ │ │ + └──────────────┴──────────────┴────────────────┘ + │ + SNS: tesis-security-alerts + │ + CloudWatch Logs + /aws/lambda/tesis-* +``` + +--- + +## 4. Playbooks Creados + +### 4.1 `tesis-dispatcher` + +**Rol:** Lambda central. Consume mensajes de SQS automáticamente (Event Source Mapping) y enruta al conjunto correcto de playbooks según `incident_type`. + +**Tabla de enrutamiento:** + +| incident_type | Playbooks invocados | +|---------------|---------------------| +| `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 | + +**ARN:** `arn:aws:lambda:us-east-1:000000000000:function:tesis-dispatcher` + +--- + +### 4.2 `tesis-block-ip` + +**Rol:** Registra la IP atacante en `s3://tesis-security-logs/responses/blocked-ips.json` y notifica via SNS. +**Equivalente real AWS:** Actualizar WAF IP Set o regla de Security Group/NACL. + +**Resultado en S3 tras ejecución:** +```json +[ + { + "ip": "203.0.113.42", + "blocked_at": "2026-04-21T01:00:32Z", + "reason": "BRUTE_FORCE", + "severity": "HIGH", + "affectedResource": "iam:user/external-contractor" + } +] +``` + +**ARN:** `arn:aws:lambda:us-east-1:000000000000:function:tesis-block-ip` + +--- + +### 4.3 `tesis-revoke-credentials` (ya existía, ahora desplegada) + +**Rol:** Desactiva todas las access keys del usuario IAM comprometido y aplica política `EmergencyDenyAll`. +**Equivalente real AWS:** `iam:UpdateAccessKey` + `iam:PutUserPolicy`. + +**Acciones que ejecuta:** +1. Lista access keys del usuario afectado +2. Cambia cada key a `Status: Inactive` +3. Adjunta política JSON de `Deny *` como contención inmediata +4. Publica resultado en SNS + +**ARN:** `arn:aws:lambda:us-east-1:000000000000:function:tesis-revoke-credentials` + +--- + +### 4.4 `tesis-isolate-instance` + +**Rol:** Registra la instancia comprometida en `s3://tesis-security-logs/responses/quarantine-instances.json` y notifica. +**Equivalente real AWS:** Reemplazar Security Group por uno vacío + tomar snapshot EBS. + +**Resultado en S3:** +```json +[ + { + "resource": "ec2:instance/i-0abc123def456", + "isolated_at": "2026-04-21T01:00:xx Z", + "reason": "EXFILTRATION", + "actions_applied": [ + "security_group_removed", + "deny_all_policy_applied", + "snapshot_triggered" + ] + } +] +``` + +**ARN:** `arn:aws:lambda:us-east-1:000000000000:function:tesis-isolate-instance` + +--- + +### 4.5 `tesis-notify-alert` (existía, sin cambios) + +**Rol:** Construye y publica el mensaje de alerta al tópico SNS. +**ARN:** `arn:aws:lambda:us-east-1:000000000000:function:tesis-notify-alert` + +--- + +## 5. Event Source Mapping — La Pieza Clave + +```bash +awslocal lambda create-event-source-mapping \ + --function-name tesis-dispatcher \ + --event-source-arn arn:aws:sqs:us-east-1:000000000000:tesis-incident-queue \ + --batch-size 1 +``` + +| Campo | Valor | +|-------|-------| +| UUID | `71e87db4-3ed3-4d73-8830-ebba22aec20d` | +| Estado | `Enabled` | +| Fuente | `arn:aws:sqs:us-east-1:000000000000:tesis-incident-queue` | +| Destino | `tesis-dispatcher` | +| Batch size | 1 mensaje por invocación | + +**Efecto:** Cuando `inject_logs.py` publica en SQS, LocalStack detecta el mensaje y dispara `tesis-dispatcher` automáticamente, sin ningún comando manual adicional. + +--- + +## 6. Prueba del Flujo Automático Completo + +### Comando ejecutado + +```bash +.venv/bin/python3 simulators/inject_logs.py brute-force +``` + +### Secuencia automática resultante + +``` +1. inject_logs.py → SQS: tesis-incident-queue (mensaje BRUTE_FORCE) +2. Event Source Mapping → dispara tesis-dispatcher automáticamente +3. dispatcher lee incident_type=BRUTE_FORCE +4. dispatcher invoca tesis-notify-alert → SUCCESS (SNS publicado) +5. dispatcher invoca tesis-block-ip → SUCCESS (S3 blocklist actualizado) +6. Mensajes en cola después: 0 (consumido y procesado) +``` + +### Log del dispatcher (CloudWatch) + +``` +START RequestId: 1e250e37-... Version: $LATEST +[dispatcher] Incidente: BRUTE_FORCE (HIGH) → playbooks: ['tesis-notify-alert', 'tesis-block-ip'] +[dispatcher] tesis-notify-alert → success +[dispatcher] tesis-block-ip → success +END RequestId: 1e250e37-... +REPORT Duration: 2220.58 ms Billed Duration: 2221 ms Memory: 128 MB +``` + +### Evidencias en S3 + +```bash +# Ver IPs bloqueadas: +.venv/bin/awslocal s3 cp s3://tesis-security-logs/responses/blocked-ips.json - + +# Ver instancias en cuarentena (tras simular exfiltration): +.venv/bin/awslocal s3 cp s3://tesis-security-logs/responses/quarantine-instances.json - + +# Ver todos los archivos de respuesta: +.venv/bin/awslocal s3 ls s3://tesis-security-logs/responses/ +``` + +--- + +## 7. Cómo Verificar Cada Parte del Flujo Tú Mismo + +### Ver el log de cualquier Lambda + +```bash +# Reemplaza NOMBRE por: tesis-dispatcher, tesis-block-ip, tesis-notify-alert, etc. +NOMBRE=tesis-dispatcher +STREAM=$(.venv/bin/awslocal logs describe-log-streams \ + --log-group-name /aws/lambda/$NOMBRE \ + --order-by LastEventTime --descending \ + --query 'logStreams[0].logStreamName' --output text) + +.venv/bin/awslocal logs get-log-events \ + --log-group-name /aws/lambda/$NOMBRE \ + --log-stream-name "$STREAM" \ + --query 'events[].message' --output text +``` + +### Simular cualquier tipo de incidente + +```bash +# Tipos: brute-force | privilege-escalation | credential-leak | exfiltration | port-scan +.venv/bin/python3 simulators/inject_logs.py credential-leak +.venv/bin/python3 simulators/inject_logs.py privilege-escalation +.venv/bin/python3 simulators/inject_logs.py exfiltration +``` + +Cada uno disparará automáticamente el playbook correspondiente en ~2-3 segundos. + +### Ver el estado del Event Source Mapping + +```bash +.venv/bin/awslocal lambda list-event-source-mappings \ + --function-name tesis-dispatcher \ + --query 'EventSourceMappings[0].[UUID,State,EventSourceArn]' --output text +``` + +### Ver todas las Lambdas desplegadas + +```bash +.venv/bin/awslocal lambda list-functions \ + --query 'Functions[].[FunctionName,Runtime]' --output table +``` + +--- + +## 8. Archivos Creados en Esta Sesión + +| Archivo | Descripción | +|---------|-------------| +| `lambdas/dispatcher/handler.py` | Lambda central de enrutamiento por `incident_type` | +| `lambdas/dispatcher/policy.json` | Política IAM mínimo privilegio: `lambda:InvokeFunction` + SQS | +| `lambdas/dispatcher/test_event.json` | Evento de prueba para invocación manual | +| `lambdas/block-ip/handler.py` | Playbook: bloquea IP en S3 blocklist + SNS | +| `lambdas/block-ip/policy.json` | Política IAM: `s3:PutObject` en `responses/*` + SNS | +| `lambdas/block-ip/test_event.json` | Evento de prueba | +| `lambdas/isolate-instance/handler.py` | Playbook: cuarentena de instancia en S3 + SNS | +| `lambdas/isolate-instance/policy.json` | Política IAM: `s3:PutObject` en `responses/*` + SNS | +| `lambdas/isolate-instance/test_event.json` | Evento de prueba | + +--- + +## 9. Estado Final del Componente C + +``` +Simular incidente → S3 + SQS ✅ inject_logs.py +Detectar con DuckDB (≈ Athena) ✅ queries/detect_*.sql +Respuesta automática (dispatcher) ✅ Event Source Mapping SQS → Lambda + BRUTE_FORCE → notify + block-ip ✅ + CREDENTIAL_LEAK → notify + revoke-credentials ✅ + PRIVILEGE_ESC → notify + revoke-credentials ✅ + EXFILTRATION → notify + isolate-instance ✅ + PORT_SCAN → notify + block-ip ✅ +Evidencias de respuesta en S3 ✅ responses/blocked-ips.json + responses/quarantine-instances.json +Logs de ejecución en CloudWatch ✅ /aws/lambda/tesis-* +Principio de mínimo privilegio ✅ policy.json por playbook +``` + +--- + +## 10. Notas para la Tesis + +### Sobre `LAMBDA_EXECUTOR=docker` +Las Lambdas se ejecutan en contenedores Docker separados lanzados por LocalStack. Esto replica el modelo de ejecución de AWS Lambda real (contenedores efímeros, aislados, con su propio filesystem). La latencia de arranque en frío (~2 segundos) que se observa en los logs es equivalente al cold start real de AWS. + +### Sobre la simulación de block-ip e isolate-instance +En AWS real, `block-ip` actualizaría un WAF IP Set o una regla NACL, y `isolate-instance` modificaría el Security Group de EC2 a uno sin reglas. Ambos servicios requieren plan Pro en LocalStack. La implementación con S3 como almacén de estado es funcionalmente equivalente para demostrar el flujo de respuesta y es la práctica estándar en entornos de prueba sin licencia. + +### Sobre el Event Source Mapping +Esta es la forma nativa de AWS de conectar SQS con Lambda. En producción, cuando `batch-size=1`, cada mensaje SQS genera exactamente una invocación de Lambda. Si la Lambda falla (excepción no manejada), el mensaje retorna a la cola hasta `maxReceiveCount=3`, tras lo cual va al DLQ (`tesis-incident-queue-dlq`). Esto garantiza que ningún incidente se pierda silenciosamente. + +### Limitación conocida +LocalStack no persiste estado entre reinicios. Al reiniciar Docker, ejecutar en orden: +```bash +source activate.sh +docker compose up -d +bash infra/setup.sh +# Re-desplegar las 5 Lambdas con el script de deploy +# Re-crear el Event Source Mapping +``` diff --git a/docker-compose.yml b/docker-compose.yml index dcee7cb..6740df3 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -12,6 +12,7 @@ services: - SERVICES=s3,sns,sqs,lambda,iam,logs,cloudwatch,events - 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" diff --git a/lambdas/block-ip/handler.py b/lambdas/block-ip/handler.py new file mode 100644 index 0000000..75e054b --- /dev/null +++ b/lambdas/block-ip/handler.py @@ -0,0 +1,90 @@ +""" +Playbook: block-ip +Registra la IP atacante en S3 (blocklist) y notifica al equipo via SNS. +En producción real: actualizaría un WAF IP Set o Security Group. +En LocalStack Community (sin WAF/EC2): persiste en S3 como fuente de verdad. +""" +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_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 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. Actualizar blocklist en S3 + blocklist = _load_blocklist() + entry = { + "ip": ip, + "blocked_at": timestamp, + "reason": incident_type, + "severity": severity, + "affectedResource": body.get("affectedResource", ""), + } + if not any(e["ip"] == ip for e in blocklist): + blocklist.append(entry) + s3.put_object( + Bucket=BUCKET, + Key="responses/blocked-ips.json", + Body=json.dumps(blocklist, indent=2).encode(), + ContentType="application/json", + ) + action = "ip_blocked" + print(f"[block-ip] IP {ip} añadida al blocklist ({len(blocklist)} IPs bloqueadas)") + else: + action = "ip_already_blocked" + print(f"[block-ip] IP {ip} ya estaba en el blocklist") + + # 2. Notificar al equipo + result = { + "playbook": "block-ip", + "action": action, + "ip": ip, + "status": "BLOCKED", + "timestamp": timestamp, + } + sns.publish( + TopicArn=SNS_ARN, + Subject=f"[{severity}] IP bloqueada: {ip}", + 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(), + } diff --git a/lambdas/block-ip/policy.json b/lambdas/block-ip/policy.json new file mode 100644 index 0000000..2502a1f --- /dev/null +++ b/lambdas/block-ip/policy.json @@ -0,0 +1,23 @@ +{ + "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:*" + } + ] +} diff --git a/lambdas/block-ip/test_event.json b/lambdas/block-ip/test_event.json new file mode 100644 index 0000000..867d145 --- /dev/null +++ b/lambdas/block-ip/test_event.json @@ -0,0 +1,12 @@ +{ + "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" + } + ] +} diff --git a/lambdas/dispatcher/handler.py b/lambdas/dispatcher/handler.py new file mode 100644 index 0000000..2531814 --- /dev/null +++ b/lambdas/dispatcher/handler.py @@ -0,0 +1,89 @@ +""" +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(), + } diff --git a/lambdas/dispatcher/policy.json b/lambdas/dispatcher/policy.json new file mode 100644 index 0000000..740e89d --- /dev/null +++ b/lambdas/dispatcher/policy.json @@ -0,0 +1,32 @@ +{ + "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:*" + } + ] +} diff --git a/lambdas/dispatcher/test_event.json b/lambdas/dispatcher/test_event.json new file mode 100644 index 0000000..6831e30 --- /dev/null +++ b/lambdas/dispatcher/test_event.json @@ -0,0 +1,12 @@ +{ + "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" + } + ] +} diff --git a/lambdas/isolate-instance/handler.py b/lambdas/isolate-instance/handler.py new file mode 100644 index 0000000..fe5421e --- /dev/null +++ b/lambdas/isolate-instance/handler.py @@ -0,0 +1,89 @@ +""" +Playbook: isolate-instance +Registra la instancia comprometida en S3 (quarantine list) y notifica via SNS. +En producción real: desasociaría Security Groups y aplicaría política de cuarentena EC2. +En LocalStack Community (sin EC2 habilitado): persiste estado en S3. +""" +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 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() + + # 1. Registrar en lista de cuarentena en S3 + quarantine = _load_quarantine() + entry = { + "resource": resource, + "isolated_at": timestamp, + "reason": incident_type, + "severity": severity, + "sourceIPAddress": source_ip, + "actions_applied": [ + "security_group_removed", # simulado + "deny_all_policy_applied", # simulado + "snapshot_triggered", # simulado + ], + } + 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} en cuarentena") + + # 2. Notificar al equipo + result = { + "playbook": "isolate-instance", + "action": "instance_isolated", + "resource": resource, + "status": "QUARANTINED", + "timestamp": timestamp, + } + sns.publish( + TopicArn=SNS_ARN, + Subject=f"[{severity}] Instancia aislada: {resource}", + Message=json.dumps(result, indent=2), + ) + + results.append({"status": "success", "action": "instance_isolated", "details": result}) + + return { + "status": "success", + "processed": len(results), + "results": results, + "timestamp": datetime.now(timezone.utc).isoformat(), + } diff --git a/lambdas/isolate-instance/policy.json b/lambdas/isolate-instance/policy.json new file mode 100644 index 0000000..50d22d8 --- /dev/null +++ b/lambdas/isolate-instance/policy.json @@ -0,0 +1,23 @@ +{ + "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:*" + } + ] +} diff --git a/lambdas/isolate-instance/test_event.json b/lambdas/isolate-instance/test_event.json new file mode 100644 index 0000000..73cdcaa --- /dev/null +++ b/lambdas/isolate-instance/test_event.json @@ -0,0 +1,12 @@ +{ + "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" + } + ] +} diff --git a/lambdas/notify-alert/handler.py b/lambdas/notify-alert/handler.py index e527a3b..b498470 100644 --- a/lambdas/notify-alert/handler.py +++ b/lambdas/notify-alert/handler.py @@ -8,7 +8,10 @@ import os import boto3 from datetime import datetime, timezone -ENDPOINT = os.environ.get("AWS_ENDPOINT_URL", "http://localhost:4566") +# 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") diff --git a/lambdas/revoke-credentials/handler.py b/lambdas/revoke-credentials/handler.py index eb83f8a..7e0cc11 100644 --- a/lambdas/revoke-credentials/handler.py +++ b/lambdas/revoke-credentials/handler.py @@ -8,7 +8,9 @@ import os import boto3 from datetime import datetime, timezone -ENDPOINT = os.environ.get("AWS_ENDPOINT_URL", "http://localhost:4566") +# LOCALSTACK_HOSTNAME es inyectada por LocalStack en contenedores Lambda (Docker executor) +_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") iam = boto3.client("iam", endpoint_url=ENDPOINT, region_name=REGION) diff --git a/queries/detect_brute_force.sql b/queries/detect_brute_force.sql index 8e888fc..e7a0ad3 100644 --- a/queries/detect_brute_force.sql +++ b/queries/detect_brute_force.sql @@ -1,18 +1,20 @@ -- 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 - 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 + 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; diff --git a/queries/detect_exfiltration.sql b/queries/detect_exfiltration.sql index 617d88d..b66f247 100644 --- a/queries/detect_exfiltration.sql +++ b/queries/detect_exfiltration.sql @@ -1,16 +1,19 @@ -- 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 - 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 + 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; diff --git a/queries/detect_privilege_esc.sql b/queries/detect_privilege_esc.sql index 3fc45b4..1f3738c 100644 --- a/queries/detect_privilege_esc.sql +++ b/queries/detect_privilege_esc.sql @@ -1,15 +1,19 @@ -- 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 - userIdentity.userName AS username, - sourceIPAddress, - eventName, - eventTime, - requestParameters -FROM read_json_auto('$LOG_PATH', format='array') -WHERE eventSource = 'iam.amazonaws.com' - AND eventName IN ( + 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', @@ -18,5 +22,4 @@ WHERE eventSource = 'iam.amazonaws.com' 'CreateLoginProfile', 'UpdateLoginProfile' ) - AND epoch_ms(eventTime) >= now() - INTERVAL '24 hours' -ORDER BY eventTime DESC; +ORDER BY r.eventTime DESC; diff --git a/simulators/__pycache__/cloudtrail_gen.cpython-314.pyc b/simulators/__pycache__/cloudtrail_gen.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aad8268fc085811ad5b92006934e1896d0827f7a GIT binary patch literal 8488 zcmc&(Yit`=cAgQ3)@#7Y!flemK?5`ejCPBrNVe^dML~n!H8TmiE}B2-FS%}E zVE?q|+~JV4qilj~yS)JKJ@Q2EXaN#DMhkP&O zU65{t)GgSzFoI(XlWEmGLZ9G-9FMsSt9ylQf(!EQYTgHV59Gboe6tV~e2{Oh=3Ah? z1@f)ce5>GJ@d|A#KB0Z3S?E}45js~|BX-@t(k66Gz05G_KV_I+^K07m_LYu)W~Dtg zY<+k=-Nl;nDR%06(5nM`ZQk+}`)p6W-vTT6^{y3vEK)DCq?ImfRK0tpduO$HbuS$| z(9Z~4gzngGt93nH@mu}8%tRBc;<GxiRi%PO;WF(5Abe*;TF9 zx30kKD{SnA#`dNR6^$`Si0Pe&96Y9_Z4YYM1loW}GX_W-iQc$`eDY~i! zXEJI&9Veok32JgSpMiQU?2ZvNoli-@jJm1?4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--2g)plAnNC3CRcg&t`vGpcUq~ZfZ|*RK*+Aqp=m; zmM0xy7J2y%Y{wdPO4Pi_VDrI+%-NTbP}1;}&F27hcUbBUGy@z>0@#59?_&hlgdLq= zNNOUsFbnOPse*Ew5uAj>`U0@VUTCn!TJoq&mNk}#$59J{Djqw1PD<(MRR-%R4{t1` zCaBWjWX{T3Rz%$%k}fr9F=7BXfmIFE*;N~((5g*trp1OWDl8U!7Rk^ir>Cb2z6cB; zMhIAJB%L&DW4qD?d-$9N&nS3^Yru*^fH%<{w~u^riC`w@2}$kH8uc^ z&S1eRMs+2h#q1nLRNYZGs#cV#@m}kTDFpz7ouOCq8VE(^ld8S6yX@=V^yx=iY4@wk zmaQ~WibTua{a`C~_kxWxeAV~B>tEmZX4jkiJH9*Od$v0#-aAkV9HtH;a2}Nc!=Tj9 zxHlNC$75PY8*awcQn!lyOmojh$8XOn3RSHlv^J?qf8p!=2hg(iI(t!rAwms?YFh4w1<%8bIjL9PYuL$-ozd@MW` z9uJT2u8I@k$+3cOeD6ef{JANt7#j<51@FYzB(@u$4DXu2>Z$NJje=yj(2I5y{uhWhn0DyNqP7?%Uj(=8MUosPSnTh`ZEAVBuXs>v>);%Tnj-u1>O%+{+?^x0OUk>=A@9{AB$RF&lL6!>i(a}WN4+xf5^-YB|3{{wjV3l{(Y literal 0 HcmV?d00001 diff --git a/simulators/inject_logs.py b/simulators/inject_logs.py index 7418531..6983892 100644 --- a/simulators/inject_logs.py +++ b/simulators/inject_logs.py @@ -18,8 +18,13 @@ 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) +_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", From d5075487239c20dea18627093e3366fcc2dfc302 Mon Sep 17 00:00:00 2001 From: bryancito1090 Date: Mon, 18 May 2026 11:29:31 -0500 Subject: [PATCH 2/9] add documentation and demo scripts for the brute-force attack simulation and automated response workflow. --- 12/05/2026/demo_profesor_2026-05-12.md | 81 ++++ .../presentacion_bruteforce_2026-05-12.md | 390 ++++++++++++++++++ 28/04/2026/diseno_flujos_automaticos.md | 98 +++++ 28/04/2026/perspectiva_atacante_incidente.md | 167 ++++++++ 4 files changed, 736 insertions(+) create mode 100644 12/05/2026/demo_profesor_2026-05-12.md create mode 100644 12/05/2026/presentacion_bruteforce_2026-05-12.md create mode 100644 28/04/2026/diseno_flujos_automaticos.md create mode 100644 28/04/2026/perspectiva_atacante_incidente.md diff --git a/12/05/2026/demo_profesor_2026-05-12.md b/12/05/2026/demo_profesor_2026-05-12.md new file mode 100644 index 0000000..10e0e78 --- /dev/null +++ b/12/05/2026/demo_profesor_2026-05-12.md @@ -0,0 +1,81 @@ +# Demo Brute-Force — 2026-05-12 + +> Escribir los skills en el chat de Claude Code. Solo los últimos 2 pasos usan terminal. + +--- + +## Pasos en orden + +| # | Dónde | Qué escribir | Qué hace | +|---|-------|-------------|----------| +| 1 | Claude Code | `/localstack-up` | Levanta LocalStack y verifica servicios | +| 2 | Claude Code | `/bootstrap-resources` | Crea S3, SNS, SQS e IAM | +| 3 | Claude Code | `/deploy-lambda notify-alert` | Despliega playbook de alertas | +| 4 | Claude Code | `/deploy-lambda block-ip` | Despliega playbook de bloqueo de IPs | +| 5 | Claude Code | `/deploy-lambda dispatcher` | Despliega el coordinador de playbooks | +| 6 | Claude Code | `/simulate-incident brute-force` | Genera el ataque y lo sube a S3 + SQS | +| 7 | Claude Code | `/query-logs brute-force` | Detecta el IoC con SQL (equivale a Athena) | +| 8 | Terminal | ver abajo | Activa la respuesta automática | +| 9 | Terminal | ver abajo | Muestra los archivos generados | + +--- + +## Paso 8 — Activar respuesta automática (terminal) + +```bash +cd ~/localstack-tesis && source activate.sh +.venv/bin/awslocal lambda invoke \ + --function-name tesis-dispatcher \ + --cli-binary-format raw-in-base64-out \ + --payload file://lambdas/dispatcher/test_event.json \ + /tmp/respuesta-dispatcher.json +python3 -m json.tool /tmp/respuesta-dispatcher.json +``` + +--- + +## Paso 9 — Ver archivos generados (terminal) + +```bash +# Qué hay en S3 +.venv/bin/awslocal s3 ls s3://tesis-security-logs/ --recursive + +# IP bloqueada +.venv/bin/awslocal s3 cp s3://tesis-security-logs/responses/blocked-ips.json - | python3 -m json.tool + +# Logs de las Lambdas +for fn in tesis-dispatcher tesis-notify-alert tesis-block-ip; do + echo "=== $fn ===" + stream=$(.venv/bin/awslocal logs describe-log-streams \ + --log-group-name /aws/lambda/$fn \ + --query 'logStreams[-1].logStreamName' --output text 2>/dev/null) + [ "$stream" != "None" ] && .venv/bin/awslocal logs get-log-events \ + --log-group-name /aws/lambda/$fn --log-stream-name "$stream" \ + --query 'events[].message' --output text 2>/dev/null +done +``` + +--- + +## Archivos generados por el sistema + +| Archivo | Dónde | Lo crea | +|---------|-------|---------| +| `cloudtrail/.../brute-force-XXXX.json` | S3 `tesis-security-logs` | Paso 6 — `/simulate-incident` | +| `responses/blocked-ips.json` | S3 `tesis-security-logs` | Paso 8 — Lambda `block-ip` | +| `/tmp/respuesta-dispatcher.json` | Disco local | Paso 8 — `lambda invoke` | +| Logs de ejecución | CloudWatch `/aws/lambda/tesis-*` | Pasos 3–5 y 8 | + +--- + +## Para la presentación — leer estos archivos + +| Qué explica | Archivo | +|-------------|---------| +| Flujo completo con diagrama y detalle de cada playbook | `presentacion_bruteforce_2026-05-12.md` | +| Pasos de la demo (este archivo) | `demo_profesor_2026-05-12.md` | +| Análisis técnico completo con hallazgos y correcciones | `analisis_flujo1_bruteforce.md` | + +--- + +> Si algo falla: repetir el skill del paso que falló. Si LocalStack se reinició, empezar desde el Paso 1. diff --git a/12/05/2026/presentacion_bruteforce_2026-05-12.md b/12/05/2026/presentacion_bruteforce_2026-05-12.md new file mode 100644 index 0000000..b939177 --- /dev/null +++ b/12/05/2026/presentacion_bruteforce_2026-05-12.md @@ -0,0 +1,390 @@ +# Ataque de Fuerza Bruta — Flujo Completo del Sistema +**Fecha:** 2026-05-12 | **Componente C — Automatización de Respuesta** | **Bryan** + +--- + +## ¿Qué es este escenario? + +Un atacante externo intenta adivinar la contraseña de un usuario IAM de AWS haciendo **10 intentos de login fallidos en ~2 minutos** desde la IP `185.220.101.5`. + +El sistema detecta el patrón, genera una alerta y **toma acciones automáticas de contención** — todo sin intervención humana. + +--- + +## Flujo de extremo a extremo + +``` +┌──────────────────────────────────────────────────────────────────────┐ +│ FASE 1 — ATAQUE │ +│ │ +│ Atacante 185.220.101.5 │ +│ │ 10x ConsoleLogin FAILED (AccessDenied) │ +│ │ usuario: admin │ ventana: ~2 minutos │ +│ ▼ │ +│ cloudtrail_gen.py → genera 10 eventos JSON con estructura real │ +│ inject_logs.py → empaqueta y distribuye los eventos │ +│ ├──▶ S3: cloudtrail/2026/.../brute-force-XXXX.json│ +│ └──▶ SQS: tesis-incident-queue (payload)│ +└──────────────────────────────────────────────────────────────────────┘ + │ │ +┌─────────────────────────▼──┐ ┌─────────────────▼─────────────────┐ +│ FASE 2 — DETECCIÓN │ │ FASE 3 — AUTOMATIZACIÓN │ +│ │ │ │ +│ queries/detect_brute_ │ │ Lambda: dispatcher │ +│ force.sql (DuckDB) │ │ ├──▶ tesis-notify-alert │ +│ │ │ └──▶ tesis-block-ip │ +│ SQL descarga logs de S3 │ │ │ +│ y detecta el IoC: │ │ Resultados guardados en S3: │ +│ ▸ misma IP │ │ responses/blocked-ips.json │ +│ ▸ mismo usuario │ │ │ +│ ▸ +5 intentos fallidos │ │ Notificación publicada en SNS: │ +│ ▸ ventana < 5 min │ │ tesis-security-alerts │ +└──────────────────────────────┘ └────────────────────────────────────┘ +``` + +--- + +## Fase 1 — El ataque y cómo se inyecta al sistema + +### Archivos que intervienen + +| Archivo | Qué hace | +|---------|----------| +| `simulators/cloudtrail_gen.py` | **Genera** los 10 eventos JSON con estructura idéntica a CloudTrail real | +| `simulators/inject_logs.py` | **Orquesta**: llama al generador, sube a S3 y envía el payload a SQS | + +### ¿Qué genera `cloudtrail_gen.py`? + +La función `brute_force()` produce **10 eventos**, uno cada 15 segundos, con esta estructura: + +```json +{ + "eventVersion": "1.08", + "eventName": "ConsoleLogin", + "eventSource": "signin.amazonaws.com", + "errorCode": "AccessDenied", + "errorMessage": "Failed authentication", + "sourceIPAddress": "185.220.101.5", + "userIdentity": { + "type": "IAMUser", + "userName": "admin" + }, + "responseElements": { + "ConsoleLogin": "Failure" + } +} +``` + +> Este JSON es sintético pero tiene la **misma estructura** que un log real de AWS CloudTrail. El campo `eventName=ConsoleLogin` + `errorCode=AccessDenied` es la firma del intento fallido. + +### ¿Qué hace `inject_logs.py`? + +Toma esos 10 eventos y hace dos cosas: + +**1. Los sube a S3** como archivo JSON (simula cómo CloudTrail almacena logs reales): +``` +s3://tesis-security-logs/cloudtrail/2026/05/12/brute-force-51cbb9f1.json +``` + +**2. Envía un mensaje a SQS** con el resumen del incidente (el payload que activa la Lambda): +```json +{ + "incident_type": "BRUTE_FORCE", + "severity": "HIGH", + "sourceIPAddress": "185.220.101.5", + "affectedResource": "iam:user/admin", + "s3_log_key": "cloudtrail/2026/05/12/.../brute-force-51cbb9f1.json", + "event_count": 10, + "timestamp": "2026-05-12T..." +} +``` + +--- + +## Fase 2 — La detección (DuckDB / equivalente a Athena) + +### Archivo que interviene + +| Archivo | Qué hace | +|---------|----------| +| `queries/detect_brute_force.sql` | Query SQL que analiza los logs y detecta el patrón de fuerza bruta | + +### La consulta SQL + +```sql +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') -- Lee el JSON descargado de S3 +) +WHERE r.eventName = 'ConsoleLogin' + AND r.errorCode = 'AccessDenied' -- Solo intentos fallidos +GROUP BY r.sourceIPAddress, r.userIdentity.userName +HAVING COUNT(*) > 5 -- Umbral: más de 5 intentos +ORDER BY failed_attempts DESC; +``` + +### Resultado que obtiene + +| sourceIPAddress | username | failed_attempts | first_attempt | last_attempt | +|----------------|----------|-----------------|---------------|--------------| +| 185.220.101.5 | admin | **10** | 2026-05-12T...Z | 2026-05-12T...Z | + +``` +IoC detectado: 1 dirección IP atacante +Regla disparada: ConsoleLogin + AccessDenied > 5 intentos en ~2 min +Acción recomendada: notify-alert + block-ip +``` + +> **¿Por qué DuckDB?** En AWS real se usaría Amazon Athena. En el entorno local, DuckDB lee los mismos archivos JSON directamente sin necesidad de internet ni costo. + +--- + +## Fase 3 — La automatización (Playbooks Lambda) + +### La cadena de respuesta automática + +``` +SQS: tesis-incident-queue + │ (payload BRUTE_FORCE) + ▼ +Lambda: dispatcher + ├──▶ Lambda: notify-alert → publica alerta en SNS + └──▶ Lambda: block-ip → registra IP en S3 + notifica SNS +``` + +### Archivos que intervienen + +| Archivo | Playbook | Qué hace | +|---------|----------|----------| +| `lambdas/dispatcher/handler.py` | dispatcher | Recibe el evento SQS, lee el tipo de incidente y llama a los playbooks correctos | +| `lambdas/notify-alert/handler.py` | notify-alert | Publica una alerta estructurada al tópico SNS del equipo | +| `lambdas/block-ip/handler.py` | block-ip | Añade la IP atacante a la lista de bloqueo en S3 y notifica | + +--- + +### Playbook 1: `dispatcher` +**Archivo:** `lambdas/dispatcher/handler.py` + +**Rol:** El cerebro de la automatización. Es la única Lambda que escucha directamente la cola SQS. Su trabajo es leer `incident_type` del payload y decidir qué playbooks ejecutar. + +**Tabla de enrutamiento interna:** +``` +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 +``` + +Para brute-force, ejecuta en secuencia `notify-alert` y luego `block-ip`, pasándole el mismo payload SQS original. El dispatcher **no toma acciones directas** — solo enruta. + +--- + +### Playbook 2: `notify-alert` +**Archivo:** `lambdas/notify-alert/handler.py` + +**Rol:** Primera respuesta ante cualquier incidente. Construye un mensaje de alerta estructurado y lo publica al canal SNS del equipo de seguridad. + +**¿Qué recibe?** +El payload SQS con `incident_type`, `severity`, `sourceIPAddress`, `affectedResource`. + +**¿Qué hace paso a paso?** +1. Extrae los campos del payload SQS +2. Construye un objeto de alerta con campos como `alert_type`, `detectedAt`, `respondedAt`, `playbook`, `status` +3. Llama a `sns.publish()` hacia `tesis-security-alerts` +4. Registra en CloudWatch: `[notify-alert] Alerta publicada: BRUTE_FORCE desde 185.220.101.5` + +**Salida que produce (al tópico SNS):** +```json +{ + "alert_type": "SECURITY_INCIDENT", + "incident_type": "BRUTE_FORCE", + "severity": "HIGH", + "sourceIPAddress": "185.220.101.5", + "affectedResource": "iam:user/admin", + "detectedAt": "2026-05-12T...", + "respondedAt": "2026-05-12T...", + "playbook": "notify-alert", + "status": "NOTIFIED" +} +``` + +**En AWS real:** este mensaje llegaría por email, SMS, o Slack vía suscripción SNS. + +--- + +### Playbook 3: `block-ip` +**Archivo:** `lambdas/block-ip/handler.py` + +**Rol:** Contención técnica. Registra la IP atacante en una lista persistente en S3 y notifica al equipo. + +**¿Qué hace paso a paso?** +1. Lee el archivo `responses/blocked-ips.json` de S3 (la lista actual de IPs bloqueadas) +2. Verifica que la IP no esté ya bloqueada (evita duplicados) +3. Añade una nueva entrada con IP, fecha, motivo y severidad +4. Sube el archivo actualizado de vuelta a S3 +5. Publica notificación al tópico SNS + +**En AWS real:** en lugar de solo guardar en S3, actualizaría un **WAF IP Set** o modificaría **Security Groups** para bloquear el tráfico a nivel de red. + +--- + +### Playbook extra referenciado: `revoke-credentials` +**Archivo:** `lambdas/revoke-credentials/handler.py` +*(No se activa en brute-force, pero está disponible para credential-leak y privilege-escalation)* + +**¿Qué hace?** +1. Lista todas las access keys del usuario IAM comprometido +2. Desactiva cada key (`Status=Inactive` en IAM) +3. Adjunta una política `EmergencyDenyAll` al usuario (bloqueo total inmediato) +4. Notifica al equipo vía SNS + +--- + +### Playbook extra referenciado: `isolate-instance` +**Archivo:** `lambdas/isolate-instance/handler.py` +*(Se activa para exfiltration)* + +**¿Qué hace?** +1. Lee la lista de instancias en cuarentena de S3 +2. Registra la instancia comprometida con fecha y razón +3. Simula 3 acciones: remover Security Group, aplicar DenyAll, disparar snapshot +4. Persiste en S3 y notifica vía SNS + +--- + +## Archivos que genera la automatización + +Estos son todos los archivos/objetos que el sistema **crea o modifica** como resultado del flujo brute-force: + +### En S3 (`tesis-security-logs`) + +| Ruta en S3 | Tipo | De dónde viene | Qué contiene | +|-----------|------|----------------|--------------| +| `cloudtrail/2026/05/12/HHMMSS/brute-force-XXXX.json` | JSON creado | `inject_logs.py` sube el output de `cloudtrail_gen.py` | Los 10 eventos CloudTrail simulados con estructura `{"Records": [...]}` | +| `responses/blocked-ips.json` | JSON creado/actualizado | Playbook `block-ip` lo escribe después de ejecutarse | Lista acumulativa de IPs bloqueadas con fecha, motivo y severidad | + +**Ejemplo de `blocked-ips.json`:** +```json +[ + { + "ip": "185.220.101.5", + "blocked_at": "2026-05-12T...", + "reason": "BRUTE_FORCE", + "severity": "HIGH", + "affectedResource": "iam:user/admin" + } +] +``` + +> Este archivo persiste entre ejecuciones. Cada nuevo ataque detectado **añade una entrada** sin borrar las anteriores. Es el registro histórico de IPs bloqueadas. + +### En SNS (`tesis-security-alerts`) + +| Qué se publica | Lo publica | Cuándo | +|----------------|-----------|--------| +| Alerta JSON estructurada (`status: NOTIFIED`) | `notify-alert` | Inmediatamente al detectar el incidente | +| Confirmación de bloqueo (`status: BLOCKED`) | `block-ip` | Tras registrar la IP en S3 | + +> En el entorno local SNS actúa como un bus de mensajes. En AWS real, estos mensajes se entregarían a suscriptores: email, SMS, Lambda adicional, HTTP endpoint. + +### En CloudWatch Logs + +| Log Group | Lo escribe | Qué registra | +|-----------|-----------|--------------| +| `/aws/lambda/tesis-dispatcher` | Lambda dispatcher | Qué incidente recibió y qué playbooks invocó | +| `/aws/lambda/tesis-notify-alert` | Lambda notify-alert | Confirmación de alerta publicada | +| `/aws/lambda/tesis-block-ip` | Lambda block-ip | Qué IP fue bloqueada y si ya estaba en la lista | + +**Ejemplo de log en CloudWatch:** +``` +START RequestId: abc123... +[dispatcher] Incidente: BRUTE_FORCE (HIGH) → playbooks: ['tesis-notify-alert', 'tesis-block-ip'] +[dispatcher] tesis-notify-alert → success +[dispatcher] tesis-block-ip → success +END RequestId: abc123... +REPORT Duration: 312 ms Billed Duration: 313 ms Memory: 128 MB +``` + +--- + +## Mapa completo de archivos del proyecto en este flujo + +``` +localstack-tesis/ +│ +├── simulators/ +│ ├── cloudtrail_gen.py ← PASO 1: genera los eventos JSON del ataque +│ └── inject_logs.py ← PASO 2: sube a S3 y envía a SQS +│ +├── queries/ +│ └── detect_brute_force.sql ← PASO 3: SQL que detecta el patrón +│ +├── lambdas/ +│ ├── dispatcher/ +│ │ └── handler.py ← PASO 4a: enruta el incidente a los playbooks +│ ├── notify-alert/ +│ │ ├── handler.py ← PASO 4b: publica la alerta a SNS +│ │ └── test_event.json ← evento de prueba para invocar la Lambda +│ └── block-ip/ +│ ├── handler.py ← PASO 4c: registra IP en S3 y notifica +│ └── test_event.json ← evento de prueba para invocar la Lambda +│ +└── infra/ + └── setup.sh ← crea S3, SNS, SQS, IAM antes de todo + +── ARCHIVOS GENERADOS POR EL SISTEMA ────────────────────────────────── +S3: cloudtrail/2026/.../brute-force-XXXX.json ← log del ataque +S3: responses/blocked-ips.json ← lista de IPs bloqueadas +SNS: tesis-security-alerts ← mensajes de alerta +CloudWatch: /aws/lambda/tesis-* ← logs de ejecución +``` + +--- + +## Resumen visual del flujo en 5 pasos + +``` +PASO 1 Ataque simulado + cloudtrail_gen.py genera 10 eventos ConsoleLogin+AccessDenied + inject_logs.py los sube a S3 y al canal SQS + +PASO 2 Almacenamiento + S3: cloudtrail/brute-force-XXXX.json (7 KB de logs) + SQS: payload JSON con incident_type=BRUTE_FORCE, severity=HIGH + +PASO 3 Detección + detect_brute_force.sql descarga el JSON de S3 y lo analiza + DuckDB agrupa por IP + usuario, cuenta intentos fallidos + Umbral superado: 10 intentos > 5 → IoC confirmado + +PASO 4 Automatización + SQS activa la Lambda dispatcher + dispatcher lee BRUTE_FORCE y llama a: + └─ notify-alert → alerta en SNS → status: NOTIFIED + └─ block-ip → IP en S3 → status: BLOCKED + +PASO 5 Evidencia generada + S3: responses/blocked-ips.json (registro de la IP bloqueada) + SNS: 2 mensajes publicados (alerta + confirmación bloqueo) + CloudWatch: logs de ejecución de cada Lambda con duración y estado +``` + +--- + +## ¿Qué pasaría en AWS real? + +| Entorno local (LocalStack) | AWS real equivalente | +|---------------------------|---------------------| +| `cloudtrail_gen.py` genera eventos JSON | CloudTrail captura automáticamente las llamadas a la API | +| `inject_logs.py` sube a S3 local | CloudTrail entrega los logs a S3 automáticamente | +| DuckDB ejecuta SQL sobre el JSON | Amazon Athena consulta la tabla de CloudTrail en S3 | +| SQS activa Lambda manualmente | EventBridge Rule o SQS trigger automático activa la Lambda | +| `block-ip` guarda en `blocked-ips.json` en S3 | `block-ip` actualizaría un WAF IP Set o Security Group | +| SNS publica en tópico local | SNS entregaría email/SMS/webhook al equipo de seguridad | diff --git a/28/04/2026/diseno_flujos_automaticos.md b/28/04/2026/diseno_flujos_automaticos.md new file mode 100644 index 0000000..6e87dc6 --- /dev/null +++ b/28/04/2026/diseno_flujos_automaticos.md @@ -0,0 +1,98 @@ +# Diseño de Flujos Automáticos para la Respuesta al Incidente + +**Proyecto:** Trabajo de Integración Curricular — Sistema de Detección y Respuesta ante Incidentes en AWS +**Componente:** C — Automatización de Respuesta +**Responsable:** Bryan +**Fecha:** 2026-04-28 + +--- + +## ¿De qué trata este documento en una sola frase? + +Responde a esta pregunta: **¿cómo le decimos al sistema qué hacer automáticamente cuando detecta un ataque?** Y compara 3 formas de hacerlo. + +--- + +## La idea central + +Cuando el sistema detecta un ataque, necesita reaccionar solo, sin que nadie haga nada manualmente. Para eso necesita un "flujo" — una secuencia de pasos automáticos. Este documento compara 3 diseños posibles para ese flujo. + +--- + +## Diseño A — SNS Directo (el más simple, el que NO usamos) + +Cada tipo de ataque tiene su propio "botón de alarma" y ese botón activa directamente una acción. + +``` +Ataque de fuerza bruta → botón 1 → Lambda "bloquear IP" +Credencial robada → botón 2 → Lambda "revocar credenciales" +``` + +**¿Por qué no lo usamos?** +- Si se quieren hacer dos cosas ante un ataque (avisar Y bloquear), SNS no las encadena bien. +- Si la Lambda falla, el mensaje se pierde y nadie se entera. + +--- + +## Diseño B — SQS + Dispatcher (el que SÍ implementamos) + +Hay un "jefe coordinador" — la Lambda `dispatcher`. Funciona así: + +1. El simulador detecta un ataque y pone un mensaje en una **cola** (SQS). +2. La cola le avisa automáticamente al dispatcher. +3. El dispatcher lee el tipo de ataque y decide qué hacer. +4. Llama a los playbooks necesarios en orden. + +``` +Ataque detectado + → Cola SQS (guarda el mensaje) + → Dispatcher (lee el mensaje, decide) + → Primero avisa al equipo (notify-alert) + → Luego bloquea la IP (block-ip) +``` + +**¿Por qué es mejor?** +- Si algo falla, la cola guarda el mensaje y lo reintenta hasta 3 veces. +- Todo queda registrado en un solo lugar (logs del dispatcher). +- Agregar un nuevo tipo de ataque = agregar una línea en la tabla del dispatcher, nada más. + +**¿Qué es el "Event Source Mapping"?** +Es la conexión automática entre la cola SQS y el dispatcher. Le dice a AWS: *"cada vez que llegue un mensaje a esta cola, activa esta Lambda"*. No hay que hacer nada manualmente. + +--- + +## Diseño C — Step Functions (el más potente, el que NO podemos usar) + +Es como un diagrama de flujo visual con cajas y flechas, donde cada caja es un paso y si algo falla hay reintentos automáticos con espera entre intentos. + +**¿Por qué no lo usamos?** +- No está disponible en la versión gratuita de LocalStack. +- Es demasiado complejo para lo que necesita la tesis. + +--- + +## Decisiones de diseño + +**¿Por qué usamos SQS y no SNS para recibir los ataques?** +Porque SNS puede perder mensajes si la Lambda falla. SQS los guarda y reintenta. En seguridad no se puede permitir perder un incidente. + +**¿Por qué se procesa un mensaje a la vez?** +Porque si el dispatcher procesa dos ataques al mismo tiempo, podrían pisarse entre sí al escribir en el mismo archivo de S3. Uno a la vez es más seguro. + +**¿Por qué `notify-alert` va siempre primero?** +Porque aunque el bloqueo falle, el equipo ya fue avisado. Lo peor que puede pasar es que el bloqueo no funcione, pero al menos alguien sabe que hubo un ataque. + +--- + +## Resumen visual + +``` +Problema: ¿Cómo automatizar la respuesta a un ataque? + +Opción A: SNS → Lambda directa ← simple pero poco confiable +Opción B: SQS → Dispatcher → Lambdas ← lo que usamos, balance ideal +Opción C: Step Functions ← muy potente pero no disponible + +Lo que implementamos (Opción B): +Simulador → Cola SQS → Dispatcher → notify-alert + block-ip / revoke / isolate +``` diff --git a/28/04/2026/perspectiva_atacante_incidente.md b/28/04/2026/perspectiva_atacante_incidente.md new file mode 100644 index 0000000..1f129e5 --- /dev/null +++ b/28/04/2026/perspectiva_atacante_incidente.md @@ -0,0 +1,167 @@ +# Perspectiva del Atacante — Materialización del Incidente + +**Proyecto:** Trabajo de Integración Curricular — Sistema de Detección y Respuesta ante Incidentes en AWS +**Componente:** C — Automatización de Respuesta +**Responsable:** Bryan +**Fecha:** 2026-04-28 + +> **Nota:** Este documento tiene propósito académico. Describe cómo un atacante intentaría comprometer un entorno AWS y cómo el sistema del Componente C lo detecta y responde automáticamente. + +--- + +## La idea general + +El atacante no ve una pantalla con alertas diciéndole "te estamos vigilando". Desde su punto de vista, está interactuando con servicios normales de AWS — la consola web, una API, un bucket S3. Lo que no sabe es que cada acción que hace queda registrada en CloudTrail, y que el sistema está leyendo esos registros en tiempo real. + +``` +Atacante actúa sobre AWS + │ + ▼ +AWS registra todo en CloudTrail (log de cada acción) + │ + ▼ +El sistema lee los logs y busca patrones sospechosos + │ + ▼ +Si detecta algo → responde automáticamente +``` + +--- + +## Ataque 1 — Fuerza Bruta (BRUTE_FORCE) + +**¿Qué intenta el atacante?** +Entrar a la consola de AWS adivinando la contraseña de un usuario. Prueba combinaciones una por una: `admin123`, `Welcome1`, `P@ssw0rd`, etc. + +**¿Qué ve el atacante?** +Cada intento le devuelve un error de "credenciales incorrectas". Sigue probando. + +**¿Qué registra AWS?** +Cada intento fallido genera un evento `ConsoleLogin` con `errorCode: AccessDenied`. Tras 10 intentos desde la misma IP, el patrón es claro. + +**¿Cómo responde el sistema?** +``` +Detecta: +5 intentos fallidos desde la misma IP en menos de 5 minutos + → notify-alert: avisa al equipo de seguridad + → block-ip: registra la IP del atacante en la lista de bloqueados +``` + +**¿Qué siente el atacante?** +No sabe que fue detectado. Sus intentos siguen fallando, pero ahora también hay un equipo revisando su IP. + +--- + +## Ataque 2 — Credencial Robada (CREDENTIAL_LEAK) + +**¿Qué intenta el atacante?** +Encontró una `AWS_ACCESS_KEY_ID` y un `AWS_SECRET_ACCESS_KEY` expuestos en un repositorio público de GitHub. Con esas dos claves puede llamar a la API de AWS directamente, sin necesidad de contraseña. + +**¿Qué ve el atacante?** +Tiene acceso real. Puede listar buckets S3, ver recursos, ejecutar comandos. Cree que nadie lo sabe. + +**¿Qué registra AWS?** +Cada llamada a la API queda registrada con la key usada. El sistema detecta que esa key está siendo usada desde una IP desconocida o en horarios inusuales. + +**¿Cómo responde el sistema?** +``` +Detecta: uso de credencial comprometida + → notify-alert: avisa al equipo + → revoke-credentials: desactiva la access key inmediatamente +``` + +**¿Qué siente el atacante?** +A los pocos segundos, todos sus comandos empiezan a fallar con `InvalidClientTokenId`. La llave fue desactivada mientras la usaba. + +--- + +## Ataque 3 — Escalada de Privilegios (PRIVILEGE_ESCALATION) + +**¿Qué intenta el atacante?** +Ya tiene acceso a AWS con una cuenta de bajos privilegios (por ejemplo, un usuario que solo puede leer logs). Intenta darse a sí mismo permisos de administrador ejecutando comandos como `iam:AttachUserPolicy` o `iam:CreateRole`. + +**¿Qué ve el atacante?** +Está ejecutando comandos IAM que normalmente no debería poder usar. Intenta escalar sus permisos para tener control total de la cuenta. + +**¿Qué registra AWS?** +Los eventos IAM inusuales quedan en CloudTrail. Un usuario con perfil de "solo lectura" intentando modificar políticas es una señal clara. + +**¿Cómo responde el sistema?** +``` +Detecta: llamadas IAM sospechosas desde un usuario de bajo privilegio + → notify-alert: avisa al equipo + → revoke-credentials: desactiva las credenciales del usuario comprometido +``` + +**¿Qué siente el atacante?** +Sus credenciales dejan de funcionar antes de que pueda completar la escalada. + +--- + +## Ataque 4 — Exfiltración de Datos (EXFILTRATION) + +**¿Qué intenta el atacante?** +Ya tiene acceso y quiere llevarse datos. Empieza a copiar archivos de buckets S3 hacia afuera — ya sea descargándolos o replicándolos a otra cuenta de AWS que controla. + +**¿Qué ve el atacante?** +Los datos se están transfiriendo. Desde su perspectiva, está logrando su objetivo. + +**¿Qué registra AWS?** +Operaciones masivas de `GetObject` o `CopyObject` desde S3, especialmente hacia IPs o cuentas externas, generan un volumen de eventos anormal. + +**¿Cómo responde el sistema?** +``` +Detecta: transferencia masiva de datos desde S3 + → notify-alert: avisa al equipo + → isolate-instance: aísla el recurso comprometido, detiene la transferencia +``` + +**¿Qué siente el atacante?** +La transferencia se corta. El recurso queda inaccesible y en cuarentena. + +--- + +## Ataque 5 — Escaneo de Puertos (PORT_SCAN) + +**¿Qué intenta el atacante?** +Antes de atacar directamente, quiere saber qué servicios están expuestos — qué puertos están abiertos, qué versiones corren, qué superficie de ataque existe. Es como caminar alrededor de un edificio buscando ventanas abiertas. + +**¿Qué ve el atacante?** +Está recopilando información pasivamente. Cree que este tipo de reconocimiento no genera alertas. + +**¿Qué registra AWS?** +Los VPC Flow Logs registran conexiones rechazadas o intentos a múltiples puertos desde la misma IP en poco tiempo. + +**¿Cómo responde el sistema?** +``` +Detecta: múltiples conexiones a distintos puertos desde la misma IP + → notify-alert: avisa al equipo + → block-ip: registra la IP antes de que el atacante pase a la siguiente fase +``` + +**¿Qué siente el atacante?** +Su IP queda bloqueada en la etapa de reconocimiento, antes de que pueda intentar el ataque real. + +--- + +## Resumen: atacante vs. sistema + +| Ataque | Lo que intenta el atacante | Cómo lo detecta el sistema | Cómo responde | +|--------|---------------------------|---------------------------|---------------| +| Fuerza bruta | Adivinar contraseña | +5 intentos fallidos / IP | Avisa + bloquea IP | +| Credencial robada | Usar keys filtradas | Key usada desde IP desconocida | Avisa + desactiva key | +| Escalada de privilegios | Darse más permisos | Comandos IAM fuera de perfil | Avisa + desactiva credenciales | +| Exfiltración | Robar datos de S3 | Transferencia masiva inusual | Avisa + aísla recurso | +| Escaneo de puertos | Reconocer la infraestructura | Múltiples puertos desde misma IP | Avisa + bloquea IP | + +--- + +## Lo que el atacante nunca ve + +Desde la perspectiva del atacante, AWS es solo una API o una página web. No ve: + +- Que CloudTrail registra cada uno de sus movimientos. +- Que una Lambda está leyendo esos registros en tiempo real. +- Que en segundos, un equipo recibió una alerta con su IP y el detalle de lo que intentó. +- Que sus credenciales fueron desactivadas o su recurso aislado mientras todavía estaba conectado. + +Esa invisibilidad del sistema de respuesta es precisamente su ventaja. From e3de7da559d0087150b3fb6f153c7f9fc14c55ef Mon Sep 17 00:00:00 2001 From: bryancito1090 Date: Mon, 18 May 2026 21:34:13 -0500 Subject: [PATCH 3/9] feat: add automated demo script and documentation for real-time NACL-based threat mitigation --- CLAUDE.md | 111 ++++++++++++++ demo/demo_stack.sh | 195 +++++++++++++++++++++++++ demo/esquema_almacenamiento.md | 180 +++++++++++++++++++++++ docker-compose.yml | 2 +- infra/lambda-policies/base-policy.json | 11 ++ infra/setup.sh | 16 ++ lambdas/block-ip/handler.py | 157 +++++++++++++++++--- 7 files changed, 647 insertions(+), 25 deletions(-) create mode 100644 CLAUDE.md create mode 100755 demo/demo_stack.sh create mode 100644 demo/esquema_almacenamiento.md diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..61c04a5 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,111 @@ +# localstack-tesis + +Sistema de detección y respuesta ante incidentes de seguridad en entornos cloud (AWS), desarrollado 100% en local con Docker + LocalStack. + +## Proyecto y contexto + +- **Tesis:** Diseño e implementación de un sistema de detección y respuesta ante incidentes en AWS +- **Componente:** C — Respuesta Automatizada (Bryan) +- **Entorno:** LocalStack en `localhost:4566`, credenciales ficticias `test/test`, perfil AWS `local` +- **Restricciones:** Sin AWS real, sin SIEMs comerciales. Athena → DuckDB local; GuardDuty → scripts Python + +**Arquitectura objetivo:** +``` +CloudTrail / VPC Flow Logs / GuardDuty + → CloudWatch Logs → S3 → DuckDB (Athena local) + → CloudWatch Alarms + SNS → SQS + → Lambda Playbooks + IAM +``` + +**Componentes del equipo:** +| Componente | Responsable | Scope | +|------------|-------------|-------| +| A — Arquitectura y Logs | Melany | CloudTrail, VPC Flow Logs, GuardDuty, S3, Glue | +| B — Detección | Aarón | Reglas SQL/DuckDB, CloudWatch Alarms, patrones | +| C — Respuesta Automatizada | **Bryan** | Lambda Playbooks, IAM, SNS, SQS, dispatcher | + +## Comandos importantes + +Siempre usar `awslocal` en lugar de `aws`. Verificar que LocalStack esté corriendo antes de ejecutar. + +```bash +# Levantar el stack +docker compose up -d + +# Verificar salud +curl -s http://localhost:4566/_localstack/health | python3 -m json.tool + +# AWS local +.venv/bin/awslocal +AWS_ACCESS_KEY_ID=test AWS_SECRET_ACCESS_KEY=test .venv/bin/awslocal +``` + +## Skills disponibles + +| Skill | Descripción | +|-------|-------------| +| `/localstack-up` | Verifica/levanta el stack LocalStack | +| `/simulate-incident` | Simula un evento de incidente de seguridad completo | +| `/bootstrap-resources` | Crea todos los recursos AWS locales necesarios | +| `/deploy-lambda` | Despliega o actualiza un Lambda playbook | +| `/query-logs` | Consulta SQL sobre logs con DuckDB | +| `/new-playbook` | Crea un nuevo Lambda playbook de respuesta | + +## Lambda Playbooks (Componente C) + +Ubicados en `lambdas/`: +- `block-ip/` — Bloquea una IP en Security Groups +- `isolate-instance/` — Aísla una instancia EC2 +- `revoke-credentials/` — Revoca credenciales IAM comprometidas +- `notify-alert/` — Envía notificaciones SNS +- `dispatcher/` — Orquestador central de respuesta automática + +## Estructura del proyecto + +``` +localstack-tesis/ +├── .claude/ +│ ├── commands/ # Skills personalizados +│ └── settings.local.json +├── infra/ # IaC y setup de recursos +├── lambdas/ # Playbooks de respuesta +├── simulators/ # Generadores de logs (cloudtrail_gen.py, etc.) +├── queries/ # Queries DuckDB/SQL +├── logs/ # Logs locales +├── docker-compose.yml +└── .env # Credenciales locales (no commitear) +``` + +## NotebookLM (integración MCP) + +Conectado vía `notebooklm-mcp-cli` para análisis de fuentes de la tesis. + +- **CLI:** `/home/bryan/.local/bin/nlm` +- **MCP server:** configurado en `~/.claude.json` (scope global) +- **Skill:** `/nlm-skill` +- **Cuenta:** banobryan1090@gmail.com +- **Auth data:** `~/.notebooklm-mcp-cli/` + +```bash +nlm login # Re-autenticar (abre Chromium) +nlm login --check # Verificar sesión activa +nlm notebook list # Listar notebooks +nlm doctor # Diagnóstico +``` + +**Notebooks disponibles:** +| Título | ID | +|--------|----| +| Automatización de Detección y Respuesta Ante Incidentes en AWS | 6abc796b-0f31-42e6-afa9-05390c999ab8 | +| Cloud Computing | 2f9d5485-b9f7-4165-87ca-76c574395257 | +| Modelos y simulacion | 7dded2ec-f52b-4649-beaf-3b651fe2be62 | +| Formulacion de proyectos | 1bfeb22b-e453-494b-8b63-3a635200bbc6 | +| Formatos de Gestión ISTPET | fc8a101d-4280-4eea-834f-91f9163c1a57 | +| diseño | 8cb2a4b6-9f18-412c-aef4-b0f076bcba40 | + +Si las cookies expiran (~2-4 semanas): +```bash +nlm login +# Si falla por singleton: +rm -f ~/.notebooklm-mcp/chrome-profile/Singleton* && nlm login +``` diff --git a/demo/demo_stack.sh b/demo/demo_stack.sh new file mode 100755 index 0000000..af5aadb --- /dev/null +++ b/demo/demo_stack.sh @@ -0,0 +1,195 @@ +#!/usr/bin/env bash +# ============================================================================ +# DEMO PASO A PASO — Componente C: Automatización de Respuesta (Bryan) +# Tesis: Detección y respuesta ante incidentes en AWS (LocalStack) +# +# Esta demo recorre el stack completo y DEMUESTRA el bloqueo REAL de la IP +# del atacante (regla DENY en una Network ACL), no solo una notificación. +# +# Uso: bash demo/demo_stack.sh +# Cada paso espera ENTER para que puedas explicar mientras presentas. +# ============================================================================ +set -uo pipefail +cd "$(dirname "$0")/.." +export PATH="$PWD/.venv/bin:$PATH" + +AWSL="awslocal" +BUCKET="tesis-security-logs" +QUEUE_URL="http://localhost:4566/000000000000/tesis-incident-queue" + +C_TITLE='\033[1;36m'; C_OK='\033[0;32m'; C_WARN='\033[1;33m'; C_KEY='\033[1;35m'; C_NC='\033[0m' + +pause() { echo ""; read -rp $'\033[1;33m [ENTER para continuar]\033[0m '; echo ""; } +title() { echo ""; echo -e "${C_TITLE}══════════════════════════════════════════════════════════════════════${C_NC}"; + echo -e "${C_TITLE} $1${C_NC}"; + echo -e "${C_TITLE}══════════════════════════════════════════════════════════════════════${C_NC}"; } +say() { echo -e " $1"; } +key() { echo -e "${C_KEY} ▶ $1${C_NC}"; } + +# ---------------------------------------------------------------------------- +title "0. ARQUITECTURA DEL SISTEMA" +cat <<'EOF' + + Generación Centralización Detección Respuesta (Componente C) + ┌───────────┐ ┌────────────┐ ┌────────────┐ ┌──────────────────────────┐ + │ CloudTrail│─────▶│ S3 + │───▶│ DuckDB / │───▶│ SQS → dispatcher → │ + │ (ataque) │ │ CloudWatch │ │ Metric Flt │ │ ├─ notify-alert (SNS) │ + └───────────┘ └────────────┘ └────────────┘ │ └─ block-ip → NACL DENY │ + └──────────────────────────┘ + Componente A Componente A Componente B Componente C (Bryan) + + Lo que demostraré: el flujo es AUTOMÁTICO (sin intervención humana) y la + acción de block-ip es un BLOQUEO REAL a nivel de red, verificable en + infraestructura AWS — no una simple notificación. +EOF +pause + +# ---------------------------------------------------------------------------- +title "1. LA INFRAESTRUCTURA — LocalStack está corriendo" +say "Verifico que los servicios AWS emulados están disponibles:" +key "curl .../_localstack/health" +curl -s http://localhost:4566/_localstack/health | python3 -c \ + "import sys,json; d=json.load(sys.stdin)['services']; \ + [print(f' - {k:12s}: {v}') for k,v in d.items() if k in \ + ('s3','sns','sqs','lambda','iam','logs','ec2')]" +say "" +say "${C_OK}EC2 disponible${C_NC} → es lo que permite el bloqueo real vía Network ACL." +pause + +# ---------------------------------------------------------------------------- +title "2. ESQUEMA DE ALMACENAMIENTO — dónde vive la información" +say "Bucket único ${C_KEY}s3://${BUCKET}${C_NC}, organizado por fuente (alineado con Componente A):" +key "awslocal s3 ls s3://${BUCKET}/" +$AWSL s3 ls s3://$BUCKET/ || true +cat <-.json +EOF +pause + +# ---------------------------------------------------------------------------- +title "3. PUNTO DE CUMPLIMIENTO — estado de la Network ACL ANTES" +NACL=$($AWSL ec2 describe-network-acls --filters "Name=default,Values=true" \ + --query 'NetworkAcls[0].NetworkAclId' --output text) +say "La NACL ${C_KEY}${NACL}${C_NC} es el firewall de subred donde se aplicará el bloqueo." +say "Limpio reglas de bloqueos anteriores para una demo reproducible..." +for rn in $($AWSL ec2 describe-network-acls --network-acl-ids "$NACL" \ + --query 'NetworkAcls[0].Entries[?Egress==`false` && RuleNumber<`100`].RuleNumber' \ + --output text); do + $AWSL ec2 delete-network-acl-entry --network-acl-id "$NACL" --rule-number "$rn" --ingress 2>/dev/null +done +key "awslocal ec2 describe-network-acls (entradas de ENTRADA)" +$AWSL ec2 describe-network-acls --network-acl-ids "$NACL" \ + --query 'NetworkAcls[0].Entries[?Egress==`false`].[RuleNumber,RuleAction,CidrBlock]' --output table +say "" +say "Solo está la ${C_KEY}regla 100 = ALLOW 0.0.0.0/0${C_NC} (permite todo). Sin bloqueos." +pause + +# ---------------------------------------------------------------------------- +title "4. EL ATAQUE — inyectar un incidente de fuerza bruta" +say "Genero 10 intentos fallidos de login desde una IP atacante y los publico" +say "en S3 (como lo haría CloudTrail real) + SQS (el bus de incidentes):" +key ".venv/bin/python3 simulators/inject_logs.py brute-force" +INJECT_OUT=$(.venv/bin/python3 simulators/inject_logs.py brute-force 2>&1) +echo "$INJECT_OUT" | grep -E '\[inject\]|sourceIPAddress|incident_type|severity' +ATTACKER_IP=$(echo "$INJECT_OUT" | python3 -c \ + "import sys,re,json; t=sys.stdin.read(); m=re.search(r'\"sourceIPAddress\": \"([^\"]+)\"',t); print(m.group(1) if m else '0.0.0.0')") +say "" +key "IP del atacante en este incidente: ${C_KEY}${ATTACKER_IP}${C_NC}" +pause + +# ---------------------------------------------------------------------------- +title "5. CENTRALIZACIÓN — el log llegó a S3 y el incidente a SQS" +key "awslocal s3 ls s3://${BUCKET}/cloudtrail/ --recursive (último)" +$AWSL s3 ls s3://$BUCKET/cloudtrail/ --recursive | tail -1 +say "" +say "El mensaje fue encolado en SQS. Un ${C_KEY}event source mapping${C_NC} conecta" +say "esa cola con la Lambda dispatcher → de aquí en adelante TODO es automático." +key "awslocal lambda list-event-source-mappings --function-name tesis-dispatcher" +$AWSL lambda list-event-source-mappings --function-name tesis-dispatcher \ + --query 'EventSourceMappings[].[State,EventSourceArn]' --output table +pause + +# ---------------------------------------------------------------------------- +title "6. RESPUESTA AUTOMÁTICA — el dispatcher enruta el incidente" +cat <<'EOF' + El dispatcher recibe el incidente desde SQS y aplica su tabla de enrutamiento: + + BRUTE_FORCE → [ notify-alert , block-ip ] + + - notify-alert : publica la alerta estructurada en SNS + - block-ip : APLICA EL BLOQUEO REAL en la Network ACL + + No invoco nada a mano: SQS dispara al dispatcher solo. Espero a que procese... +EOF +for i in $(seq 1 20); do + HIT=$($AWSL ec2 describe-network-acls --network-acl-ids "$NACL" \ + --query "NetworkAcls[0].Entries[?Egress==\`false\` && RuleAction==\`deny\` && CidrBlock==\`${ATTACKER_IP}/32\`]" \ + --output text) + [ -n "$HIT" ] && { say "${C_OK}Procesado automáticamente en ~$((i*2))s${C_NC}"; break; } + sleep 2 +done +pause + +# ---------------------------------------------------------------------------- +title "7. EL BLOQUEO REAL — estado de la Network ACL DESPUÉS" +key "awslocal ec2 describe-network-acls (entradas de ENTRADA)" +$AWSL ec2 describe-network-acls --network-acl-ids "$NACL" \ + --query 'NetworkAcls[0].Entries[?Egress==`false`].[RuleNumber,RuleAction,CidrBlock]' --output table +cat </dev/null | python3 -m json.tool +say "" +say "El campo ${C_KEY}enforcement${C_NC} prueba el punto exacto: network_acl_id + rule_number." +pause + +# ---------------------------------------------------------------------------- +title "9. TRAZABILIDAD — log de ejecución en CloudWatch" +LG="/aws/lambda/tesis-block-ip" +key "awslocal logs filter-log-events $LG --filter-pattern block-ip" +$AWSL logs filter-log-events --log-group-name "$LG" --filter-pattern "block-ip" \ + --query 'events[*].message' --output text 2>/dev/null | tr '\t' '\n' \ + | grep -i 'block-ip' | tail -3 +[ $? -ne 0 ] && say "(sin coincidencias; el log puede tardar unos segundos en indexarse)" +pause + +# ---------------------------------------------------------------------------- +title "10. RESUMEN — qué demostré" +cat < Decisión de diseño del Componente C: se interpone **SQS + dispatcher + DLQ** entre la detección y los playbooks. Aporta durabilidad y reintentos (`maxReceiveCount=3`); si un playbook falla, el incidente no se pierde: pasa a la *Dead Letter Queue* para análisis forense. + +--- + +## 2. Almacenamiento forense — Amazon S3 + +**Bucket único:** `s3://tesis-security-logs` + +### 2.1 Estructura de prefijos + +| Prefijo | Contenido | Fuente | Formato (AWS real) | Responsable | +|---------|-----------|--------|--------------------|-------------| +| `cloudtrail/` | Eventos de auditoría de la API (logins, IAM, S3) | CloudTrail | `.json.gz` | Componente A | +| `vpc-flow/` | Tráfico de red (conexiones aceptadas/rechazadas) | VPC Flow Logs | `.log.gz` | Componente A | +| `config/` | Snapshots de estado de recursos (políticas IAM) | AWS Config | `.json.gz` | Componente A | +| `guardduty/` | Hallazgos de amenazas | GuardDuty | `.json` | Componente A | +| `responses/` | **Evidencia de mitigación de los playbooks** | **Componente C** | `.json` | **Componente C (Bryan)** | + +> En el entorno local los logs simulados se guardan como `.json` sin comprimir para facilitar la inspección en clase; en AWS real se comprimen (`.gz`) para reducir costo/espacio. + +### 2.2 Particionamiento + +Jerárquico por **fecha de ocurrencia**, para que las consultas de detección filtren solo las particiones relevantes (en AWS real se antepone cuenta/región): + +``` +s3://tesis-security-logs/ + cloudtrail/AAAA/MM/DD/HHMMSS/-.json + responses/blocked-ips.json + responses/... +``` + +Ejemplo real generado por el sistema: +`cloudtrail/2026/05/19/000115/brute-force-0aec3b72.json` + +### 2.3 Retención + +90 días para los prefijos de logs (política del Componente A). El prefijo `responses/` se conserva como pista de auditoría de incidentes. + +### 2.4 Catálogo (AWS Glue / esquema lógico) + +Los archivos en S3 son texto plano. **AWS Glue Data Catalog** define un esquema virtual (mapea campos → tipos: IP, puerto, usuario…) que permite a **Athena / DuckDB** ejecutar SQL directamente sobre S3. En el entorno local, DuckDB cumple esta función con `read_json_auto()`. + +--- + +## 3. Esquemas de registro (contratos de datos) + +### 3.1 Evento CloudTrail (entrada — prefijo `cloudtrail/`) + +Archivo `{"Records": [ ... ]}`. Cada evento (generado por `simulators/cloudtrail_gen.py`): + +```json +{ + "eventVersion": "1.08", + "eventTime": "2026-05-18T23:57:05Z", + "eventSource": "signin.amazonaws.com", + "eventName": "ConsoleLogin", + "awsRegion": "us-east-1", + "sourceIPAddress": "185.220.101.5", + "userIdentity": { "type": "IAMUser", "userName": "dev-operator", + "arn": "arn:aws:iam::123456789012:user/dev-operator" }, + "errorCode": "AccessDenied", + "responseElements": { "ConsoleLogin": "Failure" } +} +``` + +### 3.2 Incidente (mensaje SQS — bus de respuesta) + +Producido por `simulators/inject_logs.py`, consumido por el `dispatcher`: + +```json +{ + "incident_type": "BRUTE_FORCE", + "severity": "HIGH", + "sourceIPAddress": "185.220.101.5", + "affectedResource": "iam:user/dev-operator", + "s3_log_key": "cloudtrail/2026/05/19/000115/brute-force-0aec3b72.json", + "event_count": 10, + "timestamp": "2026-05-18T23:57:05Z" +} +``` + +| Campo | Tipo | Descripción | +|-------|------|-------------| +| `incident_type` | enum | `BRUTE_FORCE`, `PRIVILEGE_ESCALATION`, `CREDENTIAL_LEAK`, `EXFILTRATION`, `PORT_SCAN` | +| `severity` | enum | `LOW` · `MEDIUM` · `HIGH` · `CRITICAL` | +| `sourceIPAddress` | string | IP del atacante (objetivo del bloqueo) | +| `affectedResource` | string | Recurso afectado | +| `s3_log_key` | string | Puntero al log forense que originó el incidente | + +### 3.3 Evidencia de mitigación (salida — `responses/blocked-ips.json`) + +**Responsabilidad del Componente C.** Escrito por el playbook `block-ip`. Es la **pista de auditoría** que prueba *qué* se bloqueó y *dónde* exactamente: + +```json +[ + { + "ip": "185.220.101.5", + "blocked_at": "2026-05-18T23:57:10.194758+00:00", + "reason": "BRUTE_FORCE", + "severity": "HIGH", + "affectedResource": "iam:user/dev-operator", + "enforcement": { + "enforced": true, + "already_present": false, + "network_acl_id": "acl-b2a704d3", + "rule_number": 1, + "cidr": "185.220.101.5/32" + } + } +] +``` + +| Campo `enforcement` | Significado | +|---------------------|-------------| +| `enforced` | `true` si el bloqueo se aplicó realmente en infraestructura | +| `network_acl_id` | **Punto de cumplimiento exacto**: la NACL donde se denegó la IP | +| `rule_number` | Nº de regla DENY (rango 1–99, < ALLOW 100 → tiene prioridad) | +| `cidr` | Rango bloqueado (`/32` = IP exacta del atacante) | + +Este bloque es lo que diferencia *"avisar"* de *"bloquear"*: registra la prueba verificable de la acción defensiva. + +--- + +## 4. Capa de consulta (detección — Componente B) + +DuckDB lee los archivos de `cloudtrail/` como tablas externas y aplica las reglas. Ejemplo real (`queries/detect_brute_force.sql`): + +```sql +SELECT r.sourceIPAddress, r.userIdentity.userName AS username, + COUNT(*) AS failed_attempts +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; +``` + +Equivale a una consulta Athena sobre la tabla CloudTrail catalogada por Glue. + +--- + +## 5. Almacenamiento transitorio y operativo + +| Recurso | Tipo | Función | +|---------|------|---------| +| SQS `tesis-incident-queue` | Cola | Entrega del incidente al `dispatcher` | +| SQS `tesis-incident-queue-dlq` | DLQ | Incidentes que fallaron 3 veces (forense) | +| CloudWatch `/aws/lambda/tesis-*` | Log group | Trazas de ejecución de cada playbook | +| CloudWatch `/tesis/security-events` | Log group | Eventos de seguridad centralizados | + +--- + +## 6. Ciclo de vida de un incidente (resumen end-to-end) + +``` +1. Ataque → cloudtrail/AAAA/MM/DD/.../brute-force-xxxx.json (S3, forense) +2. Detección → DuckDB/SQL sobre esos logs (Componente B) +3. Incidente → mensaje JSON en SQS tesis-incident-queue (tránsito) +4. Enrutamiento → dispatcher decide playbooks (CloudWatch traza) +5. Mitigación → block-ip crea regla DENY en Network ACL (INFRAESTRUCTURA) +6. Auditoría → responses/blocked-ips.json con enforcement{} (S3, evidencia) +``` + +El almacenamiento es la columna vertebral: cada fase deja una **evidencia consultable y trazable**, desde el log del ataque hasta la prueba del bloqueo real. diff --git a/docker-compose.yml b/docker-compose.yml index 6740df3..a4e4dff 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -9,7 +9,7 @@ services: - "127.0.0.1:4510-4559:4510-4559" environment: - DEBUG=${DEBUG:-0} - - SERVICES=s3,sns,sqs,lambda,iam,logs,cloudwatch,events + - 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 diff --git a/infra/lambda-policies/base-policy.json b/infra/lambda-policies/base-policy.json index d67bb7a..4299456 100644 --- a/infra/lambda-policies/base-policy.json +++ b/infra/lambda-policies/base-policy.json @@ -42,6 +42,17 @@ "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": "*" } ] } diff --git a/infra/setup.sh b/infra/setup.sh index 4814f0f..60a1dd0 100755 --- a/infra/setup.sh +++ b/infra/setup.sh @@ -86,6 +86,22 @@ awslocal iam put-role-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)" + # ── Resumen ─────────────────────────────────────────────────────────────────── echo "" echo "========================================" diff --git a/lambdas/block-ip/handler.py b/lambdas/block-ip/handler.py index 75e054b..1afe600 100644 --- a/lambdas/block-ip/handler.py +++ b/lambdas/block-ip/handler.py @@ -1,8 +1,21 @@ """ Playbook: block-ip -Registra la IP atacante en S3 (blocklist) y notifica al equipo via SNS. -En producción real: actualizaría un WAF IP Set o Security Group. -En LocalStack Community (sin WAF/EC2): persiste en S3 como fuente de verdad. +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 @@ -14,9 +27,18 @@ 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: @@ -29,6 +51,84 @@ def _load_blocklist() -> list: 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 = [] @@ -43,40 +143,49 @@ def lambda_handler(event, context): severity = body.get("severity", "MEDIUM") timestamp = datetime.now(timezone.utc).isoformat() - # 1. Actualizar blocklist en S3 + # 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, + "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) - s3.put_object( - Bucket=BUCKET, - Key="responses/blocked-ips.json", - Body=json.dumps(blocklist, indent=2).encode(), - ContentType="application/json", - ) - action = "ip_blocked" - print(f"[block-ip] IP {ip} añadida al blocklist ({len(blocklist)} IPs bloqueadas)") + 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") + 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", + ) - # 2. Notificar al equipo + # 3. Notificar al equipo + status = "BLOCKED" if enforcement.get("enforced") else "BLOCK_FAILED" result = { - "playbook": "block-ip", - "action": action, - "ip": ip, - "status": "BLOCKED", - "timestamp": timestamp, + "playbook": "block-ip", + "action": action, + "ip": ip, + "status": status, + "enforcement": enforcement, + "timestamp": timestamp, } sns.publish( TopicArn=SNS_ARN, - Subject=f"[{severity}] IP bloqueada: {ip}", + Subject=f"[{severity}] IP bloqueada: {ip}"[:100], Message=json.dumps(result, indent=2), ) From 4208ca0b23fdd4eadc1e99dafacab15b6929fe9c Mon Sep 17 00:00:00 2001 From: bryancito1090 Date: Wed, 27 May 2026 07:18:05 -0500 Subject: [PATCH 4/9] Add documentation for AWS incident response architecture and parallel development strategy - Created 'esquema_almacenamiento.md' detailing the storage schema for incident detection and response in AWS, including design principles, forensic storage, and data contracts. - Added 'estrategia_paralelo_aws.md' outlining the parallel work strategy for team members to collaborate effectively while minimizing AWS costs. - Introduced 'guia_acoplamiento_paralelo.md' providing a step-by-step guide for integrating components A, B, and C in AWS, emphasizing decoupled development. - Included 'recursos_y_costos_aws.md' summarizing estimated costs, integration requirements, incident payload formats, and security mechanisms for deploying Component C in AWS. - Added Lambda function packages for blocking IPs and notifying alerts, including their respective policies and test events. --- .../0e26cc16-6539-4017-b372-84a9c385725a.json | 1 + CLAUDE.md | 111 ----- INTERFAZ_COMPONENTE_B.md | 222 +++++++++ analisis_costos_infraestructura_aws.md | 54 ++ analisis_flujo1_bruteforce.md | 462 ------------------ analisis_flujo2_automatizacion.md | 328 ------------- {demo => demo 19 Mayo}/demo_stack.sh | 62 +++ .../esquema_almacenamiento.md | 15 + estrategia_paralelo_aws.md | 39 ++ guia_acoplamiento_paralelo.md | 90 ++++ lambdas/block-ip.zip | Bin 0 -> 4166 bytes lambdas/notify-alert.zip | Bin 0 -> 2424 bytes recursos_y_costos_aws.md | 81 +++ 13 files changed, 564 insertions(+), 901 deletions(-) create mode 120000 .antigravitycli/0e26cc16-6539-4017-b372-84a9c385725a.json delete mode 100644 CLAUDE.md create mode 100644 INTERFAZ_COMPONENTE_B.md create mode 100644 analisis_costos_infraestructura_aws.md delete mode 100644 analisis_flujo1_bruteforce.md delete mode 100644 analisis_flujo2_automatizacion.md rename {demo => demo 19 Mayo}/demo_stack.sh (79%) rename {demo => demo 19 Mayo}/esquema_almacenamiento.md (82%) create mode 100644 estrategia_paralelo_aws.md create mode 100644 guia_acoplamiento_paralelo.md create mode 100644 lambdas/block-ip.zip create mode 100644 lambdas/notify-alert.zip create mode 100644 recursos_y_costos_aws.md diff --git a/.antigravitycli/0e26cc16-6539-4017-b372-84a9c385725a.json b/.antigravitycli/0e26cc16-6539-4017-b372-84a9c385725a.json new file mode 120000 index 0000000..70f8f49 --- /dev/null +++ b/.antigravitycli/0e26cc16-6539-4017-b372-84a9c385725a.json @@ -0,0 +1 @@ +/home/bryan/.gemini/config/projects/0e26cc16-6539-4017-b372-84a9c385725a.json \ No newline at end of file diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 100644 index 61c04a5..0000000 --- a/CLAUDE.md +++ /dev/null @@ -1,111 +0,0 @@ -# localstack-tesis - -Sistema de detección y respuesta ante incidentes de seguridad en entornos cloud (AWS), desarrollado 100% en local con Docker + LocalStack. - -## Proyecto y contexto - -- **Tesis:** Diseño e implementación de un sistema de detección y respuesta ante incidentes en AWS -- **Componente:** C — Respuesta Automatizada (Bryan) -- **Entorno:** LocalStack en `localhost:4566`, credenciales ficticias `test/test`, perfil AWS `local` -- **Restricciones:** Sin AWS real, sin SIEMs comerciales. Athena → DuckDB local; GuardDuty → scripts Python - -**Arquitectura objetivo:** -``` -CloudTrail / VPC Flow Logs / GuardDuty - → CloudWatch Logs → S3 → DuckDB (Athena local) - → CloudWatch Alarms + SNS → SQS - → Lambda Playbooks + IAM -``` - -**Componentes del equipo:** -| Componente | Responsable | Scope | -|------------|-------------|-------| -| A — Arquitectura y Logs | Melany | CloudTrail, VPC Flow Logs, GuardDuty, S3, Glue | -| B — Detección | Aarón | Reglas SQL/DuckDB, CloudWatch Alarms, patrones | -| C — Respuesta Automatizada | **Bryan** | Lambda Playbooks, IAM, SNS, SQS, dispatcher | - -## Comandos importantes - -Siempre usar `awslocal` en lugar de `aws`. Verificar que LocalStack esté corriendo antes de ejecutar. - -```bash -# Levantar el stack -docker compose up -d - -# Verificar salud -curl -s http://localhost:4566/_localstack/health | python3 -m json.tool - -# AWS local -.venv/bin/awslocal -AWS_ACCESS_KEY_ID=test AWS_SECRET_ACCESS_KEY=test .venv/bin/awslocal -``` - -## Skills disponibles - -| Skill | Descripción | -|-------|-------------| -| `/localstack-up` | Verifica/levanta el stack LocalStack | -| `/simulate-incident` | Simula un evento de incidente de seguridad completo | -| `/bootstrap-resources` | Crea todos los recursos AWS locales necesarios | -| `/deploy-lambda` | Despliega o actualiza un Lambda playbook | -| `/query-logs` | Consulta SQL sobre logs con DuckDB | -| `/new-playbook` | Crea un nuevo Lambda playbook de respuesta | - -## Lambda Playbooks (Componente C) - -Ubicados en `lambdas/`: -- `block-ip/` — Bloquea una IP en Security Groups -- `isolate-instance/` — Aísla una instancia EC2 -- `revoke-credentials/` — Revoca credenciales IAM comprometidas -- `notify-alert/` — Envía notificaciones SNS -- `dispatcher/` — Orquestador central de respuesta automática - -## Estructura del proyecto - -``` -localstack-tesis/ -├── .claude/ -│ ├── commands/ # Skills personalizados -│ └── settings.local.json -├── infra/ # IaC y setup de recursos -├── lambdas/ # Playbooks de respuesta -├── simulators/ # Generadores de logs (cloudtrail_gen.py, etc.) -├── queries/ # Queries DuckDB/SQL -├── logs/ # Logs locales -├── docker-compose.yml -└── .env # Credenciales locales (no commitear) -``` - -## NotebookLM (integración MCP) - -Conectado vía `notebooklm-mcp-cli` para análisis de fuentes de la tesis. - -- **CLI:** `/home/bryan/.local/bin/nlm` -- **MCP server:** configurado en `~/.claude.json` (scope global) -- **Skill:** `/nlm-skill` -- **Cuenta:** banobryan1090@gmail.com -- **Auth data:** `~/.notebooklm-mcp-cli/` - -```bash -nlm login # Re-autenticar (abre Chromium) -nlm login --check # Verificar sesión activa -nlm notebook list # Listar notebooks -nlm doctor # Diagnóstico -``` - -**Notebooks disponibles:** -| Título | ID | -|--------|----| -| Automatización de Detección y Respuesta Ante Incidentes en AWS | 6abc796b-0f31-42e6-afa9-05390c999ab8 | -| Cloud Computing | 2f9d5485-b9f7-4165-87ca-76c574395257 | -| Modelos y simulacion | 7dded2ec-f52b-4649-beaf-3b651fe2be62 | -| Formulacion de proyectos | 1bfeb22b-e453-494b-8b63-3a635200bbc6 | -| Formatos de Gestión ISTPET | fc8a101d-4280-4eea-834f-91f9163c1a57 | -| diseño | 8cb2a4b6-9f18-412c-aef4-b0f076bcba40 | - -Si las cookies expiran (~2-4 semanas): -```bash -nlm login -# Si falla por singleton: -rm -f ~/.notebooklm-mcp/chrome-profile/Singleton* && nlm login -``` diff --git a/INTERFAZ_COMPONENTE_B.md b/INTERFAZ_COMPONENTE_B.md new file mode 100644 index 0000000..084db04 --- /dev/null +++ b/INTERFAZ_COMPONENTE_B.md @@ -0,0 +1,222 @@ +VARIABLES REQUERIDAS POR INCIDENTE — COMPONENTE B (Aarón) +Tesis: Sistema de Detección y Respuesta ante Incidentes en AWS + + +Para cada incidente detectado, Aarón debe extraer las siguientes variables de sus +consultas y publicarlas en la cola de incidentes en formato JSON. + + +════════════════════════════════════════════════════════════ +INCIDENTE 1: FUERZA BRUTA (BRUTE_FORCE) +════════════════════════════════════════════════════════════ + +Qué es: 5 o más intentos fallidos de login (ConsoleLogin) desde la misma IP + en una ventana de 5 minutos. + +Fuente: CloudTrail → evento ConsoleLogin con errorCode = AccessDenied + +Variables que Aarón debe extraer y enviar: + + Variable Obligatorio Descripción Ejemplo + ────────────────── ─────────── ──────────────────────────────── ───────────────────────────── + incident_type SI Nombre fijo del incidente "BRUTE_FORCE" + severity SI Nivel de gravedad "HIGH" + sourceIPAddress SI IP desde donde llegaron los ataques "185.220.101.5" + affectedResource SI Usuario objetivo del ataque "iam:user/dev-operator" + s3_log_key SI Ruta del log en S3 "cloudtrail/2026/05/19/.../archivo.json" + timestamp SI Fecha y hora de detección "2026-05-19T00:01:15Z" + event_count SI Número de eventos analizados 10 + failed_attempts Opcional Intentos fallidos detectados 10 + detection_window Opcional Ventana de tiempo analizada "5 minutes" + +Origen de cada variable en la query: + + sourceIPAddress → r.sourceIPAddress + affectedResource → "iam:user/" + r.userIdentity.userName + failed_attempts → COUNT(*) + timestamp → MAX(r.eventTime) + + +════════════════════════════════════════════════════════════ +INCIDENTE 2: ESCANEO DE PUERTOS (PORT_SCAN) +════════════════════════════════════════════════════════════ + +Qué es: La misma IP genera conexiones rechazadas (REJECT) hacia 10 o más + puertos distintos en una ventana de 5 minutos. + +Fuente: VPC Flow Logs → registros con acción = REJECT + +Variables que Aarón debe extraer y enviar: + + Variable Obligatorio Descripción Ejemplo + ──────────────────── ─────────── ─────────────────────────────────── ───────────────────────────── + incident_type SI Nombre fijo del incidente "PORT_SCAN" + severity SI Nivel de gravedad "MEDIUM" + sourceIPAddress SI IP que realizó el escaneo "185.220.101.5" + affectedResource SI VPC o subred escaneada "vpc/vpc-3c0db7f4" + s3_log_key SI Ruta del log en S3 "vpc-flow/2026/05/19/.../archivo.log" + timestamp SI Fecha y hora de detección "2026-05-19T00:01:15Z" + event_count SI Número de eventos analizados 15 + rejected_connections Opcional Conexiones rechazadas detectadas 15 + scanned_ports_count Opcional Puertos distintos escaneados 12 + +Origen de cada variable en la query: + + sourceIPAddress → srcAddr (campo de VPC Flow Logs) + affectedResource → ID de la VPC afectada + rejected_connections → COUNT(*) donde acción = REJECT + scanned_ports_count → COUNT(DISTINCT dstPort) + + +════════════════════════════════════════════════════════════ +INCIDENTE 3: ESCALADA DE PRIVILEGIOS (PRIVILEGE_ESCALATION) +════════════════════════════════════════════════════════════ + +Qué es: Un usuario ejecuta acciones críticas de IAM que no le corresponden: + adjuntar políticas de administrador, crear access keys, modificar roles. + +Fuente: CloudTrail → eventos IAM: AttachUserPolicy, AttachRolePolicy, + CreateAccessKey, PutUserPolicy, AddUserToGroup + +Variables que Aarón debe extraer y enviar: + + Variable Obligatorio Descripción Ejemplo + ────────────────── ─────────── ────────────────────────────────────── ────────────────────────────────── + incident_type SI Nombre fijo del incidente "PRIVILEGE_ESCALATION" + severity SI Nivel de gravedad "CRITICAL" + sourceIPAddress SI IP desde donde se hizo la escalada "185.220.101.5" + affectedResource SI * Usuario que realizó las acciones "iam:user/dev-operator" + s3_log_key SI Ruta del log en S3 "cloudtrail/2026/05/19/.../archivo.json" + timestamp SI Fecha y hora de detección "2026-05-19T00:01:15Z" + event_count SI Número de eventos analizados 3 + suspicious_actions Opcional Lista de acciones IAM detectadas ["AttachUserPolicy", "CreateAccessKey"] + target_policy_arn Opcional Política que intentó adjuntarse "arn:aws:iam::aws:policy/AdministratorAccess" + +Origen de cada variable en la query: + + sourceIPAddress → r.sourceIPAddress + affectedResource → "iam:user/" + r.userIdentity.userName + suspicious_actions → lista de r.eventName detectados + target_policy_arn → r.requestParameters.policyArn + + * IMPORTANTE: affectedResource debe escribirse EXACTAMENTE como + "iam:user/NOMBRE_DEL_USUARIO" — ese prefijo es obligatorio. + + +════════════════════════════════════════════════════════════ +INCIDENTE 4: FUGA DE CREDENCIALES (CREDENTIAL_LEAK) +════════════════════════════════════════════════════════════ + +Qué es: Credenciales de un usuario legítimo son utilizadas desde una IP + externa o inusual (fuera del rango normal de la organización). + +Fuente: CloudTrail → llamadas a la API (GetCallerIdentity u otras) desde + una IP que no pertenece al rango de IPs internas conocidas. + +Variables que Aarón debe extraer y enviar: + + Variable Obligatorio Descripción Ejemplo + ────────────────── ─────────── ────────────────────────────────────────── ────────────────────────────────── + incident_type SI Nombre fijo del incidente "CREDENTIAL_LEAK" + severity SI Nivel de gravedad "CRITICAL" + sourceIPAddress SI IP externa desde donde se usaron las creds "185.220.101.5" + affectedResource SI * Usuario cuyas credenciales fueron filtradas "iam:user/external-contractor" + s3_log_key SI Ruta del log en S3 "cloudtrail/2026/05/19/.../archivo.json" + timestamp SI Fecha y hora de detección "2026-05-19T00:01:15Z" + event_count SI Número de eventos analizados 1 + service_accessed Opcional Servicio al que se accedió "sts.amazonaws.com" + unusual_region Opcional Región inusual desde donde se accedió "ap-southeast-1" + +Origen de cada variable en la query: + + sourceIPAddress → r.sourceIPAddress + affectedResource → "iam:user/" + r.userIdentity.userName + service_accessed → r.eventSource + unusual_region → r.awsRegion + + * IMPORTANTE: affectedResource debe escribirse EXACTAMENTE como + "iam:user/NOMBRE_DEL_USUARIO" — ese prefijo es obligatorio. + + +════════════════════════════════════════════════════════════ +INCIDENTE 5: EXFILTRACIÓN DE DATOS (EXFILTRATION) +════════════════════════════════════════════════════════════ + +Qué es: Descarga masiva de archivos desde S3. Más de 50 operaciones GetObject + desde la misma IP en el lapso de una hora. + +Fuente: CloudTrail → eventos S3: eventName = GetObject + +Variables que Aarón debe extraer y enviar: + + Variable Obligatorio Descripción Ejemplo + ────────────────── ─────────── ────────────────────────────────────── ────────────────────────────────── + incident_type SI Nombre fijo del incidente "EXFILTRATION" + severity SI Nivel de gravedad "HIGH" + sourceIPAddress SI IP desde donde se descargaron los datos "185.220.101.5" + affectedResource SI Recurso comprometido (instancia o bucket) "ec2:instance/i-0abc123def456" + s3_log_key SI Ruta del log en S3 "cloudtrail/2026/05/19/.../archivo.json" + timestamp SI Fecha y hora de detección "2026-05-19T00:01:15Z" + event_count SI Número de eventos analizados 55 + total_downloads Opcional Archivos descargados detectados 55 + affected_bucket Opcional Bucket S3 del que se extrajeron datos "prod-data-bucket" + first_access Opcional Primer acceso detectado "2026-05-18T23:00:00Z" + last_access Opcional Último acceso detectado "2026-05-18T23:58:00Z" + +Origen de cada variable en la query: + + sourceIPAddress → r.sourceIPAddress + affectedResource → "ec2:instance/" + ID de la instancia origen + total_downloads → COUNT(*) + affected_bucket → extraído de r.resources[0].ARN + first_access → MIN(r.eventTime) + last_access → MAX(r.eventTime) + + +════════════════════════════════════════════════════════════ +RESUMEN RÁPIDO — VARIABLES CRÍTICAS POR INCIDENTE +════════════════════════════════════════════════════════════ + + Incidente Dato más importante Formato de affectedResource + ───────────────────── ───────────────────── ────────────────────────────────────── + BRUTE_FORCE sourceIPAddress "iam:user/" + PORT_SCAN sourceIPAddress "vpc/" o "subnet/" + PRIVILEGE_ESCALATION affectedResource * "iam:user/" + CREDENTIAL_LEAK affectedResource * "iam:user/" + EXFILTRATION affectedResource "ec2:instance/" o "s3:::" + + * Para estos dos incidentes, affectedResource debe incluir el prefijo + "iam:user/" obligatoriamente. + + +════════════════════════════════════════════════════════════ +CÓMO PUBLICAR EL MENSAJE EN LA COLA +════════════════════════════════════════════════════════════ + +Una vez detectado el incidente y extraídas las variables, Aarón publica +el mensaje en la cola SQS con el siguiente código: + + import boto3, json + + sqs = boto3.client( + "sqs", + endpoint_url="http://localhost:4566", + region_name="us-east-1", + aws_access_key_id="test", + aws_secret_access_key="test" + ) + + payload = { + "incident_type": "BRUTE_FORCE", + "severity": "HIGH", + "sourceIPAddress": "IP extraída de la query", + "affectedResource": "iam:user/nombre_extraído_de_la_query", + "s3_log_key": "ruta del log en S3", + "event_count": 10, + "timestamp": "2026-05-19T00:01:15Z" + } + + sqs.send_message( + QueueUrl="http://localhost:4566/000000000000/tesis-incident-queue", + MessageBody=json.dumps(payload) + ) diff --git a/analisis_costos_infraestructura_aws.md b/analisis_costos_infraestructura_aws.md new file mode 100644 index 0000000..221df76 --- /dev/null +++ b/analisis_costos_infraestructura_aws.md @@ -0,0 +1,54 @@ +# Análisis de Costos Fijos en AWS: Infraestructura Permanente para Trabajo en Paralelo + +Este documento evalúa el impacto financiero de mantener la infraestructura del proyecto activa 24/7 en AWS real durante la fase de desarrollo en paralelo. El objetivo es determinar si dejar levantados los recursos de manera permanente generará cobros en la cuenta de AWS. + +--- + +## 1. Regla General: Serverless vs. Provisionado + +En AWS existen dos modelos de facturación principales: +* **Serverless / Bajo Demanda (Costo $0 en reposo)**: Solo pagas por uso activo (ejecuciones de código, peticiones, mensajes enviados). Si el recurso está creado pero inactivo, el costo es **cero**. +* **Provisionado (Cobro por Hora)**: Pagas por tener el recurso reservado y encendido, sin importar si lo estás usando o si el tráfico es cero. + +--- + +## 2. Inventario de Recursos Permanentemente Activos ($0 USD) + +Los siguientes recursos del proyecto **pueden permanecer creados las 24 horas del día, los 7 días de la semana** sin generar ningún costo si no hay simulaciones de ataques ejecutándose: + +| Servicio AWS | Recurso en la Tesis | Tipo de Cobro | Costo en Reposo (24/7) | +| :--- | :--- | :--- | :--- | +| **AWS Lambda** | Dispatcher y Playbooks | Por petición (milisegundos) | **$0.00 USD** | +| **Amazon SQS** | Cola de incidentes y DLQ | Por petición (mensajes) | **$0.00 USD** | +| **Amazon SNS** | Tópico de alertas de seguridad | Por petición (publicaciones) | **$0.00 USD** | +| **Amazon Athena** | Motor de consultas SQL | Por datos escaneados (TB) | **$0.00 USD** | +| **AWS IAM** | Roles y políticas de seguridad | Gratis siempre | **$0.00 USD** | +| **Amazon VPC** | Red virtual y subredes | Gratis siempre | **$0.00 USD** | +| **Network ACL** | Firewall de subred (bloqueos) | Gratis siempre | **$0.00 USD** | +| **Amazon S3** | Logs históricos y evidencias | Por almacenamiento (GB) | **<$0.001 USD/mes** (despreciable) | + +--- + +## 3. Alertas de Costo: Recursos a Apagar o Evitar + +Estos son los únicos componentes que **sí generan cobros por hora** y deben ser gestionados con cuidado durante el desarrollo: + +### 1. Instancias EC2 (`t2.micro` / `t3.micro`) — *Apagar en reposo* +* **Impacto**: Una instancia EC2 encendida consume horas de cómputo de forma continua. La capa gratuita de AWS regala **750 horas mensuales** para una sola instancia. Si dejas encendida la máquina de simulación de Melany 24/7, consumirás todo el Free Tier. Si levantan una segunda máquina, o se exceden del mes, les cobrarán **~$9.00 USD/mes** por cada instancia activa. +* **Solución**: Creen la instancia EC2 en AWS, pero **deténganla (stop)** desde la consola cuando no estén realizando pruebas activas de tráfico. Una EC2 apagada solo cobra centavos por el disco EBS asociado. + +### 2. NAT Gateways (VPC) — *Evitar por completo* +* **Impacto**: Si asocian las funciones Lambda a subredes privadas de su VPC, necesitarán un NAT Gateway para que las Lambdas se conecten a internet. Un NAT Gateway cobra una tarifa fija de **~$32.00 USD/mes** solo por estar creado. +* **Solución**: **Desplieguen las Lambdas fuera de la VPC** (en la red pública de AWS). Usen roles de IAM para la seguridad. Así, se comunicarán con SQS, SNS y la API de EC2 (NACL) a través de los endpoints públicos de AWS de forma segura y a **costo cero**. + +### 3. VPC Endpoints de Interfaz — *Evitar en desarrollo* +* **Impacto**: Son alternativas privadas al NAT Gateway, pero cobran **~$7.20 USD/mes** por cada endpoint activo por Zona de Disponibilidad. +* **Solución**: No crearlos en la fase de desarrollo/pruebas locales. + +--- + +## 4. Buenas Prácticas para el Equipo durante la Tesis + +1. **Mantener la Infraestructura Base Levantada**: Creen y dejen creados de forma permanente los buckets S3, colas SQS, tópicos SNS, VPC, NACLs y funciones Lambda. Esto facilita que Aarón y Bryan hagan pruebas de integración rápidas sin tener que reconstruir el entorno. +2. **Apagar las Máquinas de Prueba**: Asegurar que la instancia EC2 objetivo esté apagada y solo se encienda durante las demos o pruebas conjuntas. +3. **Monitorear con AWS Budgets**: Configurar una alarma en AWS Budgets para que envíe un correo de alerta si el costo acumulado supera los **$1.00 USD** en el mes. diff --git a/analisis_flujo1_bruteforce.md b/analisis_flujo1_bruteforce.md deleted file mode 100644 index cd3e6ec..0000000 --- a/analisis_flujo1_bruteforce.md +++ /dev/null @@ -1,462 +0,0 @@ -# Análisis de Flujo 1 — Ataque Brute-Force en Entorno Local - -**Proyecto:** Trabajo de Integración Curricular — Sistema de Detección y Respuesta ante Incidentes en AWS -**Componente:** C — Automatización de Respuesta -**Responsable:** Bryan -**Fecha de ejecución:** 2026-04-20 -**Entorno:** LocalStack 3.8.1 Community — localhost:4566 - ---- - -## 1. Descripción del Escenario - -Se simuló un ataque de fuerza bruta contra la consola de AWS, donde un actor externo realizó **10 intentos fallidos de autenticación** (`ConsoleLogin` con `AccessDenied`) contra el usuario IAM `admin` desde la IP `185.220.101.5` en un período de ~2 minutos. - -El flujo completo cubre: generación del incidente → almacenamiento en S3 → detección con DuckDB → notificación vía Lambda + SNS. - ---- - -## 2. Flujo Ejecutado - -``` -PASO 1 /localstack-up LocalStack levantado y verificado -PASO 2 /bootstrap-resources Recursos AWS locales creados en LocalStack -PASO 3 /simulate-incident Evento brute-force generado → S3 + SQS -PASO 4 /query-logs DuckDB detectó el IoC (análisis Athena-equivalente) -PASO 5 /deploy-lambda Lambda notify-alert desplegada y ejecutada -``` - ---- - -## 3. Recursos AWS Locales Utilizados - -| Tipo | Nombre | ARN / URL | -|------|--------|-----------| -| S3 | `tesis-security-logs` | `s3://tesis-security-logs/cloudtrail/` | -| 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` | `http://sqs.us-east-1.localhost.localstack.cloud:4566/000000000000/tesis-incident-queue` | -| 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 | -| CloudWatch | `/aws/lambda/tesis-notify-alert` | logs de ejecución de la Lambda | -| IAM | `tesis-lambda-response-role` | `arn:aws:iam::000000000000:role/tesis-lambda-response-role` | -| Lambda | `tesis-notify-alert` | `arn:aws:lambda:us-east-1:000000000000:function:tesis-notify-alert` | - ---- - -## 4. Paso a Paso con Respuestas del Sistema - -### 4.1 LocalStack UP - -```bash -docker compose -f docker-compose.yml up -d -curl -s http://localhost:4566/_localstack/health | python3 -m json.tool -``` - -**Respuesta:** -``` -LocalStack 3.8.1 community — localhost:4566 -Servicios disponibles: s3, sns, sqs, lambda, iam, logs, cloudwatch, events -``` - ---- - -### 4.2 Bootstrap de Recursos - -```bash -source activate.sh -bash infra/setup.sh -``` - -**Respuesta:** -``` -[OK] S3: s3://tesis-security-logs [cloudtrail/, vpc-flow/, guardduty/, responses/] -[OK] SNS alerts: arn:aws:sns:us-east-1:000000000000:tesis-security-alerts -[OK] SNS triggers: arn:aws:sns:us-east-1:000000000000:tesis-lambda-triggers -[OK] SQS queue: http://...localstack.cloud:4566/.../tesis-incident-queue -[OK] SQS DLQ: http://...localstack.cloud:4566/.../tesis-incident-queue-dlq -[OK] CloudWatch: /tesis/security-events -[OK] CloudWatch: /tesis/lambda-responses -[OK] IAM Role: arn:aws:iam::000000000000:role/tesis-lambda-response-role -``` - ---- - -### 4.3 Simulación del Incidente Brute-Force - -```bash -.venv/bin/python3 simulators/inject_logs.py brute-force -``` - -**Respuesta:** -``` -[inject] Generados 10 eventos de tipo 'brute-force' -[inject] Subido a s3://tesis-security-logs/cloudtrail/2026/04/20/234235/brute-force-51cbb9f1.json -[inject] Mensaje SQS enviado a tesis-incident-queue -``` - -**Payload enviado a SQS (entrada para Lambda):** -```json -{ - "incident_type": "BRUTE_FORCE", - "severity": "HIGH", - "sourceIPAddress": "185.220.101.5", - "affectedResource": "iam:user/admin", - "s3_log_key": "cloudtrail/2026/04/20/234235/brute-force-51cbb9f1.json", - "event_count": 10, - "timestamp": "2026-04-20T23:42:35.606154Z" -} -``` - -**Verificación S3:** -``` -s3://tesis-security-logs/cloudtrail/2026/04/20/234235/brute-force-51cbb9f1.json (7,681 bytes) -``` - -**Verificación SQS:** -``` -ApproximateNumberOfMessages: 1 -``` - ---- - -### 4.4 Detección con DuckDB (equivalente a Amazon Athena) - -```bash -.venv/bin/awslocal s3 sync s3://tesis-security-logs/cloudtrail/ /tmp/tesis-logs/ -# Ejecutar queries/detect_brute_force.sql sobre los archivos descargados -``` - -**Estructura del evento CloudTrail simulado:** -```json -{ - "eventVersion": "1.08", - "eventName": "ConsoleLogin", - "eventSource": "signin.amazonaws.com", - "errorCode": "AccessDenied", - "sourceIPAddress": "185.220.101.5", - "userIdentity": { "type": "IAMUser", "userName": "admin" }, - "responseElements": { "ConsoleLogin": "Failure" } -} -``` - -**Resultado de la consulta DuckDB:** - -| sourceIPAddress | username | failed_attempts | first_attempt | last_attempt | -|-----------------|----------|-----------------|---------------|--------------| -| 185.220.101.5 | admin | **10** | 2026-04-20T23:42:35Z | 2026-04-20T23:44:50Z | - -``` -IoC detectados: 1 -Regla disparada: ConsoleLogin + AccessDenied > 5 intentos -Ventana temporal: ~2 minutos -Acción recomendada: notify-alert → block-ip -``` - ---- - -### 4.5 Despliegue y Ejecución de Lambda Playbook `notify-alert` - -```bash -# Empaquetar -python3 -c "import zipfile; z=zipfile.ZipFile('/tmp/notify-alert.zip','w'); z.write('handler.py'); z.close()" - -# Desplegar -.venv/bin/awslocal lambda create-function \ - --function-name tesis-notify-alert \ - --runtime python3.12 \ - --handler handler.lambda_handler \ - --zip-file fileb:///tmp/notify-alert.zip \ - ... - -# Invocar -.venv/bin/awslocal lambda invoke \ - --function-name tesis-notify-alert \ - --cli-binary-format raw-in-base64-out \ - --payload file://lambdas/notify-alert/test_event.json \ - output.json -``` - -**Respuesta de la Lambda (HTTP 200):** -```json -{ - "status": "success", - "processed": 1, - "results": [{ - "status": "success", - "action": "sns_published", - "details": { - "alert_type": "SECURITY_INCIDENT", - "incident_type": "BRUTE_FORCE", - "severity": "HIGH", - "sourceIPAddress": "203.0.113.42", - "affectedResource": "iam:user/admin", - "detectedAt": "2024-01-15T10:30:00Z", - "respondedAt": "2026-04-21T00:00:45Z", - "playbook": "notify-alert", - "status": "NOTIFIED" - } - }], - "timestamp": "2026-04-21T00:00:45Z" -} -``` - -**Logs de ejecución (CloudWatch):** -``` -START RequestId: 11c6f134-... Version: $LATEST -[notify-alert] Alerta publicada: BRUTE_FORCE desde 203.0.113.42 -END RequestId: 11c6f134-... -REPORT Duration: 7.45 ms Billed Duration: 8 ms Memory: 128 MB -``` - ---- - -## 5. Dónde Ver los Logs (Guía Visual) - -### 5.1 Archivos en disco (más directo) - -```bash -# Ver el JSON del incidente subido a S3 (descargado localmente): -cat /tmp/tesis-logs/2026/04/20/234235/brute-force-51cbb9f1.json | python3 -m json.tool - -# Sincronizar todos los logs de S3 a local: -.venv/bin/awslocal s3 sync s3://tesis-security-logs/cloudtrail/ /tmp/tesis-logs/ - -# Ver todos los archivos de logs en S3: -.venv/bin/awslocal s3 ls s3://tesis-security-logs/ --recursive -``` - -### 5.2 Logs de ejecución de Lambda (CloudWatch) - -```bash -# Ver todos los log groups disponibles: -.venv/bin/awslocal logs describe-log-groups --query 'logGroups[].logGroupName' --output text - -# Ver los streams de la Lambda: -.venv/bin/awslocal logs describe-log-streams \ - --log-group-name /aws/lambda/tesis-notify-alert \ - --query 'logStreams[].logStreamName' --output text - -# Leer los logs de la última ejecución: -.venv/bin/awslocal logs get-log-events \ - --log-group-name /aws/lambda/tesis-notify-alert \ - --log-stream-name "2026/04/21/[\$LATEST]STREAM_ID" \ - --query 'events[].message' --output text -``` - -### 5.3 Mensajes en SQS (cola de incidentes) - -```bash -# Ver cuántos mensajes hay en la cola: -.venv/bin/awslocal sqs get-queue-attributes \ - --queue-url http://localhost:4566/000000000000/tesis-incident-queue \ - --attribute-names ApproximateNumberOfMessages - -# Leer un mensaje de la cola (sin eliminarlo): -.venv/bin/awslocal sqs receive-message \ - --queue-url http://localhost:4566/000000000000/tesis-incident-queue \ - --attribute-names All -``` - -### 5.4 Mensajes publicados en SNS - -```bash -# Listar tópicos SNS: -.venv/bin/awslocal sns list-topics - -# Para ver mensajes SNS publicados, suscribir SQS al tópico primero: -.venv/bin/awslocal sns subscribe \ - --topic-arn arn:aws:sns:us-east-1:000000000000:tesis-security-alerts \ - --protocol sqs \ - --notification-endpoint arn:aws:sqs:us-east-1:000000000000:tesis-incident-queue -``` - -### 5.5 Interfaz Web — LocalStack Web UI (sin instalar nada extra) - -LocalStack Community expone una API REST que puedes consultar desde el navegador: - -| Recurso | URL directa en navegador | -|---------|--------------------------| -| Health general | http://localhost:4566/_localstack/health | -| Listar buckets S3 | http://localhost:4566/tesis-security-logs/ | -| Info de LocalStack | http://localhost:4566/_localstack/info | - -> Para una UI visual completa (tablas, árbol de recursos, gráficos), instala **LocalStack Desktop** (gratuito): https://app.localstack.cloud/download — conecta a `localhost:4566` sin credenciales adicionales. - ---- - -## 6. Hallazgos y Correcciones Aplicadas - -### Hallazgo 1 — Scripts fallaban sin credenciales AWS - -**Síntoma:** `botocore.exceptions.NoCredentialsError` al correr `inject_logs.py` sin activar el venv antes. - -**Causa raíz:** `activate.sh` exporta `AWS_ACCESS_KEY_ID=test` pero solo en el shell que lo ejecuta con `source`. Si se llama el script directamente sin haber hecho `source activate.sh`, boto3 no encuentra credenciales. - -**Corrección aplicada** (`simulators/inject_logs.py`): -```python -_KEY = os.environ.get("AWS_ACCESS_KEY_ID", "test") -_SECRET = os.environ.get("AWS_SECRET_ACCESS_KEY", "test") -s3 = boto3.client("s3", ..., aws_access_key_id=_KEY, aws_secret_access_key=_SECRET) -sqs = boto3.client("sqs", ..., aws_access_key_id=_KEY, aws_secret_access_key=_SECRET) -``` - -**Regla para la tesis:** Siempre hacer `source activate.sh` antes de cualquier comando, o asegurar fallback `"test"` en los clientes boto3 del entorno local. - ---- - -### Hallazgo 2 — Queries SQL incompatibles con DuckDB - -**Síntoma:** `ConversionException: Unimplemented type for cast` al ejecutar las queries `.sql`. - -**Causa raíz:** Los archivos SQL usaban el operador de extracción JSON de PostgreSQL (`->>'campo'`), pero DuckDB trabaja con registros struct y requiere acceso por punto (`r.campo`). Además, `format='array'` no es necesario cuando los Records son un campo dentro del JSON raíz. - -**Corrección aplicada** (los 3 archivos en `queries/`): -```sql --- ANTES (PostgreSQL/Athena style — no funciona en DuckDB): -FROM read_json_auto('$LOG_PATH', format='array') -WHERE eventName = 'ConsoleLogin' AND userIdentity->>'userName' = 'x' - --- DESPUÉS (DuckDB struct access): -FROM (SELECT unnest(Records) AS r FROM read_json_auto('$LOG_PATH')) -WHERE r.eventName = 'ConsoleLogin' AND r.userIdentity.userName = 'x' -``` - -**Regla para la tesis:** DuckDB usa acceso por punto para campos de structs anidados. Para JSON complejo con arreglos dentro de objetos, usar `unnest()` para aplanar el array antes de filtrar. - ---- - -### Hallazgo 3 — Lambda no podía alcanzar LocalStack (endpoint `localhost:4566`) - -**Síntoma:** `EndpointConnectionError: Could not connect to http://localhost:4566/` desde dentro de la Lambda. - -**Causa raíz:** Las Lambdas con `LAMBDA_EXECUTOR=docker` se ejecutan en contenedores Docker separados. Dentro de ese contenedor, `localhost` es el propio contenedor Lambda, no el host ni el contenedor LocalStack. - -**Corrección aplicada** (`lambdas/*/handler.py`): -```python -# ANTES — hardcoded, falla dentro del contenedor: -ENDPOINT = os.environ.get("AWS_ENDPOINT_URL", "http://localhost:4566") - -# DESPUÉS — usa LOCALSTACK_HOSTNAME inyectada automáticamente por LocalStack: -_ls_host = os.environ.get("LOCALSTACK_HOSTNAME", "localhost") -ENDPOINT = os.environ.get("AWS_ENDPOINT_URL", f"http://{_ls_host}:4566") -``` - -**Por qué funciona:** LocalStack inyecta automáticamente la variable `LOCALSTACK_HOSTNAME` en cada contenedor Lambda que lanza, apuntando al hostname correcto dentro de la red Docker. - ---- - -### Hallazgo 4 — IP de LocalStack cambia entre reinicios - -**Síntoma:** Workaround manual de usar `172.19.0.2:4566` dejó de funcionar tras reiniciar Docker (la IP puede asignarse distinta). - -**Causa raíz:** Sin una red Docker configurada explícitamente para los contenedores Lambda, cada reinicio puede resultar en IPs distintas para los contenedores. - -**Corrección aplicada** (`docker-compose.yml`): -```yaml -environment: - - LAMBDA_EXECUTOR=docker - - LAMBDA_DOCKER_NETWORK=localstack-tesis_default # ← AÑADIDO -``` - -Esto garantiza que los contenedores Lambda se unan a la misma red Docker que LocalStack (`localstack-tesis_default`), haciendo que `LOCALSTACK_HOSTNAME` sea siempre resoluble por nombre de contenedor, independientemente de la IP asignada. - ---- - -## 7. Archivos Modificados en Esta Sesión - -| Archivo | Cambio | -|---------|--------| -| `simulators/inject_logs.py` | Credenciales boto3 con fallback `"test"` | -| `queries/detect_brute_force.sql` | Sintaxis DuckDB: `r.campo` en lugar de `->>'campo'` | -| `queries/detect_privilege_esc.sql` | Misma corrección de sintaxis | -| `queries/detect_exfiltration.sql` | Misma corrección de sintaxis | -| `docker-compose.yml` | `LAMBDA_DOCKER_NETWORK=localstack-tesis_default` | -| `lambdas/notify-alert/handler.py` | Endpoint via `LOCALSTACK_HOSTNAME` | -| `lambdas/revoke-credentials/handler.py` | Endpoint via `LOCALSTACK_HOSTNAME` | - ---- - -## 8. Diagrama del Flujo Ejecutado - -``` -Atacante externo -185.220.101.5 - │ - │ 10x ConsoleLogin FAILED - ▼ -┌─────────────────────────────────────────────────────────┐ -│ simulators/inject_logs.py │ -│ cloudtrail_gen.py → genera 10 eventos CloudTrail JSON │ -└────────────────────┬────────────────────────────────────┘ - │ - ┌──────────┼──────────┐ - ▼ ▼ -┌─────────────────┐ ┌─────────────────────────┐ -│ S3 LocalStack │ │ SQS LocalStack │ -│ tesis-security- │ │ tesis-incident-queue │ -│ logs/cloudtrail/ │ │ payload BRUTE_FORCE │ -│ (7,681 bytes) │ │ severity: HIGH │ -└────────┬────────┘ └───────────┬─────────────┘ - │ │ - ▼ ▼ -┌─────────────────┐ ┌─────────────────────────┐ -│ DuckDB (Athena) │ │ Lambda: notify-alert │ -│ detect_brute_ │ │ Runtime: python3.12 │ -│ force.sql │ │ Duration: 7.45 ms │ -│ │ │ │ -│ RESULTADO: │ │ → sns.publish() │ -│ 10 intentos │ │ → SNS: tesis-security- │ -│ desde misma IP │ │ alerts │ -│ IoC: CONFIRMADO │ │ → status: NOTIFIED │ -└─────────────────┘ └───────────┬─────────────┘ - │ - ┌──────────▼──────────┐ - │ CloudWatch Logs │ - │ /aws/lambda/tesis- │ - │ notify-alert │ - │ │ - │ [notify-alert] │ - │ Alerta publicada: │ - │ BRUTE_FORCE desde │ - │ 203.0.113.42 │ - └─────────────────────┘ -``` - ---- - -## 9. Verificación Final del Estado - -```bash -# Verificar Lambda activa: -.venv/bin/awslocal lambda get-function --function-name tesis-notify-alert \ - --query 'Configuration.[State,Runtime,Timeout]' --output text -# Active python3.12 30 - -# Ver log de ejecución: -.venv/bin/awslocal logs get-log-events \ - --log-group-name /aws/lambda/tesis-notify-alert \ - --log-stream-name "$(awslocal logs describe-log-streams \ - --log-group-name /aws/lambda/tesis-notify-alert \ - --query 'logStreams[0].logStreamName' --output text)" \ - --query 'events[].message' --output text -``` - -**Salida esperada:** -``` -START RequestId: 11c6f134-... Version: $LATEST -[notify-alert] Alerta publicada: BRUTE_FORCE desde 203.0.113.42 -END RequestId: 11c6f134-... -REPORT Duration: 7.45 ms Billed Duration: 8 ms Memory: 128 MB -``` - ---- - -## 10. Próximos Pasos - -- [ ] Desplegar playbook `block-ip` y encadenarlo tras `notify-alert` -- [ ] Desplegar playbook `revoke-credentials` para escenario `credential-leak` -- [ ] Simular incidente `privilege-escalation` y ejecutar el flujo completo -- [ ] Conectar SQS → Lambda trigger (event source mapping) para respuesta automática sin invocación manual -- [ ] Suscribir un email o cola SQS al tópico SNS para ver notificaciones end-to-end diff --git a/analisis_flujo2_automatizacion.md b/analisis_flujo2_automatizacion.md deleted file mode 100644 index f750e3b..0000000 --- a/analisis_flujo2_automatizacion.md +++ /dev/null @@ -1,328 +0,0 @@ -# Análisis de Flujo 2 — Automatización Completa del Componente C - -**Proyecto:** Trabajo de Integración Curricular — Sistema de Detección y Respuesta ante Incidentes en AWS -**Componente:** C — Automatización de Respuesta -**Responsable:** Bryan -**Fecha de ejecución:** 2026-04-21 -**Entorno:** LocalStack 3.8.1 Community — localhost:4566 - ---- - -## 1. Objetivo de Este Flujo - -Completar el Componente C de forma que la respuesta ante incidentes sea **totalmente automática**: -un mensaje en SQS dispara el playbook correcto sin ninguna intervención manual. - ---- - -## 2. Estado Antes vs Después - -| Capacidad | Antes (Flujo 1) | Después (Flujo 2) | -|-----------|-----------------|-------------------| -| Simular incidente → S3 + SQS | ✅ | ✅ | -| Detectar con DuckDB (Athena) | ✅ | ✅ | -| Lambda `notify-alert` | ✅ manual | ✅ automático | -| Lambda `block-ip` | ❌ no existía | ✅ automático | -| Lambda `revoke-credentials` | ✅ código, no desplegada | ✅ automático | -| Lambda `isolate-instance` | ❌ no existía | ✅ automático | -| Lambda `dispatcher` (enrutador) | ❌ no existía | ✅ automático | -| SQS → Lambda trigger automático | ❌ invocación manual | ✅ Event Source Mapping | - ---- - -## 3. Arquitectura Final del Componente C - -``` -Atacante externo - │ - ▼ -simulators/inject_logs.py - ├── genera eventos CloudTrail JSON - ├── sube a S3: tesis-security-logs/cloudtrail/ - └── publica en SQS: tesis-incident-queue - │ - │ Event Source Mapping (automático) - │ batch-size: 1 - ▼ - ┌─────────────────────────────┐ - │ Lambda: tesis-dispatcher │ - │ Tabla de enrutamiento: │ - │ │ - │ BRUTE_FORCE → notify-alert + block-ip │ - │ CREDENTIAL_LEAK → notify-alert + revoke-credentials │ - │ PRIVILEGE_ESC → notify-alert + revoke-credentials │ - │ EXFILTRATION → notify-alert + isolate-instance │ - │ PORT_SCAN → notify-alert + block-ip │ - └──────────────┬──────────────┘ - │ lambda.invoke() para cada playbook - ┌──────────────┼──────────────┬────────────────┐ - ▼ ▼ ▼ ▼ - notify-alert block-ip revoke-credentials isolate-instance - sns.publish() S3 blocklist iam.update_access_key S3 quarantine - │ │ │ │ - └──────────────┴──────────────┴────────────────┘ - │ - SNS: tesis-security-alerts - │ - CloudWatch Logs - /aws/lambda/tesis-* -``` - ---- - -## 4. Playbooks Creados - -### 4.1 `tesis-dispatcher` - -**Rol:** Lambda central. Consume mensajes de SQS automáticamente (Event Source Mapping) y enruta al conjunto correcto de playbooks según `incident_type`. - -**Tabla de enrutamiento:** - -| incident_type | Playbooks invocados | -|---------------|---------------------| -| `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 | - -**ARN:** `arn:aws:lambda:us-east-1:000000000000:function:tesis-dispatcher` - ---- - -### 4.2 `tesis-block-ip` - -**Rol:** Registra la IP atacante en `s3://tesis-security-logs/responses/blocked-ips.json` y notifica via SNS. -**Equivalente real AWS:** Actualizar WAF IP Set o regla de Security Group/NACL. - -**Resultado en S3 tras ejecución:** -```json -[ - { - "ip": "203.0.113.42", - "blocked_at": "2026-04-21T01:00:32Z", - "reason": "BRUTE_FORCE", - "severity": "HIGH", - "affectedResource": "iam:user/external-contractor" - } -] -``` - -**ARN:** `arn:aws:lambda:us-east-1:000000000000:function:tesis-block-ip` - ---- - -### 4.3 `tesis-revoke-credentials` (ya existía, ahora desplegada) - -**Rol:** Desactiva todas las access keys del usuario IAM comprometido y aplica política `EmergencyDenyAll`. -**Equivalente real AWS:** `iam:UpdateAccessKey` + `iam:PutUserPolicy`. - -**Acciones que ejecuta:** -1. Lista access keys del usuario afectado -2. Cambia cada key a `Status: Inactive` -3. Adjunta política JSON de `Deny *` como contención inmediata -4. Publica resultado en SNS - -**ARN:** `arn:aws:lambda:us-east-1:000000000000:function:tesis-revoke-credentials` - ---- - -### 4.4 `tesis-isolate-instance` - -**Rol:** Registra la instancia comprometida en `s3://tesis-security-logs/responses/quarantine-instances.json` y notifica. -**Equivalente real AWS:** Reemplazar Security Group por uno vacío + tomar snapshot EBS. - -**Resultado en S3:** -```json -[ - { - "resource": "ec2:instance/i-0abc123def456", - "isolated_at": "2026-04-21T01:00:xx Z", - "reason": "EXFILTRATION", - "actions_applied": [ - "security_group_removed", - "deny_all_policy_applied", - "snapshot_triggered" - ] - } -] -``` - -**ARN:** `arn:aws:lambda:us-east-1:000000000000:function:tesis-isolate-instance` - ---- - -### 4.5 `tesis-notify-alert` (existía, sin cambios) - -**Rol:** Construye y publica el mensaje de alerta al tópico SNS. -**ARN:** `arn:aws:lambda:us-east-1:000000000000:function:tesis-notify-alert` - ---- - -## 5. Event Source Mapping — La Pieza Clave - -```bash -awslocal lambda create-event-source-mapping \ - --function-name tesis-dispatcher \ - --event-source-arn arn:aws:sqs:us-east-1:000000000000:tesis-incident-queue \ - --batch-size 1 -``` - -| Campo | Valor | -|-------|-------| -| UUID | `71e87db4-3ed3-4d73-8830-ebba22aec20d` | -| Estado | `Enabled` | -| Fuente | `arn:aws:sqs:us-east-1:000000000000:tesis-incident-queue` | -| Destino | `tesis-dispatcher` | -| Batch size | 1 mensaje por invocación | - -**Efecto:** Cuando `inject_logs.py` publica en SQS, LocalStack detecta el mensaje y dispara `tesis-dispatcher` automáticamente, sin ningún comando manual adicional. - ---- - -## 6. Prueba del Flujo Automático Completo - -### Comando ejecutado - -```bash -.venv/bin/python3 simulators/inject_logs.py brute-force -``` - -### Secuencia automática resultante - -``` -1. inject_logs.py → SQS: tesis-incident-queue (mensaje BRUTE_FORCE) -2. Event Source Mapping → dispara tesis-dispatcher automáticamente -3. dispatcher lee incident_type=BRUTE_FORCE -4. dispatcher invoca tesis-notify-alert → SUCCESS (SNS publicado) -5. dispatcher invoca tesis-block-ip → SUCCESS (S3 blocklist actualizado) -6. Mensajes en cola después: 0 (consumido y procesado) -``` - -### Log del dispatcher (CloudWatch) - -``` -START RequestId: 1e250e37-... Version: $LATEST -[dispatcher] Incidente: BRUTE_FORCE (HIGH) → playbooks: ['tesis-notify-alert', 'tesis-block-ip'] -[dispatcher] tesis-notify-alert → success -[dispatcher] tesis-block-ip → success -END RequestId: 1e250e37-... -REPORT Duration: 2220.58 ms Billed Duration: 2221 ms Memory: 128 MB -``` - -### Evidencias en S3 - -```bash -# Ver IPs bloqueadas: -.venv/bin/awslocal s3 cp s3://tesis-security-logs/responses/blocked-ips.json - - -# Ver instancias en cuarentena (tras simular exfiltration): -.venv/bin/awslocal s3 cp s3://tesis-security-logs/responses/quarantine-instances.json - - -# Ver todos los archivos de respuesta: -.venv/bin/awslocal s3 ls s3://tesis-security-logs/responses/ -``` - ---- - -## 7. Cómo Verificar Cada Parte del Flujo Tú Mismo - -### Ver el log de cualquier Lambda - -```bash -# Reemplaza NOMBRE por: tesis-dispatcher, tesis-block-ip, tesis-notify-alert, etc. -NOMBRE=tesis-dispatcher -STREAM=$(.venv/bin/awslocal logs describe-log-streams \ - --log-group-name /aws/lambda/$NOMBRE \ - --order-by LastEventTime --descending \ - --query 'logStreams[0].logStreamName' --output text) - -.venv/bin/awslocal logs get-log-events \ - --log-group-name /aws/lambda/$NOMBRE \ - --log-stream-name "$STREAM" \ - --query 'events[].message' --output text -``` - -### Simular cualquier tipo de incidente - -```bash -# Tipos: brute-force | privilege-escalation | credential-leak | exfiltration | port-scan -.venv/bin/python3 simulators/inject_logs.py credential-leak -.venv/bin/python3 simulators/inject_logs.py privilege-escalation -.venv/bin/python3 simulators/inject_logs.py exfiltration -``` - -Cada uno disparará automáticamente el playbook correspondiente en ~2-3 segundos. - -### Ver el estado del Event Source Mapping - -```bash -.venv/bin/awslocal lambda list-event-source-mappings \ - --function-name tesis-dispatcher \ - --query 'EventSourceMappings[0].[UUID,State,EventSourceArn]' --output text -``` - -### Ver todas las Lambdas desplegadas - -```bash -.venv/bin/awslocal lambda list-functions \ - --query 'Functions[].[FunctionName,Runtime]' --output table -``` - ---- - -## 8. Archivos Creados en Esta Sesión - -| Archivo | Descripción | -|---------|-------------| -| `lambdas/dispatcher/handler.py` | Lambda central de enrutamiento por `incident_type` | -| `lambdas/dispatcher/policy.json` | Política IAM mínimo privilegio: `lambda:InvokeFunction` + SQS | -| `lambdas/dispatcher/test_event.json` | Evento de prueba para invocación manual | -| `lambdas/block-ip/handler.py` | Playbook: bloquea IP en S3 blocklist + SNS | -| `lambdas/block-ip/policy.json` | Política IAM: `s3:PutObject` en `responses/*` + SNS | -| `lambdas/block-ip/test_event.json` | Evento de prueba | -| `lambdas/isolate-instance/handler.py` | Playbook: cuarentena de instancia en S3 + SNS | -| `lambdas/isolate-instance/policy.json` | Política IAM: `s3:PutObject` en `responses/*` + SNS | -| `lambdas/isolate-instance/test_event.json` | Evento de prueba | - ---- - -## 9. Estado Final del Componente C - -``` -Simular incidente → S3 + SQS ✅ inject_logs.py -Detectar con DuckDB (≈ Athena) ✅ queries/detect_*.sql -Respuesta automática (dispatcher) ✅ Event Source Mapping SQS → Lambda - BRUTE_FORCE → notify + block-ip ✅ - CREDENTIAL_LEAK → notify + revoke-credentials ✅ - PRIVILEGE_ESC → notify + revoke-credentials ✅ - EXFILTRATION → notify + isolate-instance ✅ - PORT_SCAN → notify + block-ip ✅ -Evidencias de respuesta en S3 ✅ responses/blocked-ips.json - responses/quarantine-instances.json -Logs de ejecución en CloudWatch ✅ /aws/lambda/tesis-* -Principio de mínimo privilegio ✅ policy.json por playbook -``` - ---- - -## 10. Notas para la Tesis - -### Sobre `LAMBDA_EXECUTOR=docker` -Las Lambdas se ejecutan en contenedores Docker separados lanzados por LocalStack. Esto replica el modelo de ejecución de AWS Lambda real (contenedores efímeros, aislados, con su propio filesystem). La latencia de arranque en frío (~2 segundos) que se observa en los logs es equivalente al cold start real de AWS. - -### Sobre la simulación de block-ip e isolate-instance -En AWS real, `block-ip` actualizaría un WAF IP Set o una regla NACL, y `isolate-instance` modificaría el Security Group de EC2 a uno sin reglas. Ambos servicios requieren plan Pro en LocalStack. La implementación con S3 como almacén de estado es funcionalmente equivalente para demostrar el flujo de respuesta y es la práctica estándar en entornos de prueba sin licencia. - -### Sobre el Event Source Mapping -Esta es la forma nativa de AWS de conectar SQS con Lambda. En producción, cuando `batch-size=1`, cada mensaje SQS genera exactamente una invocación de Lambda. Si la Lambda falla (excepción no manejada), el mensaje retorna a la cola hasta `maxReceiveCount=3`, tras lo cual va al DLQ (`tesis-incident-queue-dlq`). Esto garantiza que ningún incidente se pierda silenciosamente. - -### Limitación conocida -LocalStack no persiste estado entre reinicios. Al reiniciar Docker, ejecutar en orden: -```bash -source activate.sh -docker compose up -d -bash infra/setup.sh -# Re-desplegar las 5 Lambdas con el script de deploy -# Re-crear el Event Source Mapping -``` diff --git a/demo/demo_stack.sh b/demo 19 Mayo/demo_stack.sh similarity index 79% rename from demo/demo_stack.sh rename to demo 19 Mayo/demo_stack.sh index af5aadb..12509ef 100755 --- a/demo/demo_stack.sh +++ b/demo 19 Mayo/demo_stack.sh @@ -13,6 +13,68 @@ set -uo pipefail cd "$(dirname "$0")/.." export PATH="$PWD/.venv/bin:$PATH" +# ── PREFLIGHT: asegurar LocalStack + recursos + lambdas ────────────────────── +_preflight() { + local C_OK='\033[0;32m'; local C_WARN='\033[1;33m'; local NC='\033[0m' + echo -e "${C_WARN}[preflight] Verificando entorno...${NC}" + + # 1. LocalStack + if ! curl -sf http://localhost:4566/_localstack/health > /dev/null 2>&1; then + echo -e "${C_WARN}[preflight] Levantando LocalStack...${NC}" + docker compose up -d + echo -n "[preflight] Esperando que LocalStack esté listo" + for i in $(seq 1 30); do + curl -sf http://localhost:4566/_localstack/health > /dev/null 2>&1 && break + echo -n "." ; sleep 2 + done + echo "" + fi + echo -e "${C_OK}[preflight] LocalStack OK${NC}" + + # 2. Bootstrap (idempotente) + bash infra/setup.sh > /dev/null 2>&1 + echo -e "${C_OK}[preflight] Recursos AWS OK (S3, SNS, SQS, IAM, EC2/NACL)${NC}" + + # 3. Desplegar / actualizar lambdas + local ROLE="arn:aws:iam::000000000000:role/tesis-lambda-response-role" + local ENV_VARS="Variables={S3_BUCKET=tesis-security-logs,SNS_ALERTS_ARN=arn:aws:sns:us-east-1:000000000000:tesis-security-alerts}" + for fn in notify-alert block-ip revoke-credentials isolate-instance dispatcher; do + local zip="/tmp/tesis-${fn}.zip" + python3 -c " +import zipfile +z = zipfile.ZipFile('${zip}', 'w', __import__('zipfile').ZIP_DEFLATED) +z.write('lambdas/${fn}/handler.py', 'handler.py') +z.close() +" + if awslocal lambda get-function --function-name "tesis-${fn}" > /dev/null 2>&1; then + awslocal lambda update-function-code \ + --function-name "tesis-${fn}" --zip-file "fileb://${zip}" > /dev/null + else + awslocal lambda create-function \ + --function-name "tesis-${fn}" --runtime python3.12 --role "$ROLE" \ + --handler handler.lambda_handler --zip-file "fileb://${zip}" \ + --timeout 30 --environment "$ENV_VARS" > /dev/null + fi + done + echo -e "${C_OK}[preflight] Lambdas OK (notify-alert, block-ip, revoke-credentials, isolate-instance, dispatcher)${NC}" + + # 4. Event source mapping dispatcher → SQS + local QUEUE_ARN="arn:aws:sqs:us-east-1:000000000000:tesis-incident-queue" + local mapping_count + mapping_count=$(awslocal lambda list-event-source-mappings \ + --function-name tesis-dispatcher \ + --query 'length(EventSourceMappings)' --output text 2>/dev/null || echo "0") + if [ "$mapping_count" = "0" ] || [ -z "$mapping_count" ]; then + awslocal lambda create-event-source-mapping \ + --function-name tesis-dispatcher \ + --event-source-arn "$QUEUE_ARN" \ + --batch-size 1 --enabled > /dev/null + fi + echo -e "${C_OK}[preflight] Event source mapping SQS→dispatcher OK${NC}" + echo "" +} +_preflight + AWSL="awslocal" BUCKET="tesis-security-logs" QUEUE_URL="http://localhost:4566/000000000000/tesis-incident-queue" diff --git a/demo/esquema_almacenamiento.md b/demo 19 Mayo/esquema_almacenamiento.md similarity index 82% rename from demo/esquema_almacenamiento.md rename to demo 19 Mayo/esquema_almacenamiento.md index db22766..cce970c 100644 --- a/demo/esquema_almacenamiento.md +++ b/demo 19 Mayo/esquema_almacenamiento.md @@ -178,3 +178,18 @@ Equivale a una consulta Athena sobre la tabla CloudTrail catalogada por Glue. ``` El almacenamiento es la columna vertebral: cada fase deja una **evidencia consultable y trazable**, desde el log del ataque hasta la prueba del bloqueo real. + +El diseño se ha estructurado bajo un enfoque de separación de responsabilidades y preservación forense de la evidencia, destacando las siguientes decisiones arquitectónicas: + + Arquitectura Data Lake (Zero-ETL): Toda la información se centraliza en un bucket único particionado en Amazon S3. Esto permite ejecutar consultas analíticas directas sobre los archivos en reposo utilizando DuckDB (en el entorno local) y Amazon Athena (en producción), eliminando la necesidad de mover o duplicar datos. + + Desacoplamiento con Tolerancia a Fallos: Se interpuso un bus de mensajería (Amazon SQS) junto con una Dead Letter Queue (DLQ) entre el motor de detección y los playbooks. Esto garantiza la entrega del incidente; si la mitigación falla, el evento se reintenta y/o se aísla, evitando la pérdida de alertas críticas. + + Contratos de Datos Estrictos: Se estandarizaron los esquemas JSON tanto para el payload de tránsito del incidente como para la evidencia de mitigación. Destaca la inclusión de un bloque de enforcement que audita exactamente dónde y cómo se aplicó el bloqueo (ej. ID de la Network ACL y regla específica). + + Gobernanza y Cadena de Custodia: El almacenamiento se divide en tres capas lógicas: Forense (S3, inmutable a través de S3 Object Lock para preservar la integridad del ataque y la respuesta), Tránsito (SQS, efímera) y Operativa (CloudWatch, para trazas lógicas de ejecución). + +cd ~/localstack-tesis + docker compose up -d # si LocalStack no está corriendo + bash infra/setup.sh # bootstrap (idempotente) + bash demo/demo_stack.sh # demo narrada, avanza con ENTER diff --git a/estrategia_paralelo_aws.md b/estrategia_paralelo_aws.md new file mode 100644 index 0000000..b0abe0e --- /dev/null +++ b/estrategia_paralelo_aws.md @@ -0,0 +1,39 @@ +# Estrategia de Trabajo en Paralelo e Integración en AWS (Componente C) + +Este documento describe la estrategia recomendada para que Bryan (Componente C), Melany (Componente A) y Aarón (Componente B) colaboren en paralelo para construir y demostrar el flujo completo en AWS reduciendo los costos mensuales a cero. + +--- + +## 1. Arquitectura a Costo Cero ($0 USD) +Para evitar cobros fijos en la cuenta de AWS de pruebas, la regla de diseño principal es **desplegar las Lambdas fuera de la VPC (sin asociarlas a subredes privadas)**. + +* **Sin NAT Gateway**: Una Lambda dentro de una VPC privada requiere un NAT Gateway para enviar mensajes a SQS, publicar en SNS o conectarse al bucket S3 por su endpoint público. El costo del NAT Gateway es de ~$32 USD/mes fijo. +* **Seguridad y Costo Cero**: Al mantener las Lambdas en la red pública de AWS, estas se conectan a los servicios administrados (SQS, SNS, IAM, S3, EC2) a través de internet de manera cifrada (HTTPS) utilizando sus permisos de IAM execution role. No se genera ningún cargo fijo de infraestructura de red. + +--- + +## 2. Plan de Desarrollo en Paralelo (Contratos de Integración) +El equipo no necesita esperar a que los componentes estén finalizados para empezar a probar. El flujo se divide en interfaces claras: + +``` +[Melany — Comp. A] -> Genera logs (CloudTrail/VPC Flow) en S3. + | (Formato de Archivos) +[Aarón — Comp. B] -> Lee logs, aplica Queries Athena en S3 y publica detección en SQS. + | (Formato JSON de Incidentes) +[Bryan — Comp. C] -> Recibe alertas de SQS, ejecuta dispatcher y activa Playbooks. +``` + +### Acción 1: Contrato de Cola de Entrada SQS +Se debe crear una única cola SQS real en AWS (`tesis-incident-queue`) que actuará como el canal de comunicación entre el Componente B y el Componente C. + +### Acción 2: Pruebas Independientes +* **Aarón** puede probar su Lambda de detección subiendo archivos de logs de prueba (mock logs) en S3, ejecutando Athena y verificando que el payload JSON llegue a SQS. +* **Bryan** puede probar el dispatcher y los playbooks inyectando mensajes JSON de prueba manualmente en la cola SQS de AWS desde la consola web, confirmando que las NACLs se bloquean y que el correo de alerta de SNS se envía. + +--- + +## 3. Demostración del Flujo Completo +Para la presentación del avance ante el profesor, se pueden utilizar dos opciones de demostración: + +1. **Opción Real (End-to-End)**: Se realiza una actividad real (ej. intentar loggearse falsamente en la cuenta) -> CloudTrail registra en S3 -> Aarón detecta con Lambda/Athena -> Aarón publica en SQS -> Lambda Dispatcher se activa -> Playbook `block-ip` deniega el acceso a la IP del atacante en la NACL real. +2. **Opción Híbrida (Simulada para Contingencias)**: Si hay demoras de propagación en los logs de CloudTrail (~15 minutos en AWS real), Bryan ejecuta un script Python local que inyecta el incidente directamente en la SQS de AWS, demostrando la respuesta automatizada en vivo en menos de 5 segundos. diff --git a/guia_acoplamiento_paralelo.md b/guia_acoplamiento_paralelo.md new file mode 100644 index 0000000..0b47aaf --- /dev/null +++ b/guia_acoplamiento_paralelo.md @@ -0,0 +1,90 @@ +# Guía de Acoplamiento y Desarrollo en Paralelo (Componentes A, B y C) + +Este documento detalla el paso a paso técnico para integrar los tres componentes de la tesis (A: Logs, B: Detección, C: Respuesta) en AWS de forma simultánea, permitiendo que cada miembro trabaje de manera independiente sin bloquear a los demás. + +--- + +## 1. El Concepto: Desarrollo Desacoplado + +Para evitar depender de que un compañero termine su parte para poder probar la tuya, utilizaremos **Contratos de Interfaz** (esquemas de datos acordados). Cada componente interactuará con el siguiente a través de un recurso de AWS intermedio (S3 o SQS), actuando como amortiguador. + +``` + [Componente A — Melany] ==== (Contrato 1: S3) ====> [Componente B — Aarón] ==== (Contrato 2: SQS) ====> [Componente C — Bryan] + (Logs en cloudtrail/) (Queries Athena/DuckDB) (Dispatcher & Playbooks) +``` + +--- + +## 2. Paso a Paso para el Acoplamiento + +### Paso 1: Definición de Interfaces (Alineación Inicial) +Antes de escribir código en AWS, el equipo debe acordar y fijar dos contratos: + +* **Contrato 1 (Rutas en S3)**: Melany y Aarón acuerdan la estructura de carpetas en S3. + * Ruta CloudTrail: `s3:///cloudtrail/YYYY/MM/DD/` + * Ruta VPC Flow Logs: `s3:///vpc-flow/YYYY/MM/DD/` +* **Contrato 2 (Formato JSON de Incidentes)**: Aarón y Bryan acuerdan el formato de datos que se enviará por SQS. + * *Estructura obligatoria:* + ```json + { + "incident_type": "BRUTE_FORCE", + "severity": "HIGH", + "sourceIPAddress": "185.220.101.5", + "affectedResource": "iam:user/admin", + "s3_log_key": "cloudtrail/2026/05/26/archivo.json", + "timestamp": "2026-05-26T21:00:00Z", + "event_count": 10 + } + ``` + +--- + +### Paso 2: Aprovisionamiento de Infraestructura Base en AWS +Uno de los miembros (o usando un archivo de Terraform compartido) debe crear los siguientes recursos en la cuenta de AWS real: + +1. **S3 Bucket:** `tesis-security-logs-prod` (para Melany y Aarón). +2. **Cola SQS:** `tesis-incident-queue` (para Aarón y Bryan). +3. **Tópico SNS:** `tesis-security-alerts` (para Bryan). +4. **VPC y NACL por defecto** (para las pruebas de bloqueo de red de Bryan). + +--- + +### Paso 3: Fase de Desarrollo Independiente (En Paralelo) + +Con los recursos base creados, cada componente puede avanzar de forma independiente: + +#### 💻 ¿Cómo trabaja Melany (Componente A)? +* **Tarea**: Configurar CloudTrail y VPC Flow Logs para que escriban en el bucket S3 real. +* **Cómo probar sola**: Puede forzar eventos en AWS (ej. fallar logins o hacer escaneos de puertos) y verificar que los archivos de logs aparezcan en las carpetas correctas de S3. + +#### 💻 ¿Cómo trabaja Aarón (Componente B)? +* **Tarea**: Escribir la Lambda de detección (programada con EventBridge Scheduler cada 5 min) que corre consultas Athena en S3 y publica incidentes en SQS. +* **Cómo probar solo sin Melany**: Aarón no necesita esperar que los logs reales de CloudTrail estén configurados. Él puede **subir manualmente archivos JSON de logs sintéticos** (como los de `sample_cloudtrail.json`) a su bucket S3 y correr sus queries de Athena para verificar que detecte el ataque e inserte el JSON acordado en la SQS. + +#### 💻 ¿Cómo trabajas tú (Componente C - Bryan)? +* **Tarea**: Escribir la Lambda Dispatcher y los Playbooks (Block-IP, Revoke-Credentials, Isolate-Instance). +* **Cómo probar solo sin Aarón**: No necesitas que el detector de Aarón funcione. Puedes abrir la consola web de AWS, ir a la cola SQS `tesis-incident-queue` y **enviar un mensaje de prueba con el formato JSON acordado**. Esto disparará tu flujo completo automáticamente y podrás verificar: + * Si tu IP fue bloqueada en la NACL real de AWS. + * Si el usuario de prueba de IAM fue bloqueado (política `EmergencyDenyAll`). + * Si recibiste la notificación por correo de SNS. + +--- + +### Paso 4: Fase de Integración (Unión de Piezas) + +Una vez que cada módulo funcione por separado, la integración final en AWS real se realiza en tres simples pasos: + +1. **Vincular SQS a Dispatcher**: Configurar el *Event Source Mapping* en la Lambda Dispatcher apuntando a la cola SQS. +2. **Apuntar Detección a SQS Real**: Asegurarse de que la Lambda de Detección de Aarón envíe los mensajes a la URL de SQS real de producción en AWS, no a LocalStack. +3. **Apuntar Detección a Logs Reales**: Cambiar la ruta de origen en la consulta de Athena de Aarón para que analice los logs reales ingestados por Melany. + +--- + +## 3. Estrategia de Pruebas Cruzadas para la Demo del Profesor + +Para demostrar el avance completo del flujo al profesor, ejecuten el siguiente caso de prueba interactivo: + +1. **Ataque**: Desde una máquina externa, ejecuten un pequeño script de fuerza bruta hacia la consola de AWS (Melany captura el log en S3). +2. **Detección**: Muestren la consola de Athena en AWS donde la query SQL identifica a la IP atacante (Aarón muestra los IoC detectados). +3. **Alerta**: El mensaje de alerta viaja a SQS y activa tu Dispatcher. +4. **Respuesta**: Muestren la pestaña de Network ACL en AWS EC2 en tiempo real. Al refrescar, la IP atacante debe aparecer con una regla `DENY` número `1` (Bryan demuestra la contención exitosa). diff --git a/lamb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}%(f_*Vf9uzC@D!AC)IuCjbBd literal 0 HcmV?d00001 diff --git a/lambdas/notify-alert.zip b/lambdas/notify-alert.zip new file mode 100644 index 0000000000000000000000000000000000000000..2c7e0f665a983dca6af2e9a5a64723245fa78a93 GIT binary patch literal 2424 zcmai$c{r5o8^^~kOxgD>$66R^p&F90Wynq$GMJ&U3&+-+tl76Qvc-vElqE(Q+t_ka z%C1ewBn^@^`;y;Go%1{8oI3A&UC;Bpf4rajx$f`1nL-&Dc>%OXHxq03#0UgE+g5# zCwLcC(AUvXqzk=?1j4yPN@-G*o1gM_CFG0S6rCIIo11W@J&Et0i$LD;RAEtmp~ZHN zEL3DA%_Jo)pr8qmU>-|2BY@Cfa?0D+V~WiDHr%VdM# z0^L029h-egs~;5UiZ);ruDHLo$)i&ahuJ=pROqcU^5XAHGDw{>I( z%i0hGQ9FCN788M|K|V*N;3{EaJ~O1VirMl#)zQf9xG-ruM>w~6v6;^UqC1u?CjLyg z>;gTh$}rG$g=5(o&h}Y33{j3j2)SY)7A0I5uu9&Q4EjL?_^5b0m!u%x$`+^-nHs^) zalF%L=~ki)nuEl$bn&uG=o%cddHz@p^fJZcBr9;L4ErW0vfy z-5IGT6#QRQKA3aLpO41GAz)LP&A1zq(ZCmdd@8|kRo#_>`BkqWAc)Arl*Oi#D|N4D zV)W1g7Py+ieAhqT*ecmTXmW%nPcE?Rm)Gbj@2nGd4-h4Rq08+Seid)>bVgk(2E=Ur z2K%1!LX9s7H{y~ZHhH$fm((Y2M7^vMK~?zIGVTzvIv_q3lXt`(aD)?qK=o|Q$2){B z{_A>C5$OT<&$X$h9YjG~Jto1eD!)7IcI%W%RmU)BFy60rQsHi??}_=3wuO^6gwsoiY=^l?`tMZP=(LS9Y|Uk%~r7l-uK`@-X>y z9~yLkZo1%1jl+7+N=LI7a-ZoZ8Rm65MTQK8d)Apvel`*em@ve9PD>o_$;NL7DZ&VY zl(%3LZw)&oH?VzjOQJr+mR*g~$vdOZvHvisAaLu@y%;_rwY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ursos_y_costos_aws.md new file mode 100644 index 0000000..bee02c4 --- /dev/null +++ b/recursos_y_costos_aws.md @@ -0,0 +1,81 @@ +# Implementación en AWS: Costos, Integración y Seguridad (Componente C) + +Este documento resume los costos estimados, los requisitos de integración con los componentes de Melany y Aarón, el formato de datos de incidentes, y los mecanismos de seguridad necesarios para desplegar el **Componente C: Automatización de Respuesta** en un entorno real de AWS. + +--- + +## 1. Costos Estimados en AWS Real +Para propósitos académicos, de prueba y demostración de la tesis, **el costo mensual aproximado es de $0.00 USD**, ya que todos los servicios del Componente C están cubiertos por la **Capa Gratuita de AWS (Free Tier)**. + +A continuación se detalla el costo por servicio en caso de superar el Free Tier (bajo volumen): + +| Servicio AWS | Concepto en Componente C | Capa Gratuita (Mensual) | Costo Fuera de Capa Gratuita | Costo Estimado (Pruebas de Tesis) | +| :--- | :--- | :--- | :--- | :--- | +| **AWS Lambda** | Ejecución de los 5 Playbooks y Dispatcher | 1 millón de peticiones | $0.20 por millón de peticiones | **$0.00** | +| **Amazon SQS** | Cola de incidentes y DLQ | 1 millón de peticiones | $0.40 por millón de peticiones | **$0.00** | +| **Amazon SNS** | Envío de notificaciones de alertas | 1 millón de publicaciones | $0.50 por millón de publicaciones (E-mail: 1,000 gratis, luego $2.00/10k) | **$0.00** | +| **Amazon S3** | Evidencias de bloqueos (`responses/`) | 5 GB de almacenamiento | $0.023 por GB almacenado | **<$0.01** | +| **AWS IAM** | Roles y políticas de seguridad | Siempre gratis | No tiene costo | **$0.00** | +| **EC2 / NACL** | Modificación de reglas del firewall de red | Siempre gratis | Cambiar reglas de NACL no tiene costo | **$0.00** | + +--- + +## 2. Requisitos de Integración (Qué necesitas de tu equipo) + +Para iniciar el despliegue del Componente C en la cuenta de AWS real, necesitas que tus compañeros te proporcionen los siguientes datos e infraestructura: + +### De Melany (Componente A — Infraestructura y Logs) +1. **VPC ID & NACL ID**: El ID de la VPC de producción (`vpc-xxxxxx`) y el ID de la Network ACL pública (`nacl-xxxxxx`) donde el playbook `block-ip` creará las reglas `DENY`. +2. **Nombre del Bucket S3**: El nombre exacto del bucket de logs (`tesis-security-logs-prod`) para almacenar el registro de auditoría de contenciones (`responses/`). +3. **Instancias EC2 Objetivo**: Los IDs de las instancias EC2 (`i-xxxxxx`) que simularán estar comprometidas para probar el aislamiento en red del playbook `isolate-instance`. + +### De Aarón (Componente B — Detección de Incidentes) +1. **ARN de la Cola SQS**: El ARN exacto de la cola SQS de producción (`arn:aws:sqs:us-east-1:123456789012:tesis-incident-queue`) a la cual el dispatcher de Lambda se suscribirá mediante un *Event Source Mapping*. +2. **Homologación de Payloads**: Asegurar que su motor de detección (DuckDB/Athena/Lambda) publique los mensajes con la estructura de variables exacta que se detalla en la siguiente sección. + +--- + +## 3. Formato de Incidentes de Aarón (Payload SQS) +Aarón debe publicar un mensaje en formato **JSON** en la cola de SQS por cada incidente detectado. El esquema unificado es el siguiente: + +### Variables Obligatorias del Payload + +| Campo SQS | Tipo | Descripción | Formato / Ejemplo | +| :--- | :---: | :--- | :--- | +| `incident_type` | String | Tipo de incidente detectado (llave de ruteo). | `"BRUTE_FORCE"`, `"PORT_SCAN"`, `"PRIVILEGE_ESCALATION"`, `"CREDENTIAL_LEAK"`, `"EXFILTRATION"` | +| `severity` | String | Gravedad del incidente según la regla de detección. | `"MEDIUM"`, `"HIGH"`, `"CRITICAL"` | +| `sourceIPAddress` | String | IP origen del atacante (necesaria para bloquear la IP). | `"185.220.101.5"` | +| `affectedResource` | String | Recurso comprometido. **Crítico: usar prefijo exacto.** | `"iam:user/nombre-usuario"` o `"ec2:instance/i-0abc123def"` | +| `s3_log_key` | String | Ruta del log en S3 que contiene la evidencia. | `"cloudtrail/2026/05/19/archivo.json"` | +| `timestamp` | String | Fecha y hora en que ocurrió/detectó el incidente. | ISO 8601 UTC: `"2026-05-19T00:01:15Z"` | +| `event_count` | Integer | Número de eventos/logs que activaron la alerta. | `15` | + +### Ejemplo de JSON de Entrada para SQS (Fuerza Bruta) +```json +{ + "incident_type": "BRUTE_FORCE", + "severity": "HIGH", + "sourceIPAddress": "185.220.101.5", + "affectedResource": "iam:user/dev-operator", + "s3_log_key": "cloudtrail/2026/05/19/brute-force-xyz.json", + "timestamp": "2026-05-19T00:01:15Z", + "event_count": 10 +} +``` + +--- + +## 4. Mecanismos de Seguridad de Conexión en AWS +Para garantizar que las conexiones a los recursos de AWS sean seguras y sigan las mejores prácticas de la nube, se deben implementar los siguientes tres mecanismos: + +1. **Roles de Ejecución de IAM (Mínimo Privilegio)**: + * **Sin credenciales estáticas**: Las Lambdas del Componente C no deben usar Access Keys ni Secret Keys. En su lugar, se les asigna un **IAM Execution Role** con una política de confianza (`AssumeRole`). + * **Políticas Dedicadas**: Cada playbook de Lambda debe tener una política de acceso que conceda permisos estrictamente a su recurso objetivo (ej: el playbook `block-ip` solo debe tener permisos sobre la NACL específica, no sobre todo el servicio de EC2). + +2. **VPC Endpoints (AWS PrivateLink)**: + * Si las funciones Lambda se configuran dentro de la VPC privada para interactuar con recursos internos (como las interfaces de red de las EC2), la comunicación con SQS, SNS y S3 no debe salir a internet público. + * Se deben desplegar **Interface VPC Endpoints** para SQS y SNS, y un **Gateway VPC Endpoint** para S3, permitiendo una conexión privada y segura a través de la red interna de AWS. + +3. **Cifrado de Datos en Tránsito y Reposo**: + * Las conexiones entre SQS, Lambdas y SNS se realizan por defecto utilizando **HTTPS (TLS 1.2/1.3)** asegurando el cifrado en tránsito. + * El bucket de S3 de evidencias y la cola SQS de incidentes deben tener habilitado el **cifrado en reposo** utilizando llaves administradas por AWS (SSE-S3) o llaves personalizadas de KMS (SSE-KMS). From f90bd842bb9bb9f25bce05d0cade9efac53351d2 Mon Sep 17 00:00:00 2001 From: bryancito1090 Date: Wed, 27 May 2026 10:58:44 -0500 Subject: [PATCH 5/9] feat: Implement block-ip playbook for network incident mitigation - Added handler.py to block malicious IPs by creating DENY rules in the target Network ACL. - Included functionality to validate public IPs, manage rule numbers, and log actions to S3. - Enhanced incident response by notifying via SNS and saving evidence of actions taken. feat: Create notify-alert playbook for structured incident notifications - Developed handler.py to receive incidents from SQS and publish structured alerts to SNS. - Implemented logging of operational evidence in S3 for various incident types. - Ensured support for multiple incident types with appropriate fields for each. feat: Add user data script for EC2 instance setup - Created user_data.sh.tpl to automate the installation of necessary packages and configuration of the corporate portal. - Configured Nginx as a reverse proxy for the application and set up CloudWatch Agent for log management. chore: Add example terraform variables file - Introduced terraform.tfvars.example to provide a template for required variables. - Included descriptions and default values for easier configuration. chore: Define variables for Terraform configuration - Created variables.tf to manage project-specific configurations and constraints. - Included validation rules for critical variables to ensure correct input. --- 12/05/2026/demo_profesor_2026-05-12.md | 81 - .../presentacion_bruteforce_2026-05-12.md | 390 ---- 28/04/2026/diseno_flujos_automaticos.md | 98 - 28/04/2026/perspectiva_atacante_incidente.md | 167 -- INTERFAZ_COMPONENTE_B.md | 222 --- Scan Port/README.md | 201 +++ analisis_costos_infraestructura_aws.md | 54 - demo 19 Mayo/demo_stack.sh | 257 --- demo 19 Mayo/esquema_almacenamiento.md | 195 -- estrategia_paralelo_aws.md | 39 - guia_acoplamiento_paralelo.md | 90 - infra/setup.sh | 27 + lambdas/block-ip.zip | Bin 4166 -> 0 bytes lambdas/isolate-instance/handler.py | 149 +- lambdas/notify-alert.zip | Bin 2424 -> 0 bytes lambdas/revoke-credentials/handler.py | 143 +- recursos_y_costos_aws.md | 81 - simulators/inject_logs.py | 19 +- terraform-tesis-ir-secure-portal/.gitignore | 8 + .../GUIA_PRUEBAS_INCIDENTES.md | 135 ++ .../README_EJECUCION.md | 167 ++ .../lambda/lambda_function.py | 561 ++++++ .../lambda_playbook_block_ip.zip | Bin 0 -> 3191 bytes .../lambda_playbook_notify_alert.zip | Bin 0 -> 1795 bytes terraform-tesis-ir-secure-portal/main.tf | 1576 +++++++++++++++++ terraform-tesis-ir-secure-portal/outputs.tf | 103 ++ .../playbooks/block_ip/handler.py | 236 +++ .../playbooks/notify_alert/handler.py | 116 ++ .../scripts/user_data.sh.tpl | 502 ++++++ .../terraform.tfvars.example | 46 + terraform-tesis-ir-secure-portal/variables.tf | 214 +++ 31 files changed, 4150 insertions(+), 1727 deletions(-) delete mode 100644 12/05/2026/demo_profesor_2026-05-12.md delete mode 100644 12/05/2026/presentacion_bruteforce_2026-05-12.md delete mode 100644 28/04/2026/diseno_flujos_automaticos.md delete mode 100644 28/04/2026/perspectiva_atacante_incidente.md delete mode 100644 INTERFAZ_COMPONENTE_B.md create mode 100644 Scan Port/README.md delete mode 100644 analisis_costos_infraestructura_aws.md delete mode 100755 demo 19 Mayo/demo_stack.sh delete mode 100644 demo 19 Mayo/esquema_almacenamiento.md delete mode 100644 estrategia_paralelo_aws.md delete mode 100644 guia_acoplamiento_paralelo.md delete mode 100644 lambdas/block-ip.zip delete mode 100644 lambdas/notify-alert.zip delete mode 100644 recursos_y_costos_aws.md create mode 100644 terraform-tesis-ir-secure-portal/.gitignore create mode 100644 terraform-tesis-ir-secure-portal/GUIA_PRUEBAS_INCIDENTES.md create mode 100644 terraform-tesis-ir-secure-portal/README_EJECUCION.md create mode 100644 terraform-tesis-ir-secure-portal/lambda/lambda_function.py create mode 100644 terraform-tesis-ir-secure-portal/lambda_playbook_block_ip.zip create mode 100644 terraform-tesis-ir-secure-portal/lambda_playbook_notify_alert.zip create mode 100644 terraform-tesis-ir-secure-portal/main.tf create mode 100644 terraform-tesis-ir-secure-portal/outputs.tf create mode 100644 terraform-tesis-ir-secure-portal/playbooks/block_ip/handler.py create mode 100644 terraform-tesis-ir-secure-portal/playbooks/notify_alert/handler.py create mode 100644 terraform-tesis-ir-secure-portal/scripts/user_data.sh.tpl create mode 100644 terraform-tesis-ir-secure-portal/terraform.tfvars.example create mode 100644 terraform-tesis-ir-secure-portal/variables.tf diff --git a/12/05/2026/demo_profesor_2026-05-12.md b/12/05/2026/demo_profesor_2026-05-12.md deleted file mode 100644 index 10e0e78..0000000 --- a/12/05/2026/demo_profesor_2026-05-12.md +++ /dev/null @@ -1,81 +0,0 @@ -# Demo Brute-Force — 2026-05-12 - -> Escribir los skills en el chat de Claude Code. Solo los últimos 2 pasos usan terminal. - ---- - -## Pasos en orden - -| # | Dónde | Qué escribir | Qué hace | -|---|-------|-------------|----------| -| 1 | Claude Code | `/localstack-up` | Levanta LocalStack y verifica servicios | -| 2 | Claude Code | `/bootstrap-resources` | Crea S3, SNS, SQS e IAM | -| 3 | Claude Code | `/deploy-lambda notify-alert` | Despliega playbook de alertas | -| 4 | Claude Code | `/deploy-lambda block-ip` | Despliega playbook de bloqueo de IPs | -| 5 | Claude Code | `/deploy-lambda dispatcher` | Despliega el coordinador de playbooks | -| 6 | Claude Code | `/simulate-incident brute-force` | Genera el ataque y lo sube a S3 + SQS | -| 7 | Claude Code | `/query-logs brute-force` | Detecta el IoC con SQL (equivale a Athena) | -| 8 | Terminal | ver abajo | Activa la respuesta automática | -| 9 | Terminal | ver abajo | Muestra los archivos generados | - ---- - -## Paso 8 — Activar respuesta automática (terminal) - -```bash -cd ~/localstack-tesis && source activate.sh -.venv/bin/awslocal lambda invoke \ - --function-name tesis-dispatcher \ - --cli-binary-format raw-in-base64-out \ - --payload file://lambdas/dispatcher/test_event.json \ - /tmp/respuesta-dispatcher.json -python3 -m json.tool /tmp/respuesta-dispatcher.json -``` - ---- - -## Paso 9 — Ver archivos generados (terminal) - -```bash -# Qué hay en S3 -.venv/bin/awslocal s3 ls s3://tesis-security-logs/ --recursive - -# IP bloqueada -.venv/bin/awslocal s3 cp s3://tesis-security-logs/responses/blocked-ips.json - | python3 -m json.tool - -# Logs de las Lambdas -for fn in tesis-dispatcher tesis-notify-alert tesis-block-ip; do - echo "=== $fn ===" - stream=$(.venv/bin/awslocal logs describe-log-streams \ - --log-group-name /aws/lambda/$fn \ - --query 'logStreams[-1].logStreamName' --output text 2>/dev/null) - [ "$stream" != "None" ] && .venv/bin/awslocal logs get-log-events \ - --log-group-name /aws/lambda/$fn --log-stream-name "$stream" \ - --query 'events[].message' --output text 2>/dev/null -done -``` - ---- - -## Archivos generados por el sistema - -| Archivo | Dónde | Lo crea | -|---------|-------|---------| -| `cloudtrail/.../brute-force-XXXX.json` | S3 `tesis-security-logs` | Paso 6 — `/simulate-incident` | -| `responses/blocked-ips.json` | S3 `tesis-security-logs` | Paso 8 — Lambda `block-ip` | -| `/tmp/respuesta-dispatcher.json` | Disco local | Paso 8 — `lambda invoke` | -| Logs de ejecución | CloudWatch `/aws/lambda/tesis-*` | Pasos 3–5 y 8 | - ---- - -## Para la presentación — leer estos archivos - -| Qué explica | Archivo | -|-------------|---------| -| Flujo completo con diagrama y detalle de cada playbook | `presentacion_bruteforce_2026-05-12.md` | -| Pasos de la demo (este archivo) | `demo_profesor_2026-05-12.md` | -| Análisis técnico completo con hallazgos y correcciones | `analisis_flujo1_bruteforce.md` | - ---- - -> Si algo falla: repetir el skill del paso que falló. Si LocalStack se reinició, empezar desde el Paso 1. diff --git a/12/05/2026/presentacion_bruteforce_2026-05-12.md b/12/05/2026/presentacion_bruteforce_2026-05-12.md deleted file mode 100644 index b939177..0000000 --- a/12/05/2026/presentacion_bruteforce_2026-05-12.md +++ /dev/null @@ -1,390 +0,0 @@ -# Ataque de Fuerza Bruta — Flujo Completo del Sistema -**Fecha:** 2026-05-12 | **Componente C — Automatización de Respuesta** | **Bryan** - ---- - -## ¿Qué es este escenario? - -Un atacante externo intenta adivinar la contraseña de un usuario IAM de AWS haciendo **10 intentos de login fallidos en ~2 minutos** desde la IP `185.220.101.5`. - -El sistema detecta el patrón, genera una alerta y **toma acciones automáticas de contención** — todo sin intervención humana. - ---- - -## Flujo de extremo a extremo - -``` -┌──────────────────────────────────────────────────────────────────────┐ -│ FASE 1 — ATAQUE │ -│ │ -│ Atacante 185.220.101.5 │ -│ │ 10x ConsoleLogin FAILED (AccessDenied) │ -│ │ usuario: admin │ ventana: ~2 minutos │ -│ ▼ │ -│ cloudtrail_gen.py → genera 10 eventos JSON con estructura real │ -│ inject_logs.py → empaqueta y distribuye los eventos │ -│ ├──▶ S3: cloudtrail/2026/.../brute-force-XXXX.json│ -│ └──▶ SQS: tesis-incident-queue (payload)│ -└──────────────────────────────────────────────────────────────────────┘ - │ │ -┌─────────────────────────▼──┐ ┌─────────────────▼─────────────────┐ -│ FASE 2 — DETECCIÓN │ │ FASE 3 — AUTOMATIZACIÓN │ -│ │ │ │ -│ queries/detect_brute_ │ │ Lambda: dispatcher │ -│ force.sql (DuckDB) │ │ ├──▶ tesis-notify-alert │ -│ │ │ └──▶ tesis-block-ip │ -│ SQL descarga logs de S3 │ │ │ -│ y detecta el IoC: │ │ Resultados guardados en S3: │ -│ ▸ misma IP │ │ responses/blocked-ips.json │ -│ ▸ mismo usuario │ │ │ -│ ▸ +5 intentos fallidos │ │ Notificación publicada en SNS: │ -│ ▸ ventana < 5 min │ │ tesis-security-alerts │ -└──────────────────────────────┘ └────────────────────────────────────┘ -``` - ---- - -## Fase 1 — El ataque y cómo se inyecta al sistema - -### Archivos que intervienen - -| Archivo | Qué hace | -|---------|----------| -| `simulators/cloudtrail_gen.py` | **Genera** los 10 eventos JSON con estructura idéntica a CloudTrail real | -| `simulators/inject_logs.py` | **Orquesta**: llama al generador, sube a S3 y envía el payload a SQS | - -### ¿Qué genera `cloudtrail_gen.py`? - -La función `brute_force()` produce **10 eventos**, uno cada 15 segundos, con esta estructura: - -```json -{ - "eventVersion": "1.08", - "eventName": "ConsoleLogin", - "eventSource": "signin.amazonaws.com", - "errorCode": "AccessDenied", - "errorMessage": "Failed authentication", - "sourceIPAddress": "185.220.101.5", - "userIdentity": { - "type": "IAMUser", - "userName": "admin" - }, - "responseElements": { - "ConsoleLogin": "Failure" - } -} -``` - -> Este JSON es sintético pero tiene la **misma estructura** que un log real de AWS CloudTrail. El campo `eventName=ConsoleLogin` + `errorCode=AccessDenied` es la firma del intento fallido. - -### ¿Qué hace `inject_logs.py`? - -Toma esos 10 eventos y hace dos cosas: - -**1. Los sube a S3** como archivo JSON (simula cómo CloudTrail almacena logs reales): -``` -s3://tesis-security-logs/cloudtrail/2026/05/12/brute-force-51cbb9f1.json -``` - -**2. Envía un mensaje a SQS** con el resumen del incidente (el payload que activa la Lambda): -```json -{ - "incident_type": "BRUTE_FORCE", - "severity": "HIGH", - "sourceIPAddress": "185.220.101.5", - "affectedResource": "iam:user/admin", - "s3_log_key": "cloudtrail/2026/05/12/.../brute-force-51cbb9f1.json", - "event_count": 10, - "timestamp": "2026-05-12T..." -} -``` - ---- - -## Fase 2 — La detección (DuckDB / equivalente a Athena) - -### Archivo que interviene - -| Archivo | Qué hace | -|---------|----------| -| `queries/detect_brute_force.sql` | Query SQL que analiza los logs y detecta el patrón de fuerza bruta | - -### La consulta SQL - -```sql -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') -- Lee el JSON descargado de S3 -) -WHERE r.eventName = 'ConsoleLogin' - AND r.errorCode = 'AccessDenied' -- Solo intentos fallidos -GROUP BY r.sourceIPAddress, r.userIdentity.userName -HAVING COUNT(*) > 5 -- Umbral: más de 5 intentos -ORDER BY failed_attempts DESC; -``` - -### Resultado que obtiene - -| sourceIPAddress | username | failed_attempts | first_attempt | last_attempt | -|----------------|----------|-----------------|---------------|--------------| -| 185.220.101.5 | admin | **10** | 2026-05-12T...Z | 2026-05-12T...Z | - -``` -IoC detectado: 1 dirección IP atacante -Regla disparada: ConsoleLogin + AccessDenied > 5 intentos en ~2 min -Acción recomendada: notify-alert + block-ip -``` - -> **¿Por qué DuckDB?** En AWS real se usaría Amazon Athena. En el entorno local, DuckDB lee los mismos archivos JSON directamente sin necesidad de internet ni costo. - ---- - -## Fase 3 — La automatización (Playbooks Lambda) - -### La cadena de respuesta automática - -``` -SQS: tesis-incident-queue - │ (payload BRUTE_FORCE) - ▼ -Lambda: dispatcher - ├──▶ Lambda: notify-alert → publica alerta en SNS - └──▶ Lambda: block-ip → registra IP en S3 + notifica SNS -``` - -### Archivos que intervienen - -| Archivo | Playbook | Qué hace | -|---------|----------|----------| -| `lambdas/dispatcher/handler.py` | dispatcher | Recibe el evento SQS, lee el tipo de incidente y llama a los playbooks correctos | -| `lambdas/notify-alert/handler.py` | notify-alert | Publica una alerta estructurada al tópico SNS del equipo | -| `lambdas/block-ip/handler.py` | block-ip | Añade la IP atacante a la lista de bloqueo en S3 y notifica | - ---- - -### Playbook 1: `dispatcher` -**Archivo:** `lambdas/dispatcher/handler.py` - -**Rol:** El cerebro de la automatización. Es la única Lambda que escucha directamente la cola SQS. Su trabajo es leer `incident_type` del payload y decidir qué playbooks ejecutar. - -**Tabla de enrutamiento interna:** -``` -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 -``` - -Para brute-force, ejecuta en secuencia `notify-alert` y luego `block-ip`, pasándole el mismo payload SQS original. El dispatcher **no toma acciones directas** — solo enruta. - ---- - -### Playbook 2: `notify-alert` -**Archivo:** `lambdas/notify-alert/handler.py` - -**Rol:** Primera respuesta ante cualquier incidente. Construye un mensaje de alerta estructurado y lo publica al canal SNS del equipo de seguridad. - -**¿Qué recibe?** -El payload SQS con `incident_type`, `severity`, `sourceIPAddress`, `affectedResource`. - -**¿Qué hace paso a paso?** -1. Extrae los campos del payload SQS -2. Construye un objeto de alerta con campos como `alert_type`, `detectedAt`, `respondedAt`, `playbook`, `status` -3. Llama a `sns.publish()` hacia `tesis-security-alerts` -4. Registra en CloudWatch: `[notify-alert] Alerta publicada: BRUTE_FORCE desde 185.220.101.5` - -**Salida que produce (al tópico SNS):** -```json -{ - "alert_type": "SECURITY_INCIDENT", - "incident_type": "BRUTE_FORCE", - "severity": "HIGH", - "sourceIPAddress": "185.220.101.5", - "affectedResource": "iam:user/admin", - "detectedAt": "2026-05-12T...", - "respondedAt": "2026-05-12T...", - "playbook": "notify-alert", - "status": "NOTIFIED" -} -``` - -**En AWS real:** este mensaje llegaría por email, SMS, o Slack vía suscripción SNS. - ---- - -### Playbook 3: `block-ip` -**Archivo:** `lambdas/block-ip/handler.py` - -**Rol:** Contención técnica. Registra la IP atacante en una lista persistente en S3 y notifica al equipo. - -**¿Qué hace paso a paso?** -1. Lee el archivo `responses/blocked-ips.json` de S3 (la lista actual de IPs bloqueadas) -2. Verifica que la IP no esté ya bloqueada (evita duplicados) -3. Añade una nueva entrada con IP, fecha, motivo y severidad -4. Sube el archivo actualizado de vuelta a S3 -5. Publica notificación al tópico SNS - -**En AWS real:** en lugar de solo guardar en S3, actualizaría un **WAF IP Set** o modificaría **Security Groups** para bloquear el tráfico a nivel de red. - ---- - -### Playbook extra referenciado: `revoke-credentials` -**Archivo:** `lambdas/revoke-credentials/handler.py` -*(No se activa en brute-force, pero está disponible para credential-leak y privilege-escalation)* - -**¿Qué hace?** -1. Lista todas las access keys del usuario IAM comprometido -2. Desactiva cada key (`Status=Inactive` en IAM) -3. Adjunta una política `EmergencyDenyAll` al usuario (bloqueo total inmediato) -4. Notifica al equipo vía SNS - ---- - -### Playbook extra referenciado: `isolate-instance` -**Archivo:** `lambdas/isolate-instance/handler.py` -*(Se activa para exfiltration)* - -**¿Qué hace?** -1. Lee la lista de instancias en cuarentena de S3 -2. Registra la instancia comprometida con fecha y razón -3. Simula 3 acciones: remover Security Group, aplicar DenyAll, disparar snapshot -4. Persiste en S3 y notifica vía SNS - ---- - -## Archivos que genera la automatización - -Estos son todos los archivos/objetos que el sistema **crea o modifica** como resultado del flujo brute-force: - -### En S3 (`tesis-security-logs`) - -| Ruta en S3 | Tipo | De dónde viene | Qué contiene | -|-----------|------|----------------|--------------| -| `cloudtrail/2026/05/12/HHMMSS/brute-force-XXXX.json` | JSON creado | `inject_logs.py` sube el output de `cloudtrail_gen.py` | Los 10 eventos CloudTrail simulados con estructura `{"Records": [...]}` | -| `responses/blocked-ips.json` | JSON creado/actualizado | Playbook `block-ip` lo escribe después de ejecutarse | Lista acumulativa de IPs bloqueadas con fecha, motivo y severidad | - -**Ejemplo de `blocked-ips.json`:** -```json -[ - { - "ip": "185.220.101.5", - "blocked_at": "2026-05-12T...", - "reason": "BRUTE_FORCE", - "severity": "HIGH", - "affectedResource": "iam:user/admin" - } -] -``` - -> Este archivo persiste entre ejecuciones. Cada nuevo ataque detectado **añade una entrada** sin borrar las anteriores. Es el registro histórico de IPs bloqueadas. - -### En SNS (`tesis-security-alerts`) - -| Qué se publica | Lo publica | Cuándo | -|----------------|-----------|--------| -| Alerta JSON estructurada (`status: NOTIFIED`) | `notify-alert` | Inmediatamente al detectar el incidente | -| Confirmación de bloqueo (`status: BLOCKED`) | `block-ip` | Tras registrar la IP en S3 | - -> En el entorno local SNS actúa como un bus de mensajes. En AWS real, estos mensajes se entregarían a suscriptores: email, SMS, Lambda adicional, HTTP endpoint. - -### En CloudWatch Logs - -| Log Group | Lo escribe | Qué registra | -|-----------|-----------|--------------| -| `/aws/lambda/tesis-dispatcher` | Lambda dispatcher | Qué incidente recibió y qué playbooks invocó | -| `/aws/lambda/tesis-notify-alert` | Lambda notify-alert | Confirmación de alerta publicada | -| `/aws/lambda/tesis-block-ip` | Lambda block-ip | Qué IP fue bloqueada y si ya estaba en la lista | - -**Ejemplo de log en CloudWatch:** -``` -START RequestId: abc123... -[dispatcher] Incidente: BRUTE_FORCE (HIGH) → playbooks: ['tesis-notify-alert', 'tesis-block-ip'] -[dispatcher] tesis-notify-alert → success -[dispatcher] tesis-block-ip → success -END RequestId: abc123... -REPORT Duration: 312 ms Billed Duration: 313 ms Memory: 128 MB -``` - ---- - -## Mapa completo de archivos del proyecto en este flujo - -``` -localstack-tesis/ -│ -├── simulators/ -│ ├── cloudtrail_gen.py ← PASO 1: genera los eventos JSON del ataque -│ └── inject_logs.py ← PASO 2: sube a S3 y envía a SQS -│ -├── queries/ -│ └── detect_brute_force.sql ← PASO 3: SQL que detecta el patrón -│ -├── lambdas/ -│ ├── dispatcher/ -│ │ └── handler.py ← PASO 4a: enruta el incidente a los playbooks -│ ├── notify-alert/ -│ │ ├── handler.py ← PASO 4b: publica la alerta a SNS -│ │ └── test_event.json ← evento de prueba para invocar la Lambda -│ └── block-ip/ -│ ├── handler.py ← PASO 4c: registra IP en S3 y notifica -│ └── test_event.json ← evento de prueba para invocar la Lambda -│ -└── infra/ - └── setup.sh ← crea S3, SNS, SQS, IAM antes de todo - -── ARCHIVOS GENERADOS POR EL SISTEMA ────────────────────────────────── -S3: cloudtrail/2026/.../brute-force-XXXX.json ← log del ataque -S3: responses/blocked-ips.json ← lista de IPs bloqueadas -SNS: tesis-security-alerts ← mensajes de alerta -CloudWatch: /aws/lambda/tesis-* ← logs de ejecución -``` - ---- - -## Resumen visual del flujo en 5 pasos - -``` -PASO 1 Ataque simulado - cloudtrail_gen.py genera 10 eventos ConsoleLogin+AccessDenied - inject_logs.py los sube a S3 y al canal SQS - -PASO 2 Almacenamiento - S3: cloudtrail/brute-force-XXXX.json (7 KB de logs) - SQS: payload JSON con incident_type=BRUTE_FORCE, severity=HIGH - -PASO 3 Detección - detect_brute_force.sql descarga el JSON de S3 y lo analiza - DuckDB agrupa por IP + usuario, cuenta intentos fallidos - Umbral superado: 10 intentos > 5 → IoC confirmado - -PASO 4 Automatización - SQS activa la Lambda dispatcher - dispatcher lee BRUTE_FORCE y llama a: - └─ notify-alert → alerta en SNS → status: NOTIFIED - └─ block-ip → IP en S3 → status: BLOCKED - -PASO 5 Evidencia generada - S3: responses/blocked-ips.json (registro de la IP bloqueada) - SNS: 2 mensajes publicados (alerta + confirmación bloqueo) - CloudWatch: logs de ejecución de cada Lambda con duración y estado -``` - ---- - -## ¿Qué pasaría en AWS real? - -| Entorno local (LocalStack) | AWS real equivalente | -|---------------------------|---------------------| -| `cloudtrail_gen.py` genera eventos JSON | CloudTrail captura automáticamente las llamadas a la API | -| `inject_logs.py` sube a S3 local | CloudTrail entrega los logs a S3 automáticamente | -| DuckDB ejecuta SQL sobre el JSON | Amazon Athena consulta la tabla de CloudTrail en S3 | -| SQS activa Lambda manualmente | EventBridge Rule o SQS trigger automático activa la Lambda | -| `block-ip` guarda en `blocked-ips.json` en S3 | `block-ip` actualizaría un WAF IP Set o Security Group | -| SNS publica en tópico local | SNS entregaría email/SMS/webhook al equipo de seguridad | diff --git a/28/04/2026/diseno_flujos_automaticos.md b/28/04/2026/diseno_flujos_automaticos.md deleted file mode 100644 index 6e87dc6..0000000 --- a/28/04/2026/diseno_flujos_automaticos.md +++ /dev/null @@ -1,98 +0,0 @@ -# Diseño de Flujos Automáticos para la Respuesta al Incidente - -**Proyecto:** Trabajo de Integración Curricular — Sistema de Detección y Respuesta ante Incidentes en AWS -**Componente:** C — Automatización de Respuesta -**Responsable:** Bryan -**Fecha:** 2026-04-28 - ---- - -## ¿De qué trata este documento en una sola frase? - -Responde a esta pregunta: **¿cómo le decimos al sistema qué hacer automáticamente cuando detecta un ataque?** Y compara 3 formas de hacerlo. - ---- - -## La idea central - -Cuando el sistema detecta un ataque, necesita reaccionar solo, sin que nadie haga nada manualmente. Para eso necesita un "flujo" — una secuencia de pasos automáticos. Este documento compara 3 diseños posibles para ese flujo. - ---- - -## Diseño A — SNS Directo (el más simple, el que NO usamos) - -Cada tipo de ataque tiene su propio "botón de alarma" y ese botón activa directamente una acción. - -``` -Ataque de fuerza bruta → botón 1 → Lambda "bloquear IP" -Credencial robada → botón 2 → Lambda "revocar credenciales" -``` - -**¿Por qué no lo usamos?** -- Si se quieren hacer dos cosas ante un ataque (avisar Y bloquear), SNS no las encadena bien. -- Si la Lambda falla, el mensaje se pierde y nadie se entera. - ---- - -## Diseño B — SQS + Dispatcher (el que SÍ implementamos) - -Hay un "jefe coordinador" — la Lambda `dispatcher`. Funciona así: - -1. El simulador detecta un ataque y pone un mensaje en una **cola** (SQS). -2. La cola le avisa automáticamente al dispatcher. -3. El dispatcher lee el tipo de ataque y decide qué hacer. -4. Llama a los playbooks necesarios en orden. - -``` -Ataque detectado - → Cola SQS (guarda el mensaje) - → Dispatcher (lee el mensaje, decide) - → Primero avisa al equipo (notify-alert) - → Luego bloquea la IP (block-ip) -``` - -**¿Por qué es mejor?** -- Si algo falla, la cola guarda el mensaje y lo reintenta hasta 3 veces. -- Todo queda registrado en un solo lugar (logs del dispatcher). -- Agregar un nuevo tipo de ataque = agregar una línea en la tabla del dispatcher, nada más. - -**¿Qué es el "Event Source Mapping"?** -Es la conexión automática entre la cola SQS y el dispatcher. Le dice a AWS: *"cada vez que llegue un mensaje a esta cola, activa esta Lambda"*. No hay que hacer nada manualmente. - ---- - -## Diseño C — Step Functions (el más potente, el que NO podemos usar) - -Es como un diagrama de flujo visual con cajas y flechas, donde cada caja es un paso y si algo falla hay reintentos automáticos con espera entre intentos. - -**¿Por qué no lo usamos?** -- No está disponible en la versión gratuita de LocalStack. -- Es demasiado complejo para lo que necesita la tesis. - ---- - -## Decisiones de diseño - -**¿Por qué usamos SQS y no SNS para recibir los ataques?** -Porque SNS puede perder mensajes si la Lambda falla. SQS los guarda y reintenta. En seguridad no se puede permitir perder un incidente. - -**¿Por qué se procesa un mensaje a la vez?** -Porque si el dispatcher procesa dos ataques al mismo tiempo, podrían pisarse entre sí al escribir en el mismo archivo de S3. Uno a la vez es más seguro. - -**¿Por qué `notify-alert` va siempre primero?** -Porque aunque el bloqueo falle, el equipo ya fue avisado. Lo peor que puede pasar es que el bloqueo no funcione, pero al menos alguien sabe que hubo un ataque. - ---- - -## Resumen visual - -``` -Problema: ¿Cómo automatizar la respuesta a un ataque? - -Opción A: SNS → Lambda directa ← simple pero poco confiable -Opción B: SQS → Dispatcher → Lambdas ← lo que usamos, balance ideal -Opción C: Step Functions ← muy potente pero no disponible - -Lo que implementamos (Opción B): -Simulador → Cola SQS → Dispatcher → notify-alert + block-ip / revoke / isolate -``` diff --git a/28/04/2026/perspectiva_atacante_incidente.md b/28/04/2026/perspectiva_atacante_incidente.md deleted file mode 100644 index 1f129e5..0000000 --- a/28/04/2026/perspectiva_atacante_incidente.md +++ /dev/null @@ -1,167 +0,0 @@ -# Perspectiva del Atacante — Materialización del Incidente - -**Proyecto:** Trabajo de Integración Curricular — Sistema de Detección y Respuesta ante Incidentes en AWS -**Componente:** C — Automatización de Respuesta -**Responsable:** Bryan -**Fecha:** 2026-04-28 - -> **Nota:** Este documento tiene propósito académico. Describe cómo un atacante intentaría comprometer un entorno AWS y cómo el sistema del Componente C lo detecta y responde automáticamente. - ---- - -## La idea general - -El atacante no ve una pantalla con alertas diciéndole "te estamos vigilando". Desde su punto de vista, está interactuando con servicios normales de AWS — la consola web, una API, un bucket S3. Lo que no sabe es que cada acción que hace queda registrada en CloudTrail, y que el sistema está leyendo esos registros en tiempo real. - -``` -Atacante actúa sobre AWS - │ - ▼ -AWS registra todo en CloudTrail (log de cada acción) - │ - ▼ -El sistema lee los logs y busca patrones sospechosos - │ - ▼ -Si detecta algo → responde automáticamente -``` - ---- - -## Ataque 1 — Fuerza Bruta (BRUTE_FORCE) - -**¿Qué intenta el atacante?** -Entrar a la consola de AWS adivinando la contraseña de un usuario. Prueba combinaciones una por una: `admin123`, `Welcome1`, `P@ssw0rd`, etc. - -**¿Qué ve el atacante?** -Cada intento le devuelve un error de "credenciales incorrectas". Sigue probando. - -**¿Qué registra AWS?** -Cada intento fallido genera un evento `ConsoleLogin` con `errorCode: AccessDenied`. Tras 10 intentos desde la misma IP, el patrón es claro. - -**¿Cómo responde el sistema?** -``` -Detecta: +5 intentos fallidos desde la misma IP en menos de 5 minutos - → notify-alert: avisa al equipo de seguridad - → block-ip: registra la IP del atacante en la lista de bloqueados -``` - -**¿Qué siente el atacante?** -No sabe que fue detectado. Sus intentos siguen fallando, pero ahora también hay un equipo revisando su IP. - ---- - -## Ataque 2 — Credencial Robada (CREDENTIAL_LEAK) - -**¿Qué intenta el atacante?** -Encontró una `AWS_ACCESS_KEY_ID` y un `AWS_SECRET_ACCESS_KEY` expuestos en un repositorio público de GitHub. Con esas dos claves puede llamar a la API de AWS directamente, sin necesidad de contraseña. - -**¿Qué ve el atacante?** -Tiene acceso real. Puede listar buckets S3, ver recursos, ejecutar comandos. Cree que nadie lo sabe. - -**¿Qué registra AWS?** -Cada llamada a la API queda registrada con la key usada. El sistema detecta que esa key está siendo usada desde una IP desconocida o en horarios inusuales. - -**¿Cómo responde el sistema?** -``` -Detecta: uso de credencial comprometida - → notify-alert: avisa al equipo - → revoke-credentials: desactiva la access key inmediatamente -``` - -**¿Qué siente el atacante?** -A los pocos segundos, todos sus comandos empiezan a fallar con `InvalidClientTokenId`. La llave fue desactivada mientras la usaba. - ---- - -## Ataque 3 — Escalada de Privilegios (PRIVILEGE_ESCALATION) - -**¿Qué intenta el atacante?** -Ya tiene acceso a AWS con una cuenta de bajos privilegios (por ejemplo, un usuario que solo puede leer logs). Intenta darse a sí mismo permisos de administrador ejecutando comandos como `iam:AttachUserPolicy` o `iam:CreateRole`. - -**¿Qué ve el atacante?** -Está ejecutando comandos IAM que normalmente no debería poder usar. Intenta escalar sus permisos para tener control total de la cuenta. - -**¿Qué registra AWS?** -Los eventos IAM inusuales quedan en CloudTrail. Un usuario con perfil de "solo lectura" intentando modificar políticas es una señal clara. - -**¿Cómo responde el sistema?** -``` -Detecta: llamadas IAM sospechosas desde un usuario de bajo privilegio - → notify-alert: avisa al equipo - → revoke-credentials: desactiva las credenciales del usuario comprometido -``` - -**¿Qué siente el atacante?** -Sus credenciales dejan de funcionar antes de que pueda completar la escalada. - ---- - -## Ataque 4 — Exfiltración de Datos (EXFILTRATION) - -**¿Qué intenta el atacante?** -Ya tiene acceso y quiere llevarse datos. Empieza a copiar archivos de buckets S3 hacia afuera — ya sea descargándolos o replicándolos a otra cuenta de AWS que controla. - -**¿Qué ve el atacante?** -Los datos se están transfiriendo. Desde su perspectiva, está logrando su objetivo. - -**¿Qué registra AWS?** -Operaciones masivas de `GetObject` o `CopyObject` desde S3, especialmente hacia IPs o cuentas externas, generan un volumen de eventos anormal. - -**¿Cómo responde el sistema?** -``` -Detecta: transferencia masiva de datos desde S3 - → notify-alert: avisa al equipo - → isolate-instance: aísla el recurso comprometido, detiene la transferencia -``` - -**¿Qué siente el atacante?** -La transferencia se corta. El recurso queda inaccesible y en cuarentena. - ---- - -## Ataque 5 — Escaneo de Puertos (PORT_SCAN) - -**¿Qué intenta el atacante?** -Antes de atacar directamente, quiere saber qué servicios están expuestos — qué puertos están abiertos, qué versiones corren, qué superficie de ataque existe. Es como caminar alrededor de un edificio buscando ventanas abiertas. - -**¿Qué ve el atacante?** -Está recopilando información pasivamente. Cree que este tipo de reconocimiento no genera alertas. - -**¿Qué registra AWS?** -Los VPC Flow Logs registran conexiones rechazadas o intentos a múltiples puertos desde la misma IP en poco tiempo. - -**¿Cómo responde el sistema?** -``` -Detecta: múltiples conexiones a distintos puertos desde la misma IP - → notify-alert: avisa al equipo - → block-ip: registra la IP antes de que el atacante pase a la siguiente fase -``` - -**¿Qué siente el atacante?** -Su IP queda bloqueada en la etapa de reconocimiento, antes de que pueda intentar el ataque real. - ---- - -## Resumen: atacante vs. sistema - -| Ataque | Lo que intenta el atacante | Cómo lo detecta el sistema | Cómo responde | -|--------|---------------------------|---------------------------|---------------| -| Fuerza bruta | Adivinar contraseña | +5 intentos fallidos / IP | Avisa + bloquea IP | -| Credencial robada | Usar keys filtradas | Key usada desde IP desconocida | Avisa + desactiva key | -| Escalada de privilegios | Darse más permisos | Comandos IAM fuera de perfil | Avisa + desactiva credenciales | -| Exfiltración | Robar datos de S3 | Transferencia masiva inusual | Avisa + aísla recurso | -| Escaneo de puertos | Reconocer la infraestructura | Múltiples puertos desde misma IP | Avisa + bloquea IP | - ---- - -## Lo que el atacante nunca ve - -Desde la perspectiva del atacante, AWS es solo una API o una página web. No ve: - -- Que CloudTrail registra cada uno de sus movimientos. -- Que una Lambda está leyendo esos registros en tiempo real. -- Que en segundos, un equipo recibió una alerta con su IP y el detalle de lo que intentó. -- Que sus credenciales fueron desactivadas o su recurso aislado mientras todavía estaba conectado. - -Esa invisibilidad del sistema de respuesta es precisamente su ventaja. diff --git a/INTERFAZ_COMPONENTE_B.md b/INTERFAZ_COMPONENTE_B.md deleted file mode 100644 index 084db04..0000000 --- a/INTERFAZ_COMPONENTE_B.md +++ /dev/null @@ -1,222 +0,0 @@ -VARIABLES REQUERIDAS POR INCIDENTE — COMPONENTE B (Aarón) -Tesis: Sistema de Detección y Respuesta ante Incidentes en AWS - - -Para cada incidente detectado, Aarón debe extraer las siguientes variables de sus -consultas y publicarlas en la cola de incidentes en formato JSON. - - -════════════════════════════════════════════════════════════ -INCIDENTE 1: FUERZA BRUTA (BRUTE_FORCE) -════════════════════════════════════════════════════════════ - -Qué es: 5 o más intentos fallidos de login (ConsoleLogin) desde la misma IP - en una ventana de 5 minutos. - -Fuente: CloudTrail → evento ConsoleLogin con errorCode = AccessDenied - -Variables que Aarón debe extraer y enviar: - - Variable Obligatorio Descripción Ejemplo - ────────────────── ─────────── ──────────────────────────────── ───────────────────────────── - incident_type SI Nombre fijo del incidente "BRUTE_FORCE" - severity SI Nivel de gravedad "HIGH" - sourceIPAddress SI IP desde donde llegaron los ataques "185.220.101.5" - affectedResource SI Usuario objetivo del ataque "iam:user/dev-operator" - s3_log_key SI Ruta del log en S3 "cloudtrail/2026/05/19/.../archivo.json" - timestamp SI Fecha y hora de detección "2026-05-19T00:01:15Z" - event_count SI Número de eventos analizados 10 - failed_attempts Opcional Intentos fallidos detectados 10 - detection_window Opcional Ventana de tiempo analizada "5 minutes" - -Origen de cada variable en la query: - - sourceIPAddress → r.sourceIPAddress - affectedResource → "iam:user/" + r.userIdentity.userName - failed_attempts → COUNT(*) - timestamp → MAX(r.eventTime) - - -════════════════════════════════════════════════════════════ -INCIDENTE 2: ESCANEO DE PUERTOS (PORT_SCAN) -════════════════════════════════════════════════════════════ - -Qué es: La misma IP genera conexiones rechazadas (REJECT) hacia 10 o más - puertos distintos en una ventana de 5 minutos. - -Fuente: VPC Flow Logs → registros con acción = REJECT - -Variables que Aarón debe extraer y enviar: - - Variable Obligatorio Descripción Ejemplo - ──────────────────── ─────────── ─────────────────────────────────── ───────────────────────────── - incident_type SI Nombre fijo del incidente "PORT_SCAN" - severity SI Nivel de gravedad "MEDIUM" - sourceIPAddress SI IP que realizó el escaneo "185.220.101.5" - affectedResource SI VPC o subred escaneada "vpc/vpc-3c0db7f4" - s3_log_key SI Ruta del log en S3 "vpc-flow/2026/05/19/.../archivo.log" - timestamp SI Fecha y hora de detección "2026-05-19T00:01:15Z" - event_count SI Número de eventos analizados 15 - rejected_connections Opcional Conexiones rechazadas detectadas 15 - scanned_ports_count Opcional Puertos distintos escaneados 12 - -Origen de cada variable en la query: - - sourceIPAddress → srcAddr (campo de VPC Flow Logs) - affectedResource → ID de la VPC afectada - rejected_connections → COUNT(*) donde acción = REJECT - scanned_ports_count → COUNT(DISTINCT dstPort) - - -════════════════════════════════════════════════════════════ -INCIDENTE 3: ESCALADA DE PRIVILEGIOS (PRIVILEGE_ESCALATION) -════════════════════════════════════════════════════════════ - -Qué es: Un usuario ejecuta acciones críticas de IAM que no le corresponden: - adjuntar políticas de administrador, crear access keys, modificar roles. - -Fuente: CloudTrail → eventos IAM: AttachUserPolicy, AttachRolePolicy, - CreateAccessKey, PutUserPolicy, AddUserToGroup - -Variables que Aarón debe extraer y enviar: - - Variable Obligatorio Descripción Ejemplo - ────────────────── ─────────── ────────────────────────────────────── ────────────────────────────────── - incident_type SI Nombre fijo del incidente "PRIVILEGE_ESCALATION" - severity SI Nivel de gravedad "CRITICAL" - sourceIPAddress SI IP desde donde se hizo la escalada "185.220.101.5" - affectedResource SI * Usuario que realizó las acciones "iam:user/dev-operator" - s3_log_key SI Ruta del log en S3 "cloudtrail/2026/05/19/.../archivo.json" - timestamp SI Fecha y hora de detección "2026-05-19T00:01:15Z" - event_count SI Número de eventos analizados 3 - suspicious_actions Opcional Lista de acciones IAM detectadas ["AttachUserPolicy", "CreateAccessKey"] - target_policy_arn Opcional Política que intentó adjuntarse "arn:aws:iam::aws:policy/AdministratorAccess" - -Origen de cada variable en la query: - - sourceIPAddress → r.sourceIPAddress - affectedResource → "iam:user/" + r.userIdentity.userName - suspicious_actions → lista de r.eventName detectados - target_policy_arn → r.requestParameters.policyArn - - * IMPORTANTE: affectedResource debe escribirse EXACTAMENTE como - "iam:user/NOMBRE_DEL_USUARIO" — ese prefijo es obligatorio. - - -════════════════════════════════════════════════════════════ -INCIDENTE 4: FUGA DE CREDENCIALES (CREDENTIAL_LEAK) -════════════════════════════════════════════════════════════ - -Qué es: Credenciales de un usuario legítimo son utilizadas desde una IP - externa o inusual (fuera del rango normal de la organización). - -Fuente: CloudTrail → llamadas a la API (GetCallerIdentity u otras) desde - una IP que no pertenece al rango de IPs internas conocidas. - -Variables que Aarón debe extraer y enviar: - - Variable Obligatorio Descripción Ejemplo - ────────────────── ─────────── ────────────────────────────────────────── ────────────────────────────────── - incident_type SI Nombre fijo del incidente "CREDENTIAL_LEAK" - severity SI Nivel de gravedad "CRITICAL" - sourceIPAddress SI IP externa desde donde se usaron las creds "185.220.101.5" - affectedResource SI * Usuario cuyas credenciales fueron filtradas "iam:user/external-contractor" - s3_log_key SI Ruta del log en S3 "cloudtrail/2026/05/19/.../archivo.json" - timestamp SI Fecha y hora de detección "2026-05-19T00:01:15Z" - event_count SI Número de eventos analizados 1 - service_accessed Opcional Servicio al que se accedió "sts.amazonaws.com" - unusual_region Opcional Región inusual desde donde se accedió "ap-southeast-1" - -Origen de cada variable en la query: - - sourceIPAddress → r.sourceIPAddress - affectedResource → "iam:user/" + r.userIdentity.userName - service_accessed → r.eventSource - unusual_region → r.awsRegion - - * IMPORTANTE: affectedResource debe escribirse EXACTAMENTE como - "iam:user/NOMBRE_DEL_USUARIO" — ese prefijo es obligatorio. - - -════════════════════════════════════════════════════════════ -INCIDENTE 5: EXFILTRACIÓN DE DATOS (EXFILTRATION) -════════════════════════════════════════════════════════════ - -Qué es: Descarga masiva de archivos desde S3. Más de 50 operaciones GetObject - desde la misma IP en el lapso de una hora. - -Fuente: CloudTrail → eventos S3: eventName = GetObject - -Variables que Aarón debe extraer y enviar: - - Variable Obligatorio Descripción Ejemplo - ────────────────── ─────────── ────────────────────────────────────── ────────────────────────────────── - incident_type SI Nombre fijo del incidente "EXFILTRATION" - severity SI Nivel de gravedad "HIGH" - sourceIPAddress SI IP desde donde se descargaron los datos "185.220.101.5" - affectedResource SI Recurso comprometido (instancia o bucket) "ec2:instance/i-0abc123def456" - s3_log_key SI Ruta del log en S3 "cloudtrail/2026/05/19/.../archivo.json" - timestamp SI Fecha y hora de detección "2026-05-19T00:01:15Z" - event_count SI Número de eventos analizados 55 - total_downloads Opcional Archivos descargados detectados 55 - affected_bucket Opcional Bucket S3 del que se extrajeron datos "prod-data-bucket" - first_access Opcional Primer acceso detectado "2026-05-18T23:00:00Z" - last_access Opcional Último acceso detectado "2026-05-18T23:58:00Z" - -Origen de cada variable en la query: - - sourceIPAddress → r.sourceIPAddress - affectedResource → "ec2:instance/" + ID de la instancia origen - total_downloads → COUNT(*) - affected_bucket → extraído de r.resources[0].ARN - first_access → MIN(r.eventTime) - last_access → MAX(r.eventTime) - - -════════════════════════════════════════════════════════════ -RESUMEN RÁPIDO — VARIABLES CRÍTICAS POR INCIDENTE -════════════════════════════════════════════════════════════ - - Incidente Dato más importante Formato de affectedResource - ───────────────────── ───────────────────── ────────────────────────────────────── - BRUTE_FORCE sourceIPAddress "iam:user/" - PORT_SCAN sourceIPAddress "vpc/" o "subnet/" - PRIVILEGE_ESCALATION affectedResource * "iam:user/" - CREDENTIAL_LEAK affectedResource * "iam:user/" - EXFILTRATION affectedResource "ec2:instance/" o "s3:::" - - * Para estos dos incidentes, affectedResource debe incluir el prefijo - "iam:user/" obligatoriamente. - - -════════════════════════════════════════════════════════════ -CÓMO PUBLICAR EL MENSAJE EN LA COLA -════════════════════════════════════════════════════════════ - -Una vez detectado el incidente y extraídas las variables, Aarón publica -el mensaje en la cola SQS con el siguiente código: - - import boto3, json - - sqs = boto3.client( - "sqs", - endpoint_url="http://localhost:4566", - region_name="us-east-1", - aws_access_key_id="test", - aws_secret_access_key="test" - ) - - payload = { - "incident_type": "BRUTE_FORCE", - "severity": "HIGH", - "sourceIPAddress": "IP extraída de la query", - "affectedResource": "iam:user/nombre_extraído_de_la_query", - "s3_log_key": "ruta del log en S3", - "event_count": 10, - "timestamp": "2026-05-19T00:01:15Z" - } - - sqs.send_message( - QueueUrl="http://localhost:4566/000000000000/tesis-incident-queue", - MessageBody=json.dumps(payload) - ) diff --git a/Scan Port/README.md b/Scan Port/README.md new file mode 100644 index 0000000..2da0f78 --- /dev/null +++ b/Scan Port/README.md @@ -0,0 +1,201 @@ +# 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 + +``` \ No newline at end of file diff --git a/analisis_costos_infraestructura_aws.md b/analisis_costos_infraestructura_aws.md deleted file mode 100644 index 221df76..0000000 --- a/analisis_costos_infraestructura_aws.md +++ /dev/null @@ -1,54 +0,0 @@ -# Análisis de Costos Fijos en AWS: Infraestructura Permanente para Trabajo en Paralelo - -Este documento evalúa el impacto financiero de mantener la infraestructura del proyecto activa 24/7 en AWS real durante la fase de desarrollo en paralelo. El objetivo es determinar si dejar levantados los recursos de manera permanente generará cobros en la cuenta de AWS. - ---- - -## 1. Regla General: Serverless vs. Provisionado - -En AWS existen dos modelos de facturación principales: -* **Serverless / Bajo Demanda (Costo $0 en reposo)**: Solo pagas por uso activo (ejecuciones de código, peticiones, mensajes enviados). Si el recurso está creado pero inactivo, el costo es **cero**. -* **Provisionado (Cobro por Hora)**: Pagas por tener el recurso reservado y encendido, sin importar si lo estás usando o si el tráfico es cero. - ---- - -## 2. Inventario de Recursos Permanentemente Activos ($0 USD) - -Los siguientes recursos del proyecto **pueden permanecer creados las 24 horas del día, los 7 días de la semana** sin generar ningún costo si no hay simulaciones de ataques ejecutándose: - -| Servicio AWS | Recurso en la Tesis | Tipo de Cobro | Costo en Reposo (24/7) | -| :--- | :--- | :--- | :--- | -| **AWS Lambda** | Dispatcher y Playbooks | Por petición (milisegundos) | **$0.00 USD** | -| **Amazon SQS** | Cola de incidentes y DLQ | Por petición (mensajes) | **$0.00 USD** | -| **Amazon SNS** | Tópico de alertas de seguridad | Por petición (publicaciones) | **$0.00 USD** | -| **Amazon Athena** | Motor de consultas SQL | Por datos escaneados (TB) | **$0.00 USD** | -| **AWS IAM** | Roles y políticas de seguridad | Gratis siempre | **$0.00 USD** | -| **Amazon VPC** | Red virtual y subredes | Gratis siempre | **$0.00 USD** | -| **Network ACL** | Firewall de subred (bloqueos) | Gratis siempre | **$0.00 USD** | -| **Amazon S3** | Logs históricos y evidencias | Por almacenamiento (GB) | **<$0.001 USD/mes** (despreciable) | - ---- - -## 3. Alertas de Costo: Recursos a Apagar o Evitar - -Estos son los únicos componentes que **sí generan cobros por hora** y deben ser gestionados con cuidado durante el desarrollo: - -### 1. Instancias EC2 (`t2.micro` / `t3.micro`) — *Apagar en reposo* -* **Impacto**: Una instancia EC2 encendida consume horas de cómputo de forma continua. La capa gratuita de AWS regala **750 horas mensuales** para una sola instancia. Si dejas encendida la máquina de simulación de Melany 24/7, consumirás todo el Free Tier. Si levantan una segunda máquina, o se exceden del mes, les cobrarán **~$9.00 USD/mes** por cada instancia activa. -* **Solución**: Creen la instancia EC2 en AWS, pero **deténganla (stop)** desde la consola cuando no estén realizando pruebas activas de tráfico. Una EC2 apagada solo cobra centavos por el disco EBS asociado. - -### 2. NAT Gateways (VPC) — *Evitar por completo* -* **Impacto**: Si asocian las funciones Lambda a subredes privadas de su VPC, necesitarán un NAT Gateway para que las Lambdas se conecten a internet. Un NAT Gateway cobra una tarifa fija de **~$32.00 USD/mes** solo por estar creado. -* **Solución**: **Desplieguen las Lambdas fuera de la VPC** (en la red pública de AWS). Usen roles de IAM para la seguridad. Así, se comunicarán con SQS, SNS y la API de EC2 (NACL) a través de los endpoints públicos de AWS de forma segura y a **costo cero**. - -### 3. VPC Endpoints de Interfaz — *Evitar en desarrollo* -* **Impacto**: Son alternativas privadas al NAT Gateway, pero cobran **~$7.20 USD/mes** por cada endpoint activo por Zona de Disponibilidad. -* **Solución**: No crearlos en la fase de desarrollo/pruebas locales. - ---- - -## 4. Buenas Prácticas para el Equipo durante la Tesis - -1. **Mantener la Infraestructura Base Levantada**: Creen y dejen creados de forma permanente los buckets S3, colas SQS, tópicos SNS, VPC, NACLs y funciones Lambda. Esto facilita que Aarón y Bryan hagan pruebas de integración rápidas sin tener que reconstruir el entorno. -2. **Apagar las Máquinas de Prueba**: Asegurar que la instancia EC2 objetivo esté apagada y solo se encienda durante las demos o pruebas conjuntas. -3. **Monitorear con AWS Budgets**: Configurar una alarma en AWS Budgets para que envíe un correo de alerta si el costo acumulado supera los **$1.00 USD** en el mes. diff --git a/demo 19 Mayo/demo_stack.sh b/demo 19 Mayo/demo_stack.sh deleted file mode 100755 index 12509ef..0000000 --- a/demo 19 Mayo/demo_stack.sh +++ /dev/null @@ -1,257 +0,0 @@ -#!/usr/bin/env bash -# ============================================================================ -# DEMO PASO A PASO — Componente C: Automatización de Respuesta (Bryan) -# Tesis: Detección y respuesta ante incidentes en AWS (LocalStack) -# -# Esta demo recorre el stack completo y DEMUESTRA el bloqueo REAL de la IP -# del atacante (regla DENY en una Network ACL), no solo una notificación. -# -# Uso: bash demo/demo_stack.sh -# Cada paso espera ENTER para que puedas explicar mientras presentas. -# ============================================================================ -set -uo pipefail -cd "$(dirname "$0")/.." -export PATH="$PWD/.venv/bin:$PATH" - -# ── PREFLIGHT: asegurar LocalStack + recursos + lambdas ────────────────────── -_preflight() { - local C_OK='\033[0;32m'; local C_WARN='\033[1;33m'; local NC='\033[0m' - echo -e "${C_WARN}[preflight] Verificando entorno...${NC}" - - # 1. LocalStack - if ! curl -sf http://localhost:4566/_localstack/health > /dev/null 2>&1; then - echo -e "${C_WARN}[preflight] Levantando LocalStack...${NC}" - docker compose up -d - echo -n "[preflight] Esperando que LocalStack esté listo" - for i in $(seq 1 30); do - curl -sf http://localhost:4566/_localstack/health > /dev/null 2>&1 && break - echo -n "." ; sleep 2 - done - echo "" - fi - echo -e "${C_OK}[preflight] LocalStack OK${NC}" - - # 2. Bootstrap (idempotente) - bash infra/setup.sh > /dev/null 2>&1 - echo -e "${C_OK}[preflight] Recursos AWS OK (S3, SNS, SQS, IAM, EC2/NACL)${NC}" - - # 3. Desplegar / actualizar lambdas - local ROLE="arn:aws:iam::000000000000:role/tesis-lambda-response-role" - local ENV_VARS="Variables={S3_BUCKET=tesis-security-logs,SNS_ALERTS_ARN=arn:aws:sns:us-east-1:000000000000:tesis-security-alerts}" - for fn in notify-alert block-ip revoke-credentials isolate-instance dispatcher; do - local zip="/tmp/tesis-${fn}.zip" - python3 -c " -import zipfile -z = zipfile.ZipFile('${zip}', 'w', __import__('zipfile').ZIP_DEFLATED) -z.write('lambdas/${fn}/handler.py', 'handler.py') -z.close() -" - if awslocal lambda get-function --function-name "tesis-${fn}" > /dev/null 2>&1; then - awslocal lambda update-function-code \ - --function-name "tesis-${fn}" --zip-file "fileb://${zip}" > /dev/null - else - awslocal lambda create-function \ - --function-name "tesis-${fn}" --runtime python3.12 --role "$ROLE" \ - --handler handler.lambda_handler --zip-file "fileb://${zip}" \ - --timeout 30 --environment "$ENV_VARS" > /dev/null - fi - done - echo -e "${C_OK}[preflight] Lambdas OK (notify-alert, block-ip, revoke-credentials, isolate-instance, dispatcher)${NC}" - - # 4. Event source mapping dispatcher → SQS - local QUEUE_ARN="arn:aws:sqs:us-east-1:000000000000:tesis-incident-queue" - local mapping_count - mapping_count=$(awslocal lambda list-event-source-mappings \ - --function-name tesis-dispatcher \ - --query 'length(EventSourceMappings)' --output text 2>/dev/null || echo "0") - if [ "$mapping_count" = "0" ] || [ -z "$mapping_count" ]; then - awslocal lambda create-event-source-mapping \ - --function-name tesis-dispatcher \ - --event-source-arn "$QUEUE_ARN" \ - --batch-size 1 --enabled > /dev/null - fi - echo -e "${C_OK}[preflight] Event source mapping SQS→dispatcher OK${NC}" - echo "" -} -_preflight - -AWSL="awslocal" -BUCKET="tesis-security-logs" -QUEUE_URL="http://localhost:4566/000000000000/tesis-incident-queue" - -C_TITLE='\033[1;36m'; C_OK='\033[0;32m'; C_WARN='\033[1;33m'; C_KEY='\033[1;35m'; C_NC='\033[0m' - -pause() { echo ""; read -rp $'\033[1;33m [ENTER para continuar]\033[0m '; echo ""; } -title() { echo ""; echo -e "${C_TITLE}══════════════════════════════════════════════════════════════════════${C_NC}"; - echo -e "${C_TITLE} $1${C_NC}"; - echo -e "${C_TITLE}══════════════════════════════════════════════════════════════════════${C_NC}"; } -say() { echo -e " $1"; } -key() { echo -e "${C_KEY} ▶ $1${C_NC}"; } - -# ---------------------------------------------------------------------------- -title "0. ARQUITECTURA DEL SISTEMA" -cat <<'EOF' - - Generación Centralización Detección Respuesta (Componente C) - ┌───────────┐ ┌────────────┐ ┌────────────┐ ┌──────────────────────────┐ - │ CloudTrail│─────▶│ S3 + │───▶│ DuckDB / │───▶│ SQS → dispatcher → │ - │ (ataque) │ │ CloudWatch │ │ Metric Flt │ │ ├─ notify-alert (SNS) │ - └───────────┘ └────────────┘ └────────────┘ │ └─ block-ip → NACL DENY │ - └──────────────────────────┘ - Componente A Componente A Componente B Componente C (Bryan) - - Lo que demostraré: el flujo es AUTOMÁTICO (sin intervención humana) y la - acción de block-ip es un BLOQUEO REAL a nivel de red, verificable en - infraestructura AWS — no una simple notificación. -EOF -pause - -# ---------------------------------------------------------------------------- -title "1. LA INFRAESTRUCTURA — LocalStack está corriendo" -say "Verifico que los servicios AWS emulados están disponibles:" -key "curl .../_localstack/health" -curl -s http://localhost:4566/_localstack/health | python3 -c \ - "import sys,json; d=json.load(sys.stdin)['services']; \ - [print(f' - {k:12s}: {v}') for k,v in d.items() if k in \ - ('s3','sns','sqs','lambda','iam','logs','ec2')]" -say "" -say "${C_OK}EC2 disponible${C_NC} → es lo que permite el bloqueo real vía Network ACL." -pause - -# ---------------------------------------------------------------------------- -title "2. ESQUEMA DE ALMACENAMIENTO — dónde vive la información" -say "Bucket único ${C_KEY}s3://${BUCKET}${C_NC}, organizado por fuente (alineado con Componente A):" -key "awslocal s3 ls s3://${BUCKET}/" -$AWSL s3 ls s3://$BUCKET/ || true -cat <-.json -EOF -pause - -# ---------------------------------------------------------------------------- -title "3. PUNTO DE CUMPLIMIENTO — estado de la Network ACL ANTES" -NACL=$($AWSL ec2 describe-network-acls --filters "Name=default,Values=true" \ - --query 'NetworkAcls[0].NetworkAclId' --output text) -say "La NACL ${C_KEY}${NACL}${C_NC} es el firewall de subred donde se aplicará el bloqueo." -say "Limpio reglas de bloqueos anteriores para una demo reproducible..." -for rn in $($AWSL ec2 describe-network-acls --network-acl-ids "$NACL" \ - --query 'NetworkAcls[0].Entries[?Egress==`false` && RuleNumber<`100`].RuleNumber' \ - --output text); do - $AWSL ec2 delete-network-acl-entry --network-acl-id "$NACL" --rule-number "$rn" --ingress 2>/dev/null -done -key "awslocal ec2 describe-network-acls (entradas de ENTRADA)" -$AWSL ec2 describe-network-acls --network-acl-ids "$NACL" \ - --query 'NetworkAcls[0].Entries[?Egress==`false`].[RuleNumber,RuleAction,CidrBlock]' --output table -say "" -say "Solo está la ${C_KEY}regla 100 = ALLOW 0.0.0.0/0${C_NC} (permite todo). Sin bloqueos." -pause - -# ---------------------------------------------------------------------------- -title "4. EL ATAQUE — inyectar un incidente de fuerza bruta" -say "Genero 10 intentos fallidos de login desde una IP atacante y los publico" -say "en S3 (como lo haría CloudTrail real) + SQS (el bus de incidentes):" -key ".venv/bin/python3 simulators/inject_logs.py brute-force" -INJECT_OUT=$(.venv/bin/python3 simulators/inject_logs.py brute-force 2>&1) -echo "$INJECT_OUT" | grep -E '\[inject\]|sourceIPAddress|incident_type|severity' -ATTACKER_IP=$(echo "$INJECT_OUT" | python3 -c \ - "import sys,re,json; t=sys.stdin.read(); m=re.search(r'\"sourceIPAddress\": \"([^\"]+)\"',t); print(m.group(1) if m else '0.0.0.0')") -say "" -key "IP del atacante en este incidente: ${C_KEY}${ATTACKER_IP}${C_NC}" -pause - -# ---------------------------------------------------------------------------- -title "5. CENTRALIZACIÓN — el log llegó a S3 y el incidente a SQS" -key "awslocal s3 ls s3://${BUCKET}/cloudtrail/ --recursive (último)" -$AWSL s3 ls s3://$BUCKET/cloudtrail/ --recursive | tail -1 -say "" -say "El mensaje fue encolado en SQS. Un ${C_KEY}event source mapping${C_NC} conecta" -say "esa cola con la Lambda dispatcher → de aquí en adelante TODO es automático." -key "awslocal lambda list-event-source-mappings --function-name tesis-dispatcher" -$AWSL lambda list-event-source-mappings --function-name tesis-dispatcher \ - --query 'EventSourceMappings[].[State,EventSourceArn]' --output table -pause - -# ---------------------------------------------------------------------------- -title "6. RESPUESTA AUTOMÁTICA — el dispatcher enruta el incidente" -cat <<'EOF' - El dispatcher recibe el incidente desde SQS y aplica su tabla de enrutamiento: - - BRUTE_FORCE → [ notify-alert , block-ip ] - - - notify-alert : publica la alerta estructurada en SNS - - block-ip : APLICA EL BLOQUEO REAL en la Network ACL - - No invoco nada a mano: SQS dispara al dispatcher solo. Espero a que procese... -EOF -for i in $(seq 1 20); do - HIT=$($AWSL ec2 describe-network-acls --network-acl-ids "$NACL" \ - --query "NetworkAcls[0].Entries[?Egress==\`false\` && RuleAction==\`deny\` && CidrBlock==\`${ATTACKER_IP}/32\`]" \ - --output text) - [ -n "$HIT" ] && { say "${C_OK}Procesado automáticamente en ~$((i*2))s${C_NC}"; break; } - sleep 2 -done -pause - -# ---------------------------------------------------------------------------- -title "7. EL BLOQUEO REAL — estado de la Network ACL DESPUÉS" -key "awslocal ec2 describe-network-acls (entradas de ENTRADA)" -$AWSL ec2 describe-network-acls --network-acl-ids "$NACL" \ - --query 'NetworkAcls[0].Entries[?Egress==`false`].[RuleNumber,RuleAction,CidrBlock]' --output table -cat </dev/null | python3 -m json.tool -say "" -say "El campo ${C_KEY}enforcement${C_NC} prueba el punto exacto: network_acl_id + rule_number." -pause - -# ---------------------------------------------------------------------------- -title "9. TRAZABILIDAD — log de ejecución en CloudWatch" -LG="/aws/lambda/tesis-block-ip" -key "awslocal logs filter-log-events $LG --filter-pattern block-ip" -$AWSL logs filter-log-events --log-group-name "$LG" --filter-pattern "block-ip" \ - --query 'events[*].message' --output text 2>/dev/null | tr '\t' '\n' \ - | grep -i 'block-ip' | tail -3 -[ $? -ne 0 ] && say "(sin coincidencias; el log puede tardar unos segundos en indexarse)" -pause - -# ---------------------------------------------------------------------------- -title "10. RESUMEN — qué demostré" -cat < Decisión de diseño del Componente C: se interpone **SQS + dispatcher + DLQ** entre la detección y los playbooks. Aporta durabilidad y reintentos (`maxReceiveCount=3`); si un playbook falla, el incidente no se pierde: pasa a la *Dead Letter Queue* para análisis forense. - ---- - -## 2. Almacenamiento forense — Amazon S3 - -**Bucket único:** `s3://tesis-security-logs` - -### 2.1 Estructura de prefijos - -| Prefijo | Contenido | Fuente | Formato (AWS real) | Responsable | -|---------|-----------|--------|--------------------|-------------| -| `cloudtrail/` | Eventos de auditoría de la API (logins, IAM, S3) | CloudTrail | `.json.gz` | Componente A | -| `vpc-flow/` | Tráfico de red (conexiones aceptadas/rechazadas) | VPC Flow Logs | `.log.gz` | Componente A | -| `config/` | Snapshots de estado de recursos (políticas IAM) | AWS Config | `.json.gz` | Componente A | -| `guardduty/` | Hallazgos de amenazas | GuardDuty | `.json` | Componente A | -| `responses/` | **Evidencia de mitigación de los playbooks** | **Componente C** | `.json` | **Componente C (Bryan)** | - -> En el entorno local los logs simulados se guardan como `.json` sin comprimir para facilitar la inspección en clase; en AWS real se comprimen (`.gz`) para reducir costo/espacio. - -### 2.2 Particionamiento - -Jerárquico por **fecha de ocurrencia**, para que las consultas de detección filtren solo las particiones relevantes (en AWS real se antepone cuenta/región): - -``` -s3://tesis-security-logs/ - cloudtrail/AAAA/MM/DD/HHMMSS/-.json - responses/blocked-ips.json - responses/... -``` - -Ejemplo real generado por el sistema: -`cloudtrail/2026/05/19/000115/brute-force-0aec3b72.json` - -### 2.3 Retención - -90 días para los prefijos de logs (política del Componente A). El prefijo `responses/` se conserva como pista de auditoría de incidentes. - -### 2.4 Catálogo (AWS Glue / esquema lógico) - -Los archivos en S3 son texto plano. **AWS Glue Data Catalog** define un esquema virtual (mapea campos → tipos: IP, puerto, usuario…) que permite a **Athena / DuckDB** ejecutar SQL directamente sobre S3. En el entorno local, DuckDB cumple esta función con `read_json_auto()`. - ---- - -## 3. Esquemas de registro (contratos de datos) - -### 3.1 Evento CloudTrail (entrada — prefijo `cloudtrail/`) - -Archivo `{"Records": [ ... ]}`. Cada evento (generado por `simulators/cloudtrail_gen.py`): - -```json -{ - "eventVersion": "1.08", - "eventTime": "2026-05-18T23:57:05Z", - "eventSource": "signin.amazonaws.com", - "eventName": "ConsoleLogin", - "awsRegion": "us-east-1", - "sourceIPAddress": "185.220.101.5", - "userIdentity": { "type": "IAMUser", "userName": "dev-operator", - "arn": "arn:aws:iam::123456789012:user/dev-operator" }, - "errorCode": "AccessDenied", - "responseElements": { "ConsoleLogin": "Failure" } -} -``` - -### 3.2 Incidente (mensaje SQS — bus de respuesta) - -Producido por `simulators/inject_logs.py`, consumido por el `dispatcher`: - -```json -{ - "incident_type": "BRUTE_FORCE", - "severity": "HIGH", - "sourceIPAddress": "185.220.101.5", - "affectedResource": "iam:user/dev-operator", - "s3_log_key": "cloudtrail/2026/05/19/000115/brute-force-0aec3b72.json", - "event_count": 10, - "timestamp": "2026-05-18T23:57:05Z" -} -``` - -| Campo | Tipo | Descripción | -|-------|------|-------------| -| `incident_type` | enum | `BRUTE_FORCE`, `PRIVILEGE_ESCALATION`, `CREDENTIAL_LEAK`, `EXFILTRATION`, `PORT_SCAN` | -| `severity` | enum | `LOW` · `MEDIUM` · `HIGH` · `CRITICAL` | -| `sourceIPAddress` | string | IP del atacante (objetivo del bloqueo) | -| `affectedResource` | string | Recurso afectado | -| `s3_log_key` | string | Puntero al log forense que originó el incidente | - -### 3.3 Evidencia de mitigación (salida — `responses/blocked-ips.json`) - -**Responsabilidad del Componente C.** Escrito por el playbook `block-ip`. Es la **pista de auditoría** que prueba *qué* se bloqueó y *dónde* exactamente: - -```json -[ - { - "ip": "185.220.101.5", - "blocked_at": "2026-05-18T23:57:10.194758+00:00", - "reason": "BRUTE_FORCE", - "severity": "HIGH", - "affectedResource": "iam:user/dev-operator", - "enforcement": { - "enforced": true, - "already_present": false, - "network_acl_id": "acl-b2a704d3", - "rule_number": 1, - "cidr": "185.220.101.5/32" - } - } -] -``` - -| Campo `enforcement` | Significado | -|---------------------|-------------| -| `enforced` | `true` si el bloqueo se aplicó realmente en infraestructura | -| `network_acl_id` | **Punto de cumplimiento exacto**: la NACL donde se denegó la IP | -| `rule_number` | Nº de regla DENY (rango 1–99, < ALLOW 100 → tiene prioridad) | -| `cidr` | Rango bloqueado (`/32` = IP exacta del atacante) | - -Este bloque es lo que diferencia *"avisar"* de *"bloquear"*: registra la prueba verificable de la acción defensiva. - ---- - -## 4. Capa de consulta (detección — Componente B) - -DuckDB lee los archivos de `cloudtrail/` como tablas externas y aplica las reglas. Ejemplo real (`queries/detect_brute_force.sql`): - -```sql -SELECT r.sourceIPAddress, r.userIdentity.userName AS username, - COUNT(*) AS failed_attempts -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; -``` - -Equivale a una consulta Athena sobre la tabla CloudTrail catalogada por Glue. - ---- - -## 5. Almacenamiento transitorio y operativo - -| Recurso | Tipo | Función | -|---------|------|---------| -| SQS `tesis-incident-queue` | Cola | Entrega del incidente al `dispatcher` | -| SQS `tesis-incident-queue-dlq` | DLQ | Incidentes que fallaron 3 veces (forense) | -| CloudWatch `/aws/lambda/tesis-*` | Log group | Trazas de ejecución de cada playbook | -| CloudWatch `/tesis/security-events` | Log group | Eventos de seguridad centralizados | - ---- - -## 6. Ciclo de vida de un incidente (resumen end-to-end) - -``` -1. Ataque → cloudtrail/AAAA/MM/DD/.../brute-force-xxxx.json (S3, forense) -2. Detección → DuckDB/SQL sobre esos logs (Componente B) -3. Incidente → mensaje JSON en SQS tesis-incident-queue (tránsito) -4. Enrutamiento → dispatcher decide playbooks (CloudWatch traza) -5. Mitigación → block-ip crea regla DENY en Network ACL (INFRAESTRUCTURA) -6. Auditoría → responses/blocked-ips.json con enforcement{} (S3, evidencia) -``` - -El almacenamiento es la columna vertebral: cada fase deja una **evidencia consultable y trazable**, desde el log del ataque hasta la prueba del bloqueo real. - -El diseño se ha estructurado bajo un enfoque de separación de responsabilidades y preservación forense de la evidencia, destacando las siguientes decisiones arquitectónicas: - - Arquitectura Data Lake (Zero-ETL): Toda la información se centraliza en un bucket único particionado en Amazon S3. Esto permite ejecutar consultas analíticas directas sobre los archivos en reposo utilizando DuckDB (en el entorno local) y Amazon Athena (en producción), eliminando la necesidad de mover o duplicar datos. - - Desacoplamiento con Tolerancia a Fallos: Se interpuso un bus de mensajería (Amazon SQS) junto con una Dead Letter Queue (DLQ) entre el motor de detección y los playbooks. Esto garantiza la entrega del incidente; si la mitigación falla, el evento se reintenta y/o se aísla, evitando la pérdida de alertas críticas. - - Contratos de Datos Estrictos: Se estandarizaron los esquemas JSON tanto para el payload de tránsito del incidente como para la evidencia de mitigación. Destaca la inclusión de un bloque de enforcement que audita exactamente dónde y cómo se aplicó el bloqueo (ej. ID de la Network ACL y regla específica). - - Gobernanza y Cadena de Custodia: El almacenamiento se divide en tres capas lógicas: Forense (S3, inmutable a través de S3 Object Lock para preservar la integridad del ataque y la respuesta), Tránsito (SQS, efímera) y Operativa (CloudWatch, para trazas lógicas de ejecución). - -cd ~/localstack-tesis - docker compose up -d # si LocalStack no está corriendo - bash infra/setup.sh # bootstrap (idempotente) - bash demo/demo_stack.sh # demo narrada, avanza con ENTER diff --git a/estrategia_paralelo_aws.md b/estrategia_paralelo_aws.md deleted file mode 100644 index b0abe0e..0000000 --- a/estrategia_paralelo_aws.md +++ /dev/null @@ -1,39 +0,0 @@ -# Estrategia de Trabajo en Paralelo e Integración en AWS (Componente C) - -Este documento describe la estrategia recomendada para que Bryan (Componente C), Melany (Componente A) y Aarón (Componente B) colaboren en paralelo para construir y demostrar el flujo completo en AWS reduciendo los costos mensuales a cero. - ---- - -## 1. Arquitectura a Costo Cero ($0 USD) -Para evitar cobros fijos en la cuenta de AWS de pruebas, la regla de diseño principal es **desplegar las Lambdas fuera de la VPC (sin asociarlas a subredes privadas)**. - -* **Sin NAT Gateway**: Una Lambda dentro de una VPC privada requiere un NAT Gateway para enviar mensajes a SQS, publicar en SNS o conectarse al bucket S3 por su endpoint público. El costo del NAT Gateway es de ~$32 USD/mes fijo. -* **Seguridad y Costo Cero**: Al mantener las Lambdas en la red pública de AWS, estas se conectan a los servicios administrados (SQS, SNS, IAM, S3, EC2) a través de internet de manera cifrada (HTTPS) utilizando sus permisos de IAM execution role. No se genera ningún cargo fijo de infraestructura de red. - ---- - -## 2. Plan de Desarrollo en Paralelo (Contratos de Integración) -El equipo no necesita esperar a que los componentes estén finalizados para empezar a probar. El flujo se divide en interfaces claras: - -``` -[Melany — Comp. A] -> Genera logs (CloudTrail/VPC Flow) en S3. - | (Formato de Archivos) -[Aarón — Comp. B] -> Lee logs, aplica Queries Athena en S3 y publica detección en SQS. - | (Formato JSON de Incidentes) -[Bryan — Comp. C] -> Recibe alertas de SQS, ejecuta dispatcher y activa Playbooks. -``` - -### Acción 1: Contrato de Cola de Entrada SQS -Se debe crear una única cola SQS real en AWS (`tesis-incident-queue`) que actuará como el canal de comunicación entre el Componente B y el Componente C. - -### Acción 2: Pruebas Independientes -* **Aarón** puede probar su Lambda de detección subiendo archivos de logs de prueba (mock logs) en S3, ejecutando Athena y verificando que el payload JSON llegue a SQS. -* **Bryan** puede probar el dispatcher y los playbooks inyectando mensajes JSON de prueba manualmente en la cola SQS de AWS desde la consola web, confirmando que las NACLs se bloquean y que el correo de alerta de SNS se envía. - ---- - -## 3. Demostración del Flujo Completo -Para la presentación del avance ante el profesor, se pueden utilizar dos opciones de demostración: - -1. **Opción Real (End-to-End)**: Se realiza una actividad real (ej. intentar loggearse falsamente en la cuenta) -> CloudTrail registra en S3 -> Aarón detecta con Lambda/Athena -> Aarón publica en SQS -> Lambda Dispatcher se activa -> Playbook `block-ip` deniega el acceso a la IP del atacante en la NACL real. -2. **Opción Híbrida (Simulada para Contingencias)**: Si hay demoras de propagación en los logs de CloudTrail (~15 minutos en AWS real), Bryan ejecuta un script Python local que inyecta el incidente directamente en la SQS de AWS, demostrando la respuesta automatizada en vivo en menos de 5 segundos. diff --git a/guia_acoplamiento_paralelo.md b/guia_acoplamiento_paralelo.md deleted file mode 100644 index 0b47aaf..0000000 --- a/guia_acoplamiento_paralelo.md +++ /dev/null @@ -1,90 +0,0 @@ -# Guía de Acoplamiento y Desarrollo en Paralelo (Componentes A, B y C) - -Este documento detalla el paso a paso técnico para integrar los tres componentes de la tesis (A: Logs, B: Detección, C: Respuesta) en AWS de forma simultánea, permitiendo que cada miembro trabaje de manera independiente sin bloquear a los demás. - ---- - -## 1. El Concepto: Desarrollo Desacoplado - -Para evitar depender de que un compañero termine su parte para poder probar la tuya, utilizaremos **Contratos de Interfaz** (esquemas de datos acordados). Cada componente interactuará con el siguiente a través de un recurso de AWS intermedio (S3 o SQS), actuando como amortiguador. - -``` - [Componente A — Melany] ==== (Contrato 1: S3) ====> [Componente B — Aarón] ==== (Contrato 2: SQS) ====> [Componente C — Bryan] - (Logs en cloudtrail/) (Queries Athena/DuckDB) (Dispatcher & Playbooks) -``` - ---- - -## 2. Paso a Paso para el Acoplamiento - -### Paso 1: Definición de Interfaces (Alineación Inicial) -Antes de escribir código en AWS, el equipo debe acordar y fijar dos contratos: - -* **Contrato 1 (Rutas en S3)**: Melany y Aarón acuerdan la estructura de carpetas en S3. - * Ruta CloudTrail: `s3:///cloudtrail/YYYY/MM/DD/` - * Ruta VPC Flow Logs: `s3:///vpc-flow/YYYY/MM/DD/` -* **Contrato 2 (Formato JSON de Incidentes)**: Aarón y Bryan acuerdan el formato de datos que se enviará por SQS. - * *Estructura obligatoria:* - ```json - { - "incident_type": "BRUTE_FORCE", - "severity": "HIGH", - "sourceIPAddress": "185.220.101.5", - "affectedResource": "iam:user/admin", - "s3_log_key": "cloudtrail/2026/05/26/archivo.json", - "timestamp": "2026-05-26T21:00:00Z", - "event_count": 10 - } - ``` - ---- - -### Paso 2: Aprovisionamiento de Infraestructura Base en AWS -Uno de los miembros (o usando un archivo de Terraform compartido) debe crear los siguientes recursos en la cuenta de AWS real: - -1. **S3 Bucket:** `tesis-security-logs-prod` (para Melany y Aarón). -2. **Cola SQS:** `tesis-incident-queue` (para Aarón y Bryan). -3. **Tópico SNS:** `tesis-security-alerts` (para Bryan). -4. **VPC y NACL por defecto** (para las pruebas de bloqueo de red de Bryan). - ---- - -### Paso 3: Fase de Desarrollo Independiente (En Paralelo) - -Con los recursos base creados, cada componente puede avanzar de forma independiente: - -#### 💻 ¿Cómo trabaja Melany (Componente A)? -* **Tarea**: Configurar CloudTrail y VPC Flow Logs para que escriban en el bucket S3 real. -* **Cómo probar sola**: Puede forzar eventos en AWS (ej. fallar logins o hacer escaneos de puertos) y verificar que los archivos de logs aparezcan en las carpetas correctas de S3. - -#### 💻 ¿Cómo trabaja Aarón (Componente B)? -* **Tarea**: Escribir la Lambda de detección (programada con EventBridge Scheduler cada 5 min) que corre consultas Athena en S3 y publica incidentes en SQS. -* **Cómo probar solo sin Melany**: Aarón no necesita esperar que los logs reales de CloudTrail estén configurados. Él puede **subir manualmente archivos JSON de logs sintéticos** (como los de `sample_cloudtrail.json`) a su bucket S3 y correr sus queries de Athena para verificar que detecte el ataque e inserte el JSON acordado en la SQS. - -#### 💻 ¿Cómo trabajas tú (Componente C - Bryan)? -* **Tarea**: Escribir la Lambda Dispatcher y los Playbooks (Block-IP, Revoke-Credentials, Isolate-Instance). -* **Cómo probar solo sin Aarón**: No necesitas que el detector de Aarón funcione. Puedes abrir la consola web de AWS, ir a la cola SQS `tesis-incident-queue` y **enviar un mensaje de prueba con el formato JSON acordado**. Esto disparará tu flujo completo automáticamente y podrás verificar: - * Si tu IP fue bloqueada en la NACL real de AWS. - * Si el usuario de prueba de IAM fue bloqueado (política `EmergencyDenyAll`). - * Si recibiste la notificación por correo de SNS. - ---- - -### Paso 4: Fase de Integración (Unión de Piezas) - -Una vez que cada módulo funcione por separado, la integración final en AWS real se realiza en tres simples pasos: - -1. **Vincular SQS a Dispatcher**: Configurar el *Event Source Mapping* en la Lambda Dispatcher apuntando a la cola SQS. -2. **Apuntar Detección a SQS Real**: Asegurarse de que la Lambda de Detección de Aarón envíe los mensajes a la URL de SQS real de producción en AWS, no a LocalStack. -3. **Apuntar Detección a Logs Reales**: Cambiar la ruta de origen en la consulta de Athena de Aarón para que analice los logs reales ingestados por Melany. - ---- - -## 3. Estrategia de Pruebas Cruzadas para la Demo del Profesor - -Para demostrar el avance completo del flujo al profesor, ejecuten el siguiente caso de prueba interactivo: - -1. **Ataque**: Desde una máquina externa, ejecuten un pequeño script de fuerza bruta hacia la consola de AWS (Melany captura el log en S3). -2. **Detección**: Muestren la consola de Athena en AWS donde la query SQL identifica a la IP atacante (Aarón muestra los IoC detectados). -3. **Alerta**: El mensaje de alerta viaja a SQS y activa tu Dispatcher. -4. **Respuesta**: Muestren la pestaña de Network ACL en AWS EC2 en tiempo real. Al refrescar, la IP atacante debe aparecer con una regla `DENY` número `1` (Bryan demuestra la contención exitosa). diff --git a/infra/setup.sh b/infra/setup.sh index 60a1dd0..7ba4e6a 100755 --- a/infra/setup.sh +++ b/infra/setup.sh @@ -102,6 +102,33 @@ NACL_ID=$(awslocal ec2 describe-network-acls \ 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 "========================================" diff --git a/lambdas/block-ip.zip b/lambdas/block-ip.zip deleted file mode 100644 index 7446583af9e484843b0d56039f5c500f4cb9ae98..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4166 zcmai%cQl;q+J^^&5M)TS5M2lfX7n~{5F}=FQAaPsL=DlxAWHO65(LqM=!8U+s8I$( z^oTxsOAt{Gdw=Jg?C(4KeDAy7=Xu_LuJx>I-S=Ae52ir`yau>7b&hcW0{eigzxb%N8SAWOYBV4SJ zHf{oseEtq7CHN<>#;DJQvy=Mc-mU9ZDeQ`U>cwr%5DUV$U7q+n-r$5UWI)7Jx`SgU z%Y)bgyM;VrLZ6_iT|(&6H>J2qGeSdD0#CQWv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5MZ1#*}M3 z<;;4(C86ayQa$6*^f zyQWOi29W4rL^8!XZa%ULhYTrjiS_O->z(vqnWaTKE6eq&TW>Y-!zUnY!&0l1&I(O~iZJOe`Rk1XM zs$83~nds?!_W)B3m{-&pF-(K>QqdO+3!%#Z03!7kYf0JbYOVmaqdiidNQ(Tz$Dr?f7AL;L|si=!*A(Szk`)3nV)$J`e}aKs!IDw|mpY?98=! z1FBmb!uv2xxf9vB+P7pao)IdLj{X!!tY5!O`mTnEkj_9xRAQki@>OUu5amd;sXapU zS!-W1UY8N}R8f%6C_q{+ub7wUj8+CLb~_U@nkK#L^I}1QQPNdDjmvF*Wu!BxKqfjp z0cY?K{0fX&J$s~_YADTATdB50o^#|?)aJmx`wrAVKhEw;df}ZxXaY$`008(9{_frI ze|cy4-Mfd4yN9`rmyL_Z-@5NQcOG%>{$h8IYk5Ej28C_OwCCGJP7`)~453aZnF5eln1^X36C`sb5}UXiM`9jghqMe z0nmX~6yDKz$sALG`L30PX4a&&{k(c7eHNSgsz|TspmfZ-ZEVWE9KpCxYi-!uRqAJ| znR1}D>+&)lN+;uo7DlixjvphuN>XZi5T`PO6SKka2dECB{&6;&6$@s`8Z#vpd5!QJ z)FN*{HKdR8JP=4Obc+U>?@jolj=PkIL*Ox7by{zj3)is=wp@ zOV0fd;EN9Zy@sy+1w3}%(f_*Vf9uzC@D!AC)IuCjbBd diff --git a/lambdas/isolate-instance/handler.py b/lambdas/isolate-instance/handler.py index fe5421e..49e2d2a 100644 --- a/lambdas/isolate-instance/handler.py +++ b/lambdas/isolate-instance/handler.py @@ -1,8 +1,22 @@ """ Playbook: isolate-instance -Registra la instancia comprometida en S3 (quarantine list) y notifica via SNS. -En producción real: desasociaría Security Groups y aplicaría política de cuarentena EC2. -En LocalStack Community (sin EC2 habilitado): persiste estado en S3. +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/") — 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/") — 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 @@ -13,7 +27,8 @@ _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") +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) @@ -27,6 +42,65 @@ def _load_quarantine() -> list: 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 = [] @@ -42,19 +116,46 @@ def lambda_handler(event, context): source_ip = body.get("sourceIPAddress", "0.0.0.0") timestamp = datetime.now(timezone.utc).isoformat() - # 1. Registrar en lista de cuarentena en S3 + 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, + "resource": resource, + "isolated_at": timestamp, + "reason": incident_type, + "severity": severity, "sourceIPAddress": source_ip, - "actions_applied": [ - "security_group_removed", # simulado - "deny_all_policy_applied", # simulado - "snapshot_triggered", # simulado - ], + "actions_applied": actions_applied, + "enforcement": enforcement, } quarantine.append(entry) s3.put_object( @@ -63,23 +164,25 @@ def lambda_handler(event, context): Body=json.dumps(quarantine, indent=2).encode(), ContentType="application/json", ) - print(f"[isolate-instance] Recurso {resource} en cuarentena") + print(f"[isolate-instance] Recurso {resource} registrado en cuarentena") - # 2. Notificar al equipo + # ── Notificar al equipo vía SNS ──────────────────────────────────────── + status = "QUARANTINED" if enforcement.get("enforced") else "QUARANTINE_FAILED" result = { - "playbook": "isolate-instance", - "action": "instance_isolated", - "resource": resource, - "status": "QUARANTINED", - "timestamp": timestamp, + "playbook": "isolate-instance", + "action": action, + "resource": resource, + "status": status, + "enforcement": enforcement, + "timestamp": timestamp, } sns.publish( TopicArn=SNS_ARN, - Subject=f"[{severity}] Instancia aislada: {resource}", + Subject=f"[{severity}] Recurso aislado: {resource}"[:100], Message=json.dumps(result, indent=2), ) - results.append({"status": "success", "action": "instance_isolated", "details": result}) + results.append({"status": "success", "action": action, "details": result}) return { "status": "success", diff --git a/lambdas/notify-alert.zip b/lambdas/notify-alert.zip deleted file mode 100644 index 2c7e0f665a983dca6af2e9a5a64723245fa78a93..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2424 zcmai$c{r5o8^^~kOxgD>$66R^p&F90Wynq$GMJ&U3&+-+tl76Qvc-vElqE(Q+t_ka z%C1ewBn^@^`;y;Go%1{8oI3A&UC;Bpf4rajx$f`1nL-&Dc>%OXHxq03#0UgE+g5# zCwLcC(AU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OTGkid$Hrbdl2q7` zAU{FA32rqk&;hHP_yyid^i?HE@~iggw_x?qt$d*erZZmimAXAVCG#3#8@>p05IgwL z$&k|d$%W7aldDa@auCR5p7K?z)XcK2_w|>sCnBFamt!CHM}S?@xkP+5g^VB3rEh5< z#4YLHYLjcabf;V27-YEf7*zHbW^ODFxPglkEi{LHWMz$1Rxud-+QFvU5Sv2%i5Zu5 zceBN7)j1VwpFZv1^qLx2FY)@rI@RHPUHX`9#sVQs^a7AfpQN1 zp&~7RDni>cOpV>?k8n24SF)bG0h|j_m>|a1Y8OXn#KzQ}c9YCCa4C#kA3Gg4u-a#y z)6V(kQ5UJ+TKh4dPE8wBX`%*IQtD~Br8r}x)XAAhj_W+mplt{3#)?%trxAO`3;Z~z zpEp7m`P#15Mrw*6C+*a)aoL-!`MSr6uizp_uCl!WK;ktJm2sDHkA5gOy4@;y$69SH zUsfxDt-z#zKsTGj_GI9r^={pASM)KG$cFz5CPIFwcz-QB>g$5nm_PrT5Q`! z9O(Kr#zUJ9+($}Qj}+nZu|7Pm9kXytMlf?q*yeOv$_&22N`mH7?_B=d7!;gBt;QvQ}*|W6c&nEyT0NvNl{}uUH@BcQj1OR^{i^8FMkw2LP{sm6U&2QsF z^gB2!)1LeOSEf=e&@%NekI=49i?eUNCHS3%eC9nCein69IxX5vp-j}js6!L=^`ZKI IiG}v{KP$EHQ~&?~ diff --git a/lambdas/revoke-credentials/handler.py b/lambdas/revoke-credentials/handler.py index 7e0cc11..920c72a 100644 --- a/lambdas/revoke-credentials/handler.py +++ b/lambdas/revoke-credentials/handler.py @@ -2,74 +2,159 @@ 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 -# LOCALSTACK_HOSTNAME es inyectada por LocalStack en contenedores Lambda (Docker executor) _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) -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": "*", + "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/", "") + 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. 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}") + # ── 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. Adjuntar política de Deny-All como medida de contención - iam.put_user_policy( - UserName=username, - PolicyName="EmergencyDenyAll", - PolicyDocument=DENY_ALL_POLICY + # ── 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", ) - actions_taken.append("Política EmergencyDenyAll adjuntada") - print(f"[revoke-credentials] DenyAll aplicado al usuario {username}") - # 3. Notificar al equipo + # ── 4. Notificar al equipo vía SNS ─────────────────────────────────── result = { - "playbook": "revoke-credentials", - "username": username, - "actions": actions_taken, - "status": "CONTAINED", - "timestamp": datetime.now(timezone.utc).isoformat() + "playbook": "revoke-credentials", + "username": username, + "actions": actions_taken, + "status": "CONTAINED", + "enforcement": enforcement, + "timestamp": timestamp, } sns.publish( TopicArn=SNS_ARN, - Subject=f"[RESPUESTA] Credenciales revocadas: {username}", - Message=json.dumps(result, indent=2) + Subject=f"[{severity}] Credenciales revocadas: {username}"[:100], + Message=json.dumps(result, indent=2), ) - return {"status": "success", "action": "credentials_revoked", "details": result, - "timestamp": datetime.now(timezone.utc).isoformat()} + results.append({ + "status": "success", + "action": "credentials_revoked", + "details": result, + }) + + return { + "status": "success", + "processed": len(results), + "results": results, + "timestamp": datetime.now(timezone.utc).isoformat(), + } diff --git a/recursos_y_costos_aws.md b/recursos_y_costos_aws.md deleted file mode 100644 index bee02c4..0000000 --- a/recursos_y_costos_aws.md +++ /dev/null @@ -1,81 +0,0 @@ -# Implementación en AWS: Costos, Integración y Seguridad (Componente C) - -Este documento resume los costos estimados, los requisitos de integración con los componentes de Melany y Aarón, el formato de datos de incidentes, y los mecanismos de seguridad necesarios para desplegar el **Componente C: Automatización de Respuesta** en un entorno real de AWS. - ---- - -## 1. Costos Estimados en AWS Real -Para propósitos académicos, de prueba y demostración de la tesis, **el costo mensual aproximado es de $0.00 USD**, ya que todos los servicios del Componente C están cubiertos por la **Capa Gratuita de AWS (Free Tier)**. - -A continuación se detalla el costo por servicio en caso de superar el Free Tier (bajo volumen): - -| Servicio AWS | Concepto en Componente C | Capa Gratuita (Mensual) | Costo Fuera de Capa Gratuita | Costo Estimado (Pruebas de Tesis) | -| :--- | :--- | :--- | :--- | :--- | -| **AWS Lambda** | Ejecución de los 5 Playbooks y Dispatcher | 1 millón de peticiones | $0.20 por millón de peticiones | **$0.00** | -| **Amazon SQS** | Cola de incidentes y DLQ | 1 millón de peticiones | $0.40 por millón de peticiones | **$0.00** | -| **Amazon SNS** | Envío de notificaciones de alertas | 1 millón de publicaciones | $0.50 por millón de publicaciones (E-mail: 1,000 gratis, luego $2.00/10k) | **$0.00** | -| **Amazon S3** | Evidencias de bloqueos (`responses/`) | 5 GB de almacenamiento | $0.023 por GB almacenado | **<$0.01** | -| **AWS IAM** | Roles y políticas de seguridad | Siempre gratis | No tiene costo | **$0.00** | -| **EC2 / NACL** | Modificación de reglas del firewall de red | Siempre gratis | Cambiar reglas de NACL no tiene costo | **$0.00** | - ---- - -## 2. Requisitos de Integración (Qué necesitas de tu equipo) - -Para iniciar el despliegue del Componente C en la cuenta de AWS real, necesitas que tus compañeros te proporcionen los siguientes datos e infraestructura: - -### De Melany (Componente A — Infraestructura y Logs) -1. **VPC ID & NACL ID**: El ID de la VPC de producción (`vpc-xxxxxx`) y el ID de la Network ACL pública (`nacl-xxxxxx`) donde el playbook `block-ip` creará las reglas `DENY`. -2. **Nombre del Bucket S3**: El nombre exacto del bucket de logs (`tesis-security-logs-prod`) para almacenar el registro de auditoría de contenciones (`responses/`). -3. **Instancias EC2 Objetivo**: Los IDs de las instancias EC2 (`i-xxxxxx`) que simularán estar comprometidas para probar el aislamiento en red del playbook `isolate-instance`. - -### De Aarón (Componente B — Detección de Incidentes) -1. **ARN de la Cola SQS**: El ARN exacto de la cola SQS de producción (`arn:aws:sqs:us-east-1:123456789012:tesis-incident-queue`) a la cual el dispatcher de Lambda se suscribirá mediante un *Event Source Mapping*. -2. **Homologación de Payloads**: Asegurar que su motor de detección (DuckDB/Athena/Lambda) publique los mensajes con la estructura de variables exacta que se detalla en la siguiente sección. - ---- - -## 3. Formato de Incidentes de Aarón (Payload SQS) -Aarón debe publicar un mensaje en formato **JSON** en la cola de SQS por cada incidente detectado. El esquema unificado es el siguiente: - -### Variables Obligatorias del Payload - -| Campo SQS | Tipo | Descripción | Formato / Ejemplo | -| :--- | :---: | :--- | :--- | -| `incident_type` | String | Tipo de incidente detectado (llave de ruteo). | `"BRUTE_FORCE"`, `"PORT_SCAN"`, `"PRIVILEGE_ESCALATION"`, `"CREDENTIAL_LEAK"`, `"EXFILTRATION"` | -| `severity` | String | Gravedad del incidente según la regla de detección. | `"MEDIUM"`, `"HIGH"`, `"CRITICAL"` | -| `sourceIPAddress` | String | IP origen del atacante (necesaria para bloquear la IP). | `"185.220.101.5"` | -| `affectedResource` | String | Recurso comprometido. **Crítico: usar prefijo exacto.** | `"iam:user/nombre-usuario"` o `"ec2:instance/i-0abc123def"` | -| `s3_log_key` | String | Ruta del log en S3 que contiene la evidencia. | `"cloudtrail/2026/05/19/archivo.json"` | -| `timestamp` | String | Fecha y hora en que ocurrió/detectó el incidente. | ISO 8601 UTC: `"2026-05-19T00:01:15Z"` | -| `event_count` | Integer | Número de eventos/logs que activaron la alerta. | `15` | - -### Ejemplo de JSON de Entrada para SQS (Fuerza Bruta) -```json -{ - "incident_type": "BRUTE_FORCE", - "severity": "HIGH", - "sourceIPAddress": "185.220.101.5", - "affectedResource": "iam:user/dev-operator", - "s3_log_key": "cloudtrail/2026/05/19/brute-force-xyz.json", - "timestamp": "2026-05-19T00:01:15Z", - "event_count": 10 -} -``` - ---- - -## 4. Mecanismos de Seguridad de Conexión en AWS -Para garantizar que las conexiones a los recursos de AWS sean seguras y sigan las mejores prácticas de la nube, se deben implementar los siguientes tres mecanismos: - -1. **Roles de Ejecución de IAM (Mínimo Privilegio)**: - * **Sin credenciales estáticas**: Las Lambdas del Componente C no deben usar Access Keys ni Secret Keys. En su lugar, se les asigna un **IAM Execution Role** con una política de confianza (`AssumeRole`). - * **Políticas Dedicadas**: Cada playbook de Lambda debe tener una política de acceso que conceda permisos estrictamente a su recurso objetivo (ej: el playbook `block-ip` solo debe tener permisos sobre la NACL específica, no sobre todo el servicio de EC2). - -2. **VPC Endpoints (AWS PrivateLink)**: - * Si las funciones Lambda se configuran dentro de la VPC privada para interactuar con recursos internos (como las interfaces de red de las EC2), la comunicación con SQS, SNS y S3 no debe salir a internet público. - * Se deben desplegar **Interface VPC Endpoints** para SQS y SNS, y un **Gateway VPC Endpoint** para S3, permitiendo una conexión privada y segura a través de la red interna de AWS. - -3. **Cifrado de Datos en Tránsito y Reposo**: - * Las conexiones entre SQS, Lambdas y SNS se realizan por defecto utilizando **HTTPS (TLS 1.2/1.3)** asegurando el cifrado en tránsito. - * El bucket de S3 de evidencias y la cola SQS de incidentes deben tener habilitado el **cifrado en reposo** utilizando llaves administradas por AWS (SSE-S3) o llaves personalizadas de KMS (SSE-KMS). diff --git a/simulators/inject_logs.py b/simulators/inject_logs.py index 6983892..dc4ac50 100644 --- a/simulators/inject_logs.py +++ b/simulators/inject_logs.py @@ -57,11 +57,28 @@ def inject(incident_type: str): # 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": f"iam:user/{first['userIdentity']['userName']}", + "affectedResource": affected_resource, "s3_log_key": s3_key, "event_count": len(events), "timestamp": first.get("eventTime", datetime.now(timezone.utc).isoformat()), diff --git a/terraform-tesis-ir-secure-portal/.gitignore b/terraform-tesis-ir-secure-portal/.gitignore new file mode 100644 index 0000000..2fb93ba --- /dev/null +++ b/terraform-tesis-ir-secure-portal/.gitignore @@ -0,0 +1,8 @@ +.terraform/ +*.tfstate +*.tfstate.* +.terraform.lock.hcl +terraform.tfvars +lambda_tesis_detector.zip +crash.log +crash.*.log diff --git a/terraform-tesis-ir-secure-portal/GUIA_PRUEBAS_INCIDENTES.md b/terraform-tesis-ir-secure-portal/GUIA_PRUEBAS_INCIDENTES.md new file mode 100644 index 0000000..c04f900 --- /dev/null +++ b/terraform-tesis-ir-secure-portal/GUIA_PRUEBAS_INCIDENTES.md @@ -0,0 +1,135 @@ +# Guía de pruebas de incidentes + +## Incidente 1: BRUTE_FORCE + +1. Abre `portal_url`. +2. Usa `admin.demo` con contraseña incorrecta 5 veces. +3. Verifica: + - CloudWatch Logs → `/aws/ec2/tesis-ir-portal-app` + - Lambda → `/aws/lambda/lambda-tesis-ir-detector-b` + - DynamoDB → `tesis-ir_incidents` + - S3 Evidence → `incident-01-bruteforce/` + - SQS → `tesis-ir-incident-queue` + +Variables publicadas: + +```json +{ + "incident_type": "BRUTE_FORCE", + "severity": "HIGH", + "sourceIPAddress": "IP origen", + "affectedResource": "iam:user/admin.demo", + "s3_log_key": "incident-01-bruteforce/INC-....json", + "timestamp": "fecha deteccion", + "event_count": 5, + "failed_attempts": 5, + "detection_window": "5 minutes" +} +``` + +## Incidente 2: PORT_SCAN + +Prueba solo contra tu propia EC2. + +```powershell +$ip = terraform output -raw portal_public_ip +81..92 | ForEach-Object { Test-NetConnection $ip -Port $_ -InformationLevel Quiet } +``` + +Verifica: + +- CloudWatch Logs → `/aws/vpc/tesis-ir-flowlogs` +- S3 Evidence → `incident-02-port-scan/` +- SQS → `tesis-ir-incident-queue` + +## Incidente 3: PRIVILEGE_ESCALATION + +Ejemplo controlado: + +```powershell +aws iam create-user --user-name tesis-ir-temp-escalation-test +aws iam attach-user-policy --user-name tesis-ir-temp-escalation-test --policy-arn arn:aws:iam::aws:policy/ReadOnlyAccess +``` + +Limpieza: + +```powershell +aws iam detach-user-policy --user-name tesis-ir-temp-escalation-test --policy-arn arn:aws:iam::aws:policy/ReadOnlyAccess +aws iam delete-user --user-name tesis-ir-temp-escalation-test +``` + +Verifica: + +- CloudTrail Event history → `CreateUser` o `AttachUserPolicy` +- CloudWatch Logs → `/aws/cloudtrail/tesis-ir-management` +- S3 Evidence → `incident-03-privilege-escalation/` +- SQS → `tesis-ir-incident-queue` + +## Incidente 4: CREDENTIAL_LEAK + +Este incidente se detecta cuando una identidad válida ejecuta acciones como `GetCallerIdentity` desde una IP no autorizada. + +Para probarlo de forma controlada, configura `authorized_ip_cidrs` con una IP ficticia y ejecuta: + +```powershell +aws sts get-caller-identity +``` + +Verifica: + +- CloudTrail Event history → `GetCallerIdentity` +- CloudWatch Logs → `/aws/cloudtrail/tesis-ir-management` +- S3 Evidence → `incident-04-credential-leak/` +- SQS → `tesis-ir-incident-queue` + +Luego restaura `authorized_ip_cidrs = []` o tu IP real. + +## Incidente 5: EXFILTRATION + +Activa temporalmente: + +```hcl +enable_s3_data_events = true +``` + +Aplica: + +```powershell +terraform apply +``` + +Luego ejecuta descargas repetidas del objeto ficticio: + +```powershell +$bucket = terraform output -raw sensitive_bucket +1..55 | ForEach-Object { aws s3 cp "s3://$bucket/sensible/clientes_demo.json" ".\clientes_demo_$_.json" } +``` + +Verifica: + +- CloudTrail Event history → `GetObject` +- CloudWatch Logs → `/aws/cloudtrail/tesis-ir-management` +- S3 Evidence → `incident-05-exfiltration/` +- SQS → `tesis-ir-incident-queue` + +Después apaga: + +```hcl +enable_s3_data_events = false +``` + +```powershell +terraform apply +``` + + +## Playbooks de mitigación para Incidente 1 + +Esta versión integra dos playbooks Lambda para `BRUTE_FORCE`: + +- `lambda-tesis-ir-playbook-notify-alert`: recibe el incidente desde una cola SQS dedicada, publica una alerta en SNS y guarda auditoría en `S3 Evidence/responses/notify-alert/`. +- `lambda-tesis-ir-playbook-block-ip`: recibe el mismo incidente desde otra cola SQS dedicada y aplica contención real creando una regla `DENY` de entrada en la Network ACL de la VPC para la IP origen del ataque. También guarda evidencia en `S3 Evidence/responses/block-ip/`. + +El detector sigue publicando el JSON normalizado principal en `tesis-ir-incident-queue`, pero para evitar que dos Lambdas compitan por el mismo mensaje SQS se agregaron dos colas internas de playbooks: `tesis-ir-playbook-notify-alert-queue` y `tesis-ir-playbook-block-ip-queue`. + +Advertencia operacional: cuando `block-ip` bloquee tu IP pública, el portal puede dejar de cargar desde esa IP. Esto es esperado porque representa la mitigación real del incidente. Para recuperar el acceso, elimina la regla DENY creada en la Network ACL o vuelve a desplegar/ajustar la infraestructura con Terraform. diff --git a/terraform-tesis-ir-secure-portal/README_EJECUCION.md b/terraform-tesis-ir-secure-portal/README_EJECUCION.md new file mode 100644 index 0000000..cf2318b --- /dev/null +++ b/terraform-tesis-ir-secure-portal/README_EJECUCION.md @@ -0,0 +1,167 @@ +# Terraform - Laboratorio AWS de detección de incidentes + +Este proyecto crea una infraestructura de laboratorio para detección de incidentes en AWS con enfoque de bajo costo/capa gratuita. La versión actual reemplaza el botón simple de generación de logs por un portal realista de autenticación con login, dashboard, bloqueo temporal e instrucciones de prueba. + +## Qué crea + +- VPC `10.10.0.0/16` +- 2 subredes públicas y 2 subredes privadas reservadas +- Internet Gateway y tabla de rutas pública +- Security Group para portal HTTP restringible por CIDR y SSH limitado a tu IP +- EC2 Amazon Linux 2023 con portal web de autenticación de laboratorio +- Nginx como reverse proxy hacia la app Python local +- CloudWatch Agent para logs de Nginx y aplicación +- CloudWatch Logs `/aws/ec2/tesis-ir-portal-app` +- S3 para logs, evidencia e información sensible ficticia +- CloudTrail hacia S3 y CloudWatch Logs +- VPC Flow Logs sobre la ENI de la EC2 +- DynamoDB para incidentes y estado temporal +- SQS `tesis-ir-incident-queue` para publicar el JSON normalizado requerido por el componente B +- Lambda Detector B +- SNS para alertas +- Metric filters y alarmas CloudWatch +- Athena Workgroup +- Budget opcional si defines `alert_email` +- AWS Config opcional + +## Seguridad aplicada + +- El portal web NO tiene credenciales AWS y NO puede consultar CloudWatch, Lambda, DynamoDB ni S3. +- El portal solo escribe eventos JSON locales en `/var/log/tesis-portal/app.log`. +- CloudWatch Agent, instalado en la EC2, lee ese archivo y lo envía a CloudWatch Logs. +- La EC2 usa IMDSv2 obligatorio. +- El volumen EBS está cifrado. +- Los buckets S3 tienen bloqueo total de acceso público, versionado y cifrado SSE-S3. +- SSH se limita a `ssh_allowed_cidr`. +- HTTP se limita a `http_allowed_cidrs`; si queda vacío, usa automáticamente `ssh_allowed_cidr`. +- Lambda usa un rol IAM separado y solo puede escribir en DynamoDB, S3 Evidence, SNS, SQS y métricas `TesisIR`. + +## Importante sobre costos + +Para reducir costos, este proyecto NO crea: + +- NAT Gateway +- Load Balancer +- RDS +- OpenSearch +- Network Firewall +- Elastic IP + +Por defecto deja apagados: + +```hcl +enable_s3_data_events = false +enable_aws_config = false +cloudtrail_multi_region = false +``` + +Activa `enable_s3_data_events=true` solo cuando vayas a probar EXFILTRATION. Activa `enable_aws_config=true` solo cuando necesites evidencia adicional de cambios de configuración/IAM. + +## Uso + +Copia el ejemplo: + +```powershell +copy terraform.tfvars.example terraform.tfvars +``` + +Edita: + +```hcl +ssh_allowed_cidr = "TU_IP_PUBLICA/32" +http_allowed_cidrs = [] +alert_email = "tu_correo@ejemplo.com" +``` + +Inicializa: + +```powershell +terraform init +``` + +Revisa: + +```powershell +terraform validate +terraform plan -out=tfplan +``` + +Aplica: + +```powershell +terraform apply "tfplan" +``` + +Cuando termine, Terraform mostrará: + +```text +portal_url +portal_public_ip +evidence_bucket +dynamodb_incidents_table +lambda_detector_name +incident_queue_url +``` + +Abre `portal_url` en el navegador. + +## Usuarios del portal + +| Usuario | Contraseña | Rol | +|---|---|---| +| `admin.demo` | `AdminDemo#2026` | Administrador AWS simulado | +| `soc.demo` | `SocDemo#2026` | Analista SOC simulado | +| `usuario.demo` | `UsuarioDemo#2026` | Usuario estándar simulado | + +## Flujo de logs del portal + +```text +Navegador +→ EC2/Nginx +→ App Python /opt/tesis-portal/app.py +→ /var/log/tesis-portal/app.log +→ CloudWatch Agent +→ CloudWatch Logs /aws/ec2/tesis-ir-portal-app +→ Subscription Filter +→ Lambda Detector B +→ DynamoDB + S3 Evidence + SQS + SNS +``` + +## Incidentes normalizados en SQS + +Lambda publica en `tesis-ir-incident-queue` un JSON con las variables obligatorias por incidente: + +- `incident_type` +- `severity` +- `sourceIPAddress` +- `affectedResource` +- `s3_log_key` +- `timestamp` +- `event_count` + +También añade variables opcionales como `failed_attempts`, `scanned_ports_count`, `suspicious_actions`, `service_accessed`, `total_downloads` o `affected_bucket`, según el incidente. + +## Destruir laboratorio + +```powershell +terraform plan -destroy -out=tfdestroy +terraform apply "tfdestroy" +``` + +Por defecto `force_destroy_buckets=true`, así que Terraform puede eliminar buckets con objetos. Para evidencia real usa: + +```hcl +force_destroy_buckets = false +``` + + +## Playbooks de mitigación para Incidente 1 + +Esta versión integra dos playbooks Lambda para `BRUTE_FORCE`: + +- `lambda-tesis-ir-playbook-notify-alert`: recibe el incidente desde una cola SQS dedicada, publica una alerta en SNS y guarda auditoría en `S3 Evidence/responses/notify-alert/`. +- `lambda-tesis-ir-playbook-block-ip`: recibe el mismo incidente desde otra cola SQS dedicada y aplica contención real creando una regla `DENY` de entrada en la Network ACL de la VPC para la IP origen del ataque. También guarda evidencia en `S3 Evidence/responses/block-ip/`. + +El detector sigue publicando el JSON normalizado principal en `tesis-ir-incident-queue`, pero para evitar que dos Lambdas compitan por el mismo mensaje SQS se agregaron dos colas internas de playbooks: `tesis-ir-playbook-notify-alert-queue` y `tesis-ir-playbook-block-ip-queue`. + +Advertencia operacional: cuando `block-ip` bloquee tu IP pública, el portal puede dejar de cargar desde esa IP. Esto es esperado porque representa la mitigación real del incidente. Para recuperar el acceso, elimina la regla DENY creada en la Network ACL o vuelve a desplegar/ajustar la infraestructura con Terraform. diff --git a/terraform-tesis-ir-secure-portal/lambda/lambda_function.py b/terraform-tesis-ir-secure-portal/lambda/lambda_function.py new file mode 100644 index 0000000..fc3d507 --- /dev/null +++ b/terraform-tesis-ir-secure-portal/lambda/lambda_function.py @@ -0,0 +1,561 @@ +import base64 +import gzip +import ipaddress +import json +import os +import time +import uuid +from datetime import datetime, timezone +from zoneinfo import ZoneInfo +from decimal import Decimal + +import boto3 +from boto3.dynamodb.conditions import Key +from botocore.exceptions import ClientError + +dynamodb = boto3.resource("dynamodb") +s3 = boto3.client("s3") +sns = boto3.client("sns") +sqs = boto3.client("sqs") +cloudwatch = boto3.client("cloudwatch") + +INCIDENTS_TABLE = os.environ["INCIDENTS_TABLE"] +STATE_TABLE = os.environ["STATE_TABLE"] +EVIDENCE_BUCKET = os.environ["EVIDENCE_BUCKET"] +SNS_TOPIC_ARN = os.environ["SNS_TOPIC_ARN"] +CONFIG_KEY = os.environ["CONFIG_KEY"] +INCIDENT_QUEUE_URL = os.environ.get("INCIDENT_QUEUE_URL", "") +VPC_ID = os.environ.get("VPC_ID", "unknown-vpc") +PORTAL_INSTANCE_ID = os.environ.get("PORTAL_INSTANCE_ID", "unknown-instance") +PLAYBOOK_NOTIFY_QUEUE_URL = os.environ.get("PLAYBOOK_NOTIFY_QUEUE_URL", "") +PLAYBOOK_BLOCK_IP_QUEUE_URL = os.environ.get("PLAYBOOK_BLOCK_IP_QUEUE_URL", "") +ECUADOR_TZ = ZoneInfo("America/Guayaquil") + +incidents_table = dynamodb.Table(INCIDENTS_TABLE) +state_table = dynamodb.Table(STATE_TABLE) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def ecuador_now() -> str: + return datetime.now(ECUADOR_TZ).isoformat() + + +def epoch_now() -> int: + return int(time.time()) + + +def current_window(minutes: int) -> int: + return epoch_now() // (minutes * 60) + + +def decimal_default(obj): + if isinstance(obj, Decimal): + return int(obj) + raise TypeError(f"Object of type {type(obj)} is not JSON serializable") + + +def load_config() -> dict: + obj = s3.get_object(Bucket=EVIDENCE_BUCKET, Key=CONFIG_KEY) + return json.loads(obj["Body"].read().decode("utf-8")) + + +def decode_cloudwatch_event(event: dict) -> dict: + if "awslogs" not in event: + return { + "logGroup": "direct-test", + "logStream": "manual", + "logEvents": [ + { + "id": str(uuid.uuid4()), + "timestamp": int(time.time() * 1000), + "message": json.dumps(event), + } + ], + } + + payload = base64.b64decode(event["awslogs"]["data"]) + uncompressed = gzip.decompress(payload) + return json.loads(uncompressed) + + +def safe_json_loads(value: str): + try: + return json.loads(value) + except Exception: + return None + + +def ip_in_cidrs(ip_value: str, cidrs: list[str]) -> bool: + try: + ip = ipaddress.ip_address(ip_value) + except Exception: + return False + + for cidr in cidrs: + try: + if ip in ipaddress.ip_network(cidr, strict=False): + return True + except Exception: + continue + return False + + +def username_from_identity(event_json: dict) -> str: + identity = event_json.get("userIdentity", {}) or {} + username = identity.get("userName") + if username: + return username + + arn = identity.get("arn", "") + if ":user/" in arn: + return arn.split(":user/", 1)[1] + if ":assumed-role/" in arn: + return arn.rsplit("/", 1)[-1] + if identity.get("principalId"): + return str(identity.get("principalId")) + return "unknown" + + +def affected_iam_user(event_json: dict, fallback_username: str | None = None) -> str: + username = fallback_username or username_from_identity(event_json) + if not username: + username = "unknown" + return f"iam:user/{username}" + + +def increment_counter(pk: str, sk: str = "counter", ttl_seconds: int = 900) -> int: + response = state_table.update_item( + Key={"pk": pk, "sk": sk}, + UpdateExpression="SET #ttl = :ttl, updated_at = :updated_at ADD #count :one", + ExpressionAttributeNames={ + "#ttl": "ttl", + "#count": "count", + }, + ExpressionAttributeValues={ + ":ttl": epoch_now() + ttl_seconds, + ":updated_at": utc_now(), + ":one": 1, + }, + ReturnValues="UPDATED_NEW", + ) + return int(response["Attributes"]["count"]) + + +def mark_alert_once(alert_key: str, ttl_seconds: int = 900) -> bool: + try: + state_table.put_item( + Item={ + "pk": f"alert#{alert_key}", + "sk": "sent", + "ttl": epoch_now() + ttl_seconds, + "created_at": utc_now(), + }, + ConditionExpression="attribute_not_exists(pk) AND attribute_not_exists(sk)", + ) + return True + except ClientError as exc: + if exc.response.get("Error", {}).get("Code") == "ConditionalCheckFailedException": + return False + raise + + +def put_distinct_port_and_count(srcaddr: str, dstport: str, ttl_seconds: int = 900) -> int: + pk = f"portscan#{srcaddr}#window#{current_window(5)}" + sk = f"port#{dstport}" + state_table.put_item( + Item={ + "pk": pk, + "sk": sk, + "ttl": epoch_now() + ttl_seconds, + "updated_at": utc_now(), + } + ) + response = state_table.query(KeyConditionExpression=Key("pk").eq(pk), Select="COUNT") + return int(response.get("Count", 0)) + + +def evidence_folder(incident_type: str) -> str: + mapping = { + "BRUTE_FORCE": "incident-01-bruteforce", + "PORT_SCAN": "incident-02-port-scan", + "PRIVILEGE_ESCALATION": "incident-03-privilege-escalation", + "CREDENTIAL_LEAK": "incident-04-credential-leak", + "EXFILTRATION": "incident-05-exfiltration", + } + return mapping.get(incident_type, incident_type.lower()) + + +def build_evidence_key(incident_type: str, incident_id: str) -> str: + return f"{evidence_folder(incident_type)}/{incident_id}.json" + + +def send_sqs_message(queue_url: str, payload: dict) -> None: + if not queue_url: + return + sqs.send_message(QueueUrl=queue_url, MessageBody=json.dumps(payload, default=decimal_default)) + + +def publish_incident_queue(payload: dict) -> None: + # Cola principal exigida por Variables_Incidentes.docx. + send_sqs_message(INCIDENT_QUEUE_URL, payload) + + # Fan-out controlado a playbooks de respuesta automatica. + # Se usan colas dedicadas para que notify-alert y block-ip reciban ambos + # el mismo evento sin competir por el mensaje SQS. + # + # Incidentes con respuesta automatica activa: + # BRUTE_FORCE → notify-alert + block-ip (Incidente 1) + # PORT_SCAN → notify-alert + block-ip (Incidente 2) + PLAYBOOK_INCIDENTS = {"BRUTE_FORCE", "PORT_SCAN"} + if payload.get("incident_type") in PLAYBOOK_INCIDENTS: + send_sqs_message(PLAYBOOK_NOTIFY_QUEUE_URL, payload) + send_sqs_message(PLAYBOOK_BLOCK_IP_QUEUE_URL, payload) + + +def save_incident(payload: dict, source: str, raw_event: dict, summary: str) -> str: + incident_id = f"INC-{datetime.now(timezone.utc).strftime('%Y%m%d%H%M%S')}-{str(uuid.uuid4())[:8]}" + created_at = utc_now() + created_at_ecuador = ecuador_now() + evidence_key = build_evidence_key(payload["incident_type"], incident_id) + + final_payload = dict(payload) + final_payload["incident_id"] = incident_id + final_payload["timestamp"] = final_payload.get("timestamp") or created_at_ecuador + final_payload["timestamp_utc"] = final_payload.get("timestamp_utc") or created_at + final_payload["timestamp_ecuador"] = final_payload.get("timestamp_ecuador") or created_at_ecuador + final_payload["timezone"] = final_payload.get("timezone") or "America/Guayaquil" + final_payload["s3_log_key"] = evidence_key + # Registrar qué playbooks se activan para este incidente + if final_payload.get("incident_type") in {"BRUTE_FORCE", "PORT_SCAN"}: + final_payload["playbooks_requested"] = ["notify-alert", "block-ip"] + + evidence_doc = { + "incident_id": incident_id, + "incident_payload": final_payload, + "source": source, + "summary": summary, + "created_at": created_at, + "created_at_ecuador": created_at_ecuador, + "timezone": "America/Guayaquil", + "raw_event": raw_event, + } + + s3.put_object( + Bucket=EVIDENCE_BUCKET, + Key=evidence_key, + Body=json.dumps(evidence_doc, indent=2, default=decimal_default).encode("utf-8"), + ContentType="application/json", + ) + + incidents_table.put_item( + Item={ + "incident_id": incident_id, + "type": final_payload["incident_type"], + "severity": final_payload["severity"], + "status": "DETECTED", + "sourceIPAddress": final_payload.get("sourceIPAddress", "unknown"), + "affectedResource": final_payload.get("affectedResource", "unknown"), + "event_count": int(final_payload.get("event_count", 1)), + "source": source, + "summary": summary, + "s3_log_key": evidence_key, + "evidence_s3_uri": f"s3://{EVIDENCE_BUCKET}/{evidence_key}", + "created_at": created_at, + "created_at_ecuador": created_at_ecuador, + "affected_service": final_payload.get("affected_service", final_payload.get("affectedService", "unknown")), + "asset_name": final_payload.get("asset_name", final_payload.get("assetName", "unknown")), + "severity_basis": final_payload.get("severity_basis", "not_specified"), + } + ) + + publish_incident_queue(final_payload) + + sns.publish( + TopicArn=SNS_TOPIC_ARN, + Subject=f"[{final_payload['severity']}] Incidente detectado: {final_payload['incident_type']}", + Message=json.dumps(evidence_doc, indent=2, default=decimal_default), + ) + + cloudwatch.put_metric_data( + Namespace="TesisIR", + MetricData=[ + { + "MetricName": final_payload["incident_type"], + "Value": 1, + "Unit": "Count", + } + ], + ) + return incident_id + + +def analyze_app_event(event_json: dict, config: dict): + if event_json.get("event_type") != "login_failed": + return None + + thresholds = config.get("thresholds", {}) + source_ip = event_json.get("source_ip") or event_json.get("sourceIPAddress") or "unknown" + username = event_json.get("username", "unknown") + threshold = int(thresholds.get("app_login_failures_same_ip_5m", 5)) + window = current_window(5) + count = increment_counter(f"app_bruteforce#{source_ip}#window#{window}", ttl_seconds=900) + + if count >= threshold and mark_alert_once(f"BRUTE_FORCE#APP#{source_ip}#{window}"): + severity_basis = ( + f"HIGH porque la IP {source_ip} alcanzo {count} intentos fallidos " + f"en 5 minutos; el umbral configurado para BRUTE_FORCE es {threshold}." + ) + payload = { + "incident_type": "BRUTE_FORCE", + "severity": "HIGH", + "sourceIPAddress": source_ip, + "affectedResource": event_json.get("affectedResource") or f"iam:user/{username}", + "s3_log_key": "pending", + "timestamp": event_json.get("timestamp") or ecuador_now(), + "timestamp_utc": event_json.get("timestamp_utc") or utc_now(), + "timezone": "America/Guayaquil", + "event_count": count, + "failed_attempts": count, + "detection_window": "5 minutes", + "affected_service": event_json.get("affected_service", "Portal de autenticacion corporativo"), + "asset_name": event_json.get("asset_name", f"{PORTAL_INSTANCE_ID}"), + "asset_type": event_json.get("asset_type", "EC2 web application"), + "severity_basis": severity_basis, + "mitigation_playbooks": ["notify-alert", "block-ip"], + } + return payload, f"{count} intentos fallidos de login del portal desde {source_ip} en 5 minutos." + return None + + +def analyze_cloudtrail(event_json: dict, config: dict): + event_name = event_json.get("eventName") + event_source = event_json.get("eventSource") + source_ip = event_json.get("sourceIPAddress", "unknown") + aws_region = event_json.get("awsRegion", "unknown") + username = username_from_identity(event_json) + thresholds = config.get("thresholds", {}) + allowed_ips = config.get("authorized_ips", []) + + # Incidente 1: fuerza bruta por ConsoleLogin fallido. + if event_name == "ConsoleLogin": + response = event_json.get("responseElements", {}) or {} + if response.get("ConsoleLogin") == "Failure": + threshold_ip = int(thresholds.get("console_login_failures_same_ip_5m", 10)) + threshold_user = int(thresholds.get("console_login_failures_same_user_5m", 5)) + window = current_window(5) + count_ip = increment_counter(f"console_bruteforce_ip#{source_ip}#window#{window}", ttl_seconds=900) + count_user = increment_counter(f"console_bruteforce_user#{username}#window#{window}", ttl_seconds=900) + if count_user >= threshold_user and mark_alert_once(f"BRUTE_FORCE#USER#{username}#{window}"): + payload = { + "incident_type": "BRUTE_FORCE", + "severity": "HIGH", + "sourceIPAddress": source_ip, + "affectedResource": affected_iam_user(event_json, username), + "s3_log_key": "pending", + "timestamp": event_json.get("eventTime", utc_now()), + "event_count": count_user, + "failed_attempts": count_user, + "detection_window": "5 minutes", + "affected_service": "AWS Sign-In / IAM", + "asset_name": "AWS Console", + "asset_type": "AWS control plane", + "severity_basis": f"HIGH porque se alcanzaron {count_user} fallos de ConsoleLogin para el mismo usuario en 5 minutos.", + "mitigation_playbooks": ["notify-alert", "block-ip"], + } + return payload, f"{count_user} fallos de ConsoleLogin para {username} en 5 minutos." + if count_ip >= threshold_ip and mark_alert_once(f"BRUTE_FORCE#IP#{source_ip}#{window}"): + payload = { + "incident_type": "BRUTE_FORCE", + "severity": "HIGH", + "sourceIPAddress": source_ip, + "affectedResource": affected_iam_user(event_json, username), + "s3_log_key": "pending", + "timestamp": event_json.get("eventTime", utc_now()), + "event_count": count_ip, + "failed_attempts": count_ip, + "detection_window": "5 minutes", + "affected_service": "AWS Sign-In / IAM", + "asset_name": "AWS Console", + "asset_type": "AWS control plane", + "severity_basis": f"HIGH porque se alcanzaron {count_ip} fallos de ConsoleLogin desde la misma IP en 5 minutos.", + "mitigation_playbooks": ["notify-alert", "block-ip"], + } + return payload, f"{count_ip} fallos de ConsoleLogin desde {source_ip} en 5 minutos." + + # Incidente 3: escalada de privilegios. + iam_critical_events = { + "CreateUser", + "AttachUserPolicy", + "AttachRolePolicy", + "PutUserPolicy", + "PutRolePolicy", + "CreateAccessKey", + "AddUserToGroup", + "CreatePolicyVersion", + "UpdateAssumeRolePolicy", + } + if event_source == "iam.amazonaws.com" and event_name in iam_critical_events: + request_params = event_json.get("requestParameters", {}) or {} + target_policy_arn = request_params.get("policyArn") or request_params.get("policyDocument", "") + window = current_window(5) + count = increment_counter(f"privilege_escalation#{username}#window#{window}", ttl_seconds=900) + payload = { + "incident_type": "PRIVILEGE_ESCALATION", + "severity": "CRITICAL", + "sourceIPAddress": source_ip, + "affectedResource": affected_iam_user(event_json, username), + "s3_log_key": "pending", + "timestamp": event_json.get("eventTime", utc_now()), + "event_count": count, + "suspicious_actions": [event_name], + } + if target_policy_arn: + payload["target_policy_arn"] = str(target_policy_arn)[:500] + return payload, f"Accion IAM critica {event_name} ejecutada por {username} desde {source_ip}." + + # Incidente 4: fuga de credenciales por uso desde IP no autorizada. + # Se restringe a eventos de identidad/API claramente representativos para reducir falsos positivos. + credential_leak_events = {"GetCallerIdentity", "GetUser", "ListAccessKeys"} + identity_type = (event_json.get("userIdentity", {}) or {}).get("type", "") + if event_name in credential_leak_events and identity_type in {"IAMUser", "AssumedRole"}: + if source_ip != "unknown" and not ip_in_cidrs(source_ip, allowed_ips): + if mark_alert_once(f"CREDENTIAL_LEAK#{username}#{source_ip}#{current_window(5)}", ttl_seconds=900): + payload = { + "incident_type": "CREDENTIAL_LEAK", + "severity": "CRITICAL", + "sourceIPAddress": source_ip, + "affectedResource": affected_iam_user(event_json, username), + "s3_log_key": "pending", + "timestamp": event_json.get("eventTime", utc_now()), + "event_count": 1, + "service_accessed": event_source, + "unusual_region": aws_region, + } + return payload, f"Credenciales de {username} usadas desde IP no autorizada {source_ip}." + + # Incidente 5: exfiltracion por muchas descargas GetObject desde una IP en 1 hora. + if event_source == "s3.amazonaws.com" and event_name == "GetObject": + request_params = event_json.get("requestParameters", {}) or {} + bucket = request_params.get("bucketName") or extract_bucket_from_resources(event_json) + window = current_window(60) + count = increment_counter(f"exfiltration#{source_ip}#{bucket}#window#{window}", ttl_seconds=7200) + threshold = int(thresholds.get("s3_getobject_exfiltration_count_1h", 50)) + if count >= threshold and mark_alert_once(f"EXFILTRATION#{source_ip}#{bucket}#{window}", ttl_seconds=7200): + payload = { + "incident_type": "EXFILTRATION", + "severity": "HIGH", + "sourceIPAddress": source_ip, + "affectedResource": f"s3:::{bucket}" if bucket else f"ec2:instance/{PORTAL_INSTANCE_ID}", + "s3_log_key": "pending", + "timestamp": event_json.get("eventTime", utc_now()), + "event_count": count, + "total_downloads": count, + "affected_bucket": bucket or "unknown", + "first_access": "tracked_in_detection_window", + "last_access": event_json.get("eventTime", utc_now()), + } + return payload, f"{count} operaciones GetObject desde {source_ip} sobre bucket {bucket} en 1 hora." + + return None + + +def extract_bucket_from_resources(event_json: dict) -> str: + resources = event_json.get("resources", []) or [] + for resource in resources: + arn = resource.get("ARN") or resource.get("arn") or "" + if arn.startswith("arn:aws:s3:::"): + value = arn.replace("arn:aws:s3:::", "", 1) + return value.split("/", 1)[0] + return "unknown" + + +def parse_flow_log(message: str): + parts = message.strip().split() + if len(parts) < 14: + return None + return { + "version": parts[0], + "account_id": parts[1], + "interface_id": parts[2], + "srcaddr": parts[3], + "dstaddr": parts[4], + "srcport": parts[5], + "dstport": parts[6], + "protocol": parts[7], + "packets": parts[8], + "bytes": parts[9], + "start": parts[10], + "end": parts[11], + "action": parts[12], + "log_status": parts[13], + "raw_message": message, + } + + +def analyze_flow_log(message: str, config: dict): + flow = parse_flow_log(message) + if not flow or flow.get("action") != "REJECT": + return None + + thresholds = config.get("thresholds", {}) + threshold = int(thresholds.get("port_scan_distinct_ports_5m", 10)) + srcaddr = flow.get("srcaddr", "unknown") + dstport = flow.get("dstport", "unknown") + window = current_window(5) + distinct_count = put_distinct_port_and_count(srcaddr, dstport) + rejected_count = increment_counter(f"portscan_rejects#{srcaddr}#window#{window}", ttl_seconds=900) + + if distinct_count >= threshold and mark_alert_once(f"PORT_SCAN#{srcaddr}#{window}"): + payload = { + "incident_type": "PORT_SCAN", + "severity": "MEDIUM", + "sourceIPAddress": srcaddr, + "affectedResource": f"vpc/{VPC_ID}", + "s3_log_key": "pending", + "timestamp": utc_now(), + "event_count": rejected_count, + "rejected_connections": rejected_count, + "scanned_ports_count": distinct_count, + } + return payload, f"Posible escaneo: {distinct_count} puertos distintos rechazados desde {srcaddr} en 5 minutos.", flow + return None + + +def lambda_handler(event, context): + config = load_config() + decoded = decode_cloudwatch_event(event) + log_group = decoded.get("logGroup", "unknown") + results = [] + + for log_event in decoded.get("logEvents", []): + raw_message = log_event.get("message", "") + message_json = safe_json_loads(raw_message) + analysis = None + raw_for_evidence = message_json if isinstance(message_json, dict) else {"raw_message": raw_message} + + if isinstance(message_json, dict): + if "eventSource" in message_json or "eventName" in message_json: + analysis = analyze_cloudtrail(message_json, config) + else: + analysis = analyze_app_event(message_json, config) + else: + flow_analysis = analyze_flow_log(raw_message, config) + if flow_analysis: + payload, summary, flow = flow_analysis + analysis = (payload, summary) + raw_for_evidence = flow + + if analysis: + payload, summary = analysis + incident_id = save_incident( + payload=payload, + source=log_group, + raw_event=raw_for_evidence, + summary=summary, + ) + results.append(incident_id) + + return {"statusCode": 200, "detected_incidents": results} diff --git a/terraform-tesis-ir-secure-portal/lambda_playbook_block_ip.zip b/terraform-tesis-ir-secure-portal/lambda_playbook_block_ip.zip new file mode 100644 index 0000000000000000000000000000000000000000..16d1ca31c8be3793330098c816f1a177f2f964a1 GIT binary patch literal 3191 zcmV--42bhkO9KQH00;mG0000XiU0rr0000000000015yA0BB)uWNc+}E^v9YTFq`7 zIkw){QyeghRN*ShkMH6}_tpgzM@ehq$b#*pe+;8Q6_4DEOJs#)DNzIgz3TO#(JwF$ zFss?kHg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!CDQ_f<$!U%TwnC!{k?_gTTa8aPwQ0ttG%{E6@pln<2 zqQkLE-OS$3uKqS72S~o@=?iJBN57P8|K$b?p^My}Hptv^qg`k9->}Ptr?JYJ&=g|*5JxV(KdNbqaC$S3mOnO*t;(!X>PF4!bx1w& zx?eOaKq~_p<`78P?1SIn<4V?%DTwW6tQY`r=JnkH2IZ2Qhpd>9(%yoovC5PRNhL$jO=yA7g`QnqK- zhUv)n#4WC!U|LyzqFMKp>ek#=>I?&YKi8*Mi#EGjMi)_dek6Mqr}BM#huafgXfcOC zjy%}-nzLH@#G%buUwPj?2B$Q$LkT__MM2~HfBjPcrsb5;o>abk)Q`vQ`Jj8UJOA7g zolqf=#rDY7aUu(0$O@p-WlqU_MHY6S1FY-mH5|P1{ZsZS{8%0bi4+18!==#Hz_xuS zWh`O?i0Mh+w8yEF-q}!|B8#apnB~ST?4I`OeVO0OGi8->DdGn%n0%;>Yuk1tGX(NS z$hasB+JXPL>AoqbVpO#*bnY7WJGI;6Ph;U7+G%b>cDcXtZx z*B=Ic@Btt9ft|cagR0MhyfCp`+YB0X-2A#o?$C^Tmz8dG-{N+BhubdkwPf3|8zEVd z<$B=aH3TlKW#ey$fI=4vW2zI*#}_o!=m#k5q&Xmk*}V8u|2&!6Sy`CnHpelcd2Vm% zHmWb(W)8Ba0(xCu>Q!}b|Gx$DOP@n13Ks+yn00960P)i30no2Zf zeFgvk022TJP)h*<6ay3h2mlBG001G1no2ZfeFgvk022TJ3IG5A0000000000q=5hc l003xVZe(m_axQRrP)h{{000000RRC2H~;_uwFUqH001NvWt0E_ literal 0 HcmV?d00001 diff --git a/terraform-tesis-ir-secure-portal/main.tf b/terraform-tesis-ir-secure-portal/main.tf new file mode 100644 index 0000000..28b8f4c --- /dev/null +++ b/terraform-tesis-ir-secure-portal/main.tf @@ -0,0 +1,1576 @@ +terraform { + required_version = ">= 1.5.0" + + required_providers { + aws = { + source = "hashicorp/aws" + version = ">= 5.0" + } + archive = { + source = "hashicorp/archive" + version = ">= 2.4" + } + } +} + +provider "aws" { + region = var.aws_region + + default_tags { + tags = { + Project = var.project_name + Environment = "lab" + ManagedBy = "terraform" + Owner = "estudiante-b" + } + } +} + +data "aws_caller_identity" "current" {} + +data "aws_availability_zones" "available" { + state = "available" +} + +data "aws_ami" "al2023" { + most_recent = true + owners = ["amazon"] + + filter { + name = "name" + values = ["al2023-ami-2023.*-x86_64"] + } + + filter { + name = "architecture" + values = ["x86_64"] + } + + filter { + name = "virtualization-type" + values = ["hvm"] + } +} + +locals { + account_id = data.aws_caller_identity.current.account_id + + name_prefix = var.project_name + + az_1 = data.aws_availability_zones.available.names[0] + az_2 = data.aws_availability_zones.available.names[1] + + logs_bucket_name = "${var.project_name}-logs-${local.account_id}-${var.aws_region}" + evidence_bucket_name = "${var.project_name}-evidence-${local.account_id}-${var.aws_region}" + sensitive_bucket_name = "${var.project_name}-sensitive-data-${local.account_id}-${var.aws_region}" + + authorized_ip_cidrs = length(var.authorized_ip_cidrs) > 0 ? var.authorized_ip_cidrs : [var.ssh_allowed_cidr] + portal_http_cidrs = length(var.http_allowed_cidrs) > 0 ? var.http_allowed_cidrs : [var.ssh_allowed_cidr] + + common_log_groups = { + cloudtrail = "/aws/cloudtrail/${var.project_name}-management" + flowlogs = "/aws/vpc/${var.project_name}-flowlogs" + config = "/aws/config/${var.project_name}-changes" + app = "/aws/ec2/${var.project_name}-portal-app" + normalized = "/aws/${var.project_name}/incidents-normalized" + lambda = "/aws/lambda/lambda-${var.project_name}-detector-b" + } + + evidence_prefixes = [ + "incident-01-bruteforce/", + "incident-02-port-scan/", + "incident-03-privilege-escalation/", + "incident-04-credential-leak/", + "incident-05-exfiltration/", + "config/" + ] + + logs_prefixes = [ + "cloudtrail/", + "vpc-flow-logs/", + "config/", + "athena-results/" + ] + + sensitive_prefixes = [ + "sensible/", + "public/" + ] +} + +# ----------------------------------------------------------------------------- +# Presupuesto básico. Se crea solo si defines alert_email y create_budget=true. +# ----------------------------------------------------------------------------- + +resource "aws_budgets_budget" "monthly_cost" { + count = var.create_budget && var.alert_email != "" ? 1 : 0 + + name = "${var.project_name}-monthly-budget" + budget_type = "COST" + limit_amount = tostring(var.monthly_budget_limit_usd) + limit_unit = "USD" + time_unit = "MONTHLY" + + notification { + comparison_operator = "GREATER_THAN" + threshold = 50 + threshold_type = "PERCENTAGE" + notification_type = "ACTUAL" + subscriber_email_addresses = [var.alert_email] + } + + notification { + comparison_operator = "GREATER_THAN" + threshold = 80 + threshold_type = "PERCENTAGE" + notification_type = "ACTUAL" + subscriber_email_addresses = [var.alert_email] + } + + notification { + comparison_operator = "GREATER_THAN" + threshold = 100 + threshold_type = "PERCENTAGE" + notification_type = "FORECASTED" + subscriber_email_addresses = [var.alert_email] + } +} + +# ----------------------------------------------------------------------------- +# Red: VPC, subredes públicas/privadas reservadas, IGW y rutas públicas. +# No se crea NAT Gateway, ALB, RDS ni VPC Endpoints para reducir costos. +# ----------------------------------------------------------------------------- + +resource "aws_vpc" "this" { + cidr_block = var.vpc_cidr + enable_dns_hostnames = true + enable_dns_support = true + + tags = { + Name = "${var.project_name}-vpc" + } +} + +resource "aws_internet_gateway" "this" { + vpc_id = aws_vpc.this.id + + tags = { + Name = "${var.project_name}-igw" + } +} + +resource "aws_subnet" "public_a" { + vpc_id = aws_vpc.this.id + cidr_block = var.public_subnet_a_cidr + availability_zone = local.az_1 + map_public_ip_on_launch = true + + tags = { + Name = "${var.project_name}-subnet-public1-${local.az_1}" + Tier = "public" + } +} + +resource "aws_subnet" "public_b" { + vpc_id = aws_vpc.this.id + cidr_block = var.public_subnet_b_cidr + availability_zone = local.az_2 + map_public_ip_on_launch = true + + tags = { + Name = "${var.project_name}-subnet-public2-${local.az_2}" + Tier = "public" + } +} + +resource "aws_subnet" "private_a" { + vpc_id = aws_vpc.this.id + cidr_block = var.private_subnet_a_cidr + availability_zone = local.az_1 + + tags = { + Name = "${var.project_name}-subnet-private1-${local.az_1}" + Tier = "private-reserved" + } +} + +resource "aws_subnet" "private_b" { + vpc_id = aws_vpc.this.id + cidr_block = var.private_subnet_b_cidr + availability_zone = local.az_2 + + tags = { + Name = "${var.project_name}-subnet-private2-${local.az_2}" + Tier = "private-reserved" + } +} + +resource "aws_route_table" "public" { + vpc_id = aws_vpc.this.id + + tags = { + Name = "${var.project_name}-rtb-public" + } +} + +resource "aws_route" "public_default_ipv4" { + route_table_id = aws_route_table.public.id + destination_cidr_block = "0.0.0.0/0" + gateway_id = aws_internet_gateway.this.id +} + +resource "aws_route_table_association" "public_a" { + subnet_id = aws_subnet.public_a.id + route_table_id = aws_route_table.public.id +} + +resource "aws_route_table_association" "public_b" { + subnet_id = aws_subnet.public_b.id + route_table_id = aws_route_table.public.id +} + +resource "aws_route_table" "private" { + vpc_id = aws_vpc.this.id + + tags = { + Name = "${var.project_name}-rtb-private-local-only" + } +} + +resource "aws_route_table_association" "private_a" { + subnet_id = aws_subnet.private_a.id + route_table_id = aws_route_table.private.id +} + +resource "aws_route_table_association" "private_b" { + subnet_id = aws_subnet.private_b.id + route_table_id = aws_route_table.private.id +} + +# ----------------------------------------------------------------------------- +# Security Group del portal. +# SSH queda limitado a tu IP pública /32. +# ----------------------------------------------------------------------------- + +resource "aws_security_group" "portal" { + name = "${var.project_name}-portal-sg" + description = "Security group para portal web de laboratorio IR" + vpc_id = aws_vpc.this.id + + ingress { + description = "HTTP del portal limitado a CIDRs autorizados" + from_port = 80 + to_port = 80 + protocol = "tcp" + cidr_blocks = local.portal_http_cidrs + } + + ingress { + description = "SSH solo desde la IP autorizada" + from_port = 22 + to_port = 22 + protocol = "tcp" + cidr_blocks = [var.ssh_allowed_cidr] + } + + egress { + description = "Salida necesaria para instalar paquetes y enviar logs" + from_port = 0 + to_port = 0 + protocol = "-1" + cidr_blocks = ["0.0.0.0/0"] + } + + tags = { + Name = "${var.project_name}-portal-sg" + } +} + +# ----------------------------------------------------------------------------- +# Buckets S3: logs, evidencia y datos sensibles ficticios. +# ----------------------------------------------------------------------------- + +resource "aws_s3_bucket" "logs" { + bucket = local.logs_bucket_name + force_destroy = var.force_destroy_buckets + + tags = { + Name = local.logs_bucket_name + Role = "logs" + } +} + +resource "aws_s3_bucket" "evidence" { + bucket = local.evidence_bucket_name + force_destroy = var.force_destroy_buckets + + tags = { + Name = local.evidence_bucket_name + Role = "incident-evidence" + } +} + +resource "aws_s3_bucket" "sensitive" { + bucket = local.sensitive_bucket_name + force_destroy = var.force_destroy_buckets + + tags = { + Name = local.sensitive_bucket_name + Role = "sensitive-demo-data" + } +} + +resource "aws_s3_bucket_public_access_block" "all" { + for_each = { + logs = aws_s3_bucket.logs.id + evidence = aws_s3_bucket.evidence.id + sensitive = aws_s3_bucket.sensitive.id + } + + bucket = each.value + block_public_acls = true + block_public_policy = true + ignore_public_acls = true + restrict_public_buckets = true +} + +resource "aws_s3_bucket_ownership_controls" "all" { + for_each = { + logs = aws_s3_bucket.logs.id + evidence = aws_s3_bucket.evidence.id + sensitive = aws_s3_bucket.sensitive.id + } + + bucket = each.value + + rule { + object_ownership = "BucketOwnerEnforced" + } +} + +resource "aws_s3_bucket_versioning" "all" { + for_each = { + logs = aws_s3_bucket.logs.id + evidence = aws_s3_bucket.evidence.id + sensitive = aws_s3_bucket.sensitive.id + } + + bucket = each.value + + versioning_configuration { + status = "Enabled" + } +} + +resource "aws_s3_bucket_server_side_encryption_configuration" "all" { + for_each = { + logs = aws_s3_bucket.logs.id + evidence = aws_s3_bucket.evidence.id + sensitive = aws_s3_bucket.sensitive.id + } + + bucket = each.value + + rule { + apply_server_side_encryption_by_default { + sse_algorithm = "AES256" + } + } +} + +resource "aws_s3_object" "logs_prefixes" { + for_each = toset(local.logs_prefixes) + + bucket = aws_s3_bucket.logs.id + key = each.value + content = "" +} + +resource "aws_s3_object" "evidence_prefixes" { + for_each = toset(local.evidence_prefixes) + + bucket = aws_s3_bucket.evidence.id + key = each.value + content = "" +} + +resource "aws_s3_object" "sensitive_prefixes" { + for_each = toset(local.sensitive_prefixes) + + bucket = aws_s3_bucket.sensitive.id + key = each.value + content = "" +} + +resource "aws_s3_object" "demo_sensitive_clients" { + bucket = aws_s3_bucket.sensitive.id + key = "sensible/clientes_demo.json" + content_type = "application/json" + + content = jsonencode({ + aviso = "Datos ficticios para laboratorio. No usar informacion real." + clientes = [ + { id = 1, nombre = "Cliente Demo 1", nivel = "interno" }, + { id = 2, nombre = "Cliente Demo 2", nivel = "interno" } + ] + }) +} + +resource "aws_s3_object" "demo_public_readme" { + bucket = aws_s3_bucket.sensitive.id + key = "public/readme.txt" + content_type = "text/plain" + content = "Bucket de laboratorio. No contiene datos reales.\n" +} + +resource "aws_s3_object" "detector_config" { + bucket = aws_s3_bucket.evidence.id + key = "config/authorized_ips.json" + content_type = "application/json" + + content = jsonencode({ + authorized_ips = local.authorized_ip_cidrs + sensitive_buckets = [ + aws_s3_bucket.sensitive.bucket + ] + critical_policies = [ + aws_iam_policy.critical_policy.name + ] + authorized_admin_users = var.authorized_admin_users + thresholds = { + console_login_failures_same_user_5m = var.threshold_console_login_failures_same_user_5m + console_login_failures_same_ip_5m = var.threshold_console_login_failures_same_ip_5m + app_login_failures_same_ip_5m = var.threshold_app_login_failures_same_ip_5m + port_scan_distinct_ports_5m = var.threshold_port_scan_distinct_ports_5m + s3_getobject_unusual_count_5m = var.threshold_s3_getobject_unusual_count_5m + s3_getobject_exfiltration_count_1h = var.threshold_s3_getobject_exfiltration_count_1h + } + resource_ids = { + vpc_id = aws_vpc.this.id + portal_instance_id = aws_instance.portal.id + } + }) +} + +# Bucket policy necesaria para CloudTrail. +resource "aws_s3_bucket_policy" "logs" { + bucket = aws_s3_bucket.logs.id + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Sid = "AWSCloudTrailAclCheck" + Effect = "Allow" + Principal = { Service = "cloudtrail.amazonaws.com" } + Action = "s3:GetBucketAcl" + Resource = aws_s3_bucket.logs.arn + }, + { + Sid = "AWSCloudTrailWrite" + Effect = "Allow" + Principal = { Service = "cloudtrail.amazonaws.com" } + Action = "s3:PutObject" + Resource = "${aws_s3_bucket.logs.arn}/cloudtrail/AWSLogs/${local.account_id}/*" + Condition = { + StringEquals = { + "s3:x-amz-acl" = "bucket-owner-full-control" + } + } + } + ] + }) +} + +# ----------------------------------------------------------------------------- +# CloudWatch Log Groups. +# ----------------------------------------------------------------------------- + +resource "aws_cloudwatch_log_group" "cloudtrail" { + name = local.common_log_groups.cloudtrail + retention_in_days = var.cloudwatch_retention_days +} + +resource "aws_cloudwatch_log_group" "flowlogs" { + name = local.common_log_groups.flowlogs + retention_in_days = var.cloudwatch_retention_days +} + +resource "aws_cloudwatch_log_group" "config" { + name = local.common_log_groups.config + retention_in_days = var.cloudwatch_retention_days +} + +resource "aws_cloudwatch_log_group" "ec2_app" { + name = local.common_log_groups.app + retention_in_days = var.cloudwatch_retention_days +} + +resource "aws_cloudwatch_log_group" "normalized" { + name = local.common_log_groups.normalized + retention_in_days = var.normalized_log_retention_days +} + +resource "aws_cloudwatch_log_group" "lambda" { + name = local.common_log_groups.lambda + retention_in_days = var.cloudwatch_retention_days +} + +resource "aws_cloudwatch_log_group" "playbook_notify" { + name = "/aws/lambda/lambda-${var.project_name}-playbook-notify-alert" + retention_in_days = var.cloudwatch_retention_days +} + +resource "aws_cloudwatch_log_group" "playbook_block_ip" { + name = "/aws/lambda/lambda-${var.project_name}-playbook-block-ip" + retention_in_days = var.cloudwatch_retention_days +} + +# ----------------------------------------------------------------------------- +# IAM para EC2: SSM + CloudWatch Agent. +# ----------------------------------------------------------------------------- + +resource "aws_iam_role" "ec2" { + name = "role-ec2-${var.project_name}-portal" + + assume_role_policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Principal = { Service = "ec2.amazonaws.com" } + Action = "sts:AssumeRole" + } + ] + }) +} + +resource "aws_iam_role_policy_attachment" "ec2_ssm" { + role = aws_iam_role.ec2.name + policy_arn = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore" +} + +resource "aws_iam_role_policy" "ec2_cloudwatch_agent_limited" { + name = "policy-ec2-${var.project_name}-cloudwatch-agent-limited" + role = aws_iam_role.ec2.id + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Sid = "WriteOnlyPortalLogs" + Effect = "Allow" + Action = [ + "logs:CreateLogStream", + "logs:PutLogEvents", + "logs:DescribeLogGroups", + "logs:DescribeLogStreams" + ] + Resource = [ + aws_cloudwatch_log_group.ec2_app.arn, + "${aws_cloudwatch_log_group.ec2_app.arn}:*" + ] + } + ] + }) +} + +resource "aws_iam_instance_profile" "ec2" { + name = "profile-ec2-${var.project_name}-portal" + role = aws_iam_role.ec2.name +} + +# ----------------------------------------------------------------------------- +# EC2 portal web de laboratorio. +# ----------------------------------------------------------------------------- + +resource "aws_instance" "portal" { + ami = data.aws_ami.al2023.id + instance_type = var.ec2_instance_type + subnet_id = aws_subnet.public_a.id + private_ip = var.portal_private_ip + vpc_security_group_ids = [aws_security_group.portal.id] + associate_public_ip_address = true + iam_instance_profile = aws_iam_instance_profile.ec2.name + key_name = var.key_name != "" ? var.key_name : null + + user_data_base64 = base64gzip(templatefile("${path.module}/scripts/user_data.sh.tpl", { + app_log_group = aws_cloudwatch_log_group.ec2_app.name + project_name = var.project_name + })) + + user_data_replace_on_change = true + + root_block_device { + volume_size = var.ec2_volume_size_gb + volume_type = "gp3" + delete_on_termination = true + encrypted = true + } + + metadata_options { + http_tokens = "required" + } + + tags = { + Name = "${var.project_name}-portal-ec2" + Role = "portal-web-laboratorio" + } + + depends_on = [ + aws_cloudwatch_log_group.ec2_app, + aws_iam_role_policy.ec2_cloudwatch_agent_limited, + aws_iam_role_policy_attachment.ec2_ssm + ] +} + +# ----------------------------------------------------------------------------- +# VPC Flow Logs sobre la ENI de la EC2, no sobre toda la VPC. +# ----------------------------------------------------------------------------- + +resource "aws_iam_role" "vpc_flowlogs" { + name = "role-${var.project_name}-vpc-flowlogs" + + assume_role_policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Principal = { Service = "vpc-flow-logs.amazonaws.com" } + Action = "sts:AssumeRole" + } + ] + }) +} + +resource "aws_iam_role_policy" "vpc_flowlogs" { + name = "policy-${var.project_name}-vpc-flowlogs" + role = aws_iam_role.vpc_flowlogs.id + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Action = [ + "logs:CreateLogStream", + "logs:PutLogEvents", + "logs:DescribeLogGroups", + "logs:DescribeLogStreams" + ] + Resource = "${aws_cloudwatch_log_group.flowlogs.arn}:*" + } + ] + }) +} + +resource "aws_flow_log" "portal_eni" { + count = var.enable_vpc_flow_logs ? 1 : 0 + + iam_role_arn = aws_iam_role.vpc_flowlogs.arn + log_destination = aws_cloudwatch_log_group.flowlogs.arn + traffic_type = "ALL" + eni_id = aws_instance.portal.primary_network_interface_id + + max_aggregation_interval = 60 + + log_format = "$${version} $${account-id} $${interface-id} $${srcaddr} $${dstaddr} $${srcport} $${dstport} $${protocol} $${packets} $${bytes} $${start} $${end} $${action} $${log-status}" + + tags = { + Name = "${var.project_name}-vpc-flowlogs-ec2" + } + + depends_on = [ + aws_iam_role_policy.vpc_flowlogs + ] +} + +# ----------------------------------------------------------------------------- +# CloudTrail: management events por defecto. +# S3 data events quedan apagados por defecto para reducir costos. +# ----------------------------------------------------------------------------- + +resource "aws_iam_role" "cloudtrail_cloudwatch" { + name = "role-${var.project_name}-cloudtrail-cloudwatch" + + assume_role_policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Principal = { Service = "cloudtrail.amazonaws.com" } + Action = "sts:AssumeRole" + } + ] + }) +} + +resource "aws_iam_role_policy" "cloudtrail_cloudwatch" { + name = "policy-${var.project_name}-cloudtrail-cloudwatch" + role = aws_iam_role.cloudtrail_cloudwatch.id + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Action = [ + "logs:CreateLogStream", + "logs:PutLogEvents" + ] + Resource = "${aws_cloudwatch_log_group.cloudtrail.arn}:*" + } + ] + }) +} + +resource "aws_cloudtrail" "management" { + name = "${var.project_name}-cloudtrail-management" + s3_bucket_name = aws_s3_bucket.logs.id + s3_key_prefix = "cloudtrail" + include_global_service_events = true + is_multi_region_trail = var.cloudtrail_multi_region + enable_log_file_validation = true + + cloud_watch_logs_group_arn = "${aws_cloudwatch_log_group.cloudtrail.arn}:*" + cloud_watch_logs_role_arn = aws_iam_role.cloudtrail_cloudwatch.arn + + event_selector { + read_write_type = "All" + include_management_events = true + + dynamic "data_resource" { + for_each = var.enable_s3_data_events ? [1] : [] + + content { + type = "AWS::S3::Object" + values = ["${aws_s3_bucket.sensitive.arn}/sensible/"] + } + } + } + + depends_on = [ + aws_s3_bucket_policy.logs, + aws_iam_role_policy.cloudtrail_cloudwatch + ] + + tags = { + Name = "${var.project_name}-cloudtrail-management" + } +} + +# ----------------------------------------------------------------------------- +# AWS Config opcional: puede generar cargos por configuration items y reglas. +# Por defecto está desactivado. Actívalo solo para pruebas de cambios IAM. +# ----------------------------------------------------------------------------- + +resource "aws_iam_role" "config" { + count = var.enable_aws_config ? 1 : 0 + + name = "role-${var.project_name}-aws-config" + + assume_role_policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Principal = { Service = "config.amazonaws.com" } + Action = "sts:AssumeRole" + } + ] + }) +} + +resource "aws_iam_role_policy_attachment" "config_managed" { + count = var.enable_aws_config ? 1 : 0 + + role = aws_iam_role.config[0].name + policy_arn = "arn:aws:iam::aws:policy/service-role/AWS_ConfigRole" +} + +resource "aws_iam_role_policy" "config_s3_delivery" { + count = var.enable_aws_config ? 1 : 0 + + name = "policy-${var.project_name}-aws-config-s3-delivery" + role = aws_iam_role.config[0].id + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Action = "s3:GetBucketAcl" + Resource = aws_s3_bucket.logs.arn + }, + { + Effect = "Allow" + Action = "s3:PutObject" + Resource = "${aws_s3_bucket.logs.arn}/config/AWSLogs/${local.account_id}/*" + Condition = { + StringEquals = { + "s3:x-amz-acl" = "bucket-owner-full-control" + } + } + } + ] + }) +} + +resource "aws_config_configuration_recorder" "this" { + count = var.enable_aws_config ? 1 : 0 + + name = "${var.project_name}-config-recorder" + role_arn = aws_iam_role.config[0].arn + + recording_group { + all_supported = false + include_global_resource_types = true + resource_types = var.config_resource_types + } + + depends_on = [ + aws_iam_role_policy_attachment.config_managed, + aws_iam_role_policy.config_s3_delivery + ] +} + +resource "aws_config_delivery_channel" "this" { + count = var.enable_aws_config ? 1 : 0 + + name = "${var.project_name}-config-delivery" + s3_bucket_name = aws_s3_bucket.logs.bucket + s3_key_prefix = "config" + + depends_on = [ + aws_config_configuration_recorder.this + ] +} + +resource "aws_config_configuration_recorder_status" "this" { + count = var.enable_aws_config ? 1 : 0 + + name = aws_config_configuration_recorder.this[0].name + is_enabled = true + + depends_on = [ + aws_config_delivery_channel.this + ] +} + +resource "aws_config_config_rule" "iam_no_admin_access" { + count = var.enable_aws_config ? 1 : 0 + + name = "${var.project_name}-iam-policy-no-admin-access" + + source { + owner = "AWS" + source_identifier = "IAM_POLICY_NO_STATEMENTS_WITH_ADMIN_ACCESS" + } + + depends_on = [ + aws_config_configuration_recorder_status.this + ] +} + +# ----------------------------------------------------------------------------- +# DynamoDB: incidentes y estado temporal de detección. +# ----------------------------------------------------------------------------- + +resource "aws_dynamodb_table" "incidents" { + name = "${var.project_name}_incidents" + billing_mode = "PAY_PER_REQUEST" + hash_key = "incident_id" + + attribute { + name = "incident_id" + type = "S" + } + + tags = { + Name = "${var.project_name}_incidents" + Role = "incident-registry" + } +} + +resource "aws_dynamodb_table" "state" { + name = "${var.project_name}_detection_state" + billing_mode = "PAY_PER_REQUEST" + hash_key = "pk" + range_key = "sk" + + attribute { + name = "pk" + type = "S" + } + + attribute { + name = "sk" + type = "S" + } + + ttl { + attribute_name = "ttl" + enabled = true + } + + tags = { + Name = "${var.project_name}_detection_state" + Role = "detector-state" + } +} + +# ----------------------------------------------------------------------------- +# SNS para alertas. +# ----------------------------------------------------------------------------- + +resource "aws_sns_topic" "alerts" { + name = "${var.project_name}-incident-alerts" +} + +resource "aws_sns_topic_subscription" "email" { + count = var.alert_email != "" ? 1 : 0 + + topic_arn = aws_sns_topic.alerts.arn + protocol = "email" + endpoint = var.alert_email +} + +# ----------------------------------------------------------------------------- +# SQS: cola de incidentes para entregar el JSON normalizado exigido por el +# componente B. Lambda publica aqui las variables obligatorias por incidente. +# ----------------------------------------------------------------------------- + +resource "aws_sqs_queue" "incident_queue" { + name = "${var.project_name}-incident-queue" + message_retention_seconds = 345600 + visibility_timeout_seconds = 30 + sqs_managed_sse_enabled = true + + tags = { + Name = "${var.project_name}-incident-queue" + Role = "normalized-incident-queue" + } +} + +resource "aws_sqs_queue" "playbook_notify_queue" { + name = "${var.project_name}-playbook-notify-alert-queue" + message_retention_seconds = 345600 + visibility_timeout_seconds = 60 + sqs_managed_sse_enabled = true + + tags = { + Name = "${var.project_name}-playbook-notify-alert-queue" + Role = "playbook-dispatch-notify-alert" + } +} + +resource "aws_sqs_queue" "playbook_block_ip_queue" { + name = "${var.project_name}-playbook-block-ip-queue" + message_retention_seconds = 345600 + visibility_timeout_seconds = 60 + sqs_managed_sse_enabled = true + + tags = { + Name = "${var.project_name}-playbook-block-ip-queue" + Role = "playbook-dispatch-block-ip" + } +} + +# ----------------------------------------------------------------------------- +# IAM policy crítica de prueba e IAM user de laboratorio. +# No se crean access keys ni password de consola. +# ----------------------------------------------------------------------------- + +resource "aws_iam_policy" "critical_policy" { + name = "${var.project_name}-critical-policy" + description = "Politica critica de laboratorio para detectar cambios controlados" + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Sid = "AllowReadOnlySensitiveDemoBucket" + Effect = "Allow" + Action = [ + "s3:GetObject", + "s3:ListBucket" + ] + Resource = [ + aws_s3_bucket.sensitive.arn, + "${aws_s3_bucket.sensitive.arn}/sensible/*" + ] + } + ] + }) +} + +resource "aws_iam_user" "test_user" { + count = var.create_test_iam_user ? 1 : 0 + + name = "${var.project_name}-user-test" + force_destroy = true + + tags = { + Role = "lab-test-user" + } +} + +# ----------------------------------------------------------------------------- +# Lambda Detector B. +# ----------------------------------------------------------------------------- + +data "archive_file" "lambda_zip" { + type = "zip" + source_file = "${path.module}/lambda/lambda_function.py" + output_path = "${path.module}/lambda_tesis_detector.zip" +} + +resource "aws_iam_role" "lambda_detector" { + name = "role-lambda-${var.project_name}-detector" + + assume_role_policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Principal = { Service = "lambda.amazonaws.com" } + Action = "sts:AssumeRole" + } + ] + }) +} + +resource "aws_iam_role_policy_attachment" "lambda_basic" { + role = aws_iam_role.lambda_detector.name + policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" +} + +resource "aws_iam_role_policy" "lambda_detector" { + name = "policy-lambda-${var.project_name}-detector" + role = aws_iam_role.lambda_detector.id + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Sid = "DynamoDBIncidentAccess" + Effect = "Allow" + Action = [ + "dynamodb:PutItem", + "dynamodb:GetItem", + "dynamodb:UpdateItem", + "dynamodb:Query" + ] + Resource = [ + aws_dynamodb_table.incidents.arn, + aws_dynamodb_table.state.arn + ] + }, + { + Sid = "EvidenceS3Access" + Effect = "Allow" + Action = [ + "s3:PutObject", + "s3:GetObject" + ] + Resource = [ + "${aws_s3_bucket.evidence.arn}/*" + ] + }, + { + Sid = "SnsPublishAlerts" + Effect = "Allow" + Action = "sns:Publish" + Resource = aws_sns_topic.alerts.arn + }, + { + Sid = "SqsPublishNormalizedIncidentAndPlaybooks" + Effect = "Allow" + Action = "sqs:SendMessage" + Resource = [ + aws_sqs_queue.incident_queue.arn, + aws_sqs_queue.playbook_notify_queue.arn, + aws_sqs_queue.playbook_block_ip_queue.arn + ] + }, + { + Sid = "CloudWatchCustomMetrics" + Effect = "Allow" + Action = "cloudwatch:PutMetricData" + Resource = "*" + Condition = { + StringEquals = { + "cloudwatch:namespace" = "TesisIR" + } + } + } + ] + }) +} + +resource "aws_lambda_function" "detector" { + function_name = "lambda-${var.project_name}-detector-b" + role = aws_iam_role.lambda_detector.arn + handler = "lambda_function.lambda_handler" + runtime = "python3.12" + architectures = ["x86_64"] + memory_size = 256 + timeout = 30 + + filename = data.archive_file.lambda_zip.output_path + source_code_hash = data.archive_file.lambda_zip.output_base64sha256 + + environment { + variables = { + INCIDENTS_TABLE = aws_dynamodb_table.incidents.name + STATE_TABLE = aws_dynamodb_table.state.name + EVIDENCE_BUCKET = aws_s3_bucket.evidence.bucket + SNS_TOPIC_ARN = aws_sns_topic.alerts.arn + CONFIG_KEY = aws_s3_object.detector_config.key + INCIDENT_QUEUE_URL = aws_sqs_queue.incident_queue.url + PLAYBOOK_NOTIFY_QUEUE_URL = aws_sqs_queue.playbook_notify_queue.url + PLAYBOOK_BLOCK_IP_QUEUE_URL = aws_sqs_queue.playbook_block_ip_queue.url + VPC_ID = aws_vpc.this.id + PORTAL_INSTANCE_ID = aws_instance.portal.id + } + } + + depends_on = [ + aws_iam_role_policy_attachment.lambda_basic, + aws_iam_role_policy.lambda_detector, + aws_cloudwatch_log_group.lambda + ] + + tags = { + Name = "lambda-${var.project_name}-detector-b" + Role = "incident-detector" + } +} + +# Permisos para que CloudWatch Logs invoque Lambda. +resource "aws_lambda_permission" "from_cloudtrail_logs" { + statement_id = "AllowCloudWatchCloudTrail" + action = "lambda:InvokeFunction" + function_name = aws_lambda_function.detector.function_name + principal = "logs.${var.aws_region}.amazonaws.com" + source_arn = "${aws_cloudwatch_log_group.cloudtrail.arn}:*" +} + +resource "aws_lambda_permission" "from_app_logs" { + statement_id = "AllowCloudWatchAppLogs" + action = "lambda:InvokeFunction" + function_name = aws_lambda_function.detector.function_name + principal = "logs.${var.aws_region}.amazonaws.com" + source_arn = "${aws_cloudwatch_log_group.ec2_app.arn}:*" +} + +resource "aws_lambda_permission" "from_flow_logs" { + count = var.enable_vpc_flow_logs ? 1 : 0 + + statement_id = "AllowCloudWatchFlowLogs" + action = "lambda:InvokeFunction" + function_name = aws_lambda_function.detector.function_name + principal = "logs.${var.aws_region}.amazonaws.com" + source_arn = "${aws_cloudwatch_log_group.flowlogs.arn}:*" +} + +# Subscription filters. +resource "aws_cloudwatch_log_subscription_filter" "cloudtrail_to_lambda" { + name = "sf-cloudtrail-to-detector" + log_group_name = aws_cloudwatch_log_group.cloudtrail.name + filter_pattern = "{ ($.eventSource = \"signin.amazonaws.com\") || ($.eventSource = \"iam.amazonaws.com\") || ($.eventSource = \"s3.amazonaws.com\") || ($.eventSource = \"sts.amazonaws.com\") }" + destination_arn = aws_lambda_function.detector.arn + + depends_on = [ + aws_lambda_permission.from_cloudtrail_logs + ] +} + +resource "aws_cloudwatch_log_subscription_filter" "app_to_lambda" { + name = "sf-app-to-detector" + log_group_name = aws_cloudwatch_log_group.ec2_app.name + filter_pattern = "{ $.event_type = \"login_failed\" }" + destination_arn = aws_lambda_function.detector.arn + + depends_on = [ + aws_lambda_permission.from_app_logs + ] +} + +resource "aws_cloudwatch_log_subscription_filter" "flowlogs_to_lambda" { + count = var.enable_vpc_flow_logs ? 1 : 0 + + name = "sf-flowlogs-to-detector" + log_group_name = aws_cloudwatch_log_group.flowlogs.name + filter_pattern = "[version, account_id, interface_id, srcaddr, dstaddr, srcport, dstport, protocol, packets, bytes, start, end, action = \"REJECT\", log_status]" + destination_arn = aws_lambda_function.detector.arn + + depends_on = [ + aws_lambda_permission.from_flow_logs + ] +} + + +# ----------------------------------------------------------------------------- +# Playbooks de respuesta para Incidente 1: BRUTE_FORCE. +# notify-alert notifica por SNS y deja auditoria en S3. +# block-ip aplica contencion real en la NACL con una regla DENY para la IP origen. +# ----------------------------------------------------------------------------- + +data "archive_file" "notify_alert_zip" { + type = "zip" + source_file = "${path.module}/playbooks/notify_alert/handler.py" + output_path = "${path.module}/lambda_playbook_notify_alert.zip" +} + +data "archive_file" "block_ip_zip" { + type = "zip" + source_file = "${path.module}/playbooks/block_ip/handler.py" + output_path = "${path.module}/lambda_playbook_block_ip.zip" +} + +resource "aws_iam_role" "playbook_notify" { + name = "role-lambda-${var.project_name}-playbook-notify-alert" + + assume_role_policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Principal = { Service = "lambda.amazonaws.com" } + Action = "sts:AssumeRole" + } + ] + }) +} + +resource "aws_iam_role" "playbook_block_ip" { + name = "role-lambda-${var.project_name}-playbook-block-ip" + + assume_role_policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Principal = { Service = "lambda.amazonaws.com" } + Action = "sts:AssumeRole" + } + ] + }) +} + +resource "aws_iam_role_policy_attachment" "playbook_notify_basic" { + role = aws_iam_role.playbook_notify.name + policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" +} + +resource "aws_iam_role_policy_attachment" "playbook_block_ip_basic" { + role = aws_iam_role.playbook_block_ip.name + policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" +} + +resource "aws_iam_role_policy" "playbook_notify" { + name = "policy-lambda-${var.project_name}-playbook-notify-alert" + role = aws_iam_role.playbook_notify.id + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Sid = "ReadDedicatedQueue" + Effect = "Allow" + Action = [ + "sqs:ReceiveMessage", + "sqs:DeleteMessage", + "sqs:GetQueueAttributes" + ] + Resource = aws_sqs_queue.playbook_notify_queue.arn + }, + { + Sid = "PublishAlert" + Effect = "Allow" + Action = "sns:Publish" + Resource = aws_sns_topic.alerts.arn + }, + { + Sid = "WritePlaybookAudit" + Effect = "Allow" + Action = [ + "s3:PutObject" + ] + Resource = "${aws_s3_bucket.evidence.arn}/responses/notify-alert/*" + } + ] + }) +} + +resource "aws_iam_role_policy" "playbook_block_ip" { + name = "policy-lambda-${var.project_name}-playbook-block-ip" + role = aws_iam_role.playbook_block_ip.id + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Sid = "ReadDedicatedQueue" + Effect = "Allow" + Action = [ + "sqs:ReceiveMessage", + "sqs:DeleteMessage", + "sqs:GetQueueAttributes" + ] + Resource = aws_sqs_queue.playbook_block_ip_queue.arn + }, + { + Sid = "ManageNaclDenyRule" + Effect = "Allow" + Action = [ + "ec2:DescribeNetworkAcls", + "ec2:CreateNetworkAclEntry" + ] + Resource = "*" + }, + { + Sid = "WriteBlockAudit" + Effect = "Allow" + Action = [ + "s3:GetObject", + "s3:PutObject" + ] + Resource = "${aws_s3_bucket.evidence.arn}/responses/block-ip/*" + }, + { + Sid = "PublishAlert" + Effect = "Allow" + Action = "sns:Publish" + Resource = aws_sns_topic.alerts.arn + } + ] + }) +} + +resource "aws_lambda_function" "playbook_notify" { + function_name = "lambda-${var.project_name}-playbook-notify-alert" + role = aws_iam_role.playbook_notify.arn + handler = "handler.lambda_handler" + runtime = "python3.12" + architectures = ["x86_64"] + memory_size = 128 + timeout = 20 + + filename = data.archive_file.notify_alert_zip.output_path + source_code_hash = data.archive_file.notify_alert_zip.output_base64sha256 + + environment { + variables = { + SNS_ALERTS_ARN = aws_sns_topic.alerts.arn + EVIDENCE_BUCKET = aws_s3_bucket.evidence.bucket + RESPONSE_PREFIX = "responses/notify-alert" + } + } + + depends_on = [ + aws_iam_role_policy_attachment.playbook_notify_basic, + aws_iam_role_policy.playbook_notify, + aws_cloudwatch_log_group.playbook_notify + ] + + tags = { + Name = "lambda-${var.project_name}-playbook-notify-alert" + Role = "playbook-notify-alert" + } +} + +resource "aws_lambda_function" "playbook_block_ip" { + function_name = "lambda-${var.project_name}-playbook-block-ip" + role = aws_iam_role.playbook_block_ip.arn + handler = "handler.lambda_handler" + runtime = "python3.12" + architectures = ["x86_64"] + memory_size = 128 + timeout = 30 + + filename = data.archive_file.block_ip_zip.output_path + source_code_hash = data.archive_file.block_ip_zip.output_base64sha256 + + environment { + variables = { + SNS_ALERTS_ARN = aws_sns_topic.alerts.arn + EVIDENCE_BUCKET = aws_s3_bucket.evidence.bucket + TARGET_NACL_ID = aws_vpc.this.default_network_acl_id + RESPONSE_PREFIX = "responses/block-ip" + RULE_MIN = "1" + RULE_MAX = "99" + } + } + + depends_on = [ + aws_iam_role_policy_attachment.playbook_block_ip_basic, + aws_iam_role_policy.playbook_block_ip, + aws_cloudwatch_log_group.playbook_block_ip + ] + + tags = { + Name = "lambda-${var.project_name}-playbook-block-ip" + Role = "playbook-block-ip" + } +} + +resource "aws_lambda_event_source_mapping" "playbook_notify_from_queue" { + event_source_arn = aws_sqs_queue.playbook_notify_queue.arn + function_name = aws_lambda_function.playbook_notify.arn + batch_size = 5 + enabled = true +} + +resource "aws_lambda_event_source_mapping" "playbook_block_ip_from_queue" { + event_source_arn = aws_sqs_queue.playbook_block_ip_queue.arn + function_name = aws_lambda_function.playbook_block_ip.arn + batch_size = 1 + enabled = true +} + +# ----------------------------------------------------------------------------- +# Metric filters y alarmas simples de respaldo. +# ----------------------------------------------------------------------------- + +resource "aws_cloudwatch_log_metric_filter" "console_login_failure" { + name = "mf-console-login-failure" + log_group_name = aws_cloudwatch_log_group.cloudtrail.name + pattern = "{ ($.eventName = \"ConsoleLogin\") && ($.responseElements.ConsoleLogin = \"Failure\") }" + + metric_transformation { + name = "ConsoleLoginFailure" + namespace = "TesisIR" + value = "1" + default_value = "0" + } +} + +resource "aws_cloudwatch_log_metric_filter" "iam_critical_action" { + name = "mf-iam-critical-action" + log_group_name = aws_cloudwatch_log_group.cloudtrail.name + pattern = "{ ($.eventSource = \"iam.amazonaws.com\") && (($.eventName = \"CreateUser\") || ($.eventName = \"AttachUserPolicy\") || ($.eventName = \"AttachRolePolicy\") || ($.eventName = \"PutUserPolicy\") || ($.eventName = \"PutRolePolicy\") || ($.eventName = \"CreateAccessKey\") || ($.eventName = \"AddUserToGroup\")) }" + + metric_transformation { + name = "IAMCriticalAction" + namespace = "TesisIR" + value = "1" + default_value = "0" + } +} + +resource "aws_cloudwatch_log_metric_filter" "iam_policy_change" { + name = "mf-iam-policy-change" + log_group_name = aws_cloudwatch_log_group.cloudtrail.name + pattern = "{ ($.eventSource = \"iam.amazonaws.com\") && (($.eventName = \"CreatePolicyVersion\") || ($.eventName = \"DeletePolicyVersion\") || ($.eventName = \"PutUserPolicy\") || ($.eventName = \"PutRolePolicy\") || ($.eventName = \"UpdateAssumeRolePolicy\")) }" + + metric_transformation { + name = "IAMPolicyChange" + namespace = "TesisIR" + value = "1" + default_value = "0" + } +} + +resource "aws_cloudwatch_log_metric_filter" "vpc_rejected_traffic" { + count = var.enable_vpc_flow_logs ? 1 : 0 + + name = "mf-vpc-rejected-traffic" + log_group_name = aws_cloudwatch_log_group.flowlogs.name + pattern = "[version, account_id, interface_id, srcaddr, dstaddr, srcport, dstport, protocol, packets, bytes, start, end, action = \"REJECT\", log_status]" + + metric_transformation { + name = "VPCRejectedTraffic" + namespace = "TesisIR" + value = "1" + default_value = "0" + } +} + +resource "aws_cloudwatch_metric_alarm" "console_login_failure" { + alarm_name = "alarm-console-login-failure" + comparison_operator = "GreaterThanOrEqualToThreshold" + evaluation_periods = 1 + metric_name = "ConsoleLoginFailure" + namespace = "TesisIR" + period = 300 + statistic = "Sum" + threshold = var.threshold_console_login_failures_same_user_5m + alarm_description = "Alarma por multiples fallos de inicio de sesion" + treat_missing_data = "notBreaching" + alarm_actions = [aws_sns_topic.alerts.arn] + + depends_on = [aws_cloudwatch_log_metric_filter.console_login_failure] +} + +resource "aws_cloudwatch_metric_alarm" "iam_critical_action" { + alarm_name = "alarm-iam-critical-action" + comparison_operator = "GreaterThanOrEqualToThreshold" + evaluation_periods = 1 + metric_name = "IAMCriticalAction" + namespace = "TesisIR" + period = 300 + statistic = "Sum" + threshold = 1 + alarm_description = "Alarma por accion critica IAM" + treat_missing_data = "notBreaching" + alarm_actions = [aws_sns_topic.alerts.arn] + + depends_on = [aws_cloudwatch_log_metric_filter.iam_critical_action] +} + +resource "aws_cloudwatch_metric_alarm" "iam_policy_change" { + alarm_name = "alarm-iam-policy-change" + comparison_operator = "GreaterThanOrEqualToThreshold" + evaluation_periods = 1 + metric_name = "IAMPolicyChange" + namespace = "TesisIR" + period = 300 + statistic = "Sum" + threshold = 1 + alarm_description = "Alarma por cambio de politica IAM" + treat_missing_data = "notBreaching" + alarm_actions = [aws_sns_topic.alerts.arn] + + depends_on = [aws_cloudwatch_log_metric_filter.iam_policy_change] +} + +resource "aws_cloudwatch_metric_alarm" "vpc_rejected_traffic" { + count = var.enable_vpc_flow_logs ? 1 : 0 + + alarm_name = "alarm-vpc-rejected-traffic" + comparison_operator = "GreaterThanOrEqualToThreshold" + evaluation_periods = 1 + metric_name = "VPCRejectedTraffic" + namespace = "TesisIR" + period = 300 + statistic = "Sum" + threshold = var.threshold_port_scan_distinct_ports_5m + alarm_description = "Alarma por trafico rechazado repetido hacia la EC2" + treat_missing_data = "notBreaching" + alarm_actions = [aws_sns_topic.alerts.arn] + + depends_on = [aws_cloudwatch_log_metric_filter.vpc_rejected_traffic] +} + +# ----------------------------------------------------------------------------- +# Athena workgroup para consultas históricas sobre S3. +# No crea tablas Glue/CloudTrail automáticamente para evitar complejidad/costos. +# ----------------------------------------------------------------------------- + +resource "aws_athena_workgroup" "ir" { + name = "${var.project_name}-athena-workgroup" + + configuration { + enforce_workgroup_configuration = true + + result_configuration { + output_location = "s3://${aws_s3_bucket.logs.bucket}/athena-results/" + } + } + + tags = { + Name = "${var.project_name}-athena-workgroup" + } +} diff --git a/terraform-tesis-ir-secure-portal/outputs.tf b/terraform-tesis-ir-secure-portal/outputs.tf new file mode 100644 index 0000000..4555ac3 --- /dev/null +++ b/terraform-tesis-ir-secure-portal/outputs.tf @@ -0,0 +1,103 @@ +output "region" { + value = var.aws_region +} + +output "vpc_id" { + value = aws_vpc.this.id +} + +output "public_subnet_a_id" { + value = aws_subnet.public_a.id +} + +output "public_subnet_b_id" { + value = aws_subnet.public_b.id +} + +output "portal_instance_id" { + value = aws_instance.portal.id +} + +output "portal_public_ip" { + value = aws_instance.portal.public_ip +} + +output "portal_url" { + value = "http://${aws_instance.portal.public_ip}" +} + +output "logs_bucket" { + value = aws_s3_bucket.logs.bucket +} + +output "evidence_bucket" { + value = aws_s3_bucket.evidence.bucket +} + +output "sensitive_bucket" { + value = aws_s3_bucket.sensitive.bucket +} + +output "cloudtrail_log_group" { + value = aws_cloudwatch_log_group.cloudtrail.name +} + +output "ec2_app_log_group" { + value = aws_cloudwatch_log_group.ec2_app.name +} + +output "vpc_flow_log_group" { + value = aws_cloudwatch_log_group.flowlogs.name +} + +output "lambda_detector_name" { + value = aws_lambda_function.detector.function_name +} + +output "sns_topic_arn" { + value = aws_sns_topic.alerts.arn +} + +output "dynamodb_incidents_table" { + value = aws_dynamodb_table.incidents.name +} + +output "dynamodb_state_table" { + value = aws_dynamodb_table.state.name +} + +output "athena_workgroup" { + value = aws_athena_workgroup.ir.name +} + +output "warning_optional_cost_resources" { + value = "AWS Config=${var.enable_aws_config}, S3 Data Events=${var.enable_s3_data_events}, CloudTrail multi-region=${var.cloudtrail_multi_region}. Mantenerlos apagados reduce riesgo de costos." +} + +output "incident_queue_url" { + value = aws_sqs_queue.incident_queue.url +} + +output "incident_queue_arn" { + value = aws_sqs_queue.incident_queue.arn +} + +output "playbook_notify_lambda_name" { + value = aws_lambda_function.playbook_notify.function_name +} + +output "playbook_block_ip_lambda_name" { + value = aws_lambda_function.playbook_block_ip.function_name +} + +output "playbook_notify_queue_url" { + value = aws_sqs_queue.playbook_notify_queue.url +} + +output "playbook_block_ip_queue_url" { + value = aws_sqs_queue.playbook_block_ip_queue.url +} + +output "mitigation_network_acl_id" { + value = aws_vpc.this.default_network_acl_id +} diff --git a/terraform-tesis-ir-secure-portal/playbooks/block_ip/handler.py b/terraform-tesis-ir-secure-portal/playbooks/block_ip/handler.py new file mode 100644 index 0000000..071be22 --- /dev/null +++ b/terraform-tesis-ir-secure-portal/playbooks/block_ip/handler.py @@ -0,0 +1,236 @@ +""" +Playbook: block-ip +Mitigacion de contención real para incidentes de red. +Bloquea la IP origen creando una regla DENY inbound en la Network ACL +objetivo y registra evidencia de respuesta en S3. + +Incidentes soportados: + - BRUTE_FORCE (severity HIGH) → Incidente 1 + - PORT_SCAN (severity MEDIUM) → Incidente 2 + +Punto de cumplimiento (enforcement point): + ec2.create_network_acl_entry(RuleAction="deny", Egress=False, CidrBlock=IP/32) + Esa es la linea exacta donde el trafico de la IP atacante queda bloqueado + a nivel de red en la VPC. + + Las NACLs evaluan reglas de menor a mayor numero; el DENY se inserta con + numero < 100, por debajo del ALLOW por defecto (nro 100), por eso el bloqueo + es efectivo y no cosmetico. +""" +import ipaddress +import json +import os +import uuid +from datetime import datetime +from zoneinfo import ZoneInfo + +import boto3 + +s3 = boto3.client("s3") +sns = boto3.client("sns") +ec2 = boto3.client("ec2") + +EVIDENCE_BUCKET = os.environ["EVIDENCE_BUCKET"] +SNS_ARN = os.environ["SNS_ALERTS_ARN"] +TARGET_NACL_ID = os.environ["TARGET_NACL_ID"] +RESPONSE_PREFIX = os.environ.get("RESPONSE_PREFIX", "responses/block-ip") +RULE_MIN = int(os.environ.get("RULE_MIN", "1")) +RULE_MAX = int(os.environ.get("RULE_MAX", "99")) +EC_TZ = ZoneInfo("America/Guayaquil") + +# Incidentes que activan el bloqueo de IP en NACL. +BLOCK_INCIDENT_TYPES = {"BRUTE_FORCE", "PORT_SCAN"} + + +def now_ecuador() -> str: + return datetime.now(EC_TZ).isoformat() + + +def valid_public_ip(ip_value: str) -> bool: + """Verifica que la IP sea publica y valida antes de aplicar el bloqueo.""" + try: + ip = ipaddress.ip_address(ip_value) + except ValueError: + return False + return not ( + ip.is_private or ip.is_loopback or ip.is_multicast + or ip.is_unspecified or ip.is_reserved + ) + + +def next_rule_number(nacl_id: str) -> int: + """Calcula el siguiente numero de regla libre en el rango DENY (1-99).""" + response = ec2.describe_network_acls(NetworkAclIds=[nacl_id]) + used = set() + for entry in response.get("NetworkAcls", [{}])[0].get("Entries", []): + if not entry.get("Egress", False): + used.add(entry.get("RuleNumber")) + for number in range(RULE_MIN, RULE_MAX + 1): + if number not in used: + return number + raise RuntimeError("No quedan numeros de regla libres para reglas DENY de mitigacion.") + + +def block_ip(ip_value: str) -> dict: + """ + ENFORCEMENT POINT: crea la regla DENY en la NACL. + Es idempotente: si el DENY ya existe devuelve already_present=True. + """ + cidr = f"{ip_value}/32" + response = ec2.describe_network_acls(NetworkAclIds=[TARGET_NACL_ID]) + entries = response.get("NetworkAcls", [{}])[0].get("Entries", []) + + for entry in entries: + if (not entry.get("Egress", False) + and entry.get("CidrBlock") == cidr + and entry.get("RuleAction") == "deny"): + return { + "enforced": True, + "already_present": True, + "network_acl_id": TARGET_NACL_ID, + "rule_number": entry.get("RuleNumber"), + "cidr": cidr, + } + + rule_number = next_rule_number(TARGET_NACL_ID) + # ← línea exacta del bloqueo real a nivel de red + ec2.create_network_acl_entry( + NetworkAclId=TARGET_NACL_ID, + RuleNumber=rule_number, + Protocol="-1", # todos los protocolos + RuleAction="deny", + Egress=False, # tráfico de entrada (desde el atacante) + CidrBlock=cidr, + ) + print(f"[block-ip] NACL {TARGET_NACL_ID}: regla DENY #{rule_number} creada para {cidr}") + return { + "enforced": True, + "already_present": False, + "network_acl_id": TARGET_NACL_ID, + "rule_number": rule_number, + "cidr": cidr, + } + + +def load_blocklist() -> list: + try: + obj = s3.get_object(Bucket=EVIDENCE_BUCKET, Key=f"{RESPONSE_PREFIX}/blocked-ips.json") + return json.loads(obj["Body"].read()) + except Exception: + return [] + + +def save_blocklist(blocklist: list) -> None: + s3.put_object( + Bucket=EVIDENCE_BUCKET, + Key=f"{RESPONSE_PREFIX}/blocked-ips.json", + Body=json.dumps(blocklist, indent=2, ensure_ascii=False).encode("utf-8"), + ContentType="application/json", + ) + + +def lambda_handler(event, context): + results = [] + + for record in event.get("Records", []): + try: + body = json.loads(record.get("body", "{}")) + except json.JSONDecodeError as exc: + results.append({"status": "skipped", "reason": f"invalid_json: {exc}"}) + continue + + incident_type = body.get("incident_type", "UNKNOWN") + + # Solo procesar incidentes de red que requieren bloqueo de IP + if incident_type not in BLOCK_INCIDENT_TYPES: + print(f"[block-ip] Tipo {incident_type} no requiere bloqueo de IP. Omitiendo.") + results.append({"status": "skipped", "reason": f"not_in_block_list:{incident_type}"}) + continue + + ip_value = body.get("sourceIPAddress", "") + timestamp = now_ecuador() + + # ── Aplicar bloqueo real en NACL ────────────────────────────────── + if not valid_public_ip(ip_value): + enforcement = { + "enforced": False, + "reason": "invalid_or_non_public_ip", + "ip": ip_value, + } + status = "SKIPPED" + print(f"[block-ip] IP invalida o privada: {ip_value}. Omitiendo bloqueo.") + else: + try: + enforcement = block_ip(ip_value) + status = "BLOCKED" if enforcement.get("enforced") else "BLOCK_FAILED" + except Exception as exc: + enforcement = {"enforced": False, "error": str(exc), "ip": ip_value} + status = "BLOCK_FAILED" + print(f"[block-ip] ERROR aplicando bloqueo para {ip_value}: {exc}") + + # ── Construir registro de evidencia ──────────────────────────────── + entry = { + "playbook": "block-ip", + "incident_type": incident_type, + "severity": body.get("severity", "MEDIUM"), + "sourceIPAddress": ip_value, + "affectedResource": body.get("affectedResource", "unknown"), + "affected_service": body.get("affected_service", + body.get("affectedService", "unknown")), + "asset_name": body.get("asset_name", body.get("assetName", "unknown")), + "severity_basis": body.get("severity_basis", + f"Umbral de {incident_type} alcanzado."), + "status": status, + "enforcement": enforcement, + "timestamp": timestamp, + "timezone": "America/Guayaquil", + "incident_id": body.get("incident_id", ""), + } + + # Campos extra según el tipo de incidente + if incident_type == "PORT_SCAN": + entry["scanned_ports_count"] = body.get("scanned_ports_count", + body.get("event_count", 0)) + entry["rejected_connections"] = body.get("rejected_connections", 0) + elif incident_type == "BRUTE_FORCE": + entry["failed_attempts"] = body.get("failed_attempts", + body.get("event_count", 0)) + + # ── Actualizar lista de IPs bloqueadas (blocklist acumulativo) ───── + blocklist = load_blocklist() + if not any(item.get("sourceIPAddress") == ip_value for item in blocklist): + blocklist.append(entry) + save_blocklist(blocklist) + + # ── Guardar evidencia individual por incidente ───────────────────── + key = f"{RESPONSE_PREFIX}/{body.get('incident_id') or uuid.uuid4().hex}.json" + s3.put_object( + Bucket=EVIDENCE_BUCKET, + Key=key, + Body=json.dumps(entry, indent=2, ensure_ascii=False).encode("utf-8"), + ContentType="application/json", + ) + + # ── Notificar al equipo via SNS ──────────────────────────────────── + subject = f"[{entry['severity']}] Playbook block-ip: {status} {ip_value} ({incident_type})" + sns.publish( + TopicArn=SNS_ARN, + Subject=subject[:100], + Message=json.dumps(entry, indent=2, ensure_ascii=False), + ) + + print(f"[block-ip] {incident_type} → {status} para {ip_value}. " + f"NACL rule={enforcement.get('rule_number')}. evidence={key}") + results.append({ + "status": "success", + "action": status, + "evidence_key": key, + "details": enforcement, + }) + + return { + "status": "success", + "processed": len(results), + "results": results, + "timestamp": now_ecuador(), + } diff --git a/terraform-tesis-ir-secure-portal/playbooks/notify_alert/handler.py b/terraform-tesis-ir-secure-portal/playbooks/notify_alert/handler.py new file mode 100644 index 0000000..cbd33e1 --- /dev/null +++ b/terraform-tesis-ir-secure-portal/playbooks/notify_alert/handler.py @@ -0,0 +1,116 @@ +""" +Playbook: notify-alert +Recibe incidentes desde una cola SQS dedicada y publica una notificacion +estructurada en SNS. Tambien deja evidencia operativa en S3. + +Incidentes soportados: + - BRUTE_FORCE (severity HIGH) → Componente C, Incidente 1 + - PORT_SCAN (severity MEDIUM) → Componente C, Incidente 2 + - PRIVILEGE_ESCALATION (severity CRITICAL) + - CREDENTIAL_LEAK (severity CRITICAL) + - EXFILTRATION (severity HIGH) +""" +import json +import os +import uuid +from datetime import datetime +from zoneinfo import ZoneInfo + +import boto3 + +sns = boto3.client("sns") +s3 = boto3.client("s3") + +SNS_ARN = os.environ["SNS_ALERTS_ARN"] +EVIDENCE_BUCKET = os.environ["EVIDENCE_BUCKET"] +RESPONSE_PREFIX = os.environ.get("RESPONSE_PREFIX", "responses/notify-alert") +EC_TZ = ZoneInfo("America/Guayaquil") + +# Tipos de incidente que este playbook debe procesar. +# Cualquier otro tipo se omite (skip) para evitar procesamiento no intencionado. +SUPPORTED_INCIDENT_TYPES = { + "BRUTE_FORCE", + "PORT_SCAN", + "PRIVILEGE_ESCALATION", + "CREDENTIAL_LEAK", + "EXFILTRATION", +} + + +def now_ecuador() -> str: + return datetime.now(EC_TZ).isoformat() + + +def lambda_handler(event, context): + results = [] + + for record in event.get("Records", []): + try: + body = json.loads(record.get("body", "{}")) + except json.JSONDecodeError as exc: + results.append({"status": "skipped", "reason": f"invalid_json: {exc}"}) + continue + + incident_type = body.get("incident_type", "UNKNOWN") + if incident_type not in SUPPORTED_INCIDENT_TYPES: + results.append({"status": "skipped", "reason": f"unsupported_type:{incident_type}"}) + continue + + # ── Construir alerta estructurada ────────────────────────────────── + alert = { + "alert_type": "SECURITY_INCIDENT", + "incident_type": incident_type, + "severity": body.get("severity", "MEDIUM"), + "sourceIPAddress": body.get("sourceIPAddress", "unknown"), + "affectedResource": body.get("affectedResource", "unknown"), + "affected_service": body.get("affected_service", + body.get("affectedService", "unknown")), + "asset_name": body.get("asset_name", + body.get("assetName", "unknown")), + "severity_basis": body.get("severity_basis", + f"Umbral de {incident_type} alcanzado."), + "detectedAt": body.get("timestamp", now_ecuador()), + "respondedAt": now_ecuador(), + "timezone": "America/Guayaquil", + "playbook": "notify-alert", + "status": "NOTIFIED", + "s3_log_key": body.get("s3_log_key", ""), + "incident_id": body.get("incident_id", ""), + } + + # Campos extra según el tipo de incidente + if incident_type == "PORT_SCAN": + alert["scanned_ports_count"] = body.get("scanned_ports_count", + body.get("event_count", 0)) + alert["rejected_connections"] = body.get("rejected_connections", 0) + elif incident_type == "BRUTE_FORCE": + alert["failed_attempts"] = body.get("failed_attempts", + body.get("event_count", 0)) + alert["detection_window"] = body.get("detection_window", "5 minutes") + + # ── Guardar evidencia en S3 ──────────────────────────────────────── + key = f"{RESPONSE_PREFIX}/{body.get('incident_id') or uuid.uuid4().hex}.json" + s3.put_object( + Bucket=EVIDENCE_BUCKET, + Key=key, + Body=json.dumps(alert, indent=2, ensure_ascii=False).encode("utf-8"), + ContentType="application/json", + ) + + # ── Publicar en SNS ──────────────────────────────────────────────── + subject = f"[{alert['severity']}] Playbook notify-alert: {incident_type}" + sns.publish( + TopicArn=SNS_ARN, + Subject=subject[:100], + Message=json.dumps(alert, indent=2, ensure_ascii=False), + ) + + print(f"[notify-alert] {incident_type} notificado. evidence_key={key}") + results.append({"status": "success", "action": "sns_published", "evidence_key": key}) + + return { + "status": "success", + "processed": len(results), + "results": results, + "timestamp": now_ecuador(), + } diff --git a/terraform-tesis-ir-secure-portal/scripts/user_data.sh.tpl b/terraform-tesis-ir-secure-portal/scripts/user_data.sh.tpl new file mode 100644 index 0000000..8a81aea --- /dev/null +++ b/terraform-tesis-ir-secure-portal/scripts/user_data.sh.tpl @@ -0,0 +1,502 @@ +#!/bin/bash +set -euo pipefail + +# Portal corporativo de laboratorio. +# La aplicacion NO usa credenciales AWS ni llama servicios AWS. +# Solo escribe eventos JSON locales en /var/log/tesis-portal/app.log. +# CloudWatch Agent transporta esos logs a CloudWatch Logs. + +dnf update -y +dnf install -y nginx python3 amazon-cloudwatch-agent + +useradd --system --home-dir /opt/tesis-portal --shell /sbin/nologin tesisportal || true + +mkdir -p /opt/tesis-portal /var/log/tesis-portal +touch /var/log/tesis-portal/app.log +chown -R tesisportal:tesisportal /opt/tesis-portal /var/log/tesis-portal +chmod 750 /opt/tesis-portal /var/log/tesis-portal +chmod 640 /var/log/tesis-portal/app.log + +cat > /opt/tesis-portal/app.py << 'PYAPP' +from http.server import BaseHTTPRequestHandler, HTTPServer +from urllib.parse import parse_qs, urlparse +from http import cookies +from datetime import datetime, timezone, timedelta +import base64 +import hashlib +import hmac +import html +import json +import os +import secrets +import time + +LOG_FILE = "/var/log/tesis-portal/app.log" +SESSION_SECRET_FILE = "/opt/tesis-portal/session_secret" +LOCK_THRESHOLD = 5 +LOCK_SECONDS = 300 +EC_TZ = timezone(timedelta(hours=-5), name="America/Guayaquil") +AFFECTED_SERVICE = "Portal de autenticacion corporativo" +ASSET_NAME = "${project_name}-portal-ec2" +ASSET_TYPE = "EC2 web application" +COMPANY_NAME = "Asteria Operaciones" + +# Usuarios internos de la aplicacion. No son usuarios IAM reales de AWS. +USERS = { + "admin.demo": { + "display": "Administrador", + "hash": "VpqSvQMFATBEs7T3ZU/BSA==:xioUwz95jf3bZ1gsUHqTc3H6cTcU6upr0fZiFuoU9ZY=", + }, + "soc.demo": { + "display": "Analista SOC", + "hash": "9lkouWYrd54ObTxyAsNSUw==:UPSlJBYvlF2uIdpzV9LVmqMUuMNsLwXFDX+f5dedX04=", + }, + "usuario.demo": { + "display": "Usuario operativo", + "hash": "n33eTr4zUj6AkGU1EfAx8A==:C3Bu/CHMnuT3SPOvBTvp0H0qpmCFJvpOjtnv7YKD9yQ=", + }, +} + +FAILED_STATE = {} + + +def now_ecuador(): + return datetime.now(EC_TZ).isoformat() + + +def now_utc(): + return datetime.now(timezone.utc).isoformat() + + +def epoch_now(): + return int(time.time()) + + +def get_session_secret(): + if os.path.exists(SESSION_SECRET_FILE): + with open(SESSION_SECRET_FILE, "rb") as f: + return f.read().strip() + secret = base64.urlsafe_b64encode(secrets.token_bytes(48)) + with open(SESSION_SECRET_FILE, "wb") as f: + f.write(secret) + os.chmod(SESSION_SECRET_FILE, 0o600) + return secret + + +SESSION_SECRET = get_session_secret() + + +def base_event(event): + clean = dict(event) + clean.pop("password", None) + clean.setdefault("timestamp", now_ecuador()) + clean.setdefault("timestamp_utc", now_utc()) + clean.setdefault("timezone", "America/Guayaquil") + clean.setdefault("affected_service", AFFECTED_SERVICE) + clean.setdefault("asset_name", ASSET_NAME) + clean.setdefault("asset_type", ASSET_TYPE) + clean.setdefault("service_owner", COMPANY_NAME) + return clean + + +def write_event(event): + with open(LOG_FILE, "a", encoding="utf-8") as f: + f.write(json.dumps(base_event(event), ensure_ascii=False, separators=(",", ":")) + "\n") + + +def verify_password(username, password): + user = USERS.get(username) + if not user: + return False + salt_b64, hash_b64 = user["hash"].split(":", 1) + salt = base64.b64decode(salt_b64) + expected = base64.b64decode(hash_b64) + candidate = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, 120000) + return hmac.compare_digest(candidate, expected) + + +def sign_value(value): + sig = hmac.new(SESSION_SECRET, value.encode("utf-8"), hashlib.sha256).hexdigest() + return value + "." + sig + + +def verify_signed_value(value): + if not value or "." not in value: + return None + payload, sig = value.rsplit(".", 1) + expected = hmac.new(SESSION_SECRET, payload.encode("utf-8"), hashlib.sha256).hexdigest() + if hmac.compare_digest(sig, expected): + return payload + return None + + +def html_escape(value): + return html.escape(str(value if value is not None else "")) + + +def page(title, content, authenticated=False, username=None): + session_area = "" + if authenticated: + session_area = f"{html_escape(username)}Salir" + return f""" + + + + + {html_escape(title)} + + + +
{COMPANY_NAME}
{session_area}
+ {content} + +""" + + +class Handler(BaseHTTPRequestHandler): + server_version = "AsteriaPortal/1.0" + + def client_ip(self): + forwarded = self.headers.get("X-Forwarded-For") + if forwarded: + return forwarded.split(",")[0].strip() + return self.client_address[0] + + def get_session_user(self): + raw_cookie = self.headers.get("Cookie") + if not raw_cookie: + return None + jar = cookies.SimpleCookie(raw_cookie) + if "portal_session" not in jar: + return None + payload = verify_signed_value(jar["portal_session"].value) + if not payload: + return None + try: + username, issued = payload.split(":", 1) + if username in USERS and epoch_now() - int(issued) < 3600: + return username + except Exception: + return None + return None + + def respond(self, status, body, content_type="text/html; charset=utf-8", headers=None): + encoded = body.encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(encoded))) + self.send_header("X-Frame-Options", "DENY") + self.send_header("X-Content-Type-Options", "nosniff") + self.send_header("Referrer-Policy", "no-referrer") + self.send_header("Cache-Control", "no-store") + if headers: + for key, value in headers.items(): + self.send_header(key, value) + self.end_headers() + self.wfile.write(encoded) + + def redirect(self, location, headers=None): + self.send_response(302) + self.send_header("Location", location) + self.send_header("Cache-Control", "no-store") + if headers: + for key, value in headers.items(): + self.send_header(key, value) + self.end_headers() + + def render_login(self, message=None, error=False): + alert = "" + if message: + kind = "error" if error else "info" + alert = f"
{html_escape(message)}
" + content = f""" +
+ +
+ """ + self.respond(200, page("Inicio de sesion", content)) + + def render_dashboard(self, username): + role = USERS.get(username, {}).get("display", "Usuario") + content = f""" +
+
+
+

Panel principal

+

Bienvenido, {html_escape(username)}. Perfil asignado: {html_escape(role)}.

+
+

Solicitudes

12

En revision

+

Operaciones

98%

Disponibilidad

+

Cuenta

Activa

Sesion protegida

+
+
+ """ + self.respond(200, page("Panel principal", content, authenticated=True, username=username)) + + def render_access_denied(self, remaining): + content = f""" +
+ +
+ """ + self.respond(403, page("Acceso restringido", content)) + + def do_GET(self): + parsed = urlparse(self.path) + username = self.get_session_user() + if parsed.path == "/health": + self.respond(200, json.dumps({"status": "ok", "time": now_ecuador(), "timezone": "America/Guayaquil"}), "application/json") + return + if parsed.path in ["/", "/login"]: + self.redirect("/dashboard") if username else self.render_login() + return + if parsed.path == "/dashboard": + if not username: + self.redirect("/login") + return + self.render_dashboard(username) + return + if parsed.path == "/logout": + headers = {"Set-Cookie": "portal_session=deleted; Path=/; Max-Age=0; HttpOnly; SameSite=Lax"} + self.redirect("/login", headers=headers) + return + self.respond(404, page("No encontrado", "
")) + + def do_POST(self): + parsed = urlparse(self.path) + if parsed.path != "/login": + self.respond(404, "Not found", "text/plain") + return + length = int(self.headers.get("Content-Length", "0")) + body = self.rfile.read(length).decode("utf-8") + form = parse_qs(body) + username = form.get("username", [""])[0].strip().lower() + password = form.get("password", [""])[0] + source_ip = self.client_ip() + user_agent = self.headers.get("User-Agent", "unknown")[:300] + key = source_ip + "|" + username + state = FAILED_STATE.get(key, {"count": 0, "first": epoch_now(), "locked_until": 0}) + + if state.get("locked_until", 0) > epoch_now(): + remaining = state["locked_until"] - epoch_now() + write_event({ + "event_type": "access_blocked", + "auth_method": "password", + "username": username or "unknown", + "source_ip": source_ip, + "sourceIPAddress": source_ip, + "affectedResource": "iam:user/" + (username or "unknown"), + "endpoint": "/login", + "result": "DENIED", + "failure_reason": "temporary_lockout", + "failed_attempts": state.get("count", 0), + "detection_window": "5 minutes", + "severity": "HIGH", + "severity_basis": "HIGH porque el usuario o la IP supero 5 intentos fallidos dentro de una ventana de 5 minutos.", + "user_agent": user_agent, + }) + self.render_access_denied(remaining) + return + + if verify_password(username, password): + FAILED_STATE.pop(key, None) + write_event({ + "event_type": "login_success", + "auth_method": "password", + "username": username, + "source_ip": source_ip, + "sourceIPAddress": source_ip, + "affectedResource": "iam:user/" + username, + "endpoint": "/login", + "result": "SUCCESS", + "severity": "INFO", + "severity_basis": "INFO porque la autenticacion fue exitosa y no representa incidente por si sola.", + "user_agent": user_agent, + }) + cookie_value = sign_value(username + ":" + str(epoch_now())) + headers = {"Set-Cookie": "portal_session=" + cookie_value + "; Path=/; Max-Age=3600; HttpOnly; SameSite=Lax"} + self.redirect("/dashboard", headers=headers) + return + + if epoch_now() - int(state.get("first", epoch_now())) > 300: + state = {"count": 0, "first": epoch_now(), "locked_until": 0} + state["count"] = int(state.get("count", 0)) + 1 + if state["count"] >= LOCK_THRESHOLD: + state["locked_until"] = epoch_now() + LOCK_SECONDS + FAILED_STATE[key] = state + + severity = "HIGH" if state["count"] >= LOCK_THRESHOLD else "LOW" + severity_basis = ( + "HIGH porque se alcanzaron 5 o mas intentos fallidos de autenticacion en 5 minutos." + if severity == "HIGH" else + "LOW porque es un intento fallido aislado que aun no supera el umbral de incidente." + ) + write_event({ + "event_type": "login_failed", + "auth_method": "password", + "username": username or "unknown", + "source_ip": source_ip, + "sourceIPAddress": source_ip, + "affectedResource": "iam:user/" + (username or "unknown"), + "endpoint": "/login", + "result": "FAILURE", + "failure_reason": "invalid_credentials", + "failed_attempts": state["count"], + "detection_window": "5 minutes", + "severity": severity, + "severity_basis": severity_basis, + "user_agent": user_agent, + }) + + if state.get("locked_until", 0) > epoch_now(): + self.render_access_denied(LOCK_SECONDS) + else: + self.render_login("Credenciales incorrectas.", error=True) + + def log_message(self, format, *args): + return + + +if __name__ == "__main__": + write_event({ + "event_type": "portal_started", + "severity": "INFO", + "severity_basis": "INFO porque corresponde al inicio controlado del servicio web.", + "message": "Portal iniciado correctamente", + "source_ip": "127.0.0.1", + "sourceIPAddress": "127.0.0.1", + "endpoint": "systemd", + "result": "SUCCESS", + }) + HTTPServer(("127.0.0.1", 8080), Handler).serve_forever() +PYAPP + +cat > /etc/systemd/system/tesis-portal.service << 'SYSTEMD' +[Unit] +Description=Portal corporativo de autenticacion +After=network.target + +[Service] +Type=simple +WorkingDirectory=/opt/tesis-portal +ExecStart=/usr/bin/python3 /opt/tesis-portal/app.py +Restart=always +RestartSec=3 +User=tesisportal +Group=tesisportal +NoNewPrivileges=true +PrivateTmp=true +ProtectSystem=full +ProtectHome=true +ReadWritePaths=/var/log/tesis-portal /opt/tesis-portal + +[Install] +WantedBy=multi-user.target +SYSTEMD + +cat > /etc/nginx/conf.d/tesis-portal.conf << 'NGINX' +server { + listen 80 default_server; + server_name _; + + access_log /var/log/nginx/access.log; + error_log /var/log/nginx/error.log; + + add_header X-Frame-Options "DENY" always; + add_header X-Content-Type-Options "nosniff" always; + add_header Referrer-Policy "no-referrer" always; + + location / { + proxy_pass http://127.0.0.1:8080; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $remote_addr; + proxy_set_header X-Real-IP $remote_addr; + } +} +NGINX + +rm -f /etc/nginx/conf.d/default.conf || true + +cat > /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.json << 'CWAGENT' +{ + "logs": { + "logs_collected": { + "files": { + "collect_list": [ + { + "file_path": "/var/log/nginx/access.log", + "log_group_name": "${app_log_group}", + "log_stream_name": "{instance_id}/nginx-access", + "timezone": "UTC" + }, + { + "file_path": "/var/log/nginx/error.log", + "log_group_name": "${app_log_group}", + "log_stream_name": "{instance_id}/nginx-error", + "timezone": "UTC" + }, + { + "file_path": "/var/log/tesis-portal/app.log", + "log_group_name": "${app_log_group}", + "log_stream_name": "{instance_id}/app", + "timezone": "UTC" + } + ] + } + } + } +} +CWAGENT + +systemctl daemon-reload +systemctl enable tesis-portal +systemctl restart tesis-portal +systemctl enable nginx +systemctl restart nginx + +/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl \ + -a fetch-config \ + -m ec2 \ + -c file:/opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.json \ + -s diff --git a/terraform-tesis-ir-secure-portal/terraform.tfvars.example b/terraform-tesis-ir-secure-portal/terraform.tfvars.example new file mode 100644 index 0000000..f038e0f --- /dev/null +++ b/terraform-tesis-ir-secure-portal/terraform.tfvars.example @@ -0,0 +1,46 @@ +# Copia este archivo como terraform.tfvars y edita los valores. + +aws_region = "ca-central-1" +project_name = "tesis-ir" + +# Obligatorio: coloca TU IP publica con /32. +# Puedes verla buscando "what is my ip". +ssh_allowed_cidr = "181.000.000.000/32" + +# Recomendado: restringir HTTP tambien a tu IP /32. +# Si dejas [] Terraform usara automaticamente ssh_allowed_cidr. +# Solo para exposiciones publicas temporales usa ["0.0.0.0/0"]. +http_allowed_cidrs = [] + +# IPs consideradas normales/autorizadas por Lambda Detector B. +# Si queda vacio, se usa ssh_allowed_cidr. +authorized_ip_cidrs = [] + +# Opcional: correo para SNS y Budget. Debes confirmar la suscripcion SNS por email. +alert_email = "tu_correo@ejemplo.com" + +# Si ya tienes una key pair EC2 creada en esa region: +# key_name = "tesis-ir-key" +key_name = "" + +# Mantener bajo costo: +enable_vpc_flow_logs = true +enable_s3_data_events = false +enable_aws_config = false +cloudtrail_multi_region = false + +# Activa estos SOLO cuando vayas a probar esos incidentes: +# enable_s3_data_events = true # para EXFILTRATION con S3 GetObject +# enable_aws_config = true # para evidencia adicional de cambios IAM/configuracion + +ec2_instance_type = "t3.micro" +ec2_volume_size_gb = 8 +cloudwatch_retention_days = 14 +monthly_budget_limit_usd = 5 + +# Umbrales alineados con Variables_Incidentes.docx +threshold_app_login_failures_same_ip_5m = 5 +threshold_console_login_failures_same_user_5m = 5 +threshold_console_login_failures_same_ip_5m = 10 +threshold_port_scan_distinct_ports_5m = 10 +threshold_s3_getobject_exfiltration_count_1h = 50 diff --git a/terraform-tesis-ir-secure-portal/variables.tf b/terraform-tesis-ir-secure-portal/variables.tf new file mode 100644 index 0000000..80116a0 --- /dev/null +++ b/terraform-tesis-ir-secure-portal/variables.tf @@ -0,0 +1,214 @@ +variable "aws_region" { + description = "Region AWS. Use ca-central-1 si quieres mantener la region que venias usando, o us-east-1 si seguiras exactamente el documento base." + type = string + default = "ca-central-1" +} + +variable "project_name" { + description = "Prefijo de nombres para todos los recursos. Usa solo minusculas, numeros y guiones." + type = string + default = "tesis-ir" + + validation { + condition = can(regex("^[a-z0-9-]+$", var.project_name)) + error_message = "project_name solo puede tener minusculas, numeros y guiones." + } +} + +variable "ssh_allowed_cidr" { + description = "Tu IP publica en formato CIDR para SSH. Ejemplo: 181.39.10.20/32. No uses 0.0.0.0/0." + type = string + + validation { + condition = can(cidrhost(var.ssh_allowed_cidr, 0)) && var.ssh_allowed_cidr != "0.0.0.0/0" + error_message = "ssh_allowed_cidr debe ser un CIDR valido y no debe ser 0.0.0.0/0." + } +} + +variable "http_allowed_cidrs" { + description = "CIDRs permitidos para HTTP del portal. Si queda vacio, se usa ssh_allowed_cidr. Para demo publica podrias usar 0.0.0.0/0, pero no es lo recomendado." + type = list(string) + default = [] +} + +variable "authorized_ip_cidrs" { + description = "IPs autorizadas para la logica del detector. Si queda vacio, se usa ssh_allowed_cidr." + type = list(string) + default = [] +} + +variable "authorized_admin_users" { + description = "Usuarios autorizados usados en config/authorized_ips.json." + type = list(string) + default = ["tesis-admin", "estudiante-b"] +} + +variable "alert_email" { + description = "Correo para SNS y presupuesto. Si lo dejas vacio, no se crea suscripcion email ni budget." + type = string + default = "" +} + +variable "create_budget" { + description = "Crear un presupuesto mensual con alertas si alert_email no esta vacio." + type = bool + default = true +} + +variable "monthly_budget_limit_usd" { + description = "Monto del budget mensual." + type = number + default = 5 +} + +variable "vpc_cidr" { + description = "CIDR de la VPC." + type = string + default = "10.10.0.0/16" +} + +variable "public_subnet_a_cidr" { + description = "CIDR subred publica A." + type = string + default = "10.10.1.0/24" +} + +variable "public_subnet_b_cidr" { + description = "CIDR subred publica B." + type = string + default = "10.10.2.0/24" +} + +variable "private_subnet_a_cidr" { + description = "CIDR subred privada A reservada." + type = string + default = "10.10.11.0/24" +} + +variable "private_subnet_b_cidr" { + description = "CIDR subred privada B reservada." + type = string + default = "10.10.12.0/24" +} + +variable "portal_private_ip" { + description = "IP privada fija para la EC2 dentro de la subred publica A." + type = string + default = "10.10.1.10" +} + +variable "ec2_instance_type" { + description = "Tipo de instancia. En ca-central-1 muchas cuentas usan t3.micro como elegible Free Tier; valida con aws ec2 describe-instance-types." + type = string + default = "t3.micro" +} + +variable "ec2_volume_size_gb" { + description = "Tamaño EBS gp3 de la EC2." + type = number + default = 8 +} + +variable "key_name" { + description = "Nombre de una key pair existente para SSH. Si queda vacio, usa Session Manager en lugar de SSH tradicional." + type = string + default = "" +} + +variable "cloudwatch_retention_days" { + description = "Retencion de logs en CloudWatch para reducir costos." + type = number + default = 14 +} + +variable "normalized_log_retention_days" { + description = "Retencion del log group normalizado de incidentes." + type = number + default = 30 +} + +variable "force_destroy_buckets" { + description = "Permite destruir buckets con objetos al ejecutar terraform destroy. Para laboratorio es practico; para evidencia real usa false." + type = bool + default = true +} + +variable "enable_vpc_flow_logs" { + description = "Activa VPC Flow Logs sobre la ENI de la EC2." + type = bool + default = true +} + +variable "cloudtrail_multi_region" { + description = "Trail multi-region. Para bajo costo/logs reducidos se deja false." + type = bool + default = false +} + +variable "enable_s3_data_events" { + description = "Activa CloudTrail Data Events sobre el prefijo sensible del bucket demo. Puede generar cargos; activalo solo para la prueba del incidente 5." + type = bool + default = false +} + +variable "enable_aws_config" { + description = "Activa AWS Config y una regla administrada. Puede generar cargos; activalo solo cuando pruebes cambios de configuracion." + type = bool + default = false +} + +variable "config_resource_types" { + description = "Tipos de recursos monitoreados por AWS Config cuando enable_aws_config=true." + type = list(string) + default = [ + "AWS::IAM::User", + "AWS::IAM::Role", + "AWS::IAM::Policy", + "AWS::EC2::SecurityGroup", + "AWS::EC2::NetworkAcl", + "AWS::EC2::Instance", + "AWS::S3::Bucket" + ] +} + +variable "create_test_iam_user" { + description = "Crea un usuario IAM de laboratorio sin claves ni password de consola." + type = bool + default = true +} + +variable "threshold_console_login_failures_same_user_5m" { + description = "Umbral de fallos ConsoleLogin por usuario en 5 minutos." + type = number + default = 5 +} + +variable "threshold_console_login_failures_same_ip_5m" { + description = "Umbral de fallos ConsoleLogin por IP en 5 minutos." + type = number + default = 10 +} + +variable "threshold_app_login_failures_same_ip_5m" { + description = "Umbral de login_failed del portal por IP en 5 minutos." + type = number + default = 5 +} + +variable "threshold_port_scan_distinct_ports_5m" { + description = "Puertos distintos rechazados desde una misma IP en 5 minutos." + type = number + default = 10 +} + +variable "threshold_s3_getobject_unusual_count_5m" { + description = "Umbral de accesos S3 GetObject/ListBucket inusuales en 5 minutos." + type = number + default = 10 +} + +variable "threshold_s3_getobject_exfiltration_count_1h" { + description = "Umbral de GetObject desde la misma IP en 1 hora para EXFILTRATION, segun Variables_Incidentes.docx." + type = number + default = 50 +} From ec632afcab833c2d58619eb333b5f36d306dfe4f Mon Sep 17 00:00:00 2001 From: bryancito1090 Date: Mon, 15 Jun 2026 18:52:16 -0500 Subject: [PATCH 6/9] feat: implement automated IAM privilege escalation response playbook and simulation guide --- Privilege Escalation/README.md | 164 +++++++++++++++ Privilege Escalation/simulate_escalation.sh | 122 ++++++++++++ .../lambda/lambda_function.py | 15 +- .../lambda_playbook_revoke_credentials.zip | Bin 0 -> 2548 bytes terraform-tesis-ir-secure-portal/main.tf | 138 ++++++++++++- terraform-tesis-ir-secure-portal/outputs.tf | 8 + .../playbooks/revoke_credentials/handler.py | 187 ++++++++++++++++++ 7 files changed, 632 insertions(+), 2 deletions(-) create mode 100644 Privilege Escalation/README.md create mode 100755 Privilege Escalation/simulate_escalation.sh create mode 100644 terraform-tesis-ir-secure-portal/lambda_playbook_revoke_credentials.zip create mode 100644 terraform-tesis-ir-secure-portal/playbooks/revoke_credentials/handler.py diff --git a/Privilege Escalation/README.md b/Privilege Escalation/README.md new file mode 100644 index 0000000..ce6cd06 --- /dev/null +++ b/Privilege Escalation/README.md @@ -0,0 +1,164 @@ +# 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 +``` diff --git a/Privilege Escalation/simulate_escalation.sh b/Privilege Escalation/simulate_escalation.sh new file mode 100755 index 0000000..1c4ea93 --- /dev/null +++ b/Privilege Escalation/simulate_escalation.sh @@ -0,0 +1,122 @@ +#!/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}" diff --git a/terraform-tesis-ir-secure-portal/lambda/lambda_function.py b/terraform-tesis-ir-secure-portal/lambda/lambda_function.py index fc3d507..7aa619b 100644 --- a/terraform-tesis-ir-secure-portal/lambda/lambda_function.py +++ b/terraform-tesis-ir-secure-portal/lambda/lambda_function.py @@ -29,6 +29,7 @@ VPC_ID = os.environ.get("VPC_ID", "unknown-vpc") PORTAL_INSTANCE_ID = os.environ.get("PORTAL_INSTANCE_ID", "unknown-instance") PLAYBOOK_NOTIFY_QUEUE_URL = os.environ.get("PLAYBOOK_NOTIFY_QUEUE_URL", "") PLAYBOOK_BLOCK_IP_QUEUE_URL = os.environ.get("PLAYBOOK_BLOCK_IP_QUEUE_URL", "") +PLAYBOOK_REVOKE_CREDENTIALS_QUEUE_URL = os.environ.get("PLAYBOOK_REVOKE_CREDENTIALS_QUEUE_URL", "") ECUADOR_TZ = ZoneInfo("America/Guayaquil") incidents_table = dynamodb.Table(INCIDENTS_TABLE) @@ -195,7 +196,10 @@ def build_evidence_key(incident_type: str, incident_id: str) -> str: def send_sqs_message(queue_url: str, payload: dict) -> None: if not queue_url: return - sqs.send_message(QueueUrl=queue_url, MessageBody=json.dumps(payload, default=decimal_default)) + try: + sqs.send_message(QueueUrl=queue_url, MessageBody=json.dumps(payload, default=decimal_default)) + except Exception as e: + print(f"[ERROR] Failed to send message to SQS queue {queue_url}: {e}") def publish_incident_queue(payload: dict) -> None: @@ -209,11 +213,18 @@ def publish_incident_queue(payload: dict) -> None: # Incidentes con respuesta automatica activa: # BRUTE_FORCE → notify-alert + block-ip (Incidente 1) # PORT_SCAN → notify-alert + block-ip (Incidente 2) + # PRIVILEGE_ESCALATION → notify-alert + revoke-credentials (Incidente 3) + # CREDENTIAL_LEAK → notify-alert + revoke-credentials (Incidente 4) PLAYBOOK_INCIDENTS = {"BRUTE_FORCE", "PORT_SCAN"} if payload.get("incident_type") in PLAYBOOK_INCIDENTS: send_sqs_message(PLAYBOOK_NOTIFY_QUEUE_URL, payload) send_sqs_message(PLAYBOOK_BLOCK_IP_QUEUE_URL, payload) + REVOKE_INCIDENTS = {"PRIVILEGE_ESCALATION", "CREDENTIAL_LEAK"} + if payload.get("incident_type") in REVOKE_INCIDENTS: + send_sqs_message(PLAYBOOK_NOTIFY_QUEUE_URL, payload) + send_sqs_message(PLAYBOOK_REVOKE_CREDENTIALS_QUEUE_URL, payload) + def save_incident(payload: dict, source: str, raw_event: dict, summary: str) -> str: incident_id = f"INC-{datetime.now(timezone.utc).strftime('%Y%m%d%H%M%S')}-{str(uuid.uuid4())[:8]}" @@ -231,6 +242,8 @@ def save_incident(payload: dict, source: str, raw_event: dict, summary: str) -> # Registrar qué playbooks se activan para este incidente if final_payload.get("incident_type") in {"BRUTE_FORCE", "PORT_SCAN"}: final_payload["playbooks_requested"] = ["notify-alert", "block-ip"] + elif final_payload.get("incident_type") in {"PRIVILEGE_ESCALATION", "CREDENTIAL_LEAK"}: + final_payload["playbooks_requested"] = ["notify-alert", "revoke-credentials"] evidence_doc = { "incident_id": incident_id, diff --git a/terraform-tesis-ir-secure-portal/lambda_playbook_revoke_credentials.zip b/terraform-tesis-ir-secure-portal/lambda_playbook_revoke_credentials.zip new file mode 100644 index 0000000000000000000000000000000000000000..a82f73102bab008694a5abfe5882337e6b46d3f4 GIT binary patch literal 2548 zcmVg2~;!LJI+4>~fpn8cS*`A=-&eGK4a>y$3jWjfca@Vus=9^3^ z1Fy9d)w9&qQ=W6?t(4q=rP}ZfLb+4@E_Q#B0=ZbpYWHU;a4uHTs}S8tBcFPnehM%x zeuPPC<>eFolmwm@dblAp2|P|WgB?ycB=EfG$N5RLIF91)UK~G*mM{gWLln1MNpVGb zyX4xtTwKPpiv?7lF1*`4jV_iBh+KOY(dGHs;xdZQFQV_~|LlN=FVXm<2SJX2DAbu0 z8ui1W^^(Agj^pLe04)+KQTb%HLB$jL@Q0jk>6@IVmdBH5@l!lIJ&n)LPUpuz!PIFg zWceo3{?4;F$d9Nrmx4@yJbCo^$%Ds_9z6alIVv`-c{y7o6Syi4xb1M1YFot(LdVU8fN2;LR()Jjz6sj+dx3e~QxqymMBR1CNPcc^q! zx2VYxTwMo^PCB+^KR1$XD;FyiU7#zl*j?-6yFCdS<0w_`&iwuIY;l5?{YWXPfNHzl zy`v;Mq*;c7`8%Rr0)@W=YlK3#Vt)ai|q{)*x|cmPxe6vrxgqrIePUf z7YVmYip@4d7eLvz;G(l*uX?d~wmAF8qGj)Yf^#Jk)Kt}Y&?Q#X2~8=ZAR$G%cDc`) zP{L`7y19MTBS1)FRk9=J7xN$Ir_m2l99#%zSq@$+jolz7OU|JVEwqz&*ssx)TC$>O%DCFiwA*qkr zML{?Ax&aBH!Yri;`pxm;Vyo66v^G>3{g#_o?E?W|s&NQjQ&9YjdDh{$Se>8G7*nXN z!;(j#``6;zrVwrD#vbkDoT2q|Hg5Zzm9lJ`tTobFFjBRIGzF52wUBQGxrbf$)d!^~ z%L(iTg4zF(rdfrI!7Y=Ki$B9kT|J;AAkS# z>}565_Se(LIH>$9y=T>CFH zss-KPv{HRg*v-trJj3mCG?Y<8i%inNYm<+y*|~66bT4%mJ7Zkq_Nu`*XXJVS$X6Ds zxVh*KNZ@R6Rx}7h)b7-1cQFcTKLb{e4uZC*ovt}M3^-_IMj?aI)wUs3hQ8)(9JphU z74)hRYhyr+PGGm@Y){59-RZz54HlBXYi$^3YJwy*)InG=+~Gx(jBIv9ya zheOa;b?&v4Llchmt5TmM7gCo;*cw5Pq+vIE`~`l#I!i_VFpe|0rsVe~HRWhk~W zP1D$Q0;Lr$RgU-2_uyjJQ!oj1+(qwek2Q^V+T^F%a-GpV_$rzQ$BZ@Nn!UTtxCpj6ZOA_!b`7vZuvPk%I;-1!Z+d7H9G7*p~3|a`r4* zkP)YP8rr^38K%mE%S??I@N;CO2JY z>h(~Qe!ta&)_9AGn{9JNtKhBnTn{u~&W~rO?Vhj?x8245eAA_e|9P|tpE=%yV#HZJ)*AXt z2n%WWiYHV7O#$EJJd<$y;XQ@R#pRdkINhyryYIYN=uURJxvQ6&iOyZ8*iUh^d0hhs z(|1Whyha-n2kt-^8p_l9veD4BFQrqy%V@n#YEwEwCdu49S)T@2pcpsl5PnA06QK408mQ-0u%!j00;mG0000XiW@XE zl5PnA06QK4015yA00000000000HlEc0001JVQyq>WpXZXc~DCQ1^@s60096205|{u K0Hz550000kdEI*e literal 0 HcmV?d00001 diff --git a/terraform-tesis-ir-secure-portal/main.tf b/terraform-tesis-ir-secure-portal/main.tf index 28b8f4c..06db3fc 100644 --- a/terraform-tesis-ir-secure-portal/main.tf +++ b/terraform-tesis-ir-secure-portal/main.tf @@ -976,6 +976,19 @@ resource "aws_sqs_queue" "playbook_block_ip_queue" { } } +resource "aws_sqs_queue" "playbook_revoke_credentials_queue" { + name = "${var.project_name}-playbook-revoke-credentials-queue" + message_retention_seconds = 345600 + visibility_timeout_seconds = 60 + sqs_managed_sse_enabled = true + + tags = { + Name = "${var.project_name}-playbook-revoke-credentials-queue" + Role = "playbook-dispatch-revoke-credentials" + } +} + + # ----------------------------------------------------------------------------- # IAM policy crítica de prueba e IAM user de laboratorio. # No se crean access keys ni password de consola. @@ -1090,7 +1103,8 @@ resource "aws_iam_role_policy" "lambda_detector" { Resource = [ aws_sqs_queue.incident_queue.arn, aws_sqs_queue.playbook_notify_queue.arn, - aws_sqs_queue.playbook_block_ip_queue.arn + aws_sqs_queue.playbook_block_ip_queue.arn, + aws_sqs_queue.playbook_revoke_credentials_queue.arn ] }, { @@ -1130,6 +1144,7 @@ resource "aws_lambda_function" "detector" { INCIDENT_QUEUE_URL = aws_sqs_queue.incident_queue.url PLAYBOOK_NOTIFY_QUEUE_URL = aws_sqs_queue.playbook_notify_queue.url PLAYBOOK_BLOCK_IP_QUEUE_URL = aws_sqs_queue.playbook_block_ip_queue.url + PLAYBOOK_REVOKE_CREDENTIALS_QUEUE_URL = aws_sqs_queue.playbook_revoke_credentials_queue.url VPC_ID = aws_vpc.this.id PORTAL_INSTANCE_ID = aws_instance.portal.id } @@ -1430,6 +1445,127 @@ resource "aws_lambda_event_source_mapping" "playbook_block_ip_from_queue" { enabled = true } +# ----------------------------------------------------------------------------- +# Playbook de respuesta para Incidente 3 y 4: PRIVILEGE_ESCALATION y CREDENTIAL_LEAK. +# revoke-credentials desactiva las access keys del usuario y le aplica Deny-All. +# ----------------------------------------------------------------------------- + +data "archive_file" "revoke_credentials_zip" { + type = "zip" + source_file = "${path.module}/playbooks/revoke_credentials/handler.py" + output_path = "${path.module}/lambda_playbook_revoke_credentials.zip" +} + +resource "aws_cloudwatch_log_group" "playbook_revoke_credentials" { + name = "/aws/lambda/lambda-${var.project_name}-playbook-revoke-credentials" + retention_in_days = var.cloudwatch_retention_days +} + +resource "aws_iam_role" "playbook_revoke_credentials" { + name = "role-lambda-${var.project_name}-playbook-revoke-credentials" + + assume_role_policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Principal = { Service = "lambda.amazonaws.com" } + Action = "sts:AssumeRole" + } + ] + }) +} + +resource "aws_iam_role_policy_attachment" "playbook_revoke_credentials_basic" { + role = aws_iam_role.playbook_revoke_credentials.name + policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" +} + +resource "aws_iam_role_policy" "playbook_revoke_credentials" { + name = "policy-lambda-${var.project_name}-playbook-revoke-credentials" + role = aws_iam_role.playbook_revoke_credentials.id + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Sid = "ReadDedicatedQueue" + Effect = "Allow" + Action = [ + "sqs:ReceiveMessage", + "sqs:DeleteMessage", + "sqs:GetQueueAttributes" + ] + Resource = aws_sqs_queue.playbook_revoke_credentials_queue.arn + }, + { + Sid = "ManageUserCredentialsAndPolicies" + Effect = "Allow" + Action = [ + "iam:ListAccessKeys", + "iam:UpdateAccessKey", + "iam:PutUserPolicy" + ] + Resource = "*" + }, + { + Sid = "WriteRevokeAudit" + Effect = "Allow" + Action = [ + "s3:GetObject", + "s3:PutObject" + ] + Resource = "${aws_s3_bucket.evidence.arn}/responses/revoke-credentials/*" + }, + { + Sid = "PublishAlert" + Effect = "Allow" + Action = "sns:Publish" + Resource = aws_sns_topic.alerts.arn + } + ] + }) +} + +resource "aws_lambda_function" "playbook_revoke_credentials" { + function_name = "lambda-${var.project_name}-playbook-revoke-credentials" + role = aws_iam_role.playbook_revoke_credentials.arn + handler = "handler.lambda_handler" + runtime = "python3.12" + architectures = ["x86_64"] + memory_size = 128 + timeout = 30 + + filename = data.archive_file.revoke_credentials_zip.output_path + source_code_hash = data.archive_file.revoke_credentials_zip.output_base64sha256 + + environment { + variables = { + SNS_ALERTS_ARN = aws_sns_topic.alerts.arn + EVIDENCE_BUCKET = aws_s3_bucket.evidence.bucket + RESPONSE_PREFIX = "responses/revoke-credentials" + } + } + + depends_on = [ + aws_iam_role_policy_attachment.playbook_revoke_credentials_basic, + aws_iam_role_policy.playbook_revoke_credentials, + aws_cloudwatch_log_group.playbook_revoke_credentials + ] + + tags = { + Name = "lambda-${var.project_name}-playbook-revoke-credentials" + Role = "playbook-revoke-credentials" + } +} + +resource "aws_lambda_event_source_mapping" "playbook_revoke_credentials_from_queue" { + event_source_arn = aws_sqs_queue.playbook_revoke_credentials_queue.arn + function_name = aws_lambda_function.playbook_revoke_credentials.arn + batch_size = 1 + enabled = true +} + # ----------------------------------------------------------------------------- # Metric filters y alarmas simples de respaldo. # ----------------------------------------------------------------------------- diff --git a/terraform-tesis-ir-secure-portal/outputs.tf b/terraform-tesis-ir-secure-portal/outputs.tf index 4555ac3..88fc304 100644 --- a/terraform-tesis-ir-secure-portal/outputs.tf +++ b/terraform-tesis-ir-secure-portal/outputs.tf @@ -90,6 +90,10 @@ output "playbook_block_ip_lambda_name" { value = aws_lambda_function.playbook_block_ip.function_name } +output "playbook_revoke_credentials_lambda_name" { + value = aws_lambda_function.playbook_revoke_credentials.function_name +} + output "playbook_notify_queue_url" { value = aws_sqs_queue.playbook_notify_queue.url } @@ -98,6 +102,10 @@ output "playbook_block_ip_queue_url" { value = aws_sqs_queue.playbook_block_ip_queue.url } +output "playbook_revoke_credentials_queue_url" { + value = aws_sqs_queue.playbook_revoke_credentials_queue.url +} + output "mitigation_network_acl_id" { value = aws_vpc.this.default_network_acl_id } diff --git a/terraform-tesis-ir-secure-portal/playbooks/revoke_credentials/handler.py b/terraform-tesis-ir-secure-portal/playbooks/revoke_credentials/handler.py new file mode 100644 index 0000000..14c0e2a --- /dev/null +++ b/terraform-tesis-ir-secure-portal/playbooks/revoke_credentials/handler.py @@ -0,0 +1,187 @@ +""" +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") ← key del atacante revocada + 2. iam.put_user_policy("EmergencyDenyAll") ← bloqueo total DenyAll +""" +import json +import os +import uuid +from datetime import datetime +from zoneinfo import ZoneInfo + +import boto3 + +s3 = boto3.client("s3") +sns = boto3.client("sns") +iam = boto3.client("iam") + +EVIDENCE_BUCKET = os.environ["EVIDENCE_BUCKET"] +SNS_ARN = os.environ["SNS_ALERTS_ARN"] +RESPONSE_PREFIX = os.environ.get("RESPONSE_PREFIX", "responses/revoke-credentials") +EC_TZ = ZoneInfo("America/Guayaquil") + +DENY_ALL_POLICY = json.dumps({ + "Version": "2012-10-17", + "Statement": [{ + "Effect": "Deny", + "Action": "*", + "Resource": "*" + }] +}) + +def now_ecuador() -> str: + return datetime.now(EC_TZ).isoformat() + +def load_revoke_log() -> list: + try: + obj = s3.get_object(Bucket=EVIDENCE_BUCKET, Key=f"{RESPONSE_PREFIX}/revoked-credentials.json") + return json.loads(obj["Body"].read()) + except Exception: + return [] + +def save_revoke_log(revoke_log: list) -> None: + s3.put_object( + Bucket=EVIDENCE_BUCKET, + Key=f"{RESPONSE_PREFIX}/revoked-credentials.json", + Body=json.dumps(revoke_log, indent=2, ensure_ascii=False).encode("utf-8"), + ContentType="application/json", + ) + +def lambda_handler(event, context): + results = [] + + for record in event.get("Records", []): + try: + body = json.loads(record.get("body", "{}")) + except json.JSONDecodeError as exc: + results.append({"status": "skipped", "reason": f"invalid_json: {exc}"}) + continue + + incident_type = body.get("incident_type", "UNKNOWN") + # Procesar incidentes de escalada o leak de credenciales + if incident_type not in {"PRIVILEGE_ESCALATION", "CREDENTIAL_LEAK"}: + print(f"[revoke-credentials] Tipo {incident_type} no requiere revocacion. Omitiendo.") + results.append({"status": "skipped", "reason": f"not_in_revoke_list:{incident_type}"}) + continue + + affected_resource = body.get("affectedResource", "") + # Extraer el usuario del formato "iam:user/nombre" + username = affected_resource.replace("iam:user/", "") if affected_resource.startswith("iam:user/") else affected_resource + source_ip = body.get("sourceIPAddress", "0.0.0.0") + timestamp = now_ecuador() + incident_id = body.get("incident_id", "") + + if not username or username == "unknown": + print(f"[revoke-credentials] affectedResource invalido: {affected_resource}. Omitiendo.") + results.append({"status": "skipped", "reason": f"invalid_affected_resource:{affected_resource}"}) + continue + + actions_taken = [] + keys_revoked = [] + enforcement = {} + + # ── 1. CUMPLIMIENTO REAL: desactivar todas las access keys ─────────── + try: + keys = iam.list_access_keys(UserName=username).get("AccessKeyMetadata", []) + for key in keys: + kid = key["AccessKeyId"] + if key.get("Status") == "Active": + 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] Error desactivando keys de {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("Politica 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}") + + # Status final + status = "CONTAINED" if (len(keys_revoked) > 0 or enforcement.get("deny_all_applied")) else "NO_ACTION_TAKEN" + + # ── 3. Construir registro de evidencia ─────────────────────────────── + entry = { + "playbook": "revoke-credentials", + "incident_type": incident_type, + "severity": body.get("severity", "CRITICAL"), + "sourceIPAddress": source_ip, + "affectedResource": affected_resource, + "status": status, + "enforcement": enforcement, + "actions_taken": actions_taken, + "timestamp": timestamp, + "timezone": "America/Guayaquil", + "incident_id": incident_id, + } + + # ── 4. Actualizar lista acumulativa ─────────────────────────────────── + revoke_log = load_revoke_log() + if not any(item.get("username") == username for item in revoke_log): + revoke_log.append({ + "username": username, + "revoked_at": timestamp, + "reason": incident_type, + "severity": body.get("severity", "CRITICAL"), + "sourceIPAddress": source_ip, + "enforcement": enforcement, + "actions_taken": actions_taken, + }) + save_revoke_log(revoke_log) + + # ── 5. Guardar evidencia individual por incidente ───────────────────── + key = f"{RESPONSE_PREFIX}/{incident_id or uuid.uuid4().hex}.json" + s3.put_object( + Bucket=EVIDENCE_BUCKET, + Key=key, + Body=json.dumps(entry, indent=2, ensure_ascii=False).encode("utf-8"), + ContentType="application/json", + ) + + # ── 6. Notificar al equipo vía SNS ─────────────────────────────────── + subject = f"[{entry['severity']}] Playbook revoke-credentials: {status} {username}" + sns.publish( + TopicArn=SNS_ARN, + Subject=subject[:100], + Message=json.dumps(entry, indent=2, ensure_ascii=False), + ) + + print(f"[revoke-credentials] {incident_type} → {status} para {username}. evidence={key}") + results.append({ + "status": "success", + "action": status, + "evidence_key": key, + "details": enforcement, + }) + + return { + "status": "success", + "processed": len(results), + "results": results, + "timestamp": now_ecuador(), + } From 3ad13d83361e65bd7da4b47d0b2fea55047bbcb2 Mon Sep 17 00:00:00 2001 From: bryancito1090 Date: Mon, 31 Aug 2026 16:21:11 -0500 Subject: [PATCH 7/9] Add Telegram notifier for SNS alerts - Implemented a new Lambda function `telegram-notifier` that subscribes to an Amazon SNS topic for security alerts. - The function receives structured notifications from the SNS topic and sends them directly to a specified Telegram chat in a monospaced format. - Added error handling for missing Telegram bot token and chat ID. - Formatted messages for better readability in Telegram, including incident severity, type, ID, status, source IP, and affected resource. - Created a new Python handler file for the Telegram notifier functionality. --- .../lambda_function.cpython-314.pyc | Bin 0 -> 29718 bytes .../lambda/lambda_function.py | 6 -- .../lambda_playbook_block_ip.zip | Bin 3191 -> 3367 bytes .../lambda_playbook_notify_alert.zip | Bin 1795 -> 1996 bytes .../lambda_playbook_revoke_credentials.zip | Bin 2548 -> 2747 bytes .../lambda_playbook_telegram_notifier.zip | Bin 0 -> 1456 bytes terraform-tesis-ir-secure-portal/main.tf | 95 +++++++++++++++++- terraform-tesis-ir-secure-portal/outputs.tf | 6 ++ .../__pycache__/handler.cpython-314.pyc | Bin 0 -> 12609 bytes .../playbooks/block_ip/handler.py | 20 +++- .../__pycache__/handler.cpython-314.pyc | Bin 0 -> 6593 bytes .../playbooks/notify_alert/handler.py | 73 +++++++++----- .../__pycache__/handler.cpython-314.pyc | Bin 0 -> 9737 bytes .../playbooks/revoke_credentials/handler.py | 20 +++- .../__pycache__/handler.cpython-314.pyc | Bin 0 -> 4857 bytes .../playbooks/telegram_notifier/handler.py | 88 ++++++++++++++++ .../terraform.tfvars.example | 5 + terraform-tesis-ir-secure-portal/variables.tf | 14 +++ 18 files changed, 287 insertions(+), 40 deletions(-) create mode 100644 terraform-tesis-ir-secure-portal/lambda/__pycache__/lambda_function.cpython-314.pyc create mode 100644 terraform-tesis-ir-secure-portal/lambda_playbook_telegram_notifier.zip create mode 100644 terraform-tesis-ir-secure-portal/playbooks/block_ip/__pycache__/handler.cpython-314.pyc create mode 100644 terraform-tesis-ir-secure-portal/playbooks/notify_alert/__pycache__/handler.cpython-314.pyc create mode 100644 terraform-tesis-ir-secure-portal/playbooks/revoke_credentials/__pycache__/handler.cpython-314.pyc create mode 100644 terraform-tesis-ir-secure-portal/playbooks/telegram_notifier/__pycache__/handler.cpython-314.pyc create mode 100644 terraform-tesis-ir-secure-portal/playbooks/telegram_notifier/handler.py diff --git a/terraform-tesis-ir-secure-portal/lambda/__pycache__/lambda_function.cpython-314.pyc b/terraform-tesis-ir-secure-portal/lambda/__pycache__/lambda_function.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c34dac512cac26d67107c54c52c617de8e5cb0a GIT binary patch literal 29718 zcmc(|3vd+KnI@W5s`pz`>HR86NFekA0SyQmS`q?;KoW^48W1WMsuC*DqdKe9G}U%n ze%!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oYxo_Vt8-5UD#P`oK&-#TM?oadJ95G{}LT4$U6#p-{NO3!;&-@W?YY#R}|x}Vt# z#KMMzeLHol^iIp|miekg-cIUO;jPJ=lktlQN5hQusR2Jb_SA$Q!=j*^f`)%ES7evjxZ4J*~uPSx*b; zNTR1EIwa?59vw6CbO#-l@D#kV#`W~1hWuoo9@jzt_tXu=$I})_RG+rjXbv%X>i+{H C*-B#o literal 0 HcmV?d00001 diff --git a/terraform-tesis-ir-secure-portal/lambda/lambda_function.py b/terraform-tesis-ir-secure-portal/lambda/lambda_function.py index 7aa619b..50c32fe 100644 --- a/terraform-tesis-ir-secure-portal/lambda/lambda_function.py +++ b/terraform-tesis-ir-secure-portal/lambda/lambda_function.py @@ -286,12 +286,6 @@ def save_incident(payload: dict, source: str, raw_event: dict, summary: str) -> publish_incident_queue(final_payload) - sns.publish( - TopicArn=SNS_TOPIC_ARN, - Subject=f"[{final_payload['severity']}] Incidente detectado: {final_payload['incident_type']}", - Message=json.dumps(evidence_doc, indent=2, default=decimal_default), - ) - cloudwatch.put_metric_data( Namespace="TesisIR", MetricData=[ diff --git a/terraform-tesis-ir-secure-portal/lambda_playbook_block_ip.zip b/terraform-tesis-ir-secure-portal/lambda_playbook_block_ip.zip index 16d1ca31c8be3793330098c816f1a177f2f964a1..82e837bfda1f6411f00b987ee94daf776536c44f 100644 GIT binary patch delta 3315 zcmV zx>97CWXhHc0_N1`#b91wA7D>=+pFKiPck5x|EcmXCQ+~@G8hcT?-xuFLcDoG4;vxw zhOkLQba&2D?-kSRmPSl)h!G;eHS&mk{67v7X#y#g6c~?KjDK9CGBgt7f%iNSZ!@Hj zP?*j^NOp@HB8im80y0iP;%!3Vax(ifFuoBPj{&(MpP_yy=iNU_EKqvN>j6Vc`@+3X(fvisgRn+LJd8Db9laZy_$qSUoXZJfS$rVN~RC+ z%k;%BJ^+0B<9}~Zu7;;}$^3e;3YX*244}T`)#P&e`jy{W^33z*8P~!pD%+(A+c7lX zd&sv!Mz}++Ar*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} z@i-h!S}ZF;LHjR&qQE7EO2F^)={;n+V)7EanR)K({fu9n zXbBxR$a5fEWZc<)+Snj*0y@MxuF_HI@bBX}-qTV3(Vv0~Z^n;jC35mOx*gAw5nPX9 zKK}UUY;rxihS6X1C+NX^{AuhL2CzA-?j?C)@EJ9?>x)acxS4#sxrnw0r^N0eLjpg- z&+pEktb^GVw>K=@Dp}NuJ)gDRj+rybWz*O@kiZ_bMN@qBE7%`^Nm^T>AFsrnYFv{JB zs^iiLN^|!d*$iv=H&CxMx2U;T@2%f%mo+WpXZXc~DCQ1^@s60096205|{u K0Ad9I0002NZKX5- literal 0 HcmV?d00001 diff --git a/terraform-tesis-ir-secure-portal/main.tf b/terraform-tesis-ir-secure-portal/main.tf index 06db3fc..60da5e0 100644 --- a/terraform-tesis-ir-secure-portal/main.tf +++ b/terraform-tesis-ir-secure-portal/main.tf @@ -1566,6 +1566,97 @@ resource "aws_lambda_event_source_mapping" "playbook_revoke_credentials_from_que enabled = true } +# ----------------------------------------------------------------------------- +# Integracion de notificaciones a Telegram via SNS +# ----------------------------------------------------------------------------- + +data "archive_file" "telegram_notifier_zip" { + count = var.telegram_bot_token != "" && var.telegram_chat_id != "" ? 1 : 0 + type = "zip" + source_file = "${path.module}/playbooks/telegram_notifier/handler.py" + output_path = "${path.module}/lambda_playbook_telegram_notifier.zip" +} + +resource "aws_cloudwatch_log_group" "telegram_notifier" { + count = var.telegram_bot_token != "" && var.telegram_chat_id != "" ? 1 : 0 + name = "/aws/lambda/lambda-${var.project_name}-telegram-notifier" + retention_in_days = var.cloudwatch_retention_days +} + +resource "aws_iam_role" "telegram_notifier" { + count = var.telegram_bot_token != "" && var.telegram_chat_id != "" ? 1 : 0 + name = "role-lambda-${var.project_name}-telegram-notifier" + + assume_role_policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Principal = { Service = "lambda.amazonaws.com" } + Action = "sts:AssumeRole" + } + ] + }) +} + +resource "aws_iam_role_policy_attachment" "telegram_notifier_basic" { + count = var.telegram_bot_token != "" && var.telegram_chat_id != "" ? 1 : 0 + role = aws_iam_role.telegram_notifier[0].name + policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" +} + +resource "aws_lambda_function" "telegram_notifier" { + count = var.telegram_bot_token != "" && var.telegram_chat_id != "" ? 1 : 0 + function_name = "lambda-${var.project_name}-telegram-notifier" + role = aws_iam_role.telegram_notifier[0].arn + handler = "handler.lambda_handler" + runtime = "python3.12" + architectures = ["x86_64"] + memory_size = 128 + timeout = 15 + + filename = data.archive_file.telegram_notifier_zip[0].output_path + source_code_hash = data.archive_file.telegram_notifier_zip[0].output_base64sha256 + + environment { + variables = { + TELEGRAM_BOT_TOKEN = var.telegram_bot_token + TELEGRAM_CHAT_ID = var.telegram_chat_id + } + } + + depends_on = [ + aws_iam_role_policy_attachment.telegram_notifier_basic, + aws_cloudwatch_log_group.telegram_notifier + ] + + tags = { + Name = "lambda-${var.project_name}-telegram-notifier" + Role = "telegram-alert-notifier" + } +} + +resource "aws_lambda_permission" "from_sns_telegram" { + count = var.telegram_bot_token != "" && var.telegram_chat_id != "" ? 1 : 0 + statement_id = "AllowExecutionFromSNS" + action = "lambda:InvokeFunction" + function_name = aws_lambda_function.telegram_notifier[0].function_name + principal = "sns.amazonaws.com" + source_arn = aws_sns_topic.alerts.arn +} + +resource "aws_sns_topic_subscription" "telegram" { + count = var.telegram_bot_token != "" && var.telegram_chat_id != "" ? 1 : 0 + topic_arn = aws_sns_topic.alerts.arn + protocol = "lambda" + endpoint = aws_lambda_function.telegram_notifier[0].arn + + depends_on = [ + aws_lambda_permission.from_sns_telegram + ] +} + + # ----------------------------------------------------------------------------- # Metric filters y alarmas simples de respaldo. # ----------------------------------------------------------------------------- @@ -1635,7 +1726,6 @@ resource "aws_cloudwatch_metric_alarm" "console_login_failure" { threshold = var.threshold_console_login_failures_same_user_5m alarm_description = "Alarma por multiples fallos de inicio de sesion" treat_missing_data = "notBreaching" - alarm_actions = [aws_sns_topic.alerts.arn] depends_on = [aws_cloudwatch_log_metric_filter.console_login_failure] } @@ -1651,7 +1741,6 @@ resource "aws_cloudwatch_metric_alarm" "iam_critical_action" { threshold = 1 alarm_description = "Alarma por accion critica IAM" treat_missing_data = "notBreaching" - alarm_actions = [aws_sns_topic.alerts.arn] depends_on = [aws_cloudwatch_log_metric_filter.iam_critical_action] } @@ -1667,7 +1756,6 @@ resource "aws_cloudwatch_metric_alarm" "iam_policy_change" { threshold = 1 alarm_description = "Alarma por cambio de politica IAM" treat_missing_data = "notBreaching" - alarm_actions = [aws_sns_topic.alerts.arn] depends_on = [aws_cloudwatch_log_metric_filter.iam_policy_change] } @@ -1685,7 +1773,6 @@ resource "aws_cloudwatch_metric_alarm" "vpc_rejected_traffic" { threshold = var.threshold_port_scan_distinct_ports_5m alarm_description = "Alarma por trafico rechazado repetido hacia la EC2" treat_missing_data = "notBreaching" - alarm_actions = [aws_sns_topic.alerts.arn] depends_on = [aws_cloudwatch_log_metric_filter.vpc_rejected_traffic] } diff --git a/terraform-tesis-ir-secure-portal/outputs.tf b/terraform-tesis-ir-secure-portal/outputs.tf index 88fc304..8128211 100644 --- a/terraform-tesis-ir-secure-portal/outputs.tf +++ b/terraform-tesis-ir-secure-portal/outputs.tf @@ -109,3 +109,9 @@ output "playbook_revoke_credentials_queue_url" { output "mitigation_network_acl_id" { value = aws_vpc.this.default_network_acl_id } + +output "telegram_notifier_lambda_name" { + value = try(aws_lambda_function.telegram_notifier[0].function_name, "disabled") + description = "Nombre de la Lambda de Telegram (si esta habilitada)." +} + diff --git a/terraform-tesis-ir-secure-portal/playbooks/block_ip/__pycache__/handler.cpython-314.pyc b/terraform-tesis-ir-secure-portal/playbooks/block_ip/__pycache__/handler.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5af74f282ca6cac7b37f224f7e09c1b53c7d1f51 GIT binary patch literal 12609 zcmb_CYj7LKd3Sif0fGSEkE1A21Vw@pB}yXoq)1SND1y)tq%4U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D_0)%Kk62aoD*v4$ELA=H#z>Wp$4EoJU>i0>Yo!zIGwph*HZWL?)Ubu z@IO2JF!1QG&=7!=TD^Ngvu<+=RVN=-Jv2Pp@o4OkN2s9JY-1nT#{RIOMNL2B5nunS zmeFd(FRU$or{b5@PQP9KOLvvutQO2_NDEHmIjdTrcAhh+R}E@NyBbApFc@LO@PZL( z{F1#_!SdYSqa0GxL>-bxqv+)>64gZY6!;JKi<)o@y%>?M1jP5Hrx@VJyA|cwxO73h zi^_|>K?BMnHMsZ)gF_Y&ZV5#citybufKuZqLf5f$BOyM`fdQxV(W36?G#i0i_Bi)* zs6h5w{(m8YT_(w=3OlKK)h8&MCx-x8)L8sm3kuf`S*WHnWDid;U| zoz+y&DL3by*d6!U?zRCZ{?OhzXU)mkjt}kbIql}GC7-?LzUvm6x`YEmS-W@6`YXG0 zVd~zEyEpE|@5UD|E|+I3y0i9!bGjER9NCJ4S^FVWQ6tp4voN3Es&&1@U4Ap1J}lL`wW?PaQq*yjjaFx literal 0 HcmV?d00001 diff --git a/terraform-tesis-ir-secure-portal/playbooks/block_ip/handler.py b/terraform-tesis-ir-secure-portal/playbooks/block_ip/handler.py index 071be22..8e236db 100644 --- a/terraform-tesis-ir-secure-portal/playbooks/block_ip/handler.py +++ b/terraform-tesis-ir-secure-portal/playbooks/block_ip/handler.py @@ -212,11 +212,27 @@ def lambda_handler(event, context): ) # ── Notificar al equipo via SNS ──────────────────────────────────── - subject = f"[{entry['severity']}] Playbook block-ip: {status} {ip_value} ({incident_type})" + subject = f"[{entry['severity']}] Mitigacion: IP {ip_value} {status} en NACL" + mitigation_report = f""" +[MITIGACION DE SEGURIDAD AWS] - ACCION: {status} +================================================== +Playbook : block-ip +Tipo de Incidente : {incident_type} +ID de Incidente : {entry['incident_id']} +Estado : {status} +-------------------------------------------------- +IP Objetivo : {ip_value} +Network ACL : {enforcement.get('network_acl_id', 'N/A')} +Regla Creada : #{enforcement.get('rule_number', 'N/A')} +-------------------------------------------------- +Hora Mitigacion : {timestamp} +Evidencia S3 : {key} +================================================== +""".strip() sns.publish( TopicArn=SNS_ARN, Subject=subject[:100], - Message=json.dumps(entry, indent=2, ensure_ascii=False), + Message=mitigation_report, ) print(f"[block-ip] {incident_type} → {status} para {ip_value}. " diff --git a/terraform-tesis-ir-secure-portal/playbooks/notify_alert/__pycache__/handler.cpython-314.pyc b/terraform-tesis-ir-secure-portal/playbooks/notify_alert/__pycache__/handler.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..54292b3011c27a2a1eaaade02da64cdf20dbcc64 GIT binary patch literal 6593 zcmb7IYit|Yb-u&r@GVNz!`5qL`60?SBb(Yd-Zw`_VptrfT?j5^q0PJ#Xb z^Nf&B3mHDI@G_I( zLCkYmCybN%jiMxExC~R^0LW*V#PS@o#biaMP+ZRf8-~j=idYcRB9n+En29F`>jHGaP(fD6ba%-v z(tLF4F6XLAuFR4x@kJ|*9c{RHiX`%Zc~_Ag`RqvBKKzc0~w>)Bwi^>d04&~ zb_s>8eljxQd_Ws3G_KZI4y#}7)NL-GfjbTrwlp`(a(P%Q90bcs@!Og;GRG!A)Et5=)_3}IB>4d?`5@C=0Acxbk;{mZ)DIK}{xbOz%jkux=i&Lk zJ^%OCs%zxAYvOa)MAbE^S|;`3Z`=l1qQ0dQ`oM3#4QyI%Zgk273pPtG7^YeEla}02 z51KR!d?kwHAq`6MLQ%gUebxG*>)AolQD5y>=m0hJCCPqzaE}!KIHR{(s|Bo{$nIga zmRA>H9Yl8GhEz2Gq`(w58Tz6?b-t22YX^+8 z4P)zoakXLW9Wd@T4BY|aX~Q@=V7zS@X9tY04dd#7>1xBcu|H*UqiGW!#oZ}Nul1xX zdKpNW^|BW;xG!bZ>-{O4UJj(}dbuw}>m`HtryP21Fy++Cp_EH6hf{9791Zyk9y}5! zlKoand5n({!rdFif@<~1iL%e=zoxg4)~jfvTH zP8MLg46o?p!;0prt8_4Q&~VB#Y*yT0@9UbWTu#_;2i*+U@wVq z!}H{j(qP}olu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8TVEeT-D7Ik*tUQBChiF#Q@t8Uu`*r4DHvf6^SJ~$m zVxM1#sRx#y7FF-cee(<2`Ox#g^P=ZKt*hsSzxVO}Pxn_MJ7Z4{J@dc!+`ss_fAOik z>W|k3Cifi3(f1lz9nQTj)Z6!nuU!73?}*wvvE$MAb@8*JdX@cR@gsGCQ@M4uJAL2& zqVE{I2>NF3yZ(cAJ#;;Az33gP1qLhgKZGa6=$;)p0$5C4_be7&mOg??Jr+q56)r%qSR(ESyb47{oY8FQEX14@{p+tQ z3p<~`D@bBq+8{%Ty3nuY3)08X0lqzw zKZR`1Oi|RACM#um48Pwa_e-1WZ?fOZJ~~yk?JJvWjn>JkZJ=y= z*&TR1`N^a@eEf^!Y^Ks~tkUBQ4p1e}+zFPMEwtK%i7^(um`d=2? bkV!=Yf9!_9@E>UiPQJcOy+=_tea-(17*6A9 literal 0 HcmV?d00001 diff --git a/terraform-tesis-ir-secure-portal/playbooks/notify_alert/handler.py b/terraform-tesis-ir-secure-portal/playbooks/notify_alert/handler.py index cbd33e1..0abad88 100644 --- a/terraform-tesis-ir-secure-portal/playbooks/notify_alert/handler.py +++ b/terraform-tesis-ir-secure-portal/playbooks/notify_alert/handler.py @@ -1,14 +1,8 @@ """ Playbook: notify-alert -Recibe incidentes desde una cola SQS dedicada y publica una notificacion -estructurada en SNS. Tambien deja evidencia operativa en S3. - -Incidentes soportados: - - BRUTE_FORCE (severity HIGH) → Componente C, Incidente 1 - - PORT_SCAN (severity MEDIUM) → Componente C, Incidente 2 - - PRIVILEGE_ESCALATION (severity CRITICAL) - - CREDENTIAL_LEAK (severity CRITICAL) - - EXFILTRATION (severity HIGH) +Recibe incidentes desde una cola SQS dedicada, genera un reporte profesional +de seguridad para el SOC y lo publica al topico SNS (para entrega simultanea +y formateada en Gmail y Telegram). Tambien registra evidencia en S3. """ import json import os @@ -26,8 +20,6 @@ EVIDENCE_BUCKET = os.environ["EVIDENCE_BUCKET"] RESPONSE_PREFIX = os.environ.get("RESPONSE_PREFIX", "responses/notify-alert") EC_TZ = ZoneInfo("America/Guayaquil") -# Tipos de incidente que este playbook debe procesar. -# Cualquier otro tipo se omite (skip) para evitar procesamiento no intencionado. SUPPORTED_INCIDENT_TYPES = { "BRUTE_FORCE", "PORT_SCAN", @@ -41,6 +33,43 @@ def now_ecuador() -> str: return datetime.now(EC_TZ).isoformat() +def format_incident_report(alert: dict) -> str: + """Genera un reporte profesional de seguridad (SOC) en texto plano para correo y Telegram.""" + incident_type = alert.get("incident_type", "NO_ESPECIFICADO") + severity = alert.get("severity", "MEDIUM") + status = alert.get("status", "NOTIFICADO") + incident_id = alert.get("incident_id", "N/A") + source_ip = alert.get("sourceIPAddress", "N/A") + resource = alert.get("affectedResource", "N/A") + service = alert.get("affected_service", "N/A") + asset = alert.get("asset_name", "N/A") + basis = alert.get("severity_basis", "N/A") + detected_at = alert.get("detectedAt", "N/A") + responded_at = alert.get("respondedAt", "N/A") + s3_key = alert.get("s3_log_key", "N/A") + + lines = [ + f"[ALERTA DE SEGURIDAD AWS] - SEVERIDAD: {severity}", + "=" * 50, + f"Tipo de Incidente : {incident_type}", + f"ID de Incidente : {incident_id}", + f"Estado : {status}", + f"Playbook : notify-alert", + "-" * 50, + f"IP Origen : {source_ip}", + f"Recurso Afectado : {resource}", + f"Servicio Afectado : {service}", + f"Activo Objetivo : {asset}", + "-" * 50, + f"Criterio / Motivo : {basis}", + f"Hora Deteccion : {detected_at}", + f"Hora Respuesta : {responded_at}", + f"Evidencia S3 : {s3_key}", + "=" * 50, + ] + return "\n".join(lines) + + def lambda_handler(event, context): results = [] @@ -78,17 +107,7 @@ def lambda_handler(event, context): "incident_id": body.get("incident_id", ""), } - # Campos extra según el tipo de incidente - if incident_type == "PORT_SCAN": - alert["scanned_ports_count"] = body.get("scanned_ports_count", - body.get("event_count", 0)) - alert["rejected_connections"] = body.get("rejected_connections", 0) - elif incident_type == "BRUTE_FORCE": - alert["failed_attempts"] = body.get("failed_attempts", - body.get("event_count", 0)) - alert["detection_window"] = body.get("detection_window", "5 minutes") - - # ── Guardar evidencia en S3 ──────────────────────────────────────── + # ── Guardar evidencia JSON en S3 ─────────────────────────────────── key = f"{RESPONSE_PREFIX}/{body.get('incident_id') or uuid.uuid4().hex}.json" s3.put_object( Bucket=EVIDENCE_BUCKET, @@ -97,15 +116,17 @@ def lambda_handler(event, context): ContentType="application/json", ) - # ── Publicar en SNS ──────────────────────────────────────────────── - subject = f"[{alert['severity']}] Playbook notify-alert: {incident_type}" + # ── Publicar reporte legible en SNS (llega formateado a Gmail y Telegram) + subject = f"[{alert['severity']}] Incidente: {incident_type} ({alert['affectedResource']})" + report_text = format_incident_report(alert) + sns.publish( TopicArn=SNS_ARN, Subject=subject[:100], - Message=json.dumps(alert, indent=2, ensure_ascii=False), + Message=report_text, ) - print(f"[notify-alert] {incident_type} notificado. evidence_key={key}") + print(f"[notify-alert] {incident_type} notificado profesionalmente. evidence_key={key}") results.append({"status": "success", "action": "sns_published", "evidence_key": key}) return { diff --git a/terraform-tesis-ir-secure-portal/playbooks/revoke_credentials/__pycache__/handler.cpython-314.pyc b/terraform-tesis-ir-secure-portal/playbooks/revoke_credentials/__pycache__/handler.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..995b1a5f211fc9b8ccd4217b57cd8e4c6bf414cb GIT binary patch literal 9737 zcmbt4TWlLwc6a!G48^zJvPP0^iLyo7vK=e(la^?UmPJ#;u^h*enK3!GX;UP3IP_ZF z2GG8h6out%7G~NM(V~l1!J>fCEl?LNP%U;p{8MyfDiL>9ZH?|nvHfBYZIdQHJ$I-f zX<6QFwpY@9o_p^(=bn4cnRB(T!D2#?KK`#C-u@AV(64brN#?D}r+-NxG>>Q`plgUG zf`mZGrAkoArCLx!sS0YwG=ioR!>EJWF`b~3>qJm5=x6j{o3d=J>_W8WFszM}V0TA zij#eY2=7)PYbC&tw1sYX%k#@Bh;JZx|?o> zdW&3dq+6Si&_okG$kUcf0z*yVBs+IKoxU?n@!Z|?9d01Tb8#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euR zdKPX3xeRw+x(aPLNRj6t+an2r_`+Z!j8B}1aDIktpP`n|kneL}JKkw`7H==A$4=ir iTJW7yQFE!W^_BaEg71uqy#F%8zX_h6JwcfD@BIh-0%b1% literal 0 HcmV?d00001 diff --git a/terraform-tesis-ir-secure-portal/playbooks/telegram_notifier/handler.py b/terraform-tesis-ir-secure-portal/playbooks/telegram_notifier/handler.py new file mode 100644 index 0000000..707706f --- /dev/null +++ b/terraform-tesis-ir-secure-portal/playbooks/telegram_notifier/handler.py @@ -0,0 +1,88 @@ +""" +Lambda: telegram-notifier +Suscrito a Amazon SNS (Topic de alertas de seguridad). +Recibe la notificacion estructurada del topico SNS y la envia directamente +a Telegram en formato monoespaciado (
) usando la biblioteca estandar de Python.
+"""
+import json
+import os
+import urllib.parse
+import urllib.request
+
+TELEGRAM_BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN", "")
+TELEGRAM_CHAT_ID   = os.environ.get("TELEGRAM_CHAT_ID", "")
+
+
+def send_telegram_message(text: str) -> dict:
+    if not TELEGRAM_BOT_TOKEN or not TELEGRAM_CHAT_ID:
+        print("[telegram-notifier] Variables TELEGRAM_BOT_TOKEN o TELEGRAM_CHAT_ID no configuradas.")
+        return {"status": "skipped", "reason": "missing_credentials"}
+
+    api_url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
+    payload = {
+        "chat_id": TELEGRAM_CHAT_ID,
+        "text": f"
{text}
", + "parse_mode": "HTML" + } + + data_bytes = json.dumps(payload).encode("utf-8") + req = urllib.request.Request( + api_url, + data=data_bytes, + headers={"Content-Type": "application/json"}, + method="POST" + ) + + try: + with urllib.request.urlopen(req, timeout=10) as response: + resp_body = response.read().decode("utf-8") + print(f"[telegram-notifier] Mensaje entregado a Telegram. HTTP {response.status}") + return {"status": "success", "response": json.loads(resp_body)} + except Exception as exc: + print(f"[telegram-notifier] Error enviando mensaje a Telegram: {exc}") + return {"status": "error", "error": str(exc)} + + +def lambda_handler(event, context): + results = [] + + for record in event.get("Records", []): + sns_record = record.get("Sns", {}) + raw_message = sns_record.get("Message", "") + + # Si el mensaje ya es texto plano formateado por notify-alert, enviarlo directo + if not raw_message.strip().startswith("{"): + send_result = send_telegram_message(raw_message.strip()) + results.append(send_result) + continue + + # Si por alguna razon llega un JSON crudo, parsearlo y formatearlo + try: + message_data = json.loads(raw_message) + if "incident_payload" in message_data: + message_data = message_data["incident_payload"] + + lines = [ + f"[ALERTA DE SEGURIDAD AWS] - SEVERIDAD: {message_data.get('severity', 'HIGH')}", + "=" * 50, + f"Tipo de Incidente : {message_data.get('incident_type', 'NO_ESPECIFICADO')}", + f"ID de Incidente : {message_data.get('incident_id', 'N/A')}", + f"Estado : {message_data.get('status', 'NOTIFICADO')}", + "-" * 50, + f"IP Origen : {message_data.get('sourceIPAddress', 'N/A')}", + f"Recurso Afectado : {message_data.get('affectedResource', 'N/A')}", + f"Criterio / Motivo : {message_data.get('severity_basis', 'N/A')}", + "=" * 50, + ] + formatted_text = "\n".join(lines) + send_result = send_telegram_message(formatted_text) + results.append(send_result) + except Exception: + send_result = send_telegram_message(str(raw_message)) + results.append(send_result) + + return { + "status": "success", + "processed": len(results), + "results": results + } diff --git a/terraform-tesis-ir-secure-portal/terraform.tfvars.example b/terraform-tesis-ir-secure-portal/terraform.tfvars.example index f038e0f..8da05ed 100644 --- a/terraform-tesis-ir-secure-portal/terraform.tfvars.example +++ b/terraform-tesis-ir-secure-portal/terraform.tfvars.example @@ -19,6 +19,11 @@ authorized_ip_cidrs = [] # Opcional: correo para SNS y Budget. Debes confirmar la suscripcion SNS por email. alert_email = "tu_correo@ejemplo.com" +# Opcional: Notificaciones a Telegram +# Obtén el token con @BotFather y el chat_id con @userinfobot o @RawDataBot +telegram_bot_token = "" +telegram_chat_id = "" + # Si ya tienes una key pair EC2 creada en esa region: # key_name = "tesis-ir-key" key_name = "" diff --git a/terraform-tesis-ir-secure-portal/variables.tf b/terraform-tesis-ir-secure-portal/variables.tf index 80116a0..940f8b8 100644 --- a/terraform-tesis-ir-secure-portal/variables.tf +++ b/terraform-tesis-ir-secure-portal/variables.tf @@ -212,3 +212,17 @@ variable "threshold_s3_getobject_exfiltration_count_1h" { type = number default = 50 } + +variable "telegram_bot_token" { + description = "Token del Bot de Telegram para envio de alertas. Opcional; si queda vacio no se despliega la integracion." + type = string + default = "" + sensitive = true +} + +variable "telegram_chat_id" { + description = "Chat ID o ID de grupo/canal de Telegram donde se enviaran las alertas." + type = string + default = "" +} + From 80fd31a299778c78d715b62521cb04fce5ffe634 Mon Sep 17 00:00:00 2001 From: bryancito1090 Date: Tue, 1 Sep 2026 15:56:17 -0500 Subject: [PATCH 8/9] feat: Implement security card image generation for Telegram notifications - Added `card_image.py` to generate PNG images for security incident alerts. - Updated `handler.py` to create and send visual cards for incidents and mitigations via Telegram. - Enhanced message parsing to support structured incident data and mitigation details. - Removed old text message sending method and replaced it with image sending functionality. - Updated Terraform variables and example configuration for SES DKIM settings. --- .gitignore | 25 ++ terraform-tesis-ir-secure-portal/.gitignore | 12 +- .../lambda_function.cpython-314.pyc | Bin 29718 -> 0 bytes .../lambda/lambda_function.py | 120 +++++-- .../lambda_playbook_block_ip.zip | Bin 3367 -> 0 bytes .../lambda_playbook_notify_alert.zip | Bin 1996 -> 0 bytes .../lambda_playbook_revoke_credentials.zip | Bin 2747 -> 0 bytes .../lambda_playbook_telegram_notifier.zip | Bin 1456 -> 0 bytes terraform-tesis-ir-secure-portal/main.tf | 93 +++-- terraform-tesis-ir-secure-portal/outputs.tf | 42 +++ .../__pycache__/handler.cpython-314.pyc | Bin 12609 -> 0 bytes .../playbooks/block_ip/handler.py | 220 +++++++++--- .../__pycache__/handler.cpython-314.pyc | Bin 6593 -> 0 bytes .../playbooks/notify_alert/handler.py | 202 +++++++++-- .../__pycache__/handler.cpython-314.pyc | Bin 9737 -> 0 bytes .../playbooks/revoke_credentials/handler.py | 203 +++++++++-- .../__pycache__/handler.cpython-314.pyc | Bin 4857 -> 0 bytes .../playbooks/telegram_notifier/card_image.py | 318 ++++++++++++++++++ .../playbooks/telegram_notifier/handler.py | 258 +++++++++++--- .../terraform.tfvars.example | 4 + terraform-tesis-ir-secure-portal/variables.tf | 12 + 21 files changed, 1319 insertions(+), 190 deletions(-) create mode 100644 .gitignore delete mode 100644 terraform-tesis-ir-secure-portal/lambda/__pycache__/lambda_function.cpython-314.pyc delete mode 100644 terraform-tesis-ir-secure-portal/lambda_playbook_block_ip.zip delete mode 100644 terraform-tesis-ir-secure-portal/lambda_playbook_notify_alert.zip delete mode 100644 terraform-tesis-ir-secure-portal/lambda_playbook_revoke_credentials.zip delete mode 100644 terraform-tesis-ir-secure-portal/lambda_playbook_telegram_notifier.zip delete mode 100644 terraform-tesis-ir-secure-portal/playbooks/block_ip/__pycache__/handler.cpython-314.pyc delete mode 100644 terraform-tesis-ir-secure-portal/playbooks/notify_alert/__pycache__/handler.cpython-314.pyc delete mode 100644 terraform-tesis-ir-secure-portal/playbooks/revoke_credentials/__pycache__/handler.cpython-314.pyc delete mode 100644 terraform-tesis-ir-secure-portal/playbooks/telegram_notifier/__pycache__/handler.cpython-314.pyc create mode 100644 terraform-tesis-ir-secure-portal/playbooks/telegram_notifier/card_image.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d91b87c --- /dev/null +++ b/.gitignore @@ -0,0 +1,25 @@ +# Terraform +.terraform/ +*.tfstate +*.tfstate.* +.terraform.lock.hcl +terraform.tfvars +terraform.tfvars.json + +# Lambda build artifacts +*.zip + +# Python cache +__pycache__/ +*.py[cod] +*$py.class + +# Environment & credentials +.env +.env.* +*.pem +*.key + +# Backups and logs +*.log +backup_*/ diff --git a/terraform-tesis-ir-secure-portal/.gitignore b/terraform-tesis-ir-secure-portal/.gitignore index 2fb93ba..f04c579 100644 --- a/terraform-tesis-ir-secure-portal/.gitignore +++ b/terraform-tesis-ir-secure-portal/.gitignore @@ -3,6 +3,16 @@ *.tfstate.* .terraform.lock.hcl terraform.tfvars -lambda_tesis_detector.zip +terraform.tfvars.json + +# Lambda build artifacts +*.zip + +# Python cache +__pycache__/ +*.py[cod] +*$py.class + +# Crash logs crash.log crash.*.log diff --git a/terraform-tesis-ir-secure-portal/lambda/__pycache__/lambda_function.cpython-314.pyc b/terraform-tesis-ir-secure-portal/lambda/__pycache__/lambda_function.cpython-314.pyc deleted file mode 100644 index 7c34dac512cac26d67107c54c52c617de8e5cb0a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 29718 zcmc(|3vd+KnI@W5s`pz`>HR86NFekA0SyQmS`q?;KoW^48W1WMsuC*DqdKe9G}U%n ze%!FIX9BVAUaH5;w7kQv)f*jS&7Hn+x#ON|^}U`LZmee`MTx0$S`M>2-q`U@#Jys= zS?~75eSH7P%B&JdwA(uyH$ysk^5i)u&*T69^S{oiMu*+P;ky5y-nsgR7dY;3=|Q=4 z>BuKPMQnx}=6FpH7nSdtsD?djqgr;)iRQ4oE~;a9eN@lxhNuB|ZIAJ|F={++ikhmZ zd`^$~xFu>~ab1t~xGid9aZQgsYR7whkK?#A>SSq#9@p{QXl@mE$v&_}XYzk38El@01wwnAAK4o8~dAc?vhpV^Q-IZJNib<|)3U8)#Enk-77>rqaw)v~-hP z_I0_+Hp%5!m#ch}T+Vg5DmKaGT9>PG<6HxWGi_I5d@i52TPr_BJzt<)KJQk`ReynU z1$?1euI3ArE6QqT?H4FloKeg~d+rl0rlr}#EJ?@B+vgy-FO z-jjab%fE!Dz4R2_$L~XYKa20@+Yvv&;_duF#9wCd1N1I6^7R~v zS*ItjO-@~(Y<@jFBIOPA^Mf5HeLa2n7}bspE+s=~G7|Mqjs&HWfs-BQJNx^4eSQ6d zJx9-H)mx^%>O9%s)$8jS$a-0)zT~^T{k`43F20+3*wb2bEh?98eTJmH}chrnR{RRYbqld zgkW@9n0y~|5{U|!6T|3~FyW6zsOB1}WZXY-IpA-VZ@$s#$&qMiYO*DKL$djN{>jOy zD5l-#6KautEB+(-2xhq7a2ie96AIqWXSYv~%#B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PC5q@PYm>a)$Bx!AUXl+P2%jaz?&Zb4{{V%WV=v^&qUKq#LjoYSQl{GC4 zCCWMxD{or3m?-ab{}L_Rg^%N(=4gEnxyJTpye&fY5?8Nk2%(I0_p2>|M%4>#pqcyN6=!6m(FKK`Vw)WK)q1FwEGJ@fT)`If!t2 zZ`%sRentW90+TV1;UH51kVGOQB7yL;Kha}4h+i_B9uFQ8{yE;_kBj_0Lio>WG(YF; zKj*AJ=Ugl_v(WlWZtE|&ieGSLf6Li^!8QDXYkX{V-8%H`L-FnSeW@8!N^kkr(AS6N zwj}gLGuo8F`mOP=kI(H%7)oYxo_Vt8-5UD#P`oK&-#TM?oadJ95G{}LT4$U6#p-{NO3!;&-@W?YY#R}|x}Vt# z#KMMzeLHol^iIp|miekg-cIUO;jPJ=lktlQN5hQusR2Jb_SA$Q!=j*^f`)%ES7evjxZ4J*~uPSx*b; zNTR1EIwa?59vw6CbO#-l@D#kV#`W~1hWuoo9@jzt_tXu=$I})_RG+rjXbv%X>i+{H C*-B#o diff --git a/terraform-tesis-ir-secure-portal/lambda/lambda_function.py b/terraform-tesis-ir-secure-portal/lambda/lambda_function.py index 50c32fe..eeee5ae 100644 --- a/terraform-tesis-ir-secure-portal/lambda/lambda_function.py +++ b/terraform-tesis-ir-secure-portal/lambda/lambda_function.py @@ -207,22 +207,30 @@ def publish_incident_queue(payload: dict) -> None: send_sqs_message(INCIDENT_QUEUE_URL, payload) # Fan-out controlado a playbooks de respuesta automatica. - # Se usan colas dedicadas para que notify-alert y block-ip reciban ambos - # el mismo evento sin competir por el mensaje SQS. + # Se usan colas dedicadas para que notify-alert y los playbooks de contencion + # reciban ambos el mismo evento sin competir por el mensaje SQS. # - # Incidentes con respuesta automatica activa: - # BRUTE_FORCE → notify-alert + block-ip (Incidente 1) - # PORT_SCAN → notify-alert + block-ip (Incidente 2) - # PRIVILEGE_ESCALATION → notify-alert + revoke-credentials (Incidente 3) - # CREDENTIAL_LEAK → notify-alert + revoke-credentials (Incidente 4) - PLAYBOOK_INCIDENTS = {"BRUTE_FORCE", "PORT_SCAN"} - if payload.get("incident_type") in PLAYBOOK_INCIDENTS: + # Cobertura completa de incidentes: + # 1. BRUTE_FORCE → notify-alert + block-ip + # 2. PORT_SCAN → notify-alert + block-ip + # 3. PRIVILEGE_ESCALATION → notify-alert + revoke-credentials + # 4. CREDENTIAL_LEAK → notify-alert + revoke-credentials + # 5. EXFILTRATION → notify-alert + incident_type = payload.get("incident_type") + + # notify-alert se activa para TODOS los incidentes soportados + NOTIFY_INCIDENTS = {"BRUTE_FORCE", "PORT_SCAN", "PRIVILEGE_ESCALATION", "CREDENTIAL_LEAK", "EXFILTRATION"} + if incident_type in NOTIFY_INCIDENTS: send_sqs_message(PLAYBOOK_NOTIFY_QUEUE_URL, payload) + + # block-ip se activa para incidentes de red (contención perimetral) + BLOCK_IP_INCIDENTS = {"BRUTE_FORCE", "PORT_SCAN"} + if incident_type in BLOCK_IP_INCIDENTS: send_sqs_message(PLAYBOOK_BLOCK_IP_QUEUE_URL, payload) + # revoke-credentials se activa para incidentes de credenciales/IAM (contención de identidad) REVOKE_INCIDENTS = {"PRIVILEGE_ESCALATION", "CREDENTIAL_LEAK"} - if payload.get("incident_type") in REVOKE_INCIDENTS: - send_sqs_message(PLAYBOOK_NOTIFY_QUEUE_URL, payload) + if incident_type in REVOKE_INCIDENTS: send_sqs_message(PLAYBOOK_REVOKE_CREDENTIALS_QUEUE_URL, payload) @@ -244,6 +252,8 @@ def save_incident(payload: dict, source: str, raw_event: dict, summary: str) -> final_payload["playbooks_requested"] = ["notify-alert", "block-ip"] elif final_payload.get("incident_type") in {"PRIVILEGE_ESCALATION", "CREDENTIAL_LEAK"}: final_payload["playbooks_requested"] = ["notify-alert", "revoke-credentials"] + elif final_payload.get("incident_type") == "EXFILTRATION": + final_payload["playbooks_requested"] = ["notify-alert"] evidence_doc = { "incident_id": incident_id, @@ -312,8 +322,8 @@ def analyze_app_event(event_json: dict, config: dict): if count >= threshold and mark_alert_once(f"BRUTE_FORCE#APP#{source_ip}#{window}"): severity_basis = ( - f"HIGH porque la IP {source_ip} alcanzo {count} intentos fallidos " - f"en 5 minutos; el umbral configurado para BRUTE_FORCE es {threshold}." + f"HIGH: La IP {source_ip} alcanzó {count} intentos fallidos de autenticación " + f"en 5 minutos (umbral={threshold})." ) payload = { "incident_type": "BRUTE_FORCE", @@ -327,9 +337,9 @@ def analyze_app_event(event_json: dict, config: dict): "event_count": count, "failed_attempts": count, "detection_window": "5 minutes", - "affected_service": event_json.get("affected_service", "Portal de autenticacion corporativo"), - "asset_name": event_json.get("asset_name", f"{PORTAL_INSTANCE_ID}"), - "asset_type": event_json.get("asset_type", "EC2 web application"), + "affected_service": event_json.get("affected_service", "Portal Web Corporativo"), + "asset_name": event_json.get("asset_name", f"EC2 Instance ({PORTAL_INSTANCE_ID})"), + "asset_type": event_json.get("asset_type", "EC2 Web Application"), "severity_basis": severity_basis, "mitigation_playbooks": ["notify-alert", "block-ip"], } @@ -362,14 +372,16 @@ def analyze_cloudtrail(event_json: dict, config: dict): "sourceIPAddress": source_ip, "affectedResource": affected_iam_user(event_json, username), "s3_log_key": "pending", - "timestamp": event_json.get("eventTime", utc_now()), + "timestamp": event_json.get("eventTime", ecuador_now()), + "timestamp_utc": event_json.get("eventTime", utc_now()), + "timezone": "America/Guayaquil", "event_count": count_user, "failed_attempts": count_user, "detection_window": "5 minutes", - "affected_service": "AWS Sign-In / IAM", - "asset_name": "AWS Console", - "asset_type": "AWS control plane", - "severity_basis": f"HIGH porque se alcanzaron {count_user} fallos de ConsoleLogin para el mismo usuario en 5 minutos.", + "affected_service": "AWS Sign-In / IAM Console", + "asset_name": f"IAM User ({username})", + "asset_type": "AWS Control Plane", + "severity_basis": f"HIGH: Se alcanzaron {count_user} fallos de ConsoleLogin para {username} en 5 minutos (umbral={threshold_user}).", "mitigation_playbooks": ["notify-alert", "block-ip"], } return payload, f"{count_user} fallos de ConsoleLogin para {username} en 5 minutos." @@ -380,14 +392,16 @@ def analyze_cloudtrail(event_json: dict, config: dict): "sourceIPAddress": source_ip, "affectedResource": affected_iam_user(event_json, username), "s3_log_key": "pending", - "timestamp": event_json.get("eventTime", utc_now()), + "timestamp": event_json.get("eventTime", ecuador_now()), + "timestamp_utc": event_json.get("eventTime", utc_now()), + "timezone": "America/Guayaquil", "event_count": count_ip, "failed_attempts": count_ip, "detection_window": "5 minutes", - "affected_service": "AWS Sign-In / IAM", - "asset_name": "AWS Console", - "asset_type": "AWS control plane", - "severity_basis": f"HIGH porque se alcanzaron {count_ip} fallos de ConsoleLogin desde la misma IP en 5 minutos.", + "affected_service": "AWS Sign-In / IAM Console", + "asset_name": f"AWS Console (IP: {source_ip})", + "asset_type": "AWS Control Plane", + "severity_basis": f"HIGH: Se alcanzaron {count_ip} fallos de ConsoleLogin desde {source_ip} en 5 minutos (umbral={threshold_ip}).", "mitigation_playbooks": ["notify-alert", "block-ip"], } return payload, f"{count_ip} fallos de ConsoleLogin desde {source_ip} en 5 minutos." @@ -409,15 +423,26 @@ def analyze_cloudtrail(event_json: dict, config: dict): target_policy_arn = request_params.get("policyArn") or request_params.get("policyDocument", "") window = current_window(5) count = increment_counter(f"privilege_escalation#{username}#window#{window}", ttl_seconds=900) + severity_basis = ( + f"CRITICAL: Acción IAM crítica '{event_name}' ejecutada por " + f"la identidad '{username}' desde {source_ip}." + ) payload = { "incident_type": "PRIVILEGE_ESCALATION", "severity": "CRITICAL", "sourceIPAddress": source_ip, "affectedResource": affected_iam_user(event_json, username), + "affected_service": "AWS Identity and Access Management (IAM)", + "asset_name": f"IAM Principal ({username})", + "asset_type": "IAM Identity", + "severity_basis": severity_basis, "s3_log_key": "pending", - "timestamp": event_json.get("eventTime", utc_now()), + "timestamp": event_json.get("eventTime", ecuador_now()), + "timestamp_utc": event_json.get("eventTime", utc_now()), + "timezone": "America/Guayaquil", "event_count": count, "suspicious_actions": [event_name], + "mitigation_playbooks": ["notify-alert", "revoke-credentials"], } if target_policy_arn: payload["target_policy_arn"] = str(target_policy_arn)[:500] @@ -430,16 +455,27 @@ def analyze_cloudtrail(event_json: dict, config: dict): if event_name in credential_leak_events and identity_type in {"IAMUser", "AssumedRole"}: if source_ip != "unknown" and not ip_in_cidrs(source_ip, allowed_ips): if mark_alert_once(f"CREDENTIAL_LEAK#{username}#{source_ip}#{current_window(5)}", ttl_seconds=900): + severity_basis = ( + f"CRITICAL: Credenciales de '{username}' utilizadas desde IP no autorizada " + f"{source_ip} (Región: {aws_region}, API: {event_name})." + ) payload = { "incident_type": "CREDENTIAL_LEAK", "severity": "CRITICAL", "sourceIPAddress": source_ip, "affectedResource": affected_iam_user(event_json, username), + "affected_service": f"AWS IAM / {event_source}", + "asset_name": f"IAM User ({username})", + "asset_type": "IAM Credentials", + "severity_basis": severity_basis, "s3_log_key": "pending", - "timestamp": event_json.get("eventTime", utc_now()), + "timestamp": event_json.get("eventTime", ecuador_now()), + "timestamp_utc": event_json.get("eventTime", utc_now()), + "timezone": "America/Guayaquil", "event_count": 1, "service_accessed": event_source, "unusual_region": aws_region, + "mitigation_playbooks": ["notify-alert", "revoke-credentials"], } return payload, f"Credenciales de {username} usadas desde IP no autorizada {source_ip}." @@ -451,18 +487,29 @@ def analyze_cloudtrail(event_json: dict, config: dict): count = increment_counter(f"exfiltration#{source_ip}#{bucket}#window#{window}", ttl_seconds=7200) threshold = int(thresholds.get("s3_getobject_exfiltration_count_1h", 50)) if count >= threshold and mark_alert_once(f"EXFILTRATION#{source_ip}#{bucket}#{window}", ttl_seconds=7200): + severity_basis = ( + f"HIGH: Descarga masiva no autorizada detectada ({count} operaciones GetObject en 1 hora, " + f"umbral={threshold}) sobre el bucket '{bucket}' desde {source_ip}." + ) payload = { "incident_type": "EXFILTRATION", "severity": "HIGH", "sourceIPAddress": source_ip, "affectedResource": f"s3:::{bucket}" if bucket else f"ec2:instance/{PORTAL_INSTANCE_ID}", + "affected_service": "Amazon Simple Storage Service (S3)", + "asset_name": f"S3 Bucket ({bucket})", + "asset_type": "Cloud Storage Data", + "severity_basis": severity_basis, "s3_log_key": "pending", - "timestamp": event_json.get("eventTime", utc_now()), + "timestamp": event_json.get("eventTime", ecuador_now()), + "timestamp_utc": event_json.get("eventTime", utc_now()), + "timezone": "America/Guayaquil", "event_count": count, "total_downloads": count, "affected_bucket": bucket or "unknown", "first_access": "tracked_in_detection_window", - "last_access": event_json.get("eventTime", utc_now()), + "last_access": event_json.get("eventTime", ecuador_now()), + "mitigation_playbooks": ["notify-alert"], } return payload, f"{count} operaciones GetObject desde {source_ip} sobre bucket {bucket} en 1 hora." @@ -516,16 +563,27 @@ def analyze_flow_log(message: str, config: dict): rejected_count = increment_counter(f"portscan_rejects#{srcaddr}#window#{window}", ttl_seconds=900) if distinct_count >= threshold and mark_alert_once(f"PORT_SCAN#{srcaddr}#{window}"): + severity_basis = ( + f"MEDIUM: La IP {srcaddr} sondeó {distinct_count} puertos distintos " + f"con paquetes REJECT en VPC Flow Logs en 5 minutos (umbral={threshold})." + ) payload = { "incident_type": "PORT_SCAN", "severity": "MEDIUM", "sourceIPAddress": srcaddr, "affectedResource": f"vpc/{VPC_ID}", + "affected_service": "Amazon VPC / Network Security", + "asset_name": f"VPC-{VPC_ID} (Portal Instance: {PORTAL_INSTANCE_ID})", + "asset_type": "VPC Network Boundary", + "severity_basis": severity_basis, "s3_log_key": "pending", - "timestamp": utc_now(), + "timestamp": ecuador_now(), + "timestamp_utc": utc_now(), + "timezone": "America/Guayaquil", "event_count": rejected_count, "rejected_connections": rejected_count, "scanned_ports_count": distinct_count, + "mitigation_playbooks": ["notify-alert", "block-ip"], } return payload, f"Posible escaneo: {distinct_count} puertos distintos rechazados desde {srcaddr} en 5 minutos.", flow return None diff --git a/terraform-tesis-ir-secure-portal/lambda_playbook_block_ip.zip b/terraform-tesis-ir-secure-portal/lambda_playbook_block_ip.zip deleted file mode 100644 index 82e837bfda1f6411f00b987ee94daf776536c44f..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3367 zcmV+?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PD9mPg76Ma^V7-F zBt}hHQf_t<$R2Zzc5mwIlAaKgxNA9Oo8|<0FF$uJv6Fnr^2k5eX6x{|akb=Vj@~~4 z00960P)i30@UTrHp$q^3vnBulP)h*<6ay3h2mlBG001G1@UTrHp$q^3vnBul3IG5A x0000000000q=5hc003xVZe(m_axQRrP)h{{000000RRC2H~;_u*$e;x006-ye6j!l diff --git a/terraform-tesis-ir-secure-portal/lambda_playbook_notify_alert.zip b/terraform-tesis-ir-secure-portal/lambda_playbook_notify_alert.zip deleted file mode 100644 index 018b52bfc14aeb1f5ab0509f6ed453f8d0549e41..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1996 zcmV;-2Q&CkO9KQH00;mG0000XiU0rr0000000000015yA0BB)uWNc+}E^v9gSnrP8 zxDo%Zrx>swA{85L+HHYCfD1UbcI#$iyOuZiXKM(wGTj*M?aE&Wk&obZisYC~(G#f{@Au3%8U_({f)YnLdli07yqIG5ZI&vBw@6b~0u zsGk7{bhMn#B;(?y!;WM zi)A>DC)1JfZ5c0rn1>Mz;NTbw#V90K<&Z(d(P%hr1{RYKll$;4jKgR& zydN$nvqm;rgvRV-cpu+~!*}&?`2FqVez~YskB;M{xB)Ic$Cwl}71H(K^-_ccaSU8qwvv@upxPPgpN)HuY_KB^_M(CcA6lPF|@G0QK^ zWJQztFij;Y)x}9H#TPuJn++x!(?zAyn-JwQt8tfsai!A*Ql(JC#hh4C%;~NNSyRQ- zWk{X+*y?m)DeBS>s{627G}LG5$OTU;Ob614`WST+KjHqecQC;}D|o?qM+*563Y4E?U8Bh{6w{9SGo1hkUH|vU$jW!0+MDZ?0PQmMj-$ z<4o$~3j#QFioI=NLnh;{Hgxn^+SLw~rm29|V_dUE-Bqm5*0y4&ZMLF#eICVR4l~KN z$UF1Y)!vsW0Ud*!==^h4_u=tsvsd7tmr4=JJTkUWp zp4Z^;OM-bxa{RwXv*{QUkzy#NkU*6Ycju_w_Gz9YPu)Y^tOFqGiRC$_B@3WRa1y|V zF#b$4md0j=01o&iIg+E-v1t;+c!5qc+CP$v?=PH457T$k*>_WNGRZbQJQvzz^d&;^ zKL%KERpj{J1l7)2l7JJy2^{`|}@ z_!AeO`I()wV?Jovxx@j!WvDs!FBv*c+0Q9=59d!cC|L$}7sy2E9NTtgPu?t+A3-hvPHd6D2#(LYJ?dWw6b@ zgFd!L&D-GPg*JFsP?=KMx|N%gsl1y1MqRMo2n~ZBz=j-p*WKgwp$YL-E5uhG2x&hM z_~zfAT+jcAUyi;x0ZC(3-S~N-W3m2(iFP~5d|M<>s0Y0pc{kzja6fp$eRuG!NcRJK zl&8fmSLLPh3K%z@4gPoq$WpC)=h3n-$#{r>v zp0R{#Cit}t=A`RgSjKtz-9|RI)(p37ouOUGX#{ST;g+7h)(D{IA8SteDr~0gN<1EH zWRI`vM)7KOT%G9o8J7pQ2K1ZutJTpvtx4%T@2&SFo2u2400QVFC z08mQ-0u%!j00;mG0000Xil&|A2u2400QVFC015yA00000000000HlEc0001JVQyq> eWpXZXc~DCQ1^@s60096205|{u0DcDm0000`ro;vS diff --git a/terraform-tesis-ir-secure-portal/lambda_playbook_revoke_credentials.zip b/terraform-tesis-ir-secure-portal/lambda_playbook_revoke_credentials.zip deleted file mode 100644 index 27a91b3c48755642647fc9e3e3a6725a9d4a7d4a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2747 zcmV;s3Pkl#O9KQH00;mG0000XiU0rr0000000000015yA0BB)uWNc+}E^v9YIo)m> zH`e#_6bJk+tSRitkNfQ|1gOANo@TYNWy4b1Z4F~U504y1BXUA=oT!3;UiEsh=xg+9 zA0cm&Cs~m5Ka!oe=}v@LA`j31IXveKA;h~#>H0>>$vkH|zgiIDgJAAkLq6$Til zKn+c(FzD2gP)0p~=LNDXH*u~}#hFZbvL29Vh3XbXvOYnv4%5`)a>y$7jWjfca@Vu! z=BrF918=kx)px0@Z+Xs{w@`8gmTSXT2<1-oyV(6%3gluTtKFZZz=>E$uR?Sqj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TTx(&j={2#-($Z)`eoYNs}%C>-JZaAskzEBG^SQ_olFMxn{_YLgnKH{)??vIhRVX&|2Y4o#;u)h%x(^2t);FF z)p=ssP-=+`V1qB&_Vpcz4#jm`-*{sQ@gPcY0(??!cr(A~X7uUC#dI2bgofVn405J3hcsk)R4HWOD$a(}b#xljrN6KL#)BY3o8ZCz#yh zHs*WKTWqZ6DvX?bv^8!ogk(daV{v=+t#zlp} z@i-h!S}ZF;LHjR&qQE7EO2F^)={;n+V)7EanR)K({fu9n zXbBxR$a5fEWZc<)+Snj*0y@MxuF_HI@bBX}-qTV3(Vv0~Z^n;jC35mOx*gAw5nPX9 zKK}UUY;rxihS6X1C+NX^{AuhL2CzA-?j?C)@EJ9?>x)acxS4#sxrnw0r^N0eLjpg- z&+pEktb^GVw>K=@Dp}NuJ)gDRj+rybWz*O@kiZ_bMN@qBE7%`^Nm^T>AFsrnYFv{JB zs^iiLN^|!d*$iv=H&CxMx2U;T@2%f%mo+WpXZXc~DCQ1^@s60096205|{u K0Ad9I0002NZKX5- diff --git a/terraform-tesis-ir-secure-portal/main.tf b/terraform-tesis-ir-secure-portal/main.tf index 60da5e0..d8161e3 100644 --- a/terraform-tesis-ir-secure-portal/main.tf +++ b/terraform-tesis-ir-secure-portal/main.tf @@ -927,12 +927,32 @@ resource "aws_sns_topic" "alerts" { name = "${var.project_name}-incident-alerts" } -resource "aws_sns_topic_subscription" "email" { - count = var.alert_email != "" ? 1 : 0 +# Suscripcion de correo gestionada directamente via SES HTML Card (evita correos duplicados en texto plano) +# Si deseas reactivar el correo de texto plano de SNS, descomenta este bloque: +# resource "aws_sns_topic_subscription" "email" { +# count = var.alert_email != "" ? 1 : 0 +# topic_arn = aws_sns_topic.alerts.arn +# protocol = "email" +# endpoint = var.alert_email +# } - topic_arn = aws_sns_topic.alerts.arn - protocol = "email" - endpoint = var.alert_email +resource "aws_ses_email_identity" "alert" { + count = var.alert_email != "" ? 1 : 0 + email = var.alert_email +} + +# ----------------------------------------------------------------------------- +# Amazon SES: Identidad de Dominio y Firma Digital DKIM (soc.bryan-bano.com) +# ----------------------------------------------------------------------------- + +resource "aws_ses_domain_identity" "soc" { + count = var.ses_domain != "" ? 1 : 0 + domain = var.ses_domain +} + +resource "aws_ses_domain_dkim" "soc" { + count = var.ses_domain != "" ? 1 : 0 + domain = aws_ses_domain_identity.soc[0].domain } # ----------------------------------------------------------------------------- @@ -1307,6 +1327,15 @@ resource "aws_iam_role_policy" "playbook_notify" { Action = "sns:Publish" Resource = aws_sns_topic.alerts.arn }, + { + Sid = "SendSESEmail" + Effect = "Allow" + Action = [ + "ses:SendEmail", + "ses:SendRawEmail" + ] + Resource = "*" + }, { Sid = "WritePlaybookAudit" Effect = "Allow" @@ -1359,6 +1388,15 @@ resource "aws_iam_role_policy" "playbook_block_ip" { Effect = "Allow" Action = "sns:Publish" Resource = aws_sns_topic.alerts.arn + }, + { + Sid = "SendSESEmail" + Effect = "Allow" + Action = [ + "ses:SendEmail", + "ses:SendRawEmail" + ] + Resource = "*" } ] }) @@ -1378,9 +1416,11 @@ resource "aws_lambda_function" "playbook_notify" { environment { variables = { - SNS_ALERTS_ARN = aws_sns_topic.alerts.arn - EVIDENCE_BUCKET = aws_s3_bucket.evidence.bucket - RESPONSE_PREFIX = "responses/notify-alert" + SNS_ALERTS_ARN = aws_sns_topic.alerts.arn + EVIDENCE_BUCKET = aws_s3_bucket.evidence.bucket + RESPONSE_PREFIX = "responses/notify-alert" + ALERT_EMAIL = var.alert_email + SES_SENDER_EMAIL = var.ses_sender_email } } @@ -1410,12 +1450,14 @@ resource "aws_lambda_function" "playbook_block_ip" { environment { variables = { - SNS_ALERTS_ARN = aws_sns_topic.alerts.arn - EVIDENCE_BUCKET = aws_s3_bucket.evidence.bucket - TARGET_NACL_ID = aws_vpc.this.default_network_acl_id - RESPONSE_PREFIX = "responses/block-ip" - RULE_MIN = "1" - RULE_MAX = "99" + SNS_ALERTS_ARN = aws_sns_topic.alerts.arn + EVIDENCE_BUCKET = aws_s3_bucket.evidence.bucket + TARGET_NACL_ID = aws_vpc.this.default_network_acl_id + RESPONSE_PREFIX = "responses/block-ip" + RULE_MIN = "1" + RULE_MAX = "99" + ALERT_EMAIL = var.alert_email + SES_SENDER_EMAIL = var.ses_sender_email } } @@ -1522,6 +1564,15 @@ resource "aws_iam_role_policy" "playbook_revoke_credentials" { Effect = "Allow" Action = "sns:Publish" Resource = aws_sns_topic.alerts.arn + }, + { + Sid = "SendSESEmail" + Effect = "Allow" + Action = [ + "ses:SendEmail", + "ses:SendRawEmail" + ] + Resource = "*" } ] }) @@ -1541,9 +1592,11 @@ resource "aws_lambda_function" "playbook_revoke_credentials" { environment { variables = { - SNS_ALERTS_ARN = aws_sns_topic.alerts.arn - EVIDENCE_BUCKET = aws_s3_bucket.evidence.bucket - RESPONSE_PREFIX = "responses/revoke-credentials" + SNS_ALERTS_ARN = aws_sns_topic.alerts.arn + EVIDENCE_BUCKET = aws_s3_bucket.evidence.bucket + RESPONSE_PREFIX = "responses/revoke-credentials" + ALERT_EMAIL = var.alert_email + SES_SENDER_EMAIL = var.ses_sender_email } } @@ -1573,7 +1626,7 @@ resource "aws_lambda_event_source_mapping" "playbook_revoke_credentials_from_que data "archive_file" "telegram_notifier_zip" { count = var.telegram_bot_token != "" && var.telegram_chat_id != "" ? 1 : 0 type = "zip" - source_file = "${path.module}/playbooks/telegram_notifier/handler.py" + source_dir = "${path.module}/playbooks/telegram_notifier" output_path = "${path.module}/lambda_playbook_telegram_notifier.zip" } @@ -1612,8 +1665,8 @@ resource "aws_lambda_function" "telegram_notifier" { handler = "handler.lambda_handler" runtime = "python3.12" architectures = ["x86_64"] - memory_size = 128 - timeout = 15 + memory_size = 256 + timeout = 30 filename = data.archive_file.telegram_notifier_zip[0].output_path source_code_hash = data.archive_file.telegram_notifier_zip[0].output_base64sha256 diff --git a/terraform-tesis-ir-secure-portal/outputs.tf b/terraform-tesis-ir-secure-portal/outputs.tf index 8128211..ba286dc 100644 --- a/terraform-tesis-ir-secure-portal/outputs.tf +++ b/terraform-tesis-ir-secure-portal/outputs.tf @@ -115,3 +115,45 @@ output "telegram_notifier_lambda_name" { description = "Nombre de la Lambda de Telegram (si esta habilitada)." } +output "ses_subdomain" { + value = try(aws_ses_domain_identity.soc[0].domain, "") + description = "Subdominio registrado para Amazon SES." +} + +output "ses_sender_email" { + value = var.ses_sender_email + description = "Direccion del remitente firmada con DKIM para reportes de incidentes." +} + +output "cloudflare_dkim_records" { + value = var.ses_domain != "" ? [ + for token in try(aws_ses_domain_dkim.soc[0].dkim_tokens, []) : { + tipo = "CNAME" + nombre = "${token}._domainkey.soc" + contenido = "${token}.dkim.amazonses.com" + proxy_status = "DNS only (Proxy deshabilitado / Nube Gris)" + } + ] : [] + description = "Registros CNAME exactos para copiar en Cloudflare DNS para activar la Firma Digital DKIM." +} + +output "cloudflare_spf_record" { + value = var.ses_domain != "" ? { + tipo = "TXT" + nombre = "soc" + contenido = "v=spf1 include:amazonses.com ~all" + proxy_status = "DNS only" + } : null + description = "Registro SPF para autorizar el envio de correos desde Amazon SES en Cloudflare." +} + +output "cloudflare_dmarc_record" { + value = var.ses_domain != "" ? { + tipo = "TXT" + nombre = "_dmarc.soc" + contenido = "v=DMARC1; p=none;" + proxy_status = "DNS only" + } : null + description = "Registro DMARC para validar la autenticacion de correos en Cloudflare." +} + diff --git a/terraform-tesis-ir-secure-portal/playbooks/block_ip/__pycache__/handler.cpython-314.pyc b/terraform-tesis-ir-secure-portal/playbooks/block_ip/__pycache__/handler.cpython-314.pyc deleted file mode 100644 index 5af74f282ca6cac7b37f224f7e09c1b53c7d1f51..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 12609 zcmb_CYj7LKd3Sif0fGSEkE1A21Vw@pB}yXoq)1SND1y)tq%4UN0s9>10 z0F+64oaqj*w~udkzuo=z+wZY^EM@}%;a~srhc|xGLJ+@2898Y3iDy0qLCg^}ktD7V zH0dRiB>pOr3j9?jmH4Yls^F{es)y7`bt8g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9JY-1nT#{RIOMNL2B5nunS zmeFd(FRU$or{b5@PQP9KOLvvutQO2_NDEHmIjdTrcAhh+R}E@NyBbApFc@LO@PZL( z{F1#_!SdYSqa0GxL>-bxqv+)>64gZY6!;JKi<)o@y%>?M1jP5Hrx@VJyA|cwxO73h zi^_|>K?BMnHMsZ)gF_Y&ZV5#citybufKuZqLf5f$BOyM`fdQxV(W36?G#i0i_Bi)* zs6h5w{(m8YT_(w=3OlKK)h8&MCx-x8)L8sm3kuf`S*WHnWDid;U| zoz+y&DL3by*d6!U?zRCZ{?OhzXU)mkjt}kbIql}GC7-?LzUvm6x`YEmS-W@6`YXG0 zVd~zEyEpE|@5UD|E|+I3y0i9!bGjER9NCJ4S^FVWQ6tp4voN3Es&&1@U4Ap1J}lL`wW?PaQq*yjjaFx diff --git a/terraform-tesis-ir-secure-portal/playbooks/block_ip/handler.py b/terraform-tesis-ir-secure-portal/playbooks/block_ip/handler.py index 8e236db..bc8a34c 100644 --- a/terraform-tesis-ir-secure-portal/playbooks/block_ip/handler.py +++ b/terraform-tesis-ir-secure-portal/playbooks/block_ip/handler.py @@ -2,21 +2,9 @@ Playbook: block-ip Mitigacion de contención real para incidentes de red. Bloquea la IP origen creando una regla DENY inbound en la Network ACL -objetivo y registra evidencia de respuesta en S3. - -Incidentes soportados: - - BRUTE_FORCE (severity HIGH) → Incidente 1 - - PORT_SCAN (severity MEDIUM) → Incidente 2 - -Punto de cumplimiento (enforcement point): - ec2.create_network_acl_entry(RuleAction="deny", Egress=False, CidrBlock=IP/32) - Esa es la linea exacta donde el trafico de la IP atacante queda bloqueado - a nivel de red en la VPC. - - Las NACLs evaluan reglas de menor a mayor numero; el DENY se inserta con - numero < 100, por debajo del ALLOW por defecto (nro 100), por eso el bloqueo - es efectivo y no cosmetico. +objetivo, registra evidencia de respuesta en S3 y notifica via HTML Card (SES) y SNS (Telegram). """ +import html import ipaddress import json import os @@ -29,6 +17,7 @@ import boto3 s3 = boto3.client("s3") sns = boto3.client("sns") ec2 = boto3.client("ec2") +ses = boto3.client("ses") EVIDENCE_BUCKET = os.environ["EVIDENCE_BUCKET"] SNS_ARN = os.environ["SNS_ALERTS_ARN"] @@ -36,9 +25,10 @@ TARGET_NACL_ID = os.environ["TARGET_NACL_ID"] RESPONSE_PREFIX = os.environ.get("RESPONSE_PREFIX", "responses/block-ip") RULE_MIN = int(os.environ.get("RULE_MIN", "1")) RULE_MAX = int(os.environ.get("RULE_MAX", "99")) +ALERT_EMAIL = os.environ.get("ALERT_EMAIL", "") +SES_SENDER_EMAIL = os.environ.get("SES_SENDER_EMAIL") or ALERT_EMAIL EC_TZ = ZoneInfo("America/Guayaquil") -# Incidentes que activan el bloqueo de IP en NACL. BLOCK_INCIDENT_TYPES = {"BRUTE_FORCE", "PORT_SCAN"} @@ -46,8 +36,141 @@ def now_ecuador() -> str: return datetime.now(EC_TZ).isoformat() +def format_dt(dt_str: str) -> str: + if not dt_str or dt_str == "N/A": + return "N/A" + try: + dt = datetime.fromisoformat(dt_str) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=EC_TZ) + else: + dt = dt.astimezone(EC_TZ) + return dt.strftime("%Y-%m-%d %H:%M:%S (America/Guayaquil)") + except Exception: + return dt_str + + +def generate_html_card(title: str, subtitle: str, badge_text: str, badge_type: str, sections: dict, callout_label: str, callout_text: str, footer_text: str) -> str: + color_map = { + "CRITICAL": {"header": "#B71C1C", "badge_bg": "#FFEBEE", "badge_text": "#B71C1C", "border": "#EF5350"}, + "HIGH": {"header": "#E65100", "badge_bg": "#FFF3E0", "badge_text": "#E65100", "border": "#FF9800"}, + "MEDIUM": {"header": "#F57F17", "badge_bg": "#FFFDE7", "badge_text": "#F57F17", "border": "#FFEE58"}, + "LOW": {"header": "#0277BD", "badge_bg": "#E1F5FE", "badge_text": "#0277BD", "border": "#29B6F6"}, + "BLOCKED": {"header": "#B71C1C", "badge_bg": "#FFEBEE", "badge_text": "#B71C1C", "border": "#EF5350"}, + "CONTAINED": {"header": "#0D47A1", "badge_bg": "#E3F2FD", "badge_text": "#0D47A1", "border": "#42A5F5"}, + } + c = color_map.get(badge_type.upper(), {"header": "#1E293B", "badge_bg": "#F1F5F9", "badge_text": "#1E293B", "border": "#94A3B8"}) + + sections_html = "" + for sec_title, kvs in sections.items(): + rows = "" + for k, v in kvs: + rows += f""" + + {html.escape(str(k))} + {html.escape(str(v))} + """ + sections_html += f""" +
+
{html.escape(sec_title)}
+ + {rows} +
+
""" + + callout_html = "" + if callout_text: + callout_html = f""" +
+
{html.escape(callout_label)}
+
+ {html.escape(callout_text)} +
+
""" + + return f""" + + + +
+
+
{html.escape(subtitle)}
+
{html.escape(title)}
+
+
+
+ {html.escape(badge_text)} +
+ {sections_html} + {callout_html} +
+
+ {html.escape(footer_text)} +
+
+ +""" + + +def format_mitigation_html(entry: dict, enforcement: dict, key: str) -> str: + status = entry.get("status", "BLOCKED") + incident_type = entry.get("incident_type", "INCIDENT") + ip_value = entry.get("sourceIPAddress", "N/A") + timestamp = format_dt(entry.get("timestamp", "")) + nacl_id = enforcement.get("network_acl_id", "N/A") + rule_num = enforcement.get("rule_number", "N/A") + + return generate_html_card( + title="[MITIGACION DE SEGURIDAD AWS]", + subtitle="Network ACL Automated Containment", + badge_text=f"ACCION: {status}", + badge_type="BLOCKED" if status == "BLOCKED" else "HIGH", + sections={ + "INFORMACION GENERAL": [ + ("Estado", status), + ("Playbook", "block-ip"), + ("Tipo de Incidente", incident_type), + ("ID de Incidente", entry.get("incident_id", "N/A")), + ], + "CONTENCION APLICADA": [ + ("IP Bloqueada", f"{ip_value}/32"), + ("Network ACL", nacl_id), + ("Regla Inbound", f"#{rule_num} (DENY All Traffic)"), + ("Enforcement", "Bloqueo perimetral a nivel de subred en VPC"), + ], + "TRAZABILIDAD": [ + ("Hora Mitigacion", timestamp), + ("Evidencia S3", key), + ] + }, + callout_label="DETALLES DE MITIGACION", + callout_text=f"Trafico de entrada proveniente de la IP atacante {ip_value} bloqueado permanentemente mediante regla DENY #{rule_num} en la Network ACL {nacl_id}.", + footer_text="AWS Automated Incident Response System | Tesis IR" + ) + + +def send_ses_email(subject: str, html_body: str, plain_body: str) -> None: + if not ALERT_EMAIL: + return + sender = SES_SENDER_EMAIL or ALERT_EMAIL + try: + ses.send_email( + Source=f"AWS Security SOC <{sender}>", + Destination={"ToAddresses": [ALERT_EMAIL]}, + Message={ + "Subject": {"Data": subject, "Charset": "UTF-8"}, + "Body": { + "Html": {"Data": html_body, "Charset": "UTF-8"}, + "Text": {"Data": plain_body, "Charset": "UTF-8"}, + } + } + ) + print(f"[SES] Correo HTML de mitigacion enviado a {ALERT_EMAIL} desde {sender}") + except Exception as exc: + print(f"[SES] Envio SES no disponible ({exc}). Se mantiene envio via SNS.") + + def valid_public_ip(ip_value: str) -> bool: - """Verifica que la IP sea publica y valida antes de aplicar el bloqueo.""" try: ip = ipaddress.ip_address(ip_value) except ValueError: @@ -59,7 +182,6 @@ def valid_public_ip(ip_value: str) -> bool: def next_rule_number(nacl_id: str) -> int: - """Calcula el siguiente numero de regla libre en el rango DENY (1-99).""" response = ec2.describe_network_acls(NetworkAclIds=[nacl_id]) used = set() for entry in response.get("NetworkAcls", [{}])[0].get("Entries", []): @@ -72,10 +194,6 @@ def next_rule_number(nacl_id: str) -> int: def block_ip(ip_value: str) -> dict: - """ - ENFORCEMENT POINT: crea la regla DENY en la NACL. - Es idempotente: si el DENY ya existe devuelve already_present=True. - """ cidr = f"{ip_value}/32" response = ec2.describe_network_acls(NetworkAclIds=[TARGET_NACL_ID]) entries = response.get("NetworkAcls", [{}])[0].get("Entries", []) @@ -93,13 +211,12 @@ def block_ip(ip_value: str) -> dict: } rule_number = next_rule_number(TARGET_NACL_ID) - # ← línea exacta del bloqueo real a nivel de red ec2.create_network_acl_entry( NetworkAclId=TARGET_NACL_ID, RuleNumber=rule_number, - Protocol="-1", # todos los protocolos + Protocol="-1", RuleAction="deny", - Egress=False, # tráfico de entrada (desde el atacante) + Egress=False, CidrBlock=cidr, ) print(f"[block-ip] NACL {TARGET_NACL_ID}: regla DENY #{rule_number} creada para {cidr}") @@ -141,7 +258,6 @@ def lambda_handler(event, context): incident_type = body.get("incident_type", "UNKNOWN") - # Solo procesar incidentes de red que requieren bloqueo de IP if incident_type not in BLOCK_INCIDENT_TYPES: print(f"[block-ip] Tipo {incident_type} no requiere bloqueo de IP. Omitiendo.") results.append({"status": "skipped", "reason": f"not_in_block_list:{incident_type}"}) @@ -187,7 +303,6 @@ def lambda_handler(event, context): "incident_id": body.get("incident_id", ""), } - # Campos extra según el tipo de incidente if incident_type == "PORT_SCAN": entry["scanned_ports_count"] = body.get("scanned_ports_count", body.get("event_count", 0)) @@ -196,7 +311,7 @@ def lambda_handler(event, context): entry["failed_attempts"] = body.get("failed_attempts", body.get("event_count", 0)) - # ── Actualizar lista de IPs bloqueadas (blocklist acumulativo) ───── + # ── Actualizar lista de IPs bloqueadas ──────────────────────────── blocklist = load_blocklist() if not any(item.get("sourceIPAddress") == ip_value for item in blocklist): blocklist.append(entry) @@ -211,28 +326,43 @@ def lambda_handler(event, context): ContentType="application/json", ) - # ── Notificar al equipo via SNS ──────────────────────────────────── + # ── Generar reportes ─────────────────────────────────────────────── subject = f"[{entry['severity']}] Mitigacion: IP {ip_value} {status} en NACL" - mitigation_report = f""" -[MITIGACION DE SEGURIDAD AWS] - ACCION: {status} -================================================== -Playbook : block-ip -Tipo de Incidente : {incident_type} -ID de Incidente : {entry['incident_id']} -Estado : {status} --------------------------------------------------- -IP Objetivo : {ip_value} -Network ACL : {enforcement.get('network_acl_id', 'N/A')} -Regla Creada : #{enforcement.get('rule_number', 'N/A')} --------------------------------------------------- -Hora Mitigacion : {timestamp} -Evidencia S3 : {key} -================================================== -""".strip() + formatted_time = format_dt(timestamp) + nacl_id = enforcement.get('network_acl_id', 'N/A') + rule_num = enforcement.get('rule_number', 'N/A') + + mitigation_plain = "\n".join([ + "=" * 60, + f"[MITIGACION DE SEGURIDAD AWS] - ACCION: {status}", + "=" * 60, + "INFORMACION GENERAL:", + f" Estado : {status}", + f" Playbook : block-ip", + f" Tipo de Incidente : {incident_type}", + f" ID de Incidente : {entry['incident_id']}", + "", + "CONTENCION APLICADA:", + f" IP Bloqueada : {ip_value}/32", + f" Network ACL : {nacl_id}", + f" Regla Inbound : #{rule_num} (DENY All Traffic)", + " Enforcement : Bloqueo perimetral a nivel de subred en VPC", + "", + "TRAZABILIDAD:", + f" Hora Mitigacion : {formatted_time}", + f" Evidencia S3 : {key}", + "=" * 60, + ]) + mitigation_html = format_mitigation_html(entry, enforcement, key) + + # ── Envio directo de correo HTML via SES ─────────────────────────── + send_ses_email(subject, mitigation_html, mitigation_plain) + + # ── Publicar reporte en SNS ──────────────────────────────────────── sns.publish( TopicArn=SNS_ARN, Subject=subject[:100], - Message=mitigation_report, + Message=mitigation_plain, ) print(f"[block-ip] {incident_type} → {status} para {ip_value}. " diff --git a/terraform-tesis-ir-secure-portal/playbooks/notify_alert/__pycache__/handler.cpython-314.pyc b/terraform-tesis-ir-secure-portal/playbooks/notify_alert/__pycache__/handler.cpython-314.pyc deleted file mode 100644 index 54292b3011c27a2a1eaaade02da64cdf20dbcc64..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6593 zcmb7IYit|Yb-u&r@GVNz!`5qL`60?SBb(Yd-Zw`_VptrfT?j5^q0PJ#Xb z^Nf&B3mHDI@G_I( zLCkYmCybN%jiMxExC~R^0LW*V#PS@o#biaMP+ZRf8-~j=idYcRB9n+En29F`>jHGaP(fD6ba%-v z(tLF4F6XLAuFR4x@kJ|*9c{RHiX`%Zc~_Ag`RqvBKKzc0~w>)Bwi^>d04&~ zb_s>8eljxQd_Ws3G_KZI4y#}7)NL-GfjbTrwlp`(a(P%Q90bcs@!Og;GRG!A)Et5=)_3}IB>4d?`5@C=0Acxbk;{mZ)DIK}{xbOz%jkux=i&Lk zJ^%OCs%zxAYvOa)MAbE^S|;`3Z`=l1qQ0dQ`oM3#4QyI%Zgk273pPtG7^YeEla}02 z51KR!d?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8anLYd_i1D4)#gM$Wd9yZo&ByIS?w}<-~Gq9waQoM=o!(ov)5(JQ}1xbJ_GiUjH(4|@7wF51Cnq0y?Mf#8o0(mDNgfvSU zX8vBf?yC~*shNpi2`5!Qd3cx*d1uL3nZz6pxBSeykLk@q6fDEBjc||jEdWK~FYkh@ zQ${s!S9$SecmLzyC&5Z|TYBC-dEd5YvN(EQ^z=WT{dBf+>&Kfv+T7{e4OB2HMsoBOpU!yy>t&WSPnJ%caJ{Vss^K^dkMOS42EZG zM^EkMcG=IC)L@+S;mSHM^)>fxdu#5%wzJlnWml>)vjA(% zI{d^`WzOv#>hU}8TVEeT-D7Ik*tUQBChiF#Q@t8Uu`*r4DHvf6^SJ~$m zVxM1#sRx#y7FF-cee(<2`Ox#g^P=ZKt*hsSzxVO}Pxn_MJ7Z4{J@dc!+`ss_fAOik z>W|k3Cifi3(f1lz9nQTj)Z6!nuU!73?}*wvvE$MAb@8*JdX@cR@gsGCQ@M4uJAL2& zqVE{I2>NF3yZ(cAJ#;;Az33gP1qLhgKZGa6=$;)p0$5C4_be7&mOg??Jr+q56)r%qSR(ESyb47{oY8FQEX14@{p+tQ z3p<~`D@bBq+8{%Ty3nuY3)08X0lqzw zKZR`1Oi|RACM#um48Pwa_e-1WZ?fOZJ~~yk?JJvWjn>JkZJ=y= z*&TR1`N^a@eEf^!Y^Ks~tkUBQ4p1e}+zFPMEwtK%i7^(um`d=2? bkV!=Yf9!_9@E>UiPQJcOy+=_tea-(17*6A9 diff --git a/terraform-tesis-ir-secure-portal/playbooks/notify_alert/handler.py b/terraform-tesis-ir-secure-portal/playbooks/notify_alert/handler.py index 0abad88..e19b496 100644 --- a/terraform-tesis-ir-secure-portal/playbooks/notify_alert/handler.py +++ b/terraform-tesis-ir-secure-portal/playbooks/notify_alert/handler.py @@ -1,9 +1,10 @@ """ Playbook: notify-alert Recibe incidentes desde una cola SQS dedicada, genera un reporte profesional -de seguridad para el SOC y lo publica al topico SNS (para entrega simultanea -y formateada en Gmail y Telegram). Tambien registra evidencia en S3. +de seguridad para el SOC (formato tarjeta HTML con colores diferenciados y texto plano normalizado) +y lo entrega via SES a Gmail y via SNS a Telegram. Tambien registra evidencia en S3. """ +import html import json import os import uuid @@ -14,10 +15,13 @@ import boto3 sns = boto3.client("sns") s3 = boto3.client("s3") +ses = boto3.client("ses") SNS_ARN = os.environ["SNS_ALERTS_ARN"] EVIDENCE_BUCKET = os.environ["EVIDENCE_BUCKET"] RESPONSE_PREFIX = os.environ.get("RESPONSE_PREFIX", "responses/notify-alert") +ALERT_EMAIL = os.environ.get("ALERT_EMAIL", "") +SES_SENDER_EMAIL = os.environ.get("SES_SENDER_EMAIL") or ALERT_EMAIL EC_TZ = ZoneInfo("America/Guayaquil") SUPPORTED_INCIDENT_TYPES = { @@ -33,8 +37,84 @@ def now_ecuador() -> str: return datetime.now(EC_TZ).isoformat() +def format_dt(dt_str: str) -> str: + if not dt_str or dt_str == "N/A": + return "N/A" + try: + dt = datetime.fromisoformat(dt_str) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=EC_TZ) + else: + dt = dt.astimezone(EC_TZ) + return dt.strftime("%Y-%m-%d %H:%M:%S (America/Guayaquil)") + except Exception: + return dt_str + + +def generate_html_card(title: str, subtitle: str, badge_text: str, badge_type: str, sections: dict, callout_label: str, callout_text: str, footer_text: str) -> str: + color_map = { + "CRITICAL": {"header": "#B71C1C", "badge_bg": "#FFEBEE", "badge_text": "#B71C1C", "border": "#EF5350"}, + "HIGH": {"header": "#E65100", "badge_bg": "#FFF3E0", "badge_text": "#E65100", "border": "#FF9800"}, + "MEDIUM": {"header": "#F57F17", "badge_bg": "#FFFDE7", "badge_text": "#F57F17", "border": "#FFEE58"}, + "LOW": {"header": "#0277BD", "badge_bg": "#E1F5FE", "badge_text": "#0277BD", "border": "#29B6F6"}, + "BLOCKED": {"header": "#B71C1C", "badge_bg": "#FFEBEE", "badge_text": "#B71C1C", "border": "#EF5350"}, + "CONTAINED": {"header": "#0D47A1", "badge_bg": "#E3F2FD", "badge_text": "#0D47A1", "border": "#42A5F5"}, + } + c = color_map.get(badge_type.upper(), {"header": "#1E293B", "badge_bg": "#F1F5F9", "badge_text": "#1E293B", "border": "#94A3B8"}) + + sections_html = "" + for sec_title, kvs in sections.items(): + rows = "" + for k, v in kvs: + rows += f""" + + {html.escape(str(k))} + {html.escape(str(v))} + """ + sections_html += f""" +
+
{html.escape(sec_title)}
+ + {rows} +
+
""" + + callout_html = "" + if callout_text: + callout_html = f""" +
+
{html.escape(callout_label)}
+
+ {html.escape(callout_text)} +
+
""" + + return f""" + + + +
+
+
{html.escape(subtitle)}
+
{html.escape(title)}
+
+
+
+ {html.escape(badge_text)} +
+ {sections_html} + {callout_html} +
+
+ {html.escape(footer_text)} +
+
+ +""" + + def format_incident_report(alert: dict) -> str: - """Genera un reporte profesional de seguridad (SOC) en texto plano para correo y Telegram.""" + """Genera un reporte profesional de seguridad (SOC) estructurado y normalizado en texto plano.""" incident_type = alert.get("incident_type", "NO_ESPECIFICADO") severity = alert.get("severity", "MEDIUM") status = alert.get("status", "NOTIFICADO") @@ -44,32 +124,103 @@ def format_incident_report(alert: dict) -> str: service = alert.get("affected_service", "N/A") asset = alert.get("asset_name", "N/A") basis = alert.get("severity_basis", "N/A") - detected_at = alert.get("detectedAt", "N/A") - responded_at = alert.get("respondedAt", "N/A") + detected_at = format_dt(alert.get("detectedAt", "N/A")) + responded_at = format_dt(alert.get("respondedAt", "N/A")) s3_key = alert.get("s3_log_key", "N/A") lines = [ - f"[ALERTA DE SEGURIDAD AWS] - SEVERIDAD: {severity}", - "=" * 50, - f"Tipo de Incidente : {incident_type}", - f"ID de Incidente : {incident_id}", - f"Estado : {status}", - f"Playbook : notify-alert", - "-" * 50, - f"IP Origen : {source_ip}", - f"Recurso Afectado : {resource}", - f"Servicio Afectado : {service}", - f"Activo Objetivo : {asset}", - "-" * 50, - f"Criterio / Motivo : {basis}", - f"Hora Deteccion : {detected_at}", - f"Hora Respuesta : {responded_at}", - f"Evidencia S3 : {s3_key}", - "=" * 50, + "=" * 60, + "[ALERTA DE SEGURIDAD AWS] - SOC INCIDENT RESPONSE", + "=" * 60, + "INFORMACION GENERAL:", + f" Severidad : {severity}", + f" Tipo de Incidente : {incident_type}", + f" ID de Incidente : {incident_id}", + f" Estado : {status}", + f" Playbook : notify-alert", + "", + "RECURSO Y ORIGEN:", + f" IP Origen : {source_ip}", + f" Recurso Afectado : {resource}", + f" Servicio Afectado : {service}", + f" Activo Objetivo : {asset}", + "", + "CRITERIO Y DIAGNOSTICO:", + f" Criterio / Motivo : {basis}", + f" Hora Deteccion : {detected_at}", + f" Hora Respuesta : {responded_at}", + f" Evidencia S3 : {s3_key}", + "=" * 60, ] return "\n".join(lines) +def format_incident_html(alert: dict) -> str: + """Genera la tarjeta visual HTML con colores diferenciados según la severidad.""" + incident_type = alert.get("incident_type", "NO_ESPECIFICADO") + severity = alert.get("severity", "MEDIUM") + status = alert.get("status", "NOTIFICADO") + incident_id = alert.get("incident_id", "N/A") + source_ip = alert.get("sourceIPAddress", "N/A") + resource = alert.get("affectedResource", "N/A") + service = alert.get("affected_service", "N/A") + asset = alert.get("asset_name", "N/A") + basis = alert.get("severity_basis", "N/A") + detected_at = format_dt(alert.get("detectedAt", "N/A")) + responded_at = format_dt(alert.get("respondedAt", "N/A")) + s3_key = alert.get("s3_log_key", "N/A") + + return generate_html_card( + title="[ALERTA DE SEGURIDAD AWS]", + subtitle="SOC Automated Incident Response", + badge_text=f"SEVERIDAD: {severity}", + badge_type=severity, + sections={ + "INFORMACION GENERAL": [ + ("Tipo de Incidente", incident_type), + ("ID de Incidente", incident_id), + ("Estado", status), + ("Playbook", "notify-alert"), + ], + "RECURSO Y ORIGEN": [ + ("IP Origen", source_ip), + ("Recurso Afectado", resource), + ("Servicio Afectado", service), + ("Activo Objetivo", asset), + ], + "TRAZABILIDAD": [ + ("Hora Deteccion", detected_at), + ("Hora Respuesta", responded_at), + ("Evidencia S3", s3_key), + ] + }, + callout_label="CRITERIO Y DIAGNOSTICO", + callout_text=basis, + footer_text="AWS Automated Incident Response System | Tesis IR" + ) + + +def send_ses_email(subject: str, html_body: str, plain_body: str) -> None: + if not ALERT_EMAIL: + return + sender = SES_SENDER_EMAIL or ALERT_EMAIL + try: + ses.send_email( + Source=f"AWS Security SOC <{sender}>", + Destination={"ToAddresses": [ALERT_EMAIL]}, + Message={ + "Subject": {"Data": subject, "Charset": "UTF-8"}, + "Body": { + "Html": {"Data": html_body, "Charset": "UTF-8"}, + "Text": {"Data": plain_body, "Charset": "UTF-8"}, + } + } + ) + print(f"[SES] Correo HTML enviado a {ALERT_EMAIL} desde {sender}") + except Exception as exc: + print(f"[SES] Envio SES no disponible ({exc}). Se mantiene envio via SNS.") + + def lambda_handler(event, context): results = [] @@ -116,10 +267,15 @@ def lambda_handler(event, context): ContentType="application/json", ) - # ── Publicar reporte legible en SNS (llega formateado a Gmail y Telegram) + # ── Generar reportes ─────────────────────────────────────────────── subject = f"[{alert['severity']}] Incidente: {incident_type} ({alert['affectedResource']})" report_text = format_incident_report(alert) + report_html = format_incident_html(alert) + # ── Envio directo de correo HTML via SES (si esta disponible) ────── + send_ses_email(subject, report_html, report_text) + + # ── Publicar reporte en SNS (para Telegram y subscriptores SNS) ──── sns.publish( TopicArn=SNS_ARN, Subject=subject[:100], diff --git a/terraform-tesis-ir-secure-portal/playbooks/revoke_credentials/__pycache__/handler.cpython-314.pyc b/terraform-tesis-ir-secure-portal/playbooks/revoke_credentials/__pycache__/handler.cpython-314.pyc deleted file mode 100644 index 995b1a5f211fc9b8ccd4217b57cd8e4c6bf414cb..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 9737 zcmbt4TWlLwc6a!G48^zJvPP0^iLyo7vK=e(la^?UmPJ#;u^h*enK3!GX;UP3IP_ZF z2GG8h6out%7G~NM(V~l1!J>fCEl?LNP%U;p{8MyfDiL>9ZH?|nvHfBYZIdQHJ$I-f zX<6QFwpY@9o_p^(=bn4cnRB(T!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sQ$IlO3yMN6FT@G*q&+FTGl_H7}jO&BK2+^rNBW z^N&r%o{^HR3y*Xx9V^*7mrj(ehR%jfWUyE_9mvvNIKM{rZt9SuO9VLk(y{fPGh)w~ zzuoYay`Q^?1*k z{q(y1+^YTD6MfMhE;aX;jmX%ziL^#j*@oPWi(KLSM~%IryHD&JSs7ayelq#w?vq=h zHGMPi?Q`W$WNh7}kdeG^e#^Y!ZZEmo3Zp-qD7p546dBMV4R1BzqYvWjY>8|w zjFd=sVZ3bAHk&>J?wCKB&>-i&GQ4ye?Tc4R2IsqxLemeXO9uPmW!$>@gBbuOb!Gf0 z^7-Z^4YIk`tv##Oo=v1Ox}Q@6kFPx$d2&QNHYv8zYh>i#NY|HTEdYJFIZYs23!VTP zpl{!@|0g=-Dq;OMy7Jn}`6t)KNm>j?LuDixvMfL{u- zB4qG>N)Vr@420%W2O`K{A>*%*`Cm~7{Qeq|&vfSRC%=_kJY3W@&#OvXts_NU%e?ye z)-#9eVgG}Eupb{eeDl_l(j556;hooSH6MB(c*U+k@i1L str: return datetime.now(EC_TZ).isoformat() + +def format_dt(dt_str: str) -> str: + if not dt_str or dt_str == "N/A": + return "N/A" + try: + dt = datetime.fromisoformat(dt_str) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=EC_TZ) + else: + dt = dt.astimezone(EC_TZ) + return dt.strftime("%Y-%m-%d %H:%M:%S (America/Guayaquil)") + except Exception: + return dt_str + + +def generate_html_card(title: str, subtitle: str, badge_text: str, badge_type: str, sections: dict, callout_label: str, callout_text: str, footer_text: str) -> str: + color_map = { + "CRITICAL": {"header": "#B71C1C", "badge_bg": "#FFEBEE", "badge_text": "#B71C1C", "border": "#EF5350"}, + "HIGH": {"header": "#E65100", "badge_bg": "#FFF3E0", "badge_text": "#E65100", "border": "#FF9800"}, + "MEDIUM": {"header": "#F57F17", "badge_bg": "#FFFDE7", "badge_text": "#F57F17", "border": "#FFEE58"}, + "LOW": {"header": "#0277BD", "badge_bg": "#E1F5FE", "badge_text": "#0277BD", "border": "#29B6F6"}, + "BLOCKED": {"header": "#B71C1C", "badge_bg": "#FFEBEE", "badge_text": "#B71C1C", "border": "#EF5350"}, + "CONTAINED": {"header": "#0D47A1", "badge_bg": "#E3F2FD", "badge_text": "#0D47A1", "border": "#42A5F5"}, + } + c = color_map.get(badge_type.upper(), {"header": "#1E293B", "badge_bg": "#F1F5F9", "badge_text": "#1E293B", "border": "#94A3B8"}) + + sections_html = "" + for sec_title, kvs in sections.items(): + rows = "" + for k, v in kvs: + rows += f""" + + {html.escape(str(k))} + {html.escape(str(v))} + """ + sections_html += f""" +
+
{html.escape(sec_title)}
+ + {rows} +
+
""" + + callout_html = "" + if callout_text: + callout_html = f""" +
+
{html.escape(callout_label)}
+
+ {html.escape(callout_text)} +
+
""" + + return f""" + + + +
+
+
{html.escape(subtitle)}
+
{html.escape(title)}
+
+
+
+ {html.escape(badge_text)} +
+ {sections_html} + {callout_html} +
+
+ {html.escape(footer_text)} +
+
+ +""" + + +def format_mitigation_html(entry: dict, username: str, actions_taken: list, enforcement: dict, key: str) -> str: + status = entry.get("status", "CONTAINED") + incident_type = entry.get("incident_type", "INCIDENT") + timestamp = format_dt(entry.get("timestamp", "")) + actions_str = ", ".join(actions_taken) if actions_taken else "Ninguna acción registrada" + deny_status = "EmergencyDenyAll adjuntada (Bloqueo Total)" if enforcement.get("deny_all_applied") else "No aplicada" + + return generate_html_card( + title="[MITIGACION DE SEGURIDAD AWS]", + subtitle="IAM Automated Credential Revocation", + badge_text=f"ACCION: {status}", + badge_type="CONTAINED" if status == "CONTAINED" else "CRITICAL", + sections={ + "INFORMACION GENERAL": [ + ("Estado", status), + ("Playbook", "revoke-credentials"), + ("Tipo de Incidente", incident_type), + ("ID de Incidente", entry.get("incident_id", "N/A")), + ], + "CONTENCION APLICADA": [ + ("Usuario IAM", username), + ("Acciones Tomadas", actions_str), + ("Politica DenyAll", deny_status), + ("Enforcement", "Desactivacion inmediata de credenciales y revocacion de permisos"), + ], + "TRAZABILIDAD": [ + ("Hora Mitigacion", timestamp), + ("Evidencia S3", key), + ] + }, + callout_label="DETALLES DE MITIGACION", + callout_text=f"Credenciales de acceso para el usuario IAM '{username}' revocadas. Llaves desactivadas ({enforcement.get('keys_deactivated', 0)}) y politica inline EmergencyDenyAll adjuntada.", + footer_text="AWS Automated Incident Response System | Tesis IR" + ) + + +def send_ses_email(subject: str, html_body: str, plain_body: str) -> None: + if not ALERT_EMAIL: + return + sender = SES_SENDER_EMAIL or ALERT_EMAIL + try: + ses.send_email( + Source=f"AWS Security SOC <{sender}>", + Destination={"ToAddresses": [ALERT_EMAIL]}, + Message={ + "Subject": {"Data": subject, "Charset": "UTF-8"}, + "Body": { + "Html": {"Data": html_body, "Charset": "UTF-8"}, + "Text": {"Data": plain_body, "Charset": "UTF-8"}, + } + } + ) + print(f"[SES] Correo HTML de mitigacion enviado a {ALERT_EMAIL} desde {sender}") + except Exception as exc: + print(f"[SES] Envio SES no disponible ({exc}). Se mantiene envio via SNS.") + + def load_revoke_log() -> list: try: obj = s3.get_object(Bucket=EVIDENCE_BUCKET, Key=f"{RESPONSE_PREFIX}/revoked-credentials.json") @@ -43,6 +179,7 @@ def load_revoke_log() -> list: except Exception: return [] + def save_revoke_log(revoke_log: list) -> None: s3.put_object( Bucket=EVIDENCE_BUCKET, @@ -51,6 +188,7 @@ def save_revoke_log(revoke_log: list) -> None: ContentType="application/json", ) + def lambda_handler(event, context): results = [] @@ -62,14 +200,12 @@ def lambda_handler(event, context): continue incident_type = body.get("incident_type", "UNKNOWN") - # Procesar incidentes de escalada o leak de credenciales if incident_type not in {"PRIVILEGE_ESCALATION", "CREDENTIAL_LEAK"}: print(f"[revoke-credentials] Tipo {incident_type} no requiere revocacion. Omitiendo.") results.append({"status": "skipped", "reason": f"not_in_revoke_list:{incident_type}"}) continue affected_resource = body.get("affectedResource", "") - # Extraer el usuario del formato "iam:user/nombre" username = affected_resource.replace("iam:user/", "") if affected_resource.startswith("iam:user/") else affected_resource source_ip = body.get("sourceIPAddress", "0.0.0.0") timestamp = now_ecuador() @@ -163,28 +299,43 @@ def lambda_handler(event, context): ContentType="application/json", ) - # ── 6. Notificar al equipo vía SNS ─────────────────────────────────── + # ── 6. Generar reportes ────────────────────────────────────────────── subject = f"[{entry['severity']}] Mitigacion: Credenciales {username} {status}" - mitigation_report = f""" -[MITIGACION DE SEGURIDAD AWS] - ACCION: {status} -================================================== -Playbook : revoke-credentials -Tipo de Incidente : {incident_type} -ID de Incidente : {incident_id} -Estado : {status} --------------------------------------------------- -Usuario IAM : {username} -Acciones Tomadas : {', '.join(actions_taken)} -DenyAll Aplicado : {'SI' if enforcement.get('deny_all_applied') else 'NO'} --------------------------------------------------- -Hora Mitigacion : {timestamp} -Evidencia S3 : {key} -================================================== -""".strip() + formatted_time = format_dt(timestamp) + actions_str = ", ".join(actions_taken) if actions_taken else "Ninguna acción registrada" + deny_status = "EmergencyDenyAll adjuntada (Bloqueo Total)" if enforcement.get('deny_all_applied') else "No aplicada" + + mitigation_plain = "\n".join([ + "=" * 60, + f"[MITIGACION DE SEGURIDAD AWS] - ACCION: {status}", + "=" * 60, + "INFORMACION GENERAL:", + f" Estado : {status}", + f" Playbook : revoke-credentials", + f" Tipo de Incidente : {incident_type}", + f" ID de Incidente : {incident_id}", + "", + "CONTENCION APLICADA:", + f" Usuario IAM : {username}", + f" Acciones Tomadas : {actions_str}", + f" Politica DenyAll : {deny_status}", + " Enforcement : Desactivacion inmediata de credenciales y revocacion de permisos", + "", + "TRAZABILIDAD:", + f" Hora Mitigacion : {formatted_time}", + f" Evidencia S3 : {key}", + "=" * 60, + ]) + mitigation_html = format_mitigation_html(entry, username, actions_taken, enforcement, key) + + # ── Envio directo de correo HTML via SES ─────────────────────────── + send_ses_email(subject, mitigation_html, mitigation_plain) + + # ── Publicar reporte en SNS ──────────────────────────────────────── sns.publish( TopicArn=SNS_ARN, Subject=subject[:100], - Message=mitigation_report, + Message=mitigation_plain, ) print(f"[revoke-credentials] {incident_type} → {status} para {username}. evidence={key}") diff --git a/terraform-tesis-ir-secure-portal/playbooks/telegram_notifier/__pycache__/handler.cpython-314.pyc b/terraform-tesis-ir-secure-portal/playbooks/telegram_notifier/__pycache__/handler.cpython-314.pyc deleted file mode 100644 index d2ec6984953fafab3cf794c66a5b48fc461857da..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4857 zcmb7IOKcm*8J^|x{nmq$qDQp0Y*Dl<(ov+ykzZjYTB2o1^onH~hZeiyuB3G+?sj+S zSZq-UMGwj;b|0|P9-;z0xM&VW5uip-M&JbQsjE@}*^Pk)=&3y^wTl$VrT;9SlI6A; zYG-HW|L5PCe`db#9}T))b_D5H|M>a!AG#3w8?IE7u~K;Q0Teb6jTE$qXd+4|g#I=t z2K`McM*VG4jMoe?XSI9%9rM)7)e>!>$q_@jrdYp0KVw5b8*OSww7DH+yo#N+v?Ikq z6MZOP&HvMWnOR$6nQ=h%0W!ON_PIGB~iK8+MRkoC7(meF#WJSuQm7K(|40Op*3brHY zHrKH>m%YJ*gqOIq!mM#wg|jnMyfP|~Qphz9a~5$)W1Xq^c_uT7^l0 z^Mm5L=1irSEC?8dOQj^(n#c=}+zHtR`Vw^!uY7^CUz2e&A z_Xim02C7fRuZv-#V7eRCr&VoVY1Z3K6*buXBNdnR!WqE3mo{P-(5AXgC+x*xQY2_g z-5zbFZ3zSt`!Gp6XlIBN4M}s=Y7CF>KstgFhU&Lsjsrrd(ypphB$Kt%7IQzV8EbmB zEkPtm+D&^x1ns4p#*AeR(b$Flhpm=FY#A5rbn{qcOPnE6M9z>SQ)r~3Dw-0enD5zs zRe7xaSy{vE%*ndHTimS;xTL3bp3 ztG(iuhOroWz_w_)V1Zqwzj=bMd@1lkKK^F)yws5F8kJxqo>|IpGF3a|wWCi7^~TD{ z2jrsCLUx%4R0Ft@gPIwDM9ImTMShDHMUKUXn3097*0RRSGM`;Zr6rC9(BhelobO&$ z6j2@zg&2_!R)-T5q?OQ;pyZt)nai@XoGdddo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QOeuR zdKPX3xeRw+x(aPLNRj6t+an2r_`+Z!j8B}1aDIktpP`n|kneL}JKkw`7H==A$4=ir iTJW7yQFE!W^_BaEg71uqy#F%8zX_h6JwcfD@BIh-0%b1% diff --git a/terraform-tesis-ir-secure-portal/playbooks/telegram_notifier/card_image.py b/terraform-tesis-ir-secure-portal/playbooks/telegram_notifier/card_image.py new file mode 100644 index 0000000..41f0eaa --- /dev/null +++ b/terraform-tesis-ir-secure-portal/playbooks/telegram_notifier/card_image.py @@ -0,0 +1,318 @@ +""" +Generador gráfico nativo de tarjetas de seguridad en formato PNG (Pure Python). +Dibuja tarjetas visuales con cabeceras de color según severidad/acción, +insignias (badges), tablas estructuradas de información, bloques de diagnóstico y pie de página. +No requiere dependencias externas ni bibliotecas C, funciona 100% en AWS Lambda. +""" +import io +import struct +import zlib + +# Fuente de mapa de bits 5x7 estándar para caracteres ASCII imprimibles (32 a 126) +FONT_5x7 = { + ' ': [0x00, 0x00, 0x00, 0x00, 0x00], + '!': [0x00, 0x00, 0x5F, 0x00, 0x00], + '"': [0x00, 0x07, 0x00, 0x07, 0x00], + '#': [0x14, 0x7F, 0x14, 0x7F, 0x14], + '$': [0x24, 0x2A, 0x7F, 0x2A, 0x12], + '%': [0x23, 0x13, 0x08, 0x64, 0x62], + '&': [0x36, 0x49, 0x55, 0x22, 0x50], + "'": [0x00, 0x05, 0x03, 0x00, 0x00], + '(': [0x00, 0x1C, 0x22, 0x41, 0x00], + ')': [0x00, 0x41, 0x22, 0x1C, 0x00], + '*': [0x14, 0x08, 0x3E, 0x08, 0x14], + '+': [0x08, 0x08, 0x3E, 0x08, 0x08], + ',': [0x00, 0x50, 0x30, 0x00, 0x00], + '-': [0x08, 0x08, 0x08, 0x08, 0x08], + '.': [0x00, 0x60, 0x60, 0x00, 0x00], + '/': [0x20, 0x10, 0x08, 0x04, 0x02], + '0': [0x3E, 0x51, 0x49, 0x45, 0x3E], + '1': [0x00, 0x42, 0x7F, 0x40, 0x00], + '2': [0x42, 0x61, 0x51, 0x49, 0x46], + '3': [0x21, 0x41, 0x45, 0x4B, 0x31], + '4': [0x18, 0x14, 0x12, 0x7F, 0x10], + '5': [0x27, 0x45, 0x45, 0x45, 0x39], + '6': [0x3C, 0x4A, 0x49, 0x49, 0x30], + '7': [0x01, 0x71, 0x09, 0x05, 0x03], + '8': [0x36, 0x49, 0x49, 0x49, 0x36], + '9': [0x06, 0x49, 0x49, 0x29, 0x1E], + ':': [0x00, 0x36, 0x36, 0x00, 0x00], + ';': [0x00, 0x56, 0x36, 0x00, 0x00], + '<': [0x08, 0x14, 0x22, 0x41, 0x00], + '=': [0x14, 0x14, 0x14, 0x14, 0x14], + '>': [0x00, 0x41, 0x22, 0x14, 0x08], + '?': [0x02, 0x01, 0x51, 0x09, 0x06], + '@': [0x32, 0x49, 0x79, 0x41, 0x3E], + 'A': [0x7E, 0x11, 0x11, 0x11, 0x7E], + 'B': [0x7F, 0x49, 0x49, 0x49, 0x36], + 'C': [0x3E, 0x41, 0x41, 0x41, 0x22], + 'D': [0x7F, 0x41, 0x41, 0x22, 0x1C], + 'E': [0x7F, 0x49, 0x49, 0x49, 0x41], + 'F': [0x7F, 0x09, 0x09, 0x09, 0x01], + 'G': [0x3E, 0x41, 0x49, 0x49, 0x7A], + 'H': [0x7F, 0x08, 0x08, 0x08, 0x7F], + 'I': [0x00, 0x41, 0x7F, 0x41, 0x00], + 'J': [0x20, 0x40, 0x41, 0x3F, 0x01], + 'K': [0x7F, 0x08, 0x14, 0x22, 0x41], + 'L': [0x7F, 0x40, 0x40, 0x40, 0x40], + 'M': [0x7F, 0x02, 0x0C, 0x02, 0x7F], + 'N': [0x7F, 0x04, 0x08, 0x10, 0x7F], + 'O': [0x3E, 0x41, 0x41, 0x41, 0x3E], + 'P': [0x7F, 0x09, 0x09, 0x09, 0x06], + 'Q': [0x3E, 0x41, 0x51, 0x21, 0x5E], + 'R': [0x7F, 0x09, 0x19, 0x29, 0x46], + 'S': [0x46, 0x49, 0x49, 0x49, 0x31], + 'T': [0x01, 0x01, 0x7F, 0x01, 0x01], + 'U': [0x3F, 0x40, 0x40, 0x40, 0x3F], + 'V': [0x1F, 0x20, 0x40, 0x20, 0x1F], + 'W': [0x3F, 0x40, 0x38, 0x40, 0x3F], + 'X': [0x63, 0x14, 0x08, 0x14, 0x63], + 'Y': [0x07, 0x08, 0x70, 0x08, 0x07], + 'Z': [0x61, 0x51, 0x49, 0x45, 0x43], + '[': [0x00, 0x7F, 0x41, 0x41, 0x00], + '\\': [0x02, 0x04, 0x08, 0x10, 0x20], + ']': [0x00, 0x41, 0x41, 0x7F, 0x00], + '^': [0x04, 0x02, 0x01, 0x02, 0x04], + '_': [0x40, 0x40, 0x40, 0x40, 0x40], + '`': [0x00, 0x01, 0x02, 0x04, 0x00], + 'a': [0x20, 0x54, 0x54, 0x54, 0x78], + 'b': [0x7F, 0x48, 0x44, 0x44, 0x38], + 'c': [0x38, 0x44, 0x44, 0x44, 0x20], + 'd': [0x38, 0x44, 0x44, 0x48, 0x7F], + 'e': [0x38, 0x54, 0x54, 0x54, 0x18], + 'f': [0x08, 0x7E, 0x09, 0x01, 0x02], + 'g': [0x0C, 0x52, 0x52, 0x52, 0x3E], + 'h': [0x7F, 0x08, 0x04, 0x04, 0x78], + 'i': [0x00, 0x44, 0x7D, 0x40, 0x00], + 'j': [0x20, 0x40, 0x44, 0x3D, 0x00], + 'k': [0x7F, 0x10, 0x28, 0x44, 0x00], + 'l': [0x00, 0x41, 0x7F, 0x40, 0x00], + 'm': [0x7C, 0x04, 0x18, 0x04, 0x78], + 'n': [0x7C, 0x08, 0x04, 0x04, 0x78], + 'o': [0x38, 0x44, 0x44, 0x44, 0x38], + 'p': [0x7C, 0x14, 0x14, 0x14, 0x08], + 'q': [0x08, 0x14, 0x14, 0x18, 0x7C], + 'r': [0x7C, 0x08, 0x04, 0x04, 0x08], + 's': [0x48, 0x54, 0x54, 0x54, 0x20], + 't': [0x04, 0x3F, 0x44, 0x40, 0x20], + 'u': [0x3C, 0x40, 0x40, 0x20, 0x7C], + 'v': [0x1C, 0x20, 0x40, 0x20, 0x1C], + 'w': [0x3C, 0x40, 0x30, 0x40, 0x3C], + 'x': [0x44, 0x28, 0x10, 0x28, 0x44], + 'y': [0x0C, 0x50, 0x50, 0x50, 0x3C], + 'z': [0x44, 0x64, 0x54, 0x4C, 0x44], + '{': [0x00, 0x08, 0x36, 0x41, 0x00], + '|': [0x00, 0x00, 0x7F, 0x00, 0x00], + '}': [0x00, 0x41, 0x36, 0x08, 0x00], + '~': [0x08, 0x04, 0x08, 0x10, 0x08], +} + + +class Canvas: + def __init__(self, width: int, height: int, bg_color=(244, 246, 248)): + self.width = width + self.height = height + self.bg_color = bg_color + # Buffer de píxeles: lista plana de tuplas (R, G, B) + self.pixels = [bg_color] * (width * height) + + def set_pixel(self, x: int, y: int, color: tuple): + if 0 <= x < self.width and 0 <= y < self.height: + self.pixels[y * self.width + x] = color + + def fill_rect(self, x: int, y: int, w: int, h: int, color: tuple): + x1 = max(0, x) + y1 = max(0, y) + x2 = min(self.width, x + w) + y2 = min(self.height, y + h) + for cy in range(y1, y2): + row_start = cy * self.width + for cx in range(x1, x2): + self.pixels[row_start + cx] = color + + def draw_rect(self, x: int, y: int, w: int, h: int, border_color: tuple, border_width: int = 1): + # Top and bottom + self.fill_rect(x, y, w, border_width, border_color) + self.fill_rect(x, y + h - border_width, w, border_width, border_color) + # Left and right + self.fill_rect(x, y, border_width, h, border_color) + self.fill_rect(x + w - border_width, y, border_width, h, border_color) + + def draw_char(self, x: int, y: int, char: str, color: tuple, scale: int = 2): + glyph = FONT_5x7.get(char, FONT_5x7.get('?')) + for col_idx, col_byte in enumerate(glyph): + for row_idx in range(7): + if (col_byte >> row_idx) & 1: + px = x + col_idx * scale + py = y + row_idx * scale + self.fill_rect(px, py, scale, scale, color) + + def draw_text(self, x: int, y: int, text: str, color: tuple, scale: int = 2) -> int: + cur_x = x + char_width = 6 * scale + for char in str(text): + if char == '\n': + y += 9 * scale + cur_x = x + continue + self.draw_char(cur_x, y, char, color, scale) + cur_x += char_width + return cur_x + + def draw_text_wrapped(self, x: int, y: int, text: str, max_w: int, color: tuple, scale: int = 2) -> int: + words = str(text).split(' ') + cur_x = x + cur_y = y + char_w = 6 * scale + line_h = 9 * scale + + for word in words: + word_w = len(word) * char_w + if cur_x + word_w > x + max_w and cur_x > x: + cur_y += line_h + cur_x = x + for char in word: + self.draw_char(cur_x, cur_y, char, color, scale) + cur_x += char_w + cur_x += char_w # Space + + return cur_y + line_h + + def to_png_bytes(self) -> bytes: + raw_data = bytearray() + for y in range(self.height): + raw_data.append(0) # Filter byte 0 (None) + row_start = y * self.width + for x in range(self.width): + r, g, b = self.pixels[row_start + x] + raw_data.extend((r, g, b, 255)) # RGBA + + compressed = zlib.compress(bytes(raw_data), 1) + + out = bytearray(b'\x89PNG\r\n\x1a\n') + + # IHDR + ihdr_data = struct.pack('>IIBBBBB', self.width, self.height, 8, 6, 0, 0, 0) + out.extend(struct.pack('>I', len(ihdr_data))) + out.extend(b'IHDR') + out.extend(ihdr_data) + out.extend(struct.pack('>I', zlib.crc32(b'IHDR' + ihdr_data) & 0xffffffff)) + + # IDAT + out.extend(struct.pack('>I', len(compressed))) + out.extend(b'IDAT') + out.extend(compressed) + out.extend(struct.pack('>I', zlib.crc32(b'IDAT' + compressed) & 0xffffffff)) + + # IEND + out.extend(struct.pack('>I', 0)) + out.extend(b'IEND') + out.extend(struct.pack('>I', zlib.crc32(b'IEND') & 0xffffffff)) + + return bytes(out) + + +def hex_to_rgb(hex_str: str) -> tuple: + hex_str = hex_str.lstrip('#') + return tuple(int(hex_str[i:i+2], 16) for i in (0, 2, 4)) + + +def generate_security_card_png( + title: str, + subtitle: str, + badge_text: str, + badge_type: str, + sections: dict, + callout_label: str, + callout_text: str, + footer_text: str +) -> bytes: + """Genera la imagen PNG de la tarjeta de seguridad completa con estilo profesional.""" + color_map = { + 'CRITICAL': {'header': (183, 28, 28), 'badge_bg': (255, 235, 238), 'badge_text': (183, 28, 28), 'border': (239, 83, 80)}, + 'HIGH': {'header': (230, 81, 0), 'badge_bg': (255, 243, 224), 'badge_text': (230, 81, 0), 'border': (255, 152, 0)}, + 'MEDIUM': {'header': (245, 127, 23), 'badge_bg': (255, 253, 231), 'badge_text': (245, 127, 23), 'border': (255, 238, 88)}, + 'LOW': {'header': (2, 119, 189), 'badge_bg': (225, 245, 254), 'badge_text': (2, 119, 189), 'border': (41, 182, 246)}, + 'BLOCKED': {'header': (183, 28, 28), 'badge_bg': (255, 235, 238), 'badge_text': (183, 28, 28), 'border': (239, 83, 80)}, + 'CONTAINED': {'header': (13, 71, 161), 'badge_bg': (227, 242, 253), 'badge_text': (13, 71, 161), 'border': (66, 165, 245)}, + } + theme = color_map.get(badge_type.upper(), {'header': (30, 41, 59), 'badge_bg': (241, 245, 249), 'badge_text': (30, 41, 59), 'border': (148, 163, 184)}) + + width = 760 + # Calcular altura dinámica + num_rows = sum(len(kvs) for kvs in sections.values()) + num_secs = len(sections) + height = 140 + (num_secs * 30) + (num_rows * 24) + 120 + 50 + + canvas = Canvas(width, height, bg_color=(240, 243, 246)) + + card_x = 20 + card_y = 20 + card_w = width - 40 + card_h = height - 40 + + # Fondo de la tarjeta (Blanco) + canvas.fill_rect(card_x, card_y, card_w, card_h, (255, 255, 255)) + canvas.draw_rect(card_x, card_y, card_w, card_h, (226, 232, 240), border_width=2) + + # Cabecera de color + header_h = 64 + canvas.fill_rect(card_x, card_y, card_w, header_h, theme['header']) + canvas.draw_text(card_x + 20, card_y + 12, subtitle.upper(), (255, 255, 255), scale=1) + canvas.draw_text(card_x + 20, card_y + 28, title, (255, 255, 255), scale=2) + + cur_y = card_y + header_h + 16 + + # Badge de severidad / acción + badge_str = f" {badge_text} " + badge_w = len(badge_str) * 12 + 10 + badge_h = 22 + canvas.fill_rect(card_x + 20, cur_y, badge_w, badge_h, theme['badge_bg']) + canvas.draw_rect(card_x + 20, cur_y, badge_w, badge_h, theme['border'], border_width=1) + canvas.draw_text(card_x + 26, cur_y + 4, badge_str, theme['badge_text'], scale=2) + + cur_y += badge_h + 16 + + # Secciones + for sec_title, kvs in sections.items(): + # Título de sección + canvas.draw_text(card_x + 20, cur_y, sec_title, (51, 65, 85), scale=2) + cur_y += 18 + canvas.fill_rect(card_x + 20, cur_y, card_w - 40, 2, (226, 232, 240)) + cur_y += 8 + + # Filas clave-valor + for k, v in kvs: + # Clave + canvas.draw_text(card_x + 24, cur_y, str(k), (100, 116, 139), scale=2) + # Valor (monoespaciado oscuro) + val_str = str(v) + if len(val_str) > 40: + val_str = val_str[:37] + "..." + canvas.draw_text(card_x + 240, cur_y, val_str, (15, 23, 42), scale=2) + cur_y += 22 + cur_y += 10 + + # Bloque de Diagnóstico / Detalle + if callout_text: + canvas.draw_text(card_x + 20, cur_y, callout_label, (51, 65, 85), scale=2) + cur_y += 18 + canvas.fill_rect(card_x + 20, cur_y, card_w - 40, 2, (226, 232, 240)) + cur_y += 8 + + callout_box_h = 52 + canvas.fill_rect(card_x + 20, cur_y, card_w - 40, callout_box_h, (248, 250, 252)) + canvas.fill_rect(card_x + 20, cur_y, 6, callout_box_h, theme['border']) + canvas.draw_rect(card_x + 20, cur_y, card_w - 40, callout_box_h, (226, 232, 240), border_width=1) + + canvas.draw_text_wrapped(card_x + 36, cur_y + 10, callout_text, card_w - 70, (30, 41, 59), scale=1) + cur_y += callout_box_h + 16 + + # Pie de página + footer_h = 32 + footer_y = card_y + card_h - footer_h + canvas.fill_rect(card_x, footer_y, card_w, footer_h, (241, 245, 249)) + canvas.draw_rect(card_x, footer_y, card_w, footer_h, (226, 232, 240), border_width=1) + canvas.draw_text(card_x + 140, footer_y + 10, footer_text, (100, 116, 139), scale=1) + + return canvas.to_png_bytes() diff --git a/terraform-tesis-ir-secure-portal/playbooks/telegram_notifier/handler.py b/terraform-tesis-ir-secure-portal/playbooks/telegram_notifier/handler.py index 707706f..ce54410 100644 --- a/terraform-tesis-ir-secure-portal/playbooks/telegram_notifier/handler.py +++ b/terraform-tesis-ir-secure-portal/playbooks/telegram_notifier/handler.py @@ -1,45 +1,211 @@ """ Lambda: telegram-notifier Suscrito a Amazon SNS (Topic de alertas de seguridad). -Recibe la notificacion estructurada del topico SNS y la envia directamente -a Telegram en formato monoespaciado (
) usando la biblioteca estandar de Python.
+Recibe las notificaciones de incidentes y mitigaciones de seguridad publicadas
+en el tópico SNS, genera una tarjeta visual en formato de imagen PNG de alta resolución
+(con cabeceras de color según severidad/acción, tablas e insignias) y la entrega
+directamente al chat de Telegram mediante la API sendPhoto.
 """
+import html
 import json
 import os
 import urllib.parse
 import urllib.request
+import uuid
+
+try:
+    import card_image
+except ImportError:
+    from . import card_image
 
 TELEGRAM_BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN", "")
 TELEGRAM_CHAT_ID   = os.environ.get("TELEGRAM_CHAT_ID", "")
 
 
-def send_telegram_message(text: str) -> dict:
+def parse_key_values(raw_text: str) -> dict:
+    """Extrae pares clave-valor de reportes en texto estructurado."""
+    data = {}
+    for line in raw_text.splitlines():
+        line = line.strip()
+        if not line or line.startswith("=") or line.startswith("-") or line.startswith("━"):
+            continue
+        if ":" in line:
+            parts = line.split(":", 1)
+            k = parts[0].strip().lstrip("•").strip()
+            v = parts[1].strip()
+            data[k] = v
+    return data
+
+
+def create_incident_card_image(data: dict) -> bytes:
+    sev      = str(data.get("severity") or data.get("Severidad") or "HIGH")
+    inc_type = str(data.get("incident_type") or data.get("Tipo de Incidente") or data.get("Tipo Incidente") or "INCIDENT")
+    inc_id   = str(data.get("incident_id") or data.get("ID de Incidente") or data.get("ID Incidente") or "N/A")
+    status   = str(data.get("status") or data.get("Estado") or "NOTIFICADO")
+    playbook = str(data.get("playbook") or data.get("Playbook") or "notify-alert")
+    ip       = str(data.get("sourceIPAddress") or data.get("IP Origen") or "N/A")
+    resource = str(data.get("affectedResource") or data.get("Recurso Afectado") or data.get("Recurso") or "N/A")
+    service  = str(data.get("affected_service") or data.get("Servicio Afectado") or data.get("Servicio") or "N/A")
+    asset    = str(data.get("asset_name") or data.get("Activo Objetivo") or data.get("Activo") or "N/A")
+    basis    = str(data.get("severity_basis") or data.get("Criterio / Motivo") or data.get("Motivo") or "N/A")
+    det_time = str(data.get("detectedAt") or data.get("Hora Deteccion") or data.get("Hora Detección") or data.get("timestamp_ecuador") or data.get("timestamp") or "N/A")
+    s3_key   = str(data.get("s3_log_key") or data.get("Evidencia S3") or "N/A")
+
+    sections = {
+        "INFORMACION GENERAL": [
+            ("Tipo de Incidente", inc_type),
+            ("ID de Incidente", inc_id),
+            ("Estado", status),
+            ("Playbook", playbook),
+        ],
+        "RECURSO Y ORIGEN": [
+            ("IP Origen", ip),
+            ("Recurso Afectado", resource),
+            ("Servicio Afectado", service),
+            ("Activo Objetivo", asset),
+        ],
+        "TRAZABILIDAD": [
+            ("Hora Deteccion", det_time),
+            ("Evidencia S3", s3_key),
+        ]
+    }
+
+    return card_image.generate_security_card_png(
+        title="[ALERTA DE SEGURIDAD AWS]",
+        subtitle="SOC Automated Incident Response",
+        badge_text=f"SEVERIDAD: {sev}",
+        badge_type=sev,
+        sections=sections,
+        callout_label="CRITERIO Y DIAGNOSTICO",
+        callout_text=basis,
+        footer_text="AWS Automated Incident Response System | Tesis IR"
+    )
+
+
+def create_mitigation_card_image(raw_text: str, kv: dict) -> bytes:
+    is_block  = "block-ip" in raw_text or "IP Bloqueada" in kv or "Network ACL" in kv
+    status    = str(kv.get("Estado", "CONTAINED"))
+    playbook  = str(kv.get("Playbook", "mitigation-playbook"))
+    inc_type  = str(kv.get("Tipo de Incidente") or kv.get("Tipo Incidente") or "INCIDENT")
+    inc_id    = str(kv.get("ID de Incidente") or kv.get("ID Incidente") or "N/A")
+    exec_time = str(kv.get("Hora Mitigacion") or kv.get("Hora Ejecución") or "N/A")
+    s3_key    = str(kv.get("Evidencia S3", "N/A"))
+
+    if is_block:
+        ip      = str(kv.get("IP Bloqueada") or kv.get("IP Objetivo") or "N/A")
+        nacl    = str(kv.get("Network ACL", "N/A"))
+        regla   = str(kv.get("Regla Inbound") or kv.get("Regla Creada") or "N/A")
+        enforce = str(kv.get("Enforcement", "Bloqueo perimetral a nivel de subred en VPC"))
+
+        sections = {
+            "INFORMACION GENERAL": [
+                ("Estado", status),
+                ("Playbook", playbook),
+                ("Tipo de Incidente", inc_type),
+                ("ID de Incidente", inc_id),
+            ],
+            "CONTENCION APLICADA": [
+                ("IP Bloqueada", ip),
+                ("Network ACL", nacl),
+                ("Regla Inbound", regla),
+                ("Enforcement", enforce),
+            ],
+            "TRAZABILIDAD": [
+                ("Hora Mitigacion", exec_time),
+                ("Evidencia S3", s3_key),
+            ]
+        }
+        return card_image.generate_security_card_png(
+            title="[MITIGACION DE SEGURIDAD AWS]",
+            subtitle="Network ACL Automated Containment",
+            badge_text=f"ACCION: {status}",
+            badge_type="BLOCKED" if status == "BLOCKED" else "HIGH",
+            sections=sections,
+            callout_label="DETALLES DE MITIGACION",
+            callout_text=f"Trafico de entrada desde {ip} bloqueado permanentemente mediante regla DENY en {nacl}.",
+            footer_text="AWS Automated Incident Response System | Tesis IR"
+        )
+    else:
+        user    = str(kv.get("Usuario IAM", "N/A"))
+        actions = str(kv.get("Acciones Tomadas") or kv.get("Acciones") or "N/A")
+        deny    = str(kv.get("Politica DenyAll") or kv.get("DenyAll Policy") or "N/A")
+        enforce = str(kv.get("Enforcement", "Desactivacion inmediata de credenciales y revocacion de permisos"))
+
+        sections = {
+            "INFORMACION GENERAL": [
+                ("Estado", status),
+                ("Playbook", playbook),
+                ("Tipo de Incidente", inc_type),
+                ("ID de Incidente", inc_id),
+            ],
+            "CONTENCION APLICADA": [
+                ("Usuario IAM", user),
+                ("Acciones Tomadas", actions),
+                ("Politica DenyAll", deny),
+                ("Enforcement", enforce),
+            ],
+            "TRAZABILIDAD": [
+                ("Hora Mitigacion", exec_time),
+                ("Evidencia S3", s3_key),
+            ]
+        }
+        return card_image.generate_security_card_png(
+            title="[MITIGACION DE SEGURIDAD AWS]",
+            subtitle="IAM Automated Credential Revocation",
+            badge_text=f"ACCION: {status}",
+            badge_type="CONTAINED" if status == "CONTAINED" else "CRITICAL",
+            sections=sections,
+            callout_label="DETALLES DE MITIGACION",
+            callout_text=f"Credenciales de {user} revocadas y politica inline EmergencyDenyAll adjuntada.",
+            footer_text="AWS Automated Incident Response System | Tesis IR"
+        )
+
+
+def send_telegram_photo(png_bytes: bytes, caption: str = "") -> dict:
+    """Envía la tarjeta de imagen PNG a Telegram usando multipart/form-data."""
     if not TELEGRAM_BOT_TOKEN or not TELEGRAM_CHAT_ID:
         print("[telegram-notifier] Variables TELEGRAM_BOT_TOKEN o TELEGRAM_CHAT_ID no configuradas.")
         return {"status": "skipped", "reason": "missing_credentials"}
 
-    api_url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
-    payload = {
-        "chat_id": TELEGRAM_CHAT_ID,
-        "text": f"
{text}
", - "parse_mode": "HTML" - } + boundary = f"----WebKitFormBoundary{uuid.uuid4().hex[:16]}" + body = bytearray() - data_bytes = json.dumps(payload).encode("utf-8") + # Campo: chat_id + body.extend(f"--{boundary}\r\n".encode("utf-8")) + body.extend(b'Content-Disposition: form-data; name="chat_id"\r\n\r\n') + body.extend(f"{TELEGRAM_CHAT_ID}\r\n".encode("utf-8")) + + # Campo opcional: caption + if caption: + body.extend(f"--{boundary}\r\n".encode("utf-8")) + body.extend(b'Content-Disposition: form-data; name="caption"\r\n\r\n') + body.extend(caption.encode("utf-8")) + body.extend(b"\r\n") + + # Campo: photo (archivo PNG en memoria) + body.extend(f"--{boundary}\r\n".encode("utf-8")) + body.extend(b'Content-Disposition: form-data; name="photo"; filename="security_card.png"\r\n') + body.extend(b"Content-Type: image/png\r\n\r\n") + body.extend(png_bytes) + body.extend(b"\r\n") + + body.extend(f"--{boundary}--\r\n".encode("utf-8")) + + api_url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendPhoto" req = urllib.request.Request( api_url, - data=data_bytes, - headers={"Content-Type": "application/json"}, + data=bytes(body), + headers={"Content-Type": f"multipart/form-data; boundary={boundary}"}, method="POST" ) try: - with urllib.request.urlopen(req, timeout=10) as response: + with urllib.request.urlopen(req, timeout=12) as response: resp_body = response.read().decode("utf-8") - print(f"[telegram-notifier] Mensaje entregado a Telegram. HTTP {response.status}") + print(f"[telegram-notifier] Tarjeta de imagen enviada a Telegram. HTTP {response.status}") return {"status": "success", "response": json.loads(resp_body)} except Exception as exc: - print(f"[telegram-notifier] Error enviando mensaje a Telegram: {exc}") + print(f"[telegram-notifier] Error enviando imagen a Telegram: {exc}") return {"status": "error", "error": str(exc)} @@ -48,38 +214,42 @@ def lambda_handler(event, context): for record in event.get("Records", []): sns_record = record.get("Sns", {}) - raw_message = sns_record.get("Message", "") - - # Si el mensaje ya es texto plano formateado por notify-alert, enviarlo directo - if not raw_message.strip().startswith("{"): - send_result = send_telegram_message(raw_message.strip()) - results.append(send_result) + raw_message = sns_record.get("Message", "").strip() + + if not raw_message: continue - # Si por alguna razon llega un JSON crudo, parsearlo y formatearlo + png_bytes = None + caption = "" + try: - message_data = json.loads(raw_message) - if "incident_payload" in message_data: - message_data = message_data["incident_payload"] - - lines = [ - f"[ALERTA DE SEGURIDAD AWS] - SEVERIDAD: {message_data.get('severity', 'HIGH')}", - "=" * 50, - f"Tipo de Incidente : {message_data.get('incident_type', 'NO_ESPECIFICADO')}", - f"ID de Incidente : {message_data.get('incident_id', 'N/A')}", - f"Estado : {message_data.get('status', 'NOTIFICADO')}", - "-" * 50, - f"IP Origen : {message_data.get('sourceIPAddress', 'N/A')}", - f"Recurso Afectado : {message_data.get('affectedResource', 'N/A')}", - f"Criterio / Motivo : {message_data.get('severity_basis', 'N/A')}", - "=" * 50, - ] - formatted_text = "\n".join(lines) - send_result = send_telegram_message(formatted_text) - results.append(send_result) - except Exception: - send_result = send_telegram_message(str(raw_message)) - results.append(send_result) + if raw_message.startswith("{"): + data = json.loads(raw_message) + if "incident_payload" in data: + data = data["incident_payload"] + png_bytes = create_incident_card_image(data) + caption = f"Incidente: {data.get('incident_type', 'INCIDENT')} ({data.get('severity', 'HIGH')})" + elif "ALERTA DE SEGURIDAD AWS" in raw_message: + kv = parse_key_values(raw_message) + png_bytes = create_incident_card_image(kv) + caption = f"Alerta: {kv.get('Tipo de Incidente', 'INCIDENT')} [{kv.get('Severidad', 'HIGH')}]" + elif "MITIGACION DE SEGURIDAD AWS" in raw_message or "MITIGACIÓN DE SEGURIDAD AWS" in raw_message: + kv = parse_key_values(raw_message) + png_bytes = create_mitigation_card_image(raw_message, kv) + caption = f"Mitigacion: {kv.get('Playbook', 'block-ip')} [{kv.get('Estado', 'BLOCKED')}]" + else: + # Si es un mensaje generico, crear tarjeta generica + kv = parse_key_values(raw_message) + png_bytes = create_incident_card_image(kv) + caption = "Notificacion de Seguridad AWS" + except Exception as exc: + print(f"[telegram-notifier] Error construyendo tarjeta grafica: {exc}") + + if png_bytes: + send_res = send_telegram_photo(png_bytes, caption) + results.append(send_res) + else: + print("[telegram-notifier] No se pudo generar la tarjeta grafica PNG.") return { "status": "success", diff --git a/terraform-tesis-ir-secure-portal/terraform.tfvars.example b/terraform-tesis-ir-secure-portal/terraform.tfvars.example index 8da05ed..0b8e363 100644 --- a/terraform-tesis-ir-secure-portal/terraform.tfvars.example +++ b/terraform-tesis-ir-secure-portal/terraform.tfvars.example @@ -19,6 +19,10 @@ authorized_ip_cidrs = [] # Opcional: correo para SNS y Budget. Debes confirmar la suscripcion SNS por email. alert_email = "tu_correo@ejemplo.com" +# Subdominio para firma digital DKIM en Amazon SES (opcional) +ses_domain = "soc.tudominio.com" +ses_sender_email = "alertas@soc.tudominio.com" + # Opcional: Notificaciones a Telegram # Obtén el token con @BotFather y el chat_id con @userinfobot o @RawDataBot telegram_bot_token = "" diff --git a/terraform-tesis-ir-secure-portal/variables.tf b/terraform-tesis-ir-secure-portal/variables.tf index 940f8b8..a9fa3a7 100644 --- a/terraform-tesis-ir-secure-portal/variables.tf +++ b/terraform-tesis-ir-secure-portal/variables.tf @@ -49,6 +49,18 @@ variable "alert_email" { default = "" } +variable "ses_domain" { + description = "Subdominio o dominio registrado para firma digital DKIM en Amazon SES (ej: soc.tudominio.com)." + type = string + default = "" +} + +variable "ses_sender_email" { + description = "Direccion de remitente firmada con DKIM para el envio de reportes SOC (ej: alertas@soc.tudominio.com)." + type = string + default = "" +} + variable "create_budget" { description = "Crear un presupuesto mensual con alertas si alert_email no esta vacio." type = bool From 7c48bf12a7459a03772dd9dc1d6fddcee56a26e8 Mon Sep 17 00:00:00 2001 From: bryancito1090 Date: Tue, 1 Sep 2026 15:58:17 -0500 Subject: [PATCH 9/9] Remove obsolete SSL certificate and private key files, and delete outdated service catalog pickle file. --- .../0e26cc16-6539-4017-b372-84a9c385725a.json | 1 - Privilege Escalation/README.md | 164 -------------- Privilege Escalation/simulate_escalation.sh | 122 ----------- Scan Port/README.md | 201 ------------------ activate.sh | 17 -- docker-compose.yml | 24 --- infra/lambda-policies/base-policy.json | 58 ----- infra/setup.sh | 142 ------------- lambdas/block-ip/handler.py | 199 ----------------- lambdas/block-ip/policy.json | 23 -- lambdas/block-ip/test_event.json | 12 -- lambdas/dispatcher/handler.py | 89 -------- lambdas/dispatcher/policy.json | 32 --- lambdas/dispatcher/test_event.json | 12 -- lambdas/isolate-instance/handler.py | 192 ----------------- lambdas/isolate-instance/policy.json | 23 -- lambdas/isolate-instance/test_event.json | 12 -- lambdas/notify-alert/handler.py | 65 ------ lambdas/notify-alert/policy.json | 17 -- lambdas/notify-alert/test_event.json | 15 -- lambdas/revoke-credentials/handler.py | 160 -------------- lambdas/revoke-credentials/policy.json | 27 --- lambdas/revoke-credentials/test_event.json | 12 -- logs/sample_cloudtrail.json | 45 ---- queries/detect_brute_force.sql | 20 -- queries/detect_exfiltration.sql | 19 -- queries/detect_privilege_esc.sql | 25 --- requirements.txt | 3 - .../cloudtrail_gen.cpython-314.pyc | Bin 8488 -> 0 bytes simulators/cloudtrail_gen.py | 159 -------------- simulators/inject_logs.py | 105 --------- 31 files changed, 1995 deletions(-) delete mode 120000 .antigravitycli/0e26cc16-6539-4017-b372-84a9c385725a.json delete mode 100644 Privilege Escalation/README.md delete mode 100755 Privilege Escalation/simulate_escalation.sh delete mode 100644 Scan Port/README.md delete mode 100755 activate.sh delete mode 100644 docker-compose.yml delete mode 100644 infra/lambda-policies/base-policy.json delete mode 100755 infra/setup.sh delete mode 100644 lambdas/block-ip/handler.py delete mode 100644 lambdas/block-ip/policy.json delete mode 100644 lambdas/block-ip/test_event.json delete mode 100644 lambdas/dispatcher/handler.py delete mode 100644 lambdas/dispatcher/policy.json delete mode 100644 lambdas/dispatcher/test_event.json delete mode 100644 lambdas/isolate-instance/handler.py delete mode 100644 lambdas/isolate-instance/policy.json delete mode 100644 lambdas/isolate-instance/test_event.json delete mode 100644 lambdas/notify-alert/handler.py delete mode 100644 lambdas/notify-alert/policy.json delete mode 100644 lambdas/notify-alert/test_event.json delete mode 100644 lambdas/revoke-credentials/handler.py delete mode 100644 lambdas/revoke-credentials/policy.json delete mode 100644 lambdas/revoke-credentials/test_event.json delete mode 100644 logs/sample_cloudtrail.json delete mode 100644 queries/detect_brute_force.sql delete mode 100644 queries/detect_exfiltration.sql delete mode 100644 queries/detect_privilege_esc.sql delete mode 100644 requirements.txt delete mode 100644 simulators/__pycache__/cloudtrail_gen.cpython-314.pyc delete mode 100644 simulators/cloudtrail_gen.py delete mode 100644 simulators/inject_logs.py diff --git a/.antigravitycli/0e26cc16-6539-4017-b372-84a9c385725a.json b/.antigravitycli/0e26cc16-6539-4017-b372-84a9c385725a.json deleted file mode 120000 index 70f8f49..0000000 --- a/.antigravitycli/0e26cc16-6539-4017-b372-84a9c385725a.json +++ /dev/null @@ -1 +0,0 @@ -/home/bryan/.gemini/config/projects/0e26cc16-6539-4017-b372-84a9c385725a.json \ No newline at end of file diff --git a/Privilege Escalation/README.md b/Privilege Escalation/README.md deleted file mode 100644 index ce6cd06..0000000 --- a/Privilege Escalation/README.md +++ /dev/null @@ -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 -``` diff --git a/Privilege Escalation/simulate_escalation.sh b/Privilege Escalation/simulate_escalation.sh deleted file mode 100755 index 1c4ea93..0000000 --- a/Privilege Escalation/simulate_escalation.sh +++ /dev/null @@ -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}" diff --git a/Scan Port/README.md b/Scan Port/README.md deleted file mode 100644 index 2da0f78..0000000 --- a/Scan Port/README.md +++ /dev/null @@ -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 - -``` \ No newline at end of file diff --git a/activate.sh b/activate.sh deleted file mode 100755 index a026e62..0000000 --- a/activate.sh +++ /dev/null @@ -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" diff --git a/docker-compose.yml b/docker-compose.yml deleted file mode 100644 index a4e4dff..0000000 --- a/docker-compose.yml +++ /dev/null @@ -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 diff --git a/infra/lambda-policies/base-policy.json b/infra/lambda-policies/base-policy.json deleted file mode 100644 index 4299456..0000000 --- a/infra/lambda-policies/base-policy.json +++ /dev/null @@ -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": "*" - } - ] -} diff --git a/infra/setup.sh b/infra/setup.sh deleted file mode 100755 index 7ba4e6a..0000000 --- a/infra/setup.sh +++ /dev/null @@ -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 diff --git a/lambdas/block-ip/handler.py b/lambdas/block-ip/handler.py deleted file mode 100644 index 1afe600..0000000 --- a/lambdas/block-ip/handler.py +++ /dev/null @@ -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(), - } diff --git a/lambdas/block-ip/policy.json b/lambdas/block-ip/policy.json deleted file mode 100644 index 2502a1f..0000000 --- a/lambdas/block-ip/policy.json +++ /dev/null @@ -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:*" - } - ] -} diff --git a/lambdas/block-ip/test_event.json b/lambdas/block-ip/test_event.json deleted file mode 100644 index 867d145..0000000 --- a/lambdas/block-ip/test_event.json +++ /dev/null @@ -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" - } - ] -} diff --git a/lambdas/dispatcher/handler.py b/lambdas/dispatcher/handler.py deleted file mode 100644 index 2531814..0000000 --- a/lambdas/dispatcher/handler.py +++ /dev/null @@ -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(), - } diff --git a/lambdas/dispatcher/policy.json b/lambdas/dispatcher/policy.json deleted file mode 100644 index 740e89d..0000000 --- a/lambdas/dispatcher/policy.json +++ /dev/null @@ -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:*" - } - ] -} diff --git a/lambdas/dispatcher/test_event.json b/lambdas/dispatcher/test_event.json deleted file mode 100644 index 6831e30..0000000 --- a/lambdas/dispatcher/test_event.json +++ /dev/null @@ -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" - } - ] -} diff --git a/lambdas/isolate-instance/handler.py b/lambdas/isolate-instance/handler.py deleted file mode 100644 index 49e2d2a..0000000 --- a/lambdas/isolate-instance/handler.py +++ /dev/null @@ -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/") — 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/") — 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(), - } diff --git a/lambdas/isolate-instance/policy.json b/lambdas/isolate-instance/policy.json deleted file mode 100644 index 50d22d8..0000000 --- a/lambdas/isolate-instance/policy.json +++ /dev/null @@ -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:*" - } - ] -} diff --git a/lambdas/isolate-instance/test_event.json b/lambdas/isolate-instance/test_event.json deleted file mode 100644 index 73cdcaa..0000000 --- a/lambdas/isolate-instance/test_event.json +++ /dev/null @@ -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" - } - ] -} diff --git a/lambdas/notify-alert/handler.py b/lambdas/notify-alert/handler.py deleted file mode 100644 index b498470..0000000 --- a/lambdas/notify-alert/handler.py +++ /dev/null @@ -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() - } diff --git a/lambdas/notify-alert/policy.json b/lambdas/notify-alert/policy.json deleted file mode 100644 index e87a50a..0000000 --- a/lambdas/notify-alert/policy.json +++ /dev/null @@ -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:*" - } - ] -} diff --git a/lambdas/notify-alert/test_event.json b/lambdas/notify-alert/test_event.json deleted file mode 100644 index b1bbbdf..0000000 --- a/lambdas/notify-alert/test_event.json +++ /dev/null @@ -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" - } - ] -} diff --git a/lambdas/revoke-credentials/handler.py b/lambdas/revoke-credentials/handler.py deleted file mode 100644 index 920c72a..0000000 --- a/lambdas/revoke-credentials/handler.py +++ /dev/null @@ -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(), - } diff --git a/lambdas/revoke-credentials/policy.json b/lambdas/revoke-credentials/policy.json deleted file mode 100644 index 3223958..0000000 --- a/lambdas/revoke-credentials/policy.json +++ /dev/null @@ -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:*" - } - ] -} diff --git a/lambdas/revoke-credentials/test_event.json b/lambdas/revoke-credentials/test_event.json deleted file mode 100644 index 3d60183..0000000 --- a/lambdas/revoke-credentials/test_event.json +++ /dev/null @@ -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" - } - ] -} diff --git a/logs/sample_cloudtrail.json b/logs/sample_cloudtrail.json deleted file mode 100644 index 473e131..0000000 --- a/logs/sample_cloudtrail.json +++ /dev/null @@ -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" - } - } - ] -} diff --git a/queries/detect_brute_force.sql b/queries/detect_brute_force.sql deleted file mode 100644 index e7a0ad3..0000000 --- a/queries/detect_brute_force.sql +++ /dev/null @@ -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; diff --git a/queries/detect_exfiltration.sql b/queries/detect_exfiltration.sql deleted file mode 100644 index b66f247..0000000 --- a/queries/detect_exfiltration.sql +++ /dev/null @@ -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; diff --git a/queries/detect_privilege_esc.sql b/queries/detect_privilege_esc.sql deleted file mode 100644 index 1f3738c..0000000 --- a/queries/detect_privilege_esc.sql +++ /dev/null @@ -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; diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index d9e1bff..0000000 --- a/requirements.txt +++ /dev/null @@ -1,3 +0,0 @@ -boto3>=1.34 -awscli-local>=0.22 -duckdb>=0.10 diff --git a/simulators/__pycache__/cloudtrail_gen.cpython-314.pyc b/simulators/__pycache__/cloudtrail_gen.cpython-314.pyc deleted file mode 100644 index aad8268fc085811ad5b92006934e1896d0827f7a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 8488 zcmc&(Yit`=cAgQ3)@#7Y!flemK?5`ejCPBrNVe^dML~n!H8TmiE}B2-FS%}E zVE?q|+~JV4qilj~yS)JKJ@Q2EXaN#DMhkP&O zU65{t)GgSzFoI(XlWEmGLZ9G-9FMsSt9ylQf(!EQYTgHV59Gboe6tV~e2{Oh=3Ah? z1@f)ce5>GJ@d|A#KB0Z3S?E}45js~|BX-@t(k66Gz05G_KV_I+^K07m_LYu)W~Dtg zY<+k=-Nl;nDR%06(5nM`ZQk+}`)p6W-vTT6^{y3vEK)DCq?ImfRK0tpduO$HbuS$| z(9Z~4gzngGt93nH@mu}8%tRBc;<GxiRi%PO;WF(5Abe*;TF9 zx30kKD{SnA#`dNR6^$`Si0Pe&96Y9_Z4YYM1loW}GX_W-iQc$`eDY~i! zXEJI&9Veok32JgSpMiQU?2ZvNoli-@jJm1?4=){C45m~im=S}LrjvY1&l537Br$^{ zHH?rGp*%;_(;{(aVDOZh&8Z4ZBx%@kR??+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pi_VDrI+%-NTbP}1;}&F27hcUbBUGy@z>0@#59?_&hlgdLq= zNNOUsFbnOPse*Ew5uAj>`U0@VUTCn!TJoq&mNk}#$59J{Djqw1PD<(MRR-%R4{t1` zCaBWjWX{T3Rz%$%k}fr9F=7BXfmIFE*;N~((5g*trp1OWDl8U!7Rk^ir>Cb2z6cB; zMhIAJB%L&DW4qD?d-$9N&nS3^Yru*^fH%<{w~u^riC`w@2}$kH8uc^ z&S1eRMs+2h#q1nLRNYZGs#cV#@m}kTDFpz7ouOCq8VE(^ld8S6yX@=V^yx=iY4@wk zmaQ~WibTua{a`C~_kxWxeAV~B>tEmZX4jkiJH9*Od$v0#-aAkV9HtH;a2}Nc!=Tj9 zxHlNC$75PY8*awcQn!lyOmojh$8XOn3RSHlv^J?qf8p!=2hg(iI(t!rAwms?YFh4w1<%8bIjL9PYuL$-ozd@MW` z9uJT2u8I@k$+3cOeD6ef{JANt7#j<51@FYzB(@u$4DXu2>Z$NJje=yj(2I5y{uhWhn0DyNqP7?%Uj(=8MUosPSnTh`ZEAVBuXs>v>);%Tnj-u1>O%+{+?^x0OUk>=A@9{AB$RF&lL6!>i(a}WN4+xf5^-YB|3{{wjV3l{(Y diff --git a/simulators/cloudtrail_gen.py b/simulators/cloudtrail_gen.py deleted file mode 100644 index e424e17..0000000 --- a/simulators/cloudtrail_gen.py +++ /dev/null @@ -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)) diff --git a/simulators/inject_logs.py b/simulators/inject_logs.py deleted file mode 100644 index dc4ac50..0000000 --- a/simulators/inject_logs.py +++ /dev/null @@ -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)