Merge pull request 'feat(portal): integrar telemetria y simulaciones del TIC' (#12) from feature/11-portal-metricas-emil-kowalski into develop
This commit is contained in:
commit
d466a4568d
|
|
@ -52,7 +52,8 @@ jobs:
|
|||
working-directory: ansible
|
||||
run: |
|
||||
ansible-playbook -i inventory/hosts.example.yml playbook.yml --syntax-check
|
||||
ansible-lint playbook.yml
|
||||
ansible-playbook -i inventory/hosts.example.yml playbooks/simulations/run_all.yml --syntax-check
|
||||
ansible-lint playbook.yml playbooks/simulations/*.yml
|
||||
- name: Probar autenticacion, eventos, inventario y reglas de integracion
|
||||
run: python -m unittest discover -s tests -v
|
||||
|
||||
|
|
|
|||
|
|
@ -33,3 +33,6 @@ ansible/inventory/hosts.json
|
|||
.ansible/
|
||||
*.retry
|
||||
ansible/**/vault*.yml
|
||||
|
||||
# Configuracion generada de simulaciones
|
||||
ansible/playbooks/simulations/vars.yml
|
||||
|
|
|
|||
|
|
@ -0,0 +1,127 @@
|
|||
---
|
||||
- name: "Simulacion Red Team - Incidente 01: Fuerza Bruta (BRUTE_FORCE)"
|
||||
hosts: localhost
|
||||
connection: local
|
||||
gather_facts: false
|
||||
|
||||
vars_files:
|
||||
- vars.example.yml
|
||||
|
||||
pre_tasks:
|
||||
- name: Autorizar simulacion y cargar configuracion local
|
||||
ansible.builtin.import_tasks: preflight.yml
|
||||
tags: always
|
||||
|
||||
tasks:
|
||||
- name: Determinar direccion IP publica del atacante
|
||||
ansible.builtin.uri:
|
||||
url: https://checkip.amazonaws.com
|
||||
return_content: true
|
||||
register: attacker_ip_req
|
||||
retries: 3
|
||||
delay: 2
|
||||
|
||||
- name: Fijar IP publica del atacante
|
||||
ansible.builtin.set_fact:
|
||||
attacker_ip: "{{ attacker_ip_req.content | trim }}"
|
||||
|
||||
- name: Notificar inicio de la prueba
|
||||
ansible.builtin.debug:
|
||||
msg:
|
||||
- "=== INICIO SIMULACION FUERZA BRUTA (BRUTE_FORCE) ==="
|
||||
- "Destino: {{ portal_url }}/login"
|
||||
- "IP Atacante: {{ attacker_ip }}"
|
||||
- "Usuario objetivo: admin.demo"
|
||||
- "Umbral requerido: 5 intentos fallidos en ventana de 5 minutos"
|
||||
|
||||
- name: Ejecutar 4 intentos fallidos iniciales
|
||||
ansible.builtin.uri:
|
||||
url: "{{ portal_url }}/login"
|
||||
method: POST
|
||||
body_format: form-urlencoded
|
||||
body:
|
||||
username: "admin.demo"
|
||||
password: "InvalidPassword{{ item }}"
|
||||
status_code: [200, 302]
|
||||
return_content: true
|
||||
loop: [1, 2, 3, 4]
|
||||
register: failed_attempts
|
||||
delay: 1
|
||||
|
||||
- name: Ejecutar 5to intento y comprobar bloqueo defensivo (HTTP 403)
|
||||
ansible.builtin.uri:
|
||||
url: "{{ portal_url }}/login"
|
||||
method: POST
|
||||
body_format: form-urlencoded
|
||||
body:
|
||||
username: "admin.demo"
|
||||
password: "TriggerBlockedAttempt5"
|
||||
status_code: 403
|
||||
return_content: true
|
||||
register: lockout_response
|
||||
|
||||
- name: Verificar que la pantalla de bloqueo responde con 403
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- lockout_response.status == 403
|
||||
- "'Acceso bloqueado temporalmente' in lockout_response.content"
|
||||
fail_msg: "El portal no activo la respuesta defensiva 403 tras 5 fallos."
|
||||
success_msg: "El portal activo exitosamente la contencion 403 en memoria."
|
||||
|
||||
- name: Esperar procesamiento de CloudWatch Logs y Lambda Detector
|
||||
ansible.builtin.pause:
|
||||
seconds: 15
|
||||
prompt: "Esperando propagacion de telemetria hacia Lambda y Playbooks (15s)..."
|
||||
|
||||
- name: Consultar incidente registrado en DynamoDB
|
||||
ansible.builtin.command: >
|
||||
aws dynamodb scan
|
||||
--table-name {{ dynamodb_incidents_table }}
|
||||
--expression-attribute-names '{"#tp":"type"}'
|
||||
--expression-attribute-values '{":t":{"S":"BRUTE_FORCE"}}'
|
||||
--filter-expression "#tp = :t"
|
||||
--region {{ aws_region }}
|
||||
--output json
|
||||
register: ddb_incidents_raw
|
||||
changed_when: false
|
||||
|
||||
- name: Parsear registros de DynamoDB
|
||||
ansible.builtin.set_fact:
|
||||
ddb_items: "{{ (ddb_incidents_raw.stdout | from_json).Items | default([]) }}"
|
||||
|
||||
- name: Consultar reglas de Network ACL en AWS
|
||||
ansible.builtin.command: >
|
||||
aws ec2 describe-network-acls
|
||||
--network-acl-ids {{ nacl_id }}
|
||||
--region {{ aws_region }}
|
||||
--output json
|
||||
register: nacl_raw
|
||||
changed_when: false
|
||||
|
||||
- name: Parsear reglas de Network ACL
|
||||
ansible.builtin.set_fact:
|
||||
nacl_entries: "{{ ((nacl_raw.stdout | from_json).NetworkAcls[0].Entries) | default([]) }}"
|
||||
|
||||
- name: Identificar reglas DENY activas
|
||||
ansible.builtin.set_fact:
|
||||
nacl_deny_rules: >-
|
||||
{{
|
||||
nacl_entries | selectattr('Egress', 'equalto', false)
|
||||
| selectattr('RuleAction', 'equalto', 'deny')
|
||||
| rejectattr('RuleNumber', 'equalto', 32767)
|
||||
| list
|
||||
}}
|
||||
|
||||
- name: Resumen ejecutivo del resultado
|
||||
ansible.builtin.debug:
|
||||
msg:
|
||||
- "=========================================================="
|
||||
- " REPORTE FINAL DE LA PRUEBA"
|
||||
- "=========================================================="
|
||||
- "Tipo de incidente: BRUTE_FORCE"
|
||||
- "IP Atacante: {{ attacker_ip }}"
|
||||
- "Resultado Portal: HTTP 403 Lockout Exitoso"
|
||||
- "Total Incidentes BRUTE_FORCE en DynamoDB: {{ ddb_items | length }}"
|
||||
- "Reglas DENY Ingress en Network ACL: {{ nacl_deny_rules | length }}"
|
||||
- "Evidencia S3: s3://{{ evidence_bucket }}/incident-01-bruteforce/"
|
||||
- "=========================================================="
|
||||
|
|
@ -0,0 +1,109 @@
|
|||
---
|
||||
- name: "Simulacion Red Team - Incidente 02: Escaneo de Puertos (PORT_SCAN)"
|
||||
hosts: localhost
|
||||
connection: local
|
||||
gather_facts: false
|
||||
|
||||
vars_files:
|
||||
- vars.example.yml
|
||||
|
||||
pre_tasks:
|
||||
- name: Autorizar simulacion y cargar configuracion local
|
||||
ansible.builtin.import_tasks: preflight.yml
|
||||
tags: always
|
||||
|
||||
tasks:
|
||||
- name: Determinar direccion IP publica del atacante
|
||||
ansible.builtin.uri:
|
||||
url: https://checkip.amazonaws.com
|
||||
return_content: true
|
||||
register: attacker_ip_req
|
||||
retries: 3
|
||||
delay: 2
|
||||
|
||||
- name: Fijar IP publica del atacante
|
||||
ansible.builtin.set_fact:
|
||||
attacker_ip: "{{ attacker_ip_req.content | trim }}"
|
||||
|
||||
- name: Notificar inicio de la prueba de escaneo
|
||||
ansible.builtin.debug:
|
||||
msg:
|
||||
- "=== INICIO SIMULACION ESCANEO DE PUERTOS (PORT_SCAN) ==="
|
||||
- "Destino: {{ portal_public_ip }}"
|
||||
- "Rango de puertos objetivo: TCP 81 a 92 (Puertos cerrados)"
|
||||
- "IP Atacante: {{ attacker_ip }}"
|
||||
- "Objetivo de telemetria: Generar paquetes REJECT en VPC Flow Logs"
|
||||
|
||||
- name: Ejecutar sondeo TCP sobre puertos cerrados (81-92)
|
||||
ansible.builtin.command:
|
||||
cmd: |
|
||||
python3 -c '
|
||||
import socket
|
||||
for p in range(81, 93):
|
||||
s = socket.socket()
|
||||
s.settimeout(0.2)
|
||||
s.connect_ex(("{{ portal_public_ip }}", p))
|
||||
s.close()
|
||||
'
|
||||
register: port_scan_output
|
||||
changed_when: false
|
||||
|
||||
- name: Mostrar resumen del escaneo enviado
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ port_scan_output.stdout_lines }}"
|
||||
|
||||
- name: Explicar ventana de agregacion de VPC Flow Logs
|
||||
ansible.builtin.debug:
|
||||
msg:
|
||||
- "Nota: AWS VPC Flow Logs tiene un intervalo de agregacion tipico de 1 a 3 minutos."
|
||||
- "El detector Lambda procesara los registros REJECT agrupados en la tabla DynamoDB."
|
||||
|
||||
- name: Consultar incidentes de PORT_SCAN en DynamoDB
|
||||
ansible.builtin.command: >
|
||||
aws dynamodb scan
|
||||
--table-name {{ dynamodb_incidents_table }}
|
||||
--expression-attribute-names '{"#tp":"type"}'
|
||||
--expression-attribute-values '{":t":{"S":"PORT_SCAN"}}'
|
||||
--filter-expression "#tp = :t"
|
||||
--region {{ aws_region }}
|
||||
--output json
|
||||
register: ddb_portscan_raw
|
||||
changed_when: false
|
||||
|
||||
- name: Parsear registros de DynamoDB
|
||||
ansible.builtin.set_fact:
|
||||
ddb_portscan_items: "{{ (ddb_portscan_raw.stdout | from_json).Items | default([]) }}"
|
||||
|
||||
- name: Consultar reglas de Network ACL en AWS
|
||||
ansible.builtin.command: >
|
||||
aws ec2 describe-network-acls
|
||||
--network-acl-ids {{ nacl_id }}
|
||||
--region {{ aws_region }}
|
||||
--output json
|
||||
register: nacl_raw
|
||||
changed_when: false
|
||||
|
||||
- name: Identificar reglas DENY activas
|
||||
ansible.builtin.set_fact:
|
||||
nacl_deny_rules: >-
|
||||
{{
|
||||
((nacl_raw.stdout | from_json).NetworkAcls[0].Entries)
|
||||
| selectattr('Egress', 'equalto', false)
|
||||
| selectattr('RuleAction', 'equalto', 'deny')
|
||||
| rejectattr('RuleNumber', 'equalto', 32767)
|
||||
| list
|
||||
}}
|
||||
|
||||
- name: Resumen ejecutivo del resultado
|
||||
ansible.builtin.debug:
|
||||
msg:
|
||||
- "=========================================================="
|
||||
- " REPORTE FINAL DE LA PRUEBA"
|
||||
- "=========================================================="
|
||||
- "Tipo de incidente: PORT_SCAN"
|
||||
- "IP Atacante: {{ attacker_ip }}"
|
||||
- "Puertos sondeados: 81 a 92"
|
||||
- "Total Incidentes PORT_SCAN en DynamoDB: {{ ddb_portscan_items | length }}"
|
||||
- "Reglas DENY Ingress en Network ACL: {{ nacl_deny_rules | length }}"
|
||||
- "Evidencia S3: s3://{{ evidence_bucket }}/incident-02-port-scan/"
|
||||
- "=========================================================="
|
||||
|
|
@ -0,0 +1,86 @@
|
|||
---
|
||||
- name: "Simulacion Red Team - Incidente 03: Escalada de Privilegios (PRIVILEGE_ESCALATION)"
|
||||
hosts: localhost
|
||||
connection: local
|
||||
gather_facts: false
|
||||
|
||||
vars_files:
|
||||
- vars.example.yml
|
||||
|
||||
pre_tasks:
|
||||
- name: Autorizar simulacion y cargar configuracion local
|
||||
ansible.builtin.import_tasks: preflight.yml
|
||||
tags: always
|
||||
|
||||
tasks:
|
||||
- name: Validar identidad desechable del actor IAM
|
||||
ansible.builtin.import_tasks: iam_actor.yml
|
||||
|
||||
- name: Notificar inicio de la prueba de escalada
|
||||
ansible.builtin.debug:
|
||||
msg:
|
||||
- "=== INICIO SIMULACION ESCALADA DE PRIVILEGIOS (PRIVILEGE_ESCALATION) ==="
|
||||
- "Usuario de prueba temporal: {{ test_iam_username }}"
|
||||
- "Politica detonante: {{ test_escalation_policy_arn }}"
|
||||
- "Accion esperada: CloudTrail -> Lambda -> Playbook revoke-credentials"
|
||||
- "Resultado esperado de contencion: Adjuncion de EmergencyDenyAll"
|
||||
|
||||
- name: Adjuntar politica al actor desechable para detonar la escalada
|
||||
ansible.builtin.command: >
|
||||
aws --profile {{ simulation_iam_profile }} iam attach-user-policy
|
||||
--user-name {{ test_iam_username }}
|
||||
--policy-arn {{ test_escalation_policy_arn }}
|
||||
register: iam_attach_res
|
||||
changed_when: true
|
||||
|
||||
- name: Notificar detonador exitoso
|
||||
ansible.builtin.debug:
|
||||
msg:
|
||||
- "Evento de escalada generado en AWS CloudTrail: AttachUserPolicy"
|
||||
- "Esperando captura y ejecucion automatica del playbook revoke-credentials..."
|
||||
|
||||
- name: Esperar procesamiento de CloudTrail y ejecucion de la contencion
|
||||
ansible.builtin.pause:
|
||||
seconds: 20
|
||||
prompt: "Esperando propagacion y contencion automatica en IAM (20s)..."
|
||||
|
||||
- name: Verificar si la contencion EmergencyDenyAll fue aplicada
|
||||
ansible.builtin.command: >
|
||||
aws iam get-user-policy
|
||||
--user-name {{ test_iam_username }}
|
||||
--policy-name {{ emergency_deny_policy_name }}
|
||||
register: emergency_policy_check
|
||||
changed_when: false
|
||||
retries: 60
|
||||
delay: 15
|
||||
until: emergency_policy_check.rc == 0
|
||||
|
||||
- name: Consultar incidentes de PRIVILEGE_ESCALATION en DynamoDB
|
||||
ansible.builtin.command: >
|
||||
aws dynamodb scan
|
||||
--table-name {{ dynamodb_incidents_table }}
|
||||
--expression-attribute-names '{"#tp":"type"}'
|
||||
--expression-attribute-values '{":t":{"S":"PRIVILEGE_ESCALATION"}}'
|
||||
--filter-expression "#tp = :t"
|
||||
--region {{ aws_region }}
|
||||
--output json
|
||||
register: ddb_escalation_raw
|
||||
changed_when: false
|
||||
|
||||
- name: Parsear registros de DynamoDB
|
||||
ansible.builtin.set_fact:
|
||||
ddb_escalation_items: "{{ (ddb_escalation_raw.stdout | from_json).Items | default([]) }}"
|
||||
|
||||
- name: Resumen ejecutivo del resultado
|
||||
ansible.builtin.debug:
|
||||
msg:
|
||||
- "=========================================================="
|
||||
- " REPORTE FINAL DE LA PRUEBA"
|
||||
- "=========================================================="
|
||||
- "Tipo de incidente: PRIVILEGE_ESCALATION"
|
||||
- "Usuario objetivo: {{ test_iam_username }}"
|
||||
- "Estado Contencion EmergencyDenyAll: {{ 'APLICADA EXITOSAMENTE' if emergency_policy_check.rc == 0 else 'PENDIENTE DE PROPAGACION' }}"
|
||||
- "Total Incidentes PRIVILEGE_ESCALATION en DynamoDB: {{ ddb_escalation_items | length }}"
|
||||
- "Evidencia S3: s3://{{ evidence_bucket }}/incident-03-privilege-escalation/"
|
||||
- "Para limpiar este usuario ejecuta: ansible-playbook rollback_cleanup.yml"
|
||||
- "=========================================================="
|
||||
|
|
@ -0,0 +1,75 @@
|
|||
---
|
||||
- name: "Simulacion Red Team - Incidente 04: Fuga de Credenciales (CREDENTIAL_LEAK)"
|
||||
hosts: localhost
|
||||
connection: local
|
||||
gather_facts: false
|
||||
|
||||
vars_files:
|
||||
- vars.example.yml
|
||||
|
||||
pre_tasks:
|
||||
- name: Autorizar simulacion y cargar configuracion local
|
||||
ansible.builtin.import_tasks: preflight.yml
|
||||
tags: always
|
||||
|
||||
tasks:
|
||||
- name: Validar identidad desechable del actor IAM
|
||||
ansible.builtin.import_tasks: iam_actor.yml
|
||||
|
||||
- name: Determinar direccion IP publica de la ejecucion
|
||||
ansible.builtin.uri:
|
||||
url: https://checkip.amazonaws.com
|
||||
return_content: true
|
||||
register: current_ip_req
|
||||
retries: 3
|
||||
delay: 2
|
||||
|
||||
- name: Fijar IP publica
|
||||
ansible.builtin.set_fact:
|
||||
current_ip: "{{ current_ip_req.content | trim }}"
|
||||
|
||||
- name: Notificar condiciones de la prueba
|
||||
ansible.builtin.debug:
|
||||
msg:
|
||||
- "=== INICIO SIMULACION FUGA DE CREDENCIALES (CREDENTIAL_LEAK) ==="
|
||||
- "IP Actual: {{ current_ip }}"
|
||||
- "Criterio de activacion: Llamadas a la API de AWS (STS GetCallerIdentity) desde IP no autorizada"
|
||||
- "Condicion positiva: ejecutar el perfil desechable desde una red fuera de authorized_ip_cidrs; conservar acceso administrativo de recuperacion"
|
||||
|
||||
- name: Ejecutar llamada a STS GetCallerIdentity
|
||||
ansible.builtin.command: >
|
||||
aws --profile {{ simulation_iam_profile }} sts get-caller-identity --output json
|
||||
register: sts_caller_id
|
||||
changed_when: false
|
||||
|
||||
- name: Mostrar identidad que ejecuto la llamada
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ sts_caller_id.stdout | from_json }}"
|
||||
|
||||
- name: Consultar incidentes de CREDENTIAL_LEAK en DynamoDB
|
||||
ansible.builtin.command: >
|
||||
aws dynamodb scan
|
||||
--table-name {{ dynamodb_incidents_table }}
|
||||
--expression-attribute-names '{"#tp":"type"}'
|
||||
--expression-attribute-values '{":t":{"S":"CREDENTIAL_LEAK"}}'
|
||||
--filter-expression "#tp = :t"
|
||||
--region {{ aws_region }}
|
||||
--output json
|
||||
register: ddb_leak_raw
|
||||
changed_when: false
|
||||
|
||||
- name: Parsear registros de DynamoDB
|
||||
ansible.builtin.set_fact:
|
||||
ddb_leak_items: "{{ (ddb_leak_raw.stdout | from_json).Items | default([]) }}"
|
||||
|
||||
- name: Resumen ejecutivo del resultado
|
||||
ansible.builtin.debug:
|
||||
msg:
|
||||
- "=========================================================="
|
||||
- " REPORTE FINAL DE LA PRUEBA"
|
||||
- "=========================================================="
|
||||
- "Tipo de incidente: CREDENTIAL_LEAK"
|
||||
- "IP Emisora: {{ current_ip }}"
|
||||
- "Total Incidentes CREDENTIAL_LEAK en DynamoDB: {{ ddb_leak_items | length }}"
|
||||
- "Evidencia S3: s3://{{ evidence_bucket }}/incident-04-credential-leak/"
|
||||
- "=========================================================="
|
||||
|
|
@ -0,0 +1,70 @@
|
|||
---
|
||||
- name: "Simulacion Red Team - Incidente 05: Exfiltracion de Datos S3 (EXFILTRATION)"
|
||||
hosts: localhost
|
||||
connection: local
|
||||
gather_facts: false
|
||||
|
||||
vars_files:
|
||||
- vars.example.yml
|
||||
|
||||
pre_tasks:
|
||||
- name: Autorizar simulacion y cargar configuracion local
|
||||
ansible.builtin.import_tasks: preflight.yml
|
||||
tags: always
|
||||
|
||||
tasks:
|
||||
- name: Notificar inicio de la prueba de exfiltracion
|
||||
ansible.builtin.debug:
|
||||
msg:
|
||||
- "=== INICIO SIMULACION EXFILTRACION DE DATOS S3 (EXFILTRATION) ==="
|
||||
- "Bucket Sensible: s3://{{ sensitive_bucket }}"
|
||||
- "Ruta del recurso: sensible/clientes_demo.json"
|
||||
- "Umbral requerido: Mas de 50 peticiones GetObject en ventana de 1 hora"
|
||||
- "Condicion previa: enable_s3_data_events = true en terraform.tfvars"
|
||||
|
||||
- name: Verificar objeto ficticio existente sin sobrescribirlo
|
||||
ansible.builtin.command: >
|
||||
aws s3api head-object --bucket {{ sensitive_bucket }}
|
||||
--key sensible/clientes_demo.json --region {{ aws_region }}
|
||||
changed_when: false
|
||||
|
||||
- name: Ejecutar rafaga de 55 descargas consecutivas (GetObject)
|
||||
ansible.builtin.command:
|
||||
cmd: |
|
||||
{{ ansible_playbook_python }} -c '
|
||||
import boto3
|
||||
s3 = boto3.client("s3", region_name="{{ aws_region }}")
|
||||
for _ in range(55):
|
||||
with s3.get_object(Bucket="{{ sensitive_bucket }}", Key="sensible/clientes_demo.json")["Body"] as body:
|
||||
body.read()
|
||||
'
|
||||
register: s3_downloads
|
||||
changed_when: false
|
||||
|
||||
- name: Consultar incidentes de EXFILTRATION en DynamoDB
|
||||
ansible.builtin.command: >
|
||||
aws dynamodb scan
|
||||
--table-name {{ dynamodb_incidents_table }}
|
||||
--expression-attribute-names '{"#tp":"type"}'
|
||||
--expression-attribute-values '{":t":{"S":"EXFILTRATION"}}'
|
||||
--filter-expression "#tp = :t"
|
||||
--region {{ aws_region }}
|
||||
--output json
|
||||
register: ddb_exfil_raw
|
||||
changed_when: false
|
||||
|
||||
- name: Parsear registros de DynamoDB
|
||||
ansible.builtin.set_fact:
|
||||
ddb_exfil_items: "{{ (ddb_exfil_raw.stdout | from_json).Items | default([]) }}"
|
||||
|
||||
- name: Resumen ejecutivo del resultado
|
||||
ansible.builtin.debug:
|
||||
msg:
|
||||
- "=========================================================="
|
||||
- " REPORTE FINAL DE LA PRUEBA"
|
||||
- "=========================================================="
|
||||
- "Tipo de incidente: EXFILTRATION"
|
||||
- "Descargas GetObject ejecutadas: 55"
|
||||
- "Total Incidentes EXFILTRATION en DynamoDB: {{ ddb_exfil_items | length }}"
|
||||
- "Evidencia S3: s3://{{ evidence_bucket }}/incident-05-exfiltration/"
|
||||
- "=========================================================="
|
||||
|
|
@ -0,0 +1,85 @@
|
|||
# Simulaciones del laboratorio TIC
|
||||
|
||||
La suite genera estímulos de los cinco incidentes soportados. Las consultas a
|
||||
DynamoDB muestran registros acumulados: su presencia **no prueba** que la ejecución
|
||||
actual haya sido detectada o contenida. Para el TIC se deben correlacionar identidad,
|
||||
IP, timestamp UTC, ID del incidente y evidencia S3 con cada ensayo, siguiendo el
|
||||
plan de métricas de `docs/`. Esta integración valida código y controles sin ejecutar
|
||||
ataques en AWS; las simulaciones requieren validación experimental en el laboratorio.
|
||||
|
||||
| Playbook | Estímulo | Condición relevante |
|
||||
| --- | --- | --- |
|
||||
| `01_brute_force.yml` | Intentos de login fallidos | Puede bloquear el acceso desde la IP emisora |
|
||||
| `02_port_scan.yml` | Conexiones TCP a 81–92 | Esperar agregación y entrega de VPC Flow Logs |
|
||||
| `03_privilege_escalation.yml` | AttachUserPolicy sobre el propio actor desechable | Perfil IAM separado; espera EmergencyDenyAll hasta 15 minutos |
|
||||
| `04_credential_leak.yml` | GetCallerIdentity del actor desechable | Origen fuera de authorized_ip_cidrs para caso positivo |
|
||||
| `05_s3_exfiltration.yml` | 55 GetObject completos del objeto ficticio | CloudTrail S3 Data Events activado y objeto existente |
|
||||
| `rollback_cleanup.yml` | Limpieza explícita y reinicio del portal vía SSM | Conserva evidencias e incidentes históricos |
|
||||
|
||||
Desde la raíz del repositorio, activar `.venv` con las dependencias de
|
||||
`ansible/requirements.txt`, AWS CLI y credenciales del operador. Regenerar los
|
||||
identificadores desde el estado Terraform local del despliegue:
|
||||
|
||||
```bash
|
||||
python ansible/scripts/generate_inventory.py
|
||||
python ansible/scripts/generate_simulation_vars.py
|
||||
```
|
||||
|
||||
`vars.example.yml` contiene ejemplos portables. El archivo generado `vars.yml` es
|
||||
local y está excluido de Git. Revisar cuenta, región y recursos antes de ejecutar.
|
||||
Todas las entradas abortan por defecto, incluso en modo check, antes de llamar AWS.
|
||||
La comprobación estática usa `--syntax-check` y no requiere el archivo generado.
|
||||
|
||||
Ejecutar un escenario elegido, en un laboratorio autorizado:
|
||||
|
||||
```bash
|
||||
ansible-playbook ansible/playbooks/simulations/run_all.yml \
|
||||
--tags brute_force -e simulation_confirm=true
|
||||
```
|
||||
|
||||
No omitir `--tags` salvo que se quiera ejecutar toda la suite con su limpieza final.
|
||||
La suite no garantiza limpieza si un escenario anterior falla; ejecutar el rollback
|
||||
seleccionado después de revisar el resultado. La entrega de CloudTrail y Flow Logs
|
||||
es asíncrona: los resúmenes inmediatos pueden preceder a la detección.
|
||||
|
||||
Para los escenarios IAM preparar previamente un usuario desechable con prefijo
|
||||
`tesis-ir-temp-` y su perfil AWS CLI con clave estática, separado de la identidad del
|
||||
operador. El usuario requiere únicamente los permisos del escenario (para escalada,
|
||||
AttachUserPolicy sobre sí mismo y ReadOnlyAccess). Las claves se pueden desactivar
|
||||
como resultado de la prueba; conservar una identidad administrativa de recuperación.
|
||||
No se crean usuarios ni claves automáticamente. SSO y perfiles de roles no están
|
||||
soportados como actor de esta suite. El preflight consulta con el operador quién es
|
||||
el dueño de la clave antes de invocar el perfil del actor; no registra claves.
|
||||
|
||||
```bash
|
||||
ansible-playbook ansible/playbooks/simulations/run_all.yml \
|
||||
--tags privilege_escalation -e simulation_confirm=true \
|
||||
-e simulation_iam_profile=tesis-lab \
|
||||
-e test_iam_username=tesis-ir-temp-escalation-test
|
||||
```
|
||||
|
||||
Para fuga de credenciales usar `--tags credential_leak` con las mismas opciones,
|
||||
desde una red de prueba no autorizada. La red autorizada sirve de control negativo.
|
||||
El operador debe usar una red autorizada para sus consultas; no retirar su acceso
|
||||
administrativo de recuperación para forzar una detección.
|
||||
|
||||
La limpieza IAM requiere `cleanup_iam_confirm=true`: elimina todas las claves,
|
||||
la política EmergencyDenyAll, ReadOnlyAccess y el usuario desechable indicado.
|
||||
Por defecto se omite. La limpieza NACL solo elimina reglas ingress DENY 1–99 que
|
||||
coincidan tanto con los números elegidos como con el CIDR /32 del ensayo. Sin esa
|
||||
selección no elimina reglas. Revisar los números en AWS y la evidencia del ensayo:
|
||||
|
||||
```bash
|
||||
ansible-playbook ansible/playbooks/simulations/rollback_cleanup.yml \
|
||||
-e '{"simulation_confirm":true,"cleanup_iam_confirm":true,"simulation_attacker_cidr":"198.51.100.8/32","simulation_cleanup_rule_numbers":[42]}'
|
||||
```
|
||||
|
||||
Ese CIDR y número son ejemplos, no valores detectados. El rollback espera la
|
||||
finalización del reinicio SSM antes de consultar `/health`. El reinicio borra los
|
||||
bloqueos, contadores y muestras en memoria del portal. No borra DynamoDB, objetos
|
||||
históricos ni otras reglas NACL; no representa un restablecimiento total del entorno.
|
||||
|
||||
La telemetría del portal conserva las últimas 100 muestras de tiempo interno hasta
|
||||
la emisión de cabeceras, con p50 y p95 por rango más próximo. No equivale a la latencia
|
||||
HTTP completa desde el cliente. Los contadores se reinician con el proceso. Usar la
|
||||
sonda externa y las evidencias del plan cuantitativo para las mediciones del TIC.
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
---
|
||||
- name: Exigir perfil IAM separado para el actor desechable
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- simulation_iam_profile | length > 0
|
||||
- simulation_iam_profile != 'default'
|
||||
fail_msg: "Indicar simulation_iam_profile de un usuario IAM desechable con clave estatica."
|
||||
|
||||
- name: Leer identificador de clave del perfil sin invocar AWS
|
||||
ansible.builtin.command:
|
||||
argv: [aws, configure, get, aws_access_key_id, --profile, "{{ simulation_iam_profile }}"]
|
||||
register: simulation_actor_key
|
||||
no_log: true
|
||||
changed_when: false
|
||||
|
||||
- name: Consultar propietario de la clave con la identidad del operador
|
||||
ansible.builtin.command:
|
||||
argv: [aws, iam, get-access-key-last-used, --access-key-id, "{{ simulation_actor_key.stdout | trim }}", --output, json]
|
||||
register: simulation_actor_owner
|
||||
no_log: true
|
||||
changed_when: false
|
||||
|
||||
- name: Rechazar claves ajenas al usuario desechable esperado
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- (simulation_actor_owner.stdout | from_json).UserName == test_iam_username
|
||||
fail_msg: "El perfil no pertenece al usuario desechable indicado; no se ejecutara el estimulo."
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
---
|
||||
- name: Exigir ejecucion explicita fuera del modo check
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- simulation_confirm | default(false) | bool
|
||||
- not ansible_check_mode
|
||||
fail_msg: "Simulacion deshabilitada: requiere simulation_confirm=true y ejecucion explicita sin --check."
|
||||
|
||||
- name: Cargar variables generadas del despliegue
|
||||
ansible.builtin.include_vars: vars.yml
|
||||
|
||||
- name: Validar nombre reservado para usuarios desechables
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- test_iam_username is match('^tesis-ir-temp-[a-z0-9-]+$')
|
||||
fail_msg: "El usuario de simulacion debe tener el prefijo tesis-ir-temp-."
|
||||
|
|
@ -0,0 +1,168 @@
|
|||
---
|
||||
- name: "Rollback y Limpieza Automatizada del Laboratorio de Seguridad"
|
||||
hosts: localhost
|
||||
connection: local
|
||||
gather_facts: false
|
||||
|
||||
vars_files:
|
||||
- vars.example.yml
|
||||
|
||||
pre_tasks:
|
||||
- name: Autorizar simulacion y cargar configuracion local
|
||||
ansible.builtin.import_tasks: preflight.yml
|
||||
tags: always
|
||||
|
||||
tasks:
|
||||
- name: Notificar inicio de la restauracion
|
||||
ansible.builtin.debug:
|
||||
msg:
|
||||
- "=== INICIO ROLLBACK Y LIMPIEZA AUTOMATIZADA ==="
|
||||
- "Objetivo: Restaurar el entorno de laboratorio al estado base limpio"
|
||||
|
||||
# 1. Limpieza de Identidad IAM Temporal
|
||||
- name: Verificar existencia de usuario temporal IAM
|
||||
ansible.builtin.command: >
|
||||
aws iam get-user --user-name {{ test_iam_username }}
|
||||
register: iam_user_check
|
||||
when: cleanup_iam_confirm | bool
|
||||
ignore_errors: true
|
||||
changed_when: false
|
||||
|
||||
- name: Bloque de limpieza IAM temporal
|
||||
when:
|
||||
- cleanup_iam_confirm | bool
|
||||
- iam_user_check.rc | default(1) == 0
|
||||
block:
|
||||
- name: Retirar politica inline de contencion EmergencyDenyAll
|
||||
ansible.builtin.command: >
|
||||
aws iam delete-user-policy
|
||||
--user-name {{ test_iam_username }}
|
||||
--policy-name {{ emergency_deny_policy_name }}
|
||||
ignore_errors: true
|
||||
register: iam_del_emergency
|
||||
changed_when: iam_del_emergency.rc == 0
|
||||
|
||||
- name: Desasociar politica ReadOnlyAccess
|
||||
ansible.builtin.command: >
|
||||
aws iam detach-user-policy
|
||||
--user-name {{ test_iam_username }}
|
||||
--policy-arn {{ test_escalation_policy_arn }}
|
||||
ignore_errors: true
|
||||
register: iam_detach_ro
|
||||
changed_when: iam_detach_ro.rc == 0
|
||||
|
||||
- name: Listar y eliminar claves de acceso del usuario temporal
|
||||
ansible.builtin.command: >
|
||||
aws iam list-access-keys --user-name {{ test_iam_username }} --output json
|
||||
register: access_keys_raw
|
||||
changed_when: false
|
||||
|
||||
- name: Eliminar claves de acceso asociadas
|
||||
ansible.builtin.command: >
|
||||
aws iam delete-access-key
|
||||
--user-name {{ test_iam_username }}
|
||||
--access-key-id {{ item.AccessKeyId }}
|
||||
loop: "{{ (access_keys_raw.stdout | from_json).AccessKeyMetadata | default([]) }}"
|
||||
when: (access_keys_raw.stdout | from_json).AccessKeyMetadata is defined
|
||||
changed_when: true
|
||||
|
||||
- name: Eliminar usuario temporal IAM
|
||||
ansible.builtin.command: >
|
||||
aws iam delete-user --user-name {{ test_iam_username }}
|
||||
register: iam_delete_user
|
||||
changed_when: iam_delete_user.rc == 0
|
||||
|
||||
- name: Confirmar limpieza IAM
|
||||
ansible.builtin.debug:
|
||||
msg: "Usuario IAM temporal {{ test_iam_username }} y sus politicas fueron eliminados."
|
||||
|
||||
# 2. Desbloqueo de Red (Network ACL): solo numeros y origen elegidos.
|
||||
- name: Exigir CIDR de origen cuando se solicita retirar reglas
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- simulation_attacker_cidr is match('^[0-9.]+/32$')
|
||||
fail_msg: "Indicar simulation_attacker_cidr /32 y los numeros exactos de reglas de esta prueba."
|
||||
when: simulation_cleanup_rule_numbers | length > 0
|
||||
|
||||
- name: Obtener reglas activas de la Network ACL
|
||||
ansible.builtin.command: >
|
||||
aws ec2 describe-network-acls
|
||||
--network-acl-ids {{ nacl_id }}
|
||||
--region {{ aws_region }}
|
||||
--output json
|
||||
register: nacl_status_raw
|
||||
changed_when: false
|
||||
|
||||
- name: Identificar reglas DENY del origen y numeros indicados
|
||||
ansible.builtin.set_fact:
|
||||
temp_deny_rules: >-
|
||||
{{
|
||||
((nacl_status_raw.stdout | from_json).NetworkAcls[0].Entries)
|
||||
| selectattr('Egress', 'equalto', false)
|
||||
| selectattr('RuleAction', 'equalto', 'deny')
|
||||
| selectattr('RuleNumber', 'gt', 0)
|
||||
| selectattr('RuleNumber', 'lt', 100)
|
||||
| selectattr('RuleNumber', 'in', simulation_cleanup_rule_numbers)
|
||||
| selectattr('CidrBlock', 'defined')
|
||||
| selectattr('CidrBlock', 'equalto', simulation_attacker_cidr)
|
||||
| map(attribute='RuleNumber')
|
||||
| list
|
||||
}}
|
||||
|
||||
- name: Notificar reglas DENY a eliminar de la Network ACL
|
||||
ansible.builtin.debug:
|
||||
msg: "Reglas de bloqueo identificadas en NACL: {{ temp_deny_rules }}"
|
||||
when: temp_deny_rules | length > 0
|
||||
|
||||
- name: Eliminar reglas DENY temporales de la Network ACL
|
||||
ansible.builtin.command: >
|
||||
aws ec2 delete-network-acl-entry
|
||||
--network-acl-id {{ nacl_id }}
|
||||
--rule-number {{ item }}
|
||||
--ingress
|
||||
--region {{ aws_region }}
|
||||
loop: "{{ temp_deny_rules }}"
|
||||
when: temp_deny_rules | length > 0
|
||||
register: nacl_deleted_rules
|
||||
changed_when: true
|
||||
|
||||
# 3. Reinicio de Servicio Web en EC2 para limpiar bloqueos en memoria
|
||||
- name: Reiniciar servicio tesis-portal via AWS SSM para limpiar memoria de bloqueos
|
||||
ansible.builtin.command: >
|
||||
aws ssm send-command
|
||||
--instance-ids {{ portal_instance_id }}
|
||||
--document-name "AWS-RunShellScript"
|
||||
--parameters 'commands=["systemctl restart tesis-portal"]'
|
||||
--region {{ aws_region }}
|
||||
--output json
|
||||
register: ssm_restart_cmd
|
||||
changed_when: true
|
||||
|
||||
- name: Esperar finalizacion efectiva del reinicio en SSM
|
||||
ansible.builtin.command: >
|
||||
aws ssm wait command-executed
|
||||
--command-id {{ (ssm_restart_cmd.stdout | from_json).Command.CommandId }}
|
||||
--instance-id {{ portal_instance_id }} --region {{ aws_region }}
|
||||
changed_when: false
|
||||
|
||||
# 4. Verificacion de Salud Final
|
||||
- name: Verificar restablecimiento del acceso al portal web
|
||||
ansible.builtin.uri:
|
||||
url: "{{ portal_url }}/health"
|
||||
status_code: 200
|
||||
return_content: true
|
||||
register: final_health_check
|
||||
retries: 5
|
||||
delay: 2
|
||||
|
||||
- name: Resumen de restauracion completada
|
||||
ansible.builtin.debug:
|
||||
msg:
|
||||
- "=========================================================="
|
||||
- " ESTADO DEL LABORATORIO RESTAURADO"
|
||||
- "=========================================================="
|
||||
- "NACL: Reglas eliminadas de este origen: {{ temp_deny_rules }}"
|
||||
- "IAM: Limpieza solicitada: {{ cleanup_iam_confirm | bool }}"
|
||||
- "Portal Web: Memoria de bloqueos reiniciada; /health responde"
|
||||
- "Health Check: {{ final_health_check.json.status }} (Version: {{ final_health_check.json.version }})"
|
||||
- "=========================================================="
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
---
|
||||
# ==============================================================================
|
||||
# Suite Completa de Simulaciones Red Team y Limpieza limitada
|
||||
# Sistema IR Automatizado en AWS (TIC Tesis)
|
||||
#
|
||||
# Uso desde la raiz (requiere vars.yml generado y confirmacion explicita):
|
||||
# ansible-playbook ansible/playbooks/simulations/run_all.yml \
|
||||
# --tags brute_force -e simulation_confirm=true
|
||||
# Consultar README.md para perfiles IAM y alcance de cleanup.
|
||||
# ==============================================================================
|
||||
|
||||
- name: "Ejecutar Simulacion: 01 Fuerza Bruta"
|
||||
ansible.builtin.import_playbook: 01_brute_force.yml
|
||||
tags: [brute_force, all]
|
||||
|
||||
- name: "Ejecutar Simulacion: 02 Escaneo de Puertos"
|
||||
ansible.builtin.import_playbook: 02_port_scan.yml
|
||||
tags: [port_scan, all]
|
||||
|
||||
- name: "Ejecutar Simulacion: 03 Escalada de Privilegios"
|
||||
ansible.builtin.import_playbook: 03_privilege_escalation.yml
|
||||
tags: [privilege_escalation, all]
|
||||
|
||||
- name: "Ejecutar Simulacion: 04 Fuga de Credenciales"
|
||||
ansible.builtin.import_playbook: 04_credential_leak.yml
|
||||
tags: [credential_leak, all]
|
||||
|
||||
- name: "Ejecutar Simulacion: 05 Exfiltracion S3"
|
||||
ansible.builtin.import_playbook: 05_s3_exfiltration.yml
|
||||
tags: [exfiltration, all]
|
||||
|
||||
- name: "Ejecutar Rollback y Limpieza limitada"
|
||||
ansible.builtin.import_playbook: rollback_cleanup.yml
|
||||
tags: [cleanup, rollback, all]
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
---
|
||||
# Ejemplo portable. Generar vars.yml localmente antes de ejecutar.
|
||||
|
||||
portal_public_ip: 192.0.2.10
|
||||
portal_url: http://192.0.2.10
|
||||
aws_region: us-east-2
|
||||
vpc_id: vpc-example
|
||||
nacl_id: acl-example
|
||||
sensitive_bucket: tesis-ir-sensitive-data-123456789012-us-east-2
|
||||
evidence_bucket: tesis-ir-evidence-123456789012-us-east-2
|
||||
logs_bucket: tesis-ir-logs-123456789012-us-east-2
|
||||
dynamodb_incidents_table: tesis-ir_incidents
|
||||
dynamodb_state_table: tesis-ir_detection_state
|
||||
portal_instance_id: i-example
|
||||
test_iam_username: tesis-ir-temp-escalation-test
|
||||
test_escalation_policy_arn: arn:aws:iam::aws:policy/ReadOnlyAccess
|
||||
emergency_deny_policy_name: EmergencyDenyAll
|
||||
|
||||
simulation_confirm: false
|
||||
simulation_iam_profile: ""
|
||||
cleanup_iam_confirm: false
|
||||
simulation_attacker_cidr: ""
|
||||
simulation_cleanup_rule_numbers: []
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,49 @@
|
|||
"""Genera ansible/playbooks/simulations/vars.yml desde outputs de Terraform."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import yaml
|
||||
|
||||
|
||||
def main():
|
||||
root = Path(__file__).resolve().parents[2]
|
||||
tf_dir = root / "terraform-tesis-ir-secure-portal"
|
||||
out_file = root / "ansible/playbooks/simulations/vars.yml"
|
||||
try:
|
||||
raw = subprocess.run(
|
||||
["terraform", f"-chdir={tf_dir}", "output", "-json"],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
data = json.loads(raw.stdout)
|
||||
vars_content = {
|
||||
"portal_public_ip": data["portal_public_ip"]["value"],
|
||||
"portal_url": data["portal_url"]["value"],
|
||||
"aws_region": data["region"]["value"],
|
||||
"vpc_id": data["vpc_id"]["value"],
|
||||
"nacl_id": data["mitigation_network_acl_id"]["value"],
|
||||
"sensitive_bucket": data["sensitive_bucket"]["value"],
|
||||
"evidence_bucket": data["evidence_bucket"]["value"],
|
||||
"logs_bucket": data["logs_bucket"]["value"],
|
||||
"dynamodb_incidents_table": data["dynamodb_incidents_table"]["value"],
|
||||
"dynamodb_state_table": data["dynamodb_state_table"]["value"],
|
||||
"portal_instance_id": data["portal_instance_id"]["value"],
|
||||
"test_iam_username": "tesis-ir-temp-escalation-test",
|
||||
"test_escalation_policy_arn": "arn:aws:iam::aws:policy/ReadOnlyAccess",
|
||||
"emergency_deny_policy_name": "EmergencyDenyAll",
|
||||
}
|
||||
with open(out_file, "w", encoding="utf-8") as f:
|
||||
f.write("---\n# Variables de simulacion actualizadas automaticamente desde Terraform\n\n")
|
||||
yaml.dump(vars_content, f, default_flow_style=False, sort_keys=False)
|
||||
print(f"Variables de simulacion actualizadas: {out_file}")
|
||||
except (OSError, ValueError, subprocess.CalledProcessError) as exc:
|
||||
print(f"Error generando vars.yml: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
|
|
@ -22,14 +22,20 @@ class PortalTest(unittest.TestCase):
|
|||
self.secret = Path(self.tmp.name) / "session_secret"
|
||||
self.secret.write_bytes(b"local-test-session-value")
|
||||
from unittest.mock import patch
|
||||
env = patch.dict(os.environ, {
|
||||
"PORTAL_LOG_FILE": str(self.log),
|
||||
"PORTAL_SESSION_SECRET_FILE": str(self.secret),
|
||||
"PORTAL_ASSET_NAME": "custom-portal-ec2",
|
||||
})
|
||||
|
||||
env = patch.dict(
|
||||
os.environ,
|
||||
{
|
||||
"PORTAL_LOG_FILE": str(self.log),
|
||||
"PORTAL_SESSION_SECRET_FILE": str(self.secret),
|
||||
"PORTAL_ASSET_NAME": "custom-portal-ec2",
|
||||
},
|
||||
)
|
||||
env.start()
|
||||
self.addCleanup(env.stop)
|
||||
spec = importlib.util.spec_from_file_location("portal_app", ROOT / "ansible/roles/portal_app/files/app.py")
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"portal_app", ROOT / "ansible/roles/portal_app/files/app.py"
|
||||
)
|
||||
self.app = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(self.app)
|
||||
self.server = HTTPServer(("127.0.0.1", 0), self.app.Handler)
|
||||
|
|
@ -61,10 +67,23 @@ class PortalTest(unittest.TestCase):
|
|||
|
||||
def test_five_failures_lock_account_and_preserve_detector_contract(self):
|
||||
password = "incorrect-test-password"
|
||||
headers = {"Content-Type": "application/x-www-form-urlencoded", "X-Forwarded-For": "198.51.100.8"}
|
||||
headers = {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
"X-Forwarded-For": "198.51.100.8",
|
||||
}
|
||||
for _ in range(5):
|
||||
self.request("POST", "/login", urlencode({"username": "admin.demo", "password": password}), headers)
|
||||
self.request("POST", "/login", urlencode({"username": "admin.demo", "password": password}), headers)
|
||||
self.request(
|
||||
"POST",
|
||||
"/login",
|
||||
urlencode({"username": "admin.demo", "password": password}),
|
||||
headers,
|
||||
)
|
||||
self.request(
|
||||
"POST",
|
||||
"/login",
|
||||
urlencode({"username": "admin.demo", "password": password}),
|
||||
headers,
|
||||
)
|
||||
events = [json.loads(line) for line in self.log.read_text().splitlines()]
|
||||
failed = [event for event in events if event["event_type"] == "login_failed"]
|
||||
self.assertEqual(len(failed), 5)
|
||||
|
|
@ -81,19 +100,170 @@ class PortalTest(unittest.TestCase):
|
|||
def test_valid_login_signed_session_and_tamper_rejection(self):
|
||||
import base64
|
||||
import hashlib
|
||||
|
||||
salt = b"test-salt"
|
||||
digest = hashlib.pbkdf2_hmac("sha256", b"correct-test-password", salt, 120000)
|
||||
self.app.USERS["test.demo"] = {
|
||||
"display": "Test",
|
||||
"hash": base64.b64encode(salt).decode() + ":" + base64.b64encode(digest).decode(),
|
||||
"hash": base64.b64encode(salt).decode()
|
||||
+ ":"
|
||||
+ base64.b64encode(digest).decode(),
|
||||
}
|
||||
status, headers, _ = self.request(
|
||||
"POST", "/login", urlencode({"username": "test.demo", "password": "correct-test-password"}),
|
||||
"POST",
|
||||
"/login",
|
||||
urlencode({"username": "test.demo", "password": "correct-test-password"}),
|
||||
{"Content-Type": "application/x-www-form-urlencoded"},
|
||||
)
|
||||
self.assertEqual(status, 302)
|
||||
cookie = headers["Set-Cookie"].split(";", 1)[0]
|
||||
self.assertEqual(self.request("GET", "/dashboard", headers={"Cookie": cookie})[0], 200)
|
||||
self.assertEqual(self.request("GET", "/dashboard", headers={"Cookie": cookie + "tampered"})[0], 302)
|
||||
self.assertEqual(
|
||||
self.request("GET", "/dashboard", headers={"Cookie": cookie})[0], 200
|
||||
)
|
||||
self.assertEqual(
|
||||
self.request("GET", "/dashboard", headers={"Cookie": cookie + "tampered"})[
|
||||
0
|
||||
],
|
||||
302,
|
||||
)
|
||||
self.assertEqual(self.secret.read_bytes(), b"local-test-session-value")
|
||||
self.assertEqual(json.loads(self.log.read_text().splitlines()[0])["event_type"], "login_success")
|
||||
self.assertEqual(
|
||||
json.loads(self.log.read_text().splitlines()[0])["event_type"],
|
||||
"login_success",
|
||||
)
|
||||
|
||||
def test_metrics_and_telemetry_endpoint(self):
|
||||
status, headers, data = self.request("GET", "/health")
|
||||
self.assertEqual(status, 200)
|
||||
self.assertIn("x-response-time", {k.lower(): v for k, v in headers.items()})
|
||||
health_json = json.loads(data)
|
||||
self.assertEqual(health_json["status"], "ok")
|
||||
self.assertIn("uptime_seconds", health_json)
|
||||
self.assertIn("version", health_json)
|
||||
|
||||
# /api/metrics sin autenticar desde IP externa devuelve 401
|
||||
ext_headers = {"X-Forwarded-For": "203.0.113.50"}
|
||||
status, _, _ = self.request("GET", "/api/metrics", headers=ext_headers)
|
||||
self.assertEqual(status, 401)
|
||||
|
||||
# /api/metrics desde loopback devuelve 200 con telemetría completa
|
||||
status, _, data = self.request("GET", "/api/metrics")
|
||||
self.assertEqual(status, 200)
|
||||
metrics = json.loads(data)
|
||||
self.assertIn("latency", metrics)
|
||||
self.assertIn("requests", metrics)
|
||||
self.assertIn("uptime", metrics)
|
||||
self.assertIn("system", metrics)
|
||||
self.assertIn("audit", metrics)
|
||||
|
||||
def test_metrics_use_observations_and_nearest_rank_percentiles(self):
|
||||
from unittest.mock import patch
|
||||
|
||||
empty = self.app.get_latency_stats()
|
||||
self.assertEqual(empty["samples"], 0)
|
||||
self.assertIsNone(empty["p95_ms"])
|
||||
self.assertEqual(empty["recent"], [])
|
||||
self.app.METRICS["latencies_ms"] = list(range(1, 22))
|
||||
stats = self.app.get_latency_stats()
|
||||
self.assertEqual(stats["p95_ms"], 20)
|
||||
self.assertEqual(stats["p50_ms"], 11)
|
||||
with patch.object(self.app.os, "getloadavg", side_effect=OSError), patch.object(
|
||||
self.app.os.path, "exists", return_value=False
|
||||
):
|
||||
unavailable = self.app.get_system_stats()
|
||||
self.assertIsNone(unavailable["load_1m"])
|
||||
self.assertIsNone(unavailable["mem_percent"])
|
||||
|
||||
def test_lock_count_only_includes_distinct_active_ips(self):
|
||||
future = self.app.epoch_now() + 60
|
||||
self.app.FAILED_STATE.update({
|
||||
"198.51.100.1|alice": {"locked_until": future},
|
||||
"198.51.100.1|bob": {"locked_until": future},
|
||||
"198.51.100.2|carol": {"locked_until": 0},
|
||||
})
|
||||
_, _, data = self.request("GET", "/api/metrics")
|
||||
self.assertEqual(json.loads(data)["security"]["locked_ips_count"], 1)
|
||||
|
||||
def test_audit_polling_escapes_untrusted_fields_in_browser(self):
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
cookie = self.app.sign_value(f"admin.demo:{self.app.epoch_now()}")
|
||||
_, _, data = self.request(
|
||||
"GET", "/dashboard", headers={"Cookie": f"portal_session={cookie}"}
|
||||
)
|
||||
script = next(s for s in re.findall(r"<script>(.*?)</script>", data.decode(), re.S)
|
||||
if "function updateTelemetry" in s)
|
||||
_, _, data = self.request("GET", "/api/metrics")
|
||||
metrics = json.loads(data)
|
||||
payload = '<img src=x onerror="alert(1)">'
|
||||
metrics["audit"] = [dict.fromkeys(
|
||||
["time", "event_type", "username", "source_ip", "severity", "result", "reason"],
|
||||
payload,
|
||||
)]
|
||||
harness = """
|
||||
const vm = require('node:vm');
|
||||
const assert = require('node:assert/strict');
|
||||
const input = JSON.parse(require('node:fs').readFileSync(0, 'utf8'));
|
||||
const nodes = {};
|
||||
const context = {
|
||||
document: {getElementById: id => nodes[id] ??= {style: {}}},
|
||||
performance: {now: () => 0}, setInterval: () => {},
|
||||
console: {warn: error => {throw error;}},
|
||||
fetch: async () => ({ok: true, json: async () => input.metrics})
|
||||
};
|
||||
vm.createContext(context);
|
||||
vm.runInContext(input.script, context);
|
||||
context.updateTelemetry().then(() => {
|
||||
const rendered = nodes['audit-tbody'].innerHTML;
|
||||
assert(!rendered.includes('<img'));
|
||||
assert(rendered.includes('<img'));
|
||||
assert(rendered.includes('"'));
|
||||
}).catch(error => {console.error(error); process.exitCode = 1;});
|
||||
"""
|
||||
subprocess.run(["node", "-e", harness], input=json.dumps({
|
||||
"script": script, "metrics": metrics,
|
||||
}), text=True, capture_output=True, check=True)
|
||||
|
||||
def test_light_mode_and_zero_emojis_in_rendered_html(self):
|
||||
import re
|
||||
|
||||
status, _, data = self.request("GET", "/login")
|
||||
self.assertEqual(status, 200)
|
||||
html_login = data.decode("utf-8")
|
||||
self.assertIn("data-theme", html_login)
|
||||
self.assertIn("btn-theme", html_login)
|
||||
self.assertIn("<svg", html_login)
|
||||
|
||||
# Verificar ausencia total de emojis en login
|
||||
login_emojis = re.findall(
|
||||
r"[\U00010000-\U0010ffff\u2600-\u27bf\u2300-\u23ff]", html_login
|
||||
)
|
||||
self.assertEqual(login_emojis, [])
|
||||
|
||||
# Verificar dashboard renderizado y ausencia total de emojis
|
||||
cookie = self.app.sign_value(f"admin.demo:{self.app.epoch_now()}")
|
||||
headers = {"Cookie": f"portal_session={cookie}"}
|
||||
status, _, data = self.request("GET", "/dashboard", headers=headers)
|
||||
self.assertEqual(status, 200)
|
||||
html_dash = data.decode("utf-8")
|
||||
self.assertIn("btn-theme", html_dash)
|
||||
self.assertIn("data-theme", html_dash)
|
||||
self.assertIn("<svg", html_dash)
|
||||
dash_emojis = re.findall(
|
||||
r"[\U00010000-\U0010ffff\u2600-\u27bf\u2300-\u23ff]", html_dash
|
||||
)
|
||||
self.assertEqual(dash_emojis, [])
|
||||
|
||||
def test_glassmorphism_login_styling(self):
|
||||
status, _, data = self.request("GET", "/login")
|
||||
self.assertEqual(status, 200)
|
||||
html_login = data.decode("utf-8")
|
||||
self.assertIn("glass-card", html_login)
|
||||
self.assertIn("ambient-orb", html_login)
|
||||
self.assertIn("glass-input", html_login)
|
||||
self.assertIn("glass-btn-primary", html_login)
|
||||
self.assertIn("glass-demo-pill", html_login)
|
||||
self.assertIn("backdrop-filter", html_login)
|
||||
self.assertIn("saturate", html_login)
|
||||
self.assertIn("fillDemo", html_login)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,31 @@
|
|||
"""Las simulaciones abortan sin consentimiento antes de cargar datos o llamar AWS."""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class SimulationGuardTest(unittest.TestCase):
|
||||
def test_all_entrypoints_refuse_execution_by_default(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
aws = Path(tmp) / "aws"
|
||||
marker = Path(tmp) / "called"
|
||||
aws.write_text('#!/bin/sh\ntouch "' + str(marker) + '"\nexit 97\n')
|
||||
aws.chmod(0o700)
|
||||
playbooks = ROOT / "ansible/playbooks/simulations"
|
||||
for playbook in [*sorted(playbooks.glob("0*.yml")), playbooks / "rollback_cleanup.yml"]:
|
||||
with self.subTest(playbook=playbook.name):
|
||||
result = subprocess.run(
|
||||
[shutil.which("ansible-playbook"), "-i", "localhost,", str(playbook)],
|
||||
env={**os.environ, "PATH": tmp + os.pathsep + os.environ["PATH"],
|
||||
"ANSIBLE_CONFIG": str(ROOT / "ansible/ansible.cfg")},
|
||||
capture_output=True, text=True, timeout=30,
|
||||
)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("Simulacion deshabilitada", result.stdout)
|
||||
self.assertFalse(marker.exists(), "Se invoco AWS antes de confirmar")
|
||||
Loading…
Reference in New Issue