feat: implement automated incident response dispatcher with new block-ip and isolate-instance playbooks and update SQL query parsing
This commit is contained in:
parent
eda4d68aba
commit
a294c8daeb
|
|
@ -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
|
||||||
|
|
@ -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
|
||||||
|
```
|
||||||
|
|
@ -12,6 +12,7 @@ services:
|
||||||
- SERVICES=s3,sns,sqs,lambda,iam,logs,cloudwatch,events
|
- SERVICES=s3,sns,sqs,lambda,iam,logs,cloudwatch,events
|
||||||
- DOCKER_HOST=unix:///var/run/docker.sock
|
- DOCKER_HOST=unix:///var/run/docker.sock
|
||||||
- LAMBDA_EXECUTOR=docker
|
- LAMBDA_EXECUTOR=docker
|
||||||
|
- LAMBDA_DOCKER_NETWORK=localstack-tesis_default
|
||||||
- AWS_DEFAULT_REGION=us-east-1
|
- AWS_DEFAULT_REGION=us-east-1
|
||||||
volumes:
|
volumes:
|
||||||
- "${LOCALSTACK_VOLUME_DIR:-./volume}:/var/lib/localstack"
|
- "${LOCALSTACK_VOLUME_DIR:-./volume}:/var/lib/localstack"
|
||||||
|
|
|
||||||
|
|
@ -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(),
|
||||||
|
}
|
||||||
|
|
@ -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:*"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
@ -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"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
@ -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(),
|
||||||
|
}
|
||||||
|
|
@ -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:*"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
@ -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"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
@ -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(),
|
||||||
|
}
|
||||||
|
|
@ -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:*"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
@ -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"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
@ -8,7 +8,10 @@ import os
|
||||||
import boto3
|
import boto3
|
||||||
from datetime import datetime, timezone
|
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")
|
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_ARN = os.environ.get("SNS_ALERTS_ARN", "arn:aws:sns:us-east-1:000000000000:tesis-security-alerts")
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,9 @@ import os
|
||||||
import boto3
|
import boto3
|
||||||
from datetime import datetime, timezone
|
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")
|
REGION = os.environ.get("AWS_DEFAULT_REGION", "us-east-1")
|
||||||
|
|
||||||
iam = boto3.client("iam", endpoint_url=ENDPOINT, region_name=REGION)
|
iam = boto3.client("iam", endpoint_url=ENDPOINT, region_name=REGION)
|
||||||
|
|
|
||||||
|
|
@ -1,18 +1,20 @@
|
||||||
-- Detección de Fuerza Bruta
|
-- Detección de Fuerza Bruta
|
||||||
-- Busca >5 intentos fallidos de ConsoleLogin desde la misma IP en una ventana de 5 minutos
|
-- 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
|
-- Equivalente a una regla Athena sobre la tabla de CloudTrail
|
||||||
|
-- Sintaxis DuckDB: acceso por campo de struct (r.campo), no por operador JSON (->>)
|
||||||
|
|
||||||
SELECT
|
SELECT
|
||||||
sourceIPAddress,
|
r.sourceIPAddress,
|
||||||
userIdentity.userName AS username,
|
r.userIdentity.userName AS username,
|
||||||
COUNT(*) AS failed_attempts,
|
COUNT(*) AS failed_attempts,
|
||||||
MIN(eventTime) AS first_attempt,
|
MIN(r.eventTime) AS first_attempt,
|
||||||
MAX(eventTime) AS last_attempt,
|
MAX(r.eventTime) AS last_attempt
|
||||||
epoch_ms(MAX(epoch_ms(last_attempt)) - MIN(epoch_ms(first_attempt))) AS window_seconds
|
FROM (
|
||||||
FROM read_json_auto('$LOG_PATH', format='array')
|
SELECT unnest(Records) AS r
|
||||||
WHERE eventName = 'ConsoleLogin'
|
FROM read_json_auto('$LOG_PATH')
|
||||||
AND errorCode = 'AccessDenied'
|
)
|
||||||
AND epoch_ms(eventTime) >= now() - INTERVAL '1 hour'
|
WHERE r.eventName = 'ConsoleLogin'
|
||||||
GROUP BY sourceIPAddress, userIdentity.userName
|
AND r.errorCode = 'AccessDenied'
|
||||||
|
GROUP BY r.sourceIPAddress, r.userIdentity.userName
|
||||||
HAVING COUNT(*) > 5
|
HAVING COUNT(*) > 5
|
||||||
ORDER BY failed_attempts DESC;
|
ORDER BY failed_attempts DESC;
|
||||||
|
|
|
||||||
|
|
@ -1,16 +1,19 @@
|
||||||
-- Detección de Exfiltración de Datos
|
-- Detección de Exfiltración de Datos
|
||||||
-- Busca acceso masivo a S3 GetObject (>50 objetos) desde la misma IP en 1 hora
|
-- 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
|
SELECT
|
||||||
sourceIPAddress,
|
r.sourceIPAddress,
|
||||||
userIdentity.userName AS username,
|
r.userIdentity.userName AS username,
|
||||||
COUNT(*) AS total_downloads,
|
COUNT(*) AS total_downloads,
|
||||||
MIN(eventTime) AS first_access,
|
MIN(r.eventTime) AS first_access,
|
||||||
MAX(eventTime) AS last_access
|
MAX(r.eventTime) AS last_access
|
||||||
FROM read_json_auto('$LOG_PATH', format='array')
|
FROM (
|
||||||
WHERE eventSource = 's3.amazonaws.com'
|
SELECT unnest(Records) AS r
|
||||||
AND eventName = 'GetObject'
|
FROM read_json_auto('$LOG_PATH')
|
||||||
AND epoch_ms(eventTime) >= now() - INTERVAL '1 hour'
|
)
|
||||||
GROUP BY sourceIPAddress, userIdentity.userName
|
WHERE r.eventSource = 's3.amazonaws.com'
|
||||||
|
AND r.eventName = 'GetObject'
|
||||||
|
GROUP BY r.sourceIPAddress, r.userIdentity.userName
|
||||||
HAVING COUNT(*) > 50
|
HAVING COUNT(*) > 50
|
||||||
ORDER BY total_downloads DESC;
|
ORDER BY total_downloads DESC;
|
||||||
|
|
|
||||||
|
|
@ -1,15 +1,19 @@
|
||||||
-- Detección de Escalada de Privilegios
|
-- Detección de Escalada de Privilegios
|
||||||
-- Busca eventos IAM sospechosos: adjuntar políticas admin, crear keys, modificar roles
|
-- 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
|
SELECT
|
||||||
userIdentity.userName AS username,
|
r.userIdentity.userName AS username,
|
||||||
sourceIPAddress,
|
r.sourceIPAddress,
|
||||||
eventName,
|
r.eventName,
|
||||||
eventTime,
|
r.eventTime,
|
||||||
requestParameters
|
r.requestParameters
|
||||||
FROM read_json_auto('$LOG_PATH', format='array')
|
FROM (
|
||||||
WHERE eventSource = 'iam.amazonaws.com'
|
SELECT unnest(Records) AS r
|
||||||
AND eventName IN (
|
FROM read_json_auto('$LOG_PATH')
|
||||||
|
)
|
||||||
|
WHERE r.eventSource = 'iam.amazonaws.com'
|
||||||
|
AND r.eventName IN (
|
||||||
'AttachUserPolicy',
|
'AttachUserPolicy',
|
||||||
'AttachRolePolicy',
|
'AttachRolePolicy',
|
||||||
'CreateAccessKey',
|
'CreateAccessKey',
|
||||||
|
|
@ -18,5 +22,4 @@ WHERE eventSource = 'iam.amazonaws.com'
|
||||||
'CreateLoginProfile',
|
'CreateLoginProfile',
|
||||||
'UpdateLoginProfile'
|
'UpdateLoginProfile'
|
||||||
)
|
)
|
||||||
AND epoch_ms(eventTime) >= now() - INTERVAL '24 hours'
|
ORDER BY r.eventTime DESC;
|
||||||
ORDER BY eventTime DESC;
|
|
||||||
|
|
|
||||||
Binary file not shown.
|
|
@ -18,8 +18,13 @@ BUCKET = os.environ.get("S3_BUCKET", "tesis-security-logs")
|
||||||
QUEUE = os.environ.get("SQS_QUEUE", "tesis-incident-queue")
|
QUEUE = os.environ.get("SQS_QUEUE", "tesis-incident-queue")
|
||||||
QUEUE_URL = f"{ENDPOINT}/000000000000/{QUEUE}"
|
QUEUE_URL = f"{ENDPOINT}/000000000000/{QUEUE}"
|
||||||
|
|
||||||
s3 = boto3.client("s3", endpoint_url=ENDPOINT, region_name=REGION)
|
_KEY = os.environ.get("AWS_ACCESS_KEY_ID", "test")
|
||||||
sqs = boto3.client("sqs", endpoint_url=ENDPOINT, region_name=REGION)
|
_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 = {
|
SEVERITY_MAP = {
|
||||||
"brute-force": "HIGH",
|
"brute-force": "HIGH",
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue