diff --git a/ansible/playbooks/simulations/01_brute_force.yml b/ansible/playbooks/simulations/01_brute_force.yml new file mode 100644 index 0000000..ab8ee1b --- /dev/null +++ b/ansible/playbooks/simulations/01_brute_force.yml @@ -0,0 +1,122 @@ +--- +- name: "Simulacion Red Team - Incidente 01: Fuerza Bruta (BRUTE_FORCE)" + hosts: localhost + connection: local + gather_facts: false + + vars_files: + - vars.yml + + 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/" + - "==========================================================" diff --git a/ansible/playbooks/simulations/02_port_scan.yml b/ansible/playbooks/simulations/02_port_scan.yml new file mode 100644 index 0000000..ec945b6 --- /dev/null +++ b/ansible/playbooks/simulations/02_port_scan.yml @@ -0,0 +1,104 @@ +--- +- name: "Simulacion Red Team - Incidente 02: Escaneo de Puertos (PORT_SCAN)" + hosts: localhost + connection: local + gather_facts: false + + vars_files: + - vars.yml + + 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/" + - "==========================================================" diff --git a/ansible/playbooks/simulations/03_privilege_escalation.yml b/ansible/playbooks/simulations/03_privilege_escalation.yml new file mode 100644 index 0000000..aa4b595 --- /dev/null +++ b/ansible/playbooks/simulations/03_privilege_escalation.yml @@ -0,0 +1,90 @@ +--- +- name: "Simulacion Red Team - Incidente 03: Escalada de Privilegios (PRIVILEGE_ESCALATION)" + hosts: localhost + connection: local + gather_facts: false + + vars_files: + - vars.yml + + tasks: + - 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: Verificar si el usuario temporal ya existe + ansible.builtin.command: > + aws iam get-user --user-name {{ test_iam_username }} + register: iam_get_user + ignore_errors: true + changed_when: false + + - name: Crear usuario IAM temporal si no existe + ansible.builtin.command: > + aws iam create-user --user-name {{ test_iam_username }} + when: iam_get_user.rc != 0 + register: iam_create_res + changed_when: true + + - name: Adjuntar politica administrativa para detonar la escalada + ansible.builtin.command: > + aws 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 + ignore_errors: true + changed_when: false + + - 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" + - "==========================================================" diff --git a/ansible/playbooks/simulations/04_credential_leak.yml b/ansible/playbooks/simulations/04_credential_leak.yml new file mode 100644 index 0000000..68407d9 --- /dev/null +++ b/ansible/playbooks/simulations/04_credential_leak.yml @@ -0,0 +1,67 @@ +--- +- name: "Simulacion Red Team - Incidente 04: Fuga de Credenciales (CREDENTIAL_LEAK)" + hosts: localhost + connection: local + gather_facts: false + + vars_files: + - vars.yml + + tasks: + - 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" + - "Nota: Requiere que terraform.tfvars configure authorized_ip_cidrs con una IP distinta a {{ current_ip }}" + + - name: Ejecutar llamada a STS GetCallerIdentity + ansible.builtin.command: > + aws 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/" + - "==========================================================" diff --git a/ansible/playbooks/simulations/05_s3_exfiltration.yml b/ansible/playbooks/simulations/05_s3_exfiltration.yml new file mode 100644 index 0000000..020c361 --- /dev/null +++ b/ansible/playbooks/simulations/05_s3_exfiltration.yml @@ -0,0 +1,65 @@ +--- +- name: "Simulacion Red Team - Incidente 05: Exfiltracion de Datos S3 (EXFILTRATION)" + hosts: localhost + connection: local + gather_facts: false + + vars_files: + - vars.yml + + 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: Asegurar que el archivo sensible simulado existe en el bucket + ansible.builtin.command: > + aws s3 cp - "s3://{{ sensitive_bucket }}/sensible/clientes_demo.json" + args: + stdin: '{"clientes_vip": [{"id": 1, "nombre": "Empresa Demo S.A.", "saldo": 540000}]}' + 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): + s3.get_object(Bucket="{{ sensitive_bucket }}", Key="sensible/clientes_demo.json") + ' + 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/" + - "==========================================================" diff --git a/ansible/playbooks/simulations/README.md b/ansible/playbooks/simulations/README.md new file mode 100644 index 0000000..61466e6 --- /dev/null +++ b/ansible/playbooks/simulations/README.md @@ -0,0 +1,67 @@ +# Suite de Simulaciones Red Team y Rollback Automatizado (Ansible) + +Esta suite automatiza la generación de ataques controlados para validar de forma integral el pipeline de **Detección y Respuesta Automatizada ante Incidentes en AWS** (TIC Tesis), permitiendo simular los 5 incidentes soportados y restaurar el laboratorio a su estado base (*Zero-State*) con un solo comando. + +--- + +## 1. Inventario de Playbooks de Simulación + +| Playbook | Incidente Validado | Severidad | Mitigación Automatizada Probada | Canales | +|---|---|---|---|---| +| `01_brute_force.yml` | `BRUTE_FORCE` | `HIGH` | Bloqueo IP en Network ACL (Ingress DENY) + Lockout 403 en Portal | SES (Gmail) + Telegram | +| `02_port_scan.yml` | `PORT_SCAN` | `MEDIUM` | Detección de `REJECT` en VPC Flow Logs + Bloqueo IP en Network ACL | SES (Gmail) + Telegram | +| `03_privilege_escalation.yml` | `PRIVILEGE_ESCALATION` | `CRITICAL` | Desactivación de claves IAM + Adjunta `EmergencyDenyAll` | SES (Gmail) + Telegram | +| `04_credential_leak.yml` | `CREDENTIAL_LEAK` | `CRITICAL` | Validación de IP autorizada + Inactivación de credenciales | SES (Gmail) + Telegram | +| `05_s3_exfiltration.yml` | `EXFILTRATION` | `HIGH` | Detección de tasa de `GetObject` (>50/h) en CloudTrail Data Events | SES (Gmail) + Telegram | +| `rollback_cleanup.yml` | **Restauración** | — | Limpia reglas DENY en NACL, retira `EmergencyDenyAll` y reinicia memoria del portal | Consola / Logs | +| `run_all.yml` | **Suite Completa** | — | Orquestador maestro para correr las 5 simulaciones y el rollback con tags | Todos | + +--- + +## 2. Requisitos Previos + +1. Contar con credenciales de AWS configuradas en la terminal (ejecutar `aws sts get-caller-identity`). +2. Entorno virtual activo con Ansible y colecciones de AWS: + ```bash + source .venv/bin/activate + ``` + +--- + +## 3. Modo de Uso + +### A. Simular Fuerza Bruta (`BRUTE_FORCE`) +Dispara 5 intentos con contraseñas inválidas contra `/login`, comprueba la respuesta defensiva `403 Bloqueado` y verifica la regla de bloqueo en la Network ACL: +```bash +ansible-playbook ansible/playbooks/simulations/01_brute_force.yml +``` + +### B. Simular Escaneo de Puertos (`PORT_SCAN`) +Envía paquetes TCP hacia puertos cerrados (81 a 92) forzando registros `REJECT` en VPC Flow Logs: +```bash +ansible-playbook ansible/playbooks/simulations/02_port_scan.yml +``` + +### C. Simular Escalada de Privilegios (`PRIVILEGE_ESCALATION`) +Crea el usuario temporal `tesis-ir-temp-escalation-test` y adjunta una política administrativa para gatillar la revocación automática: +```bash +ansible-playbook ansible/playbooks/simulations/03_privilege_escalation.yml +``` + +### D. Simular Fuga de Credenciales (`CREDENTIAL_LEAK`) +Ejecuta la verificación de llamadas API desde origen no autorizado: +```bash +ansible-playbook ansible/playbooks/simulations/04_credential_leak.yml +``` + +### E. Simular Exfiltración en S3 (`EXFILTRATION`) +Ejecuta una ráfaga de 55 descargas sobre el bucket confidencial: +```bash +ansible-playbook ansible/playbooks/simulations/05_s3_exfiltration.yml +``` + +### F. Restauración y Limpieza del Laboratorio (*Rollback Zero-State*) +Elimina las reglas de bloqueo en Network ACL, remueve usuarios y políticas temporales de contención en IAM, y reinicia la memoria del portal web para dejar el entorno 100% limpio y listo para una nueva demostración: +```bash +ansible-playbook ansible/playbooks/simulations/rollback_cleanup.yml +``` diff --git a/ansible/playbooks/simulations/rollback_cleanup.yml b/ansible/playbooks/simulations/rollback_cleanup.yml new file mode 100644 index 0000000..8f7dec9 --- /dev/null +++ b/ansible/playbooks/simulations/rollback_cleanup.yml @@ -0,0 +1,146 @@ +--- +- name: "Rollback y Limpieza Automatizada del Laboratorio de Seguridad (Zero-State)" + hosts: localhost + connection: local + gather_facts: false + + vars_files: + - vars.yml + + 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 (Zero-State)" + + # 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 + ignore_errors: true + changed_when: false + + - name: Bloque de limpieza IAM temporal + when: iam_user_check.rc == 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) + - 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 temporales (numeros 1 a 99) + 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', 'lt', 100) + | 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 5 segundos tras reinicio + ansible.builtin.pause: + seconds: 5 + + # 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 de bloqueo DENY temporales eliminadas" + - "IAM: Usuario temporal y EmergencyDenyAll eliminados" + - "Portal Web: Memoria reiniciada y servicio 100% operativo" + - "Health Check: {{ final_health_check.json.status }} (Version: {{ final_health_check.json.version }})" + - "==========================================================" diff --git a/ansible/playbooks/simulations/run_all.yml b/ansible/playbooks/simulations/run_all.yml new file mode 100644 index 0000000..39e3dda --- /dev/null +++ b/ansible/playbooks/simulations/run_all.yml @@ -0,0 +1,41 @@ +--- +# ============================================================================== +# Suite Completa de Simulaciones Red Team y Restauracion Zero-State +# Sistema IR Automatizado en AWS (TIC Tesis) +# +# Uso: +# - Ejecutar todo el ciclo con rollback final: +# ansible-playbook ansible/playbooks/simulations/run_all.yml +# +# - Ejecutar solo un ataque especifico: +# ansible-playbook ansible/playbooks/simulations/run_all.yml --tags brute_force +# ansible-playbook ansible/playbooks/simulations/run_all.yml --tags port_scan +# ansible-playbook ansible/playbooks/simulations/run_all.yml --tags privilege_escalation +# ansible-playbook ansible/playbooks/simulations/run_all.yml --tags credential_leak +# ansible-playbook ansible/playbooks/simulations/run_all.yml --tags exfiltration +# ansible-playbook ansible/playbooks/simulations/run_all.yml --tags 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 Zero-State" + ansible.builtin.import_playbook: rollback_cleanup.yml + tags: [cleanup, rollback, all] diff --git a/ansible/playbooks/simulations/vars.yml b/ansible/playbooks/simulations/vars.yml new file mode 100644 index 0000000..490b5a4 --- /dev/null +++ b/ansible/playbooks/simulations/vars.yml @@ -0,0 +1,21 @@ +--- +# Variables centrales para la Suite de Ataques Red Team y Rollback (TIC Tesis) +# Alineadas con los outputs activos de Terraform en AWS us-east-2 + +portal_public_ip: "18.219.62.81" +portal_url: "http://18.219.62.81" +aws_region: "us-east-2" +vpc_id: "vpc-00cd654d72a84e9f0" +nacl_id: "acl-0c072d7e12b416874" + +sensitive_bucket: "tesis-ir-sensitive-data-056176271407-us-east-2" +evidence_bucket: "tesis-ir-evidence-056176271407-us-east-2" +logs_bucket: "tesis-ir-logs-056176271407-us-east-2" + +dynamodb_incidents_table: "tesis-ir_incidents" +dynamodb_state_table: "tesis-ir_detection_state" + +portal_instance_id: "i-05a276d44211bf7e7" +test_iam_username: "tesis-ir-temp-escalation-test" +test_escalation_policy_arn: "arn:aws:iam::aws:policy/ReadOnlyAccess" +emergency_deny_policy_name: "EmergencyDenyAll"