diff --git a/.forgejo/workflows/validate.yml b/.forgejo/workflows/validate.yml index 0d68f2e..aa15fa2 100644 --- a/.forgejo/workflows/validate.yml +++ b/.forgejo/workflows/validate.yml @@ -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 diff --git a/.gitignore b/.gitignore index e16bb6f..c9200cf 100644 --- a/.gitignore +++ b/.gitignore @@ -33,3 +33,6 @@ ansible/inventory/hosts.json .ansible/ *.retry ansible/**/vault*.yml + +# Configuracion generada de simulaciones +ansible/playbooks/simulations/vars.yml diff --git a/ansible/playbooks/simulations/01_brute_force.yml b/ansible/playbooks/simulations/01_brute_force.yml new file mode 100644 index 0000000..68c8fcd --- /dev/null +++ b/ansible/playbooks/simulations/01_brute_force.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/" + - "==========================================================" diff --git a/ansible/playbooks/simulations/02_port_scan.yml b/ansible/playbooks/simulations/02_port_scan.yml new file mode 100644 index 0000000..dd3d1c5 --- /dev/null +++ b/ansible/playbooks/simulations/02_port_scan.yml @@ -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/" + - "==========================================================" diff --git a/ansible/playbooks/simulations/03_privilege_escalation.yml b/ansible/playbooks/simulations/03_privilege_escalation.yml new file mode 100644 index 0000000..c4ceaa2 --- /dev/null +++ b/ansible/playbooks/simulations/03_privilege_escalation.yml @@ -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" + - "==========================================================" diff --git a/ansible/playbooks/simulations/04_credential_leak.yml b/ansible/playbooks/simulations/04_credential_leak.yml new file mode 100644 index 0000000..0fee578 --- /dev/null +++ b/ansible/playbooks/simulations/04_credential_leak.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/" + - "==========================================================" diff --git a/ansible/playbooks/simulations/05_s3_exfiltration.yml b/ansible/playbooks/simulations/05_s3_exfiltration.yml new file mode 100644 index 0000000..299d37a --- /dev/null +++ b/ansible/playbooks/simulations/05_s3_exfiltration.yml @@ -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/" + - "==========================================================" diff --git a/ansible/playbooks/simulations/README.md b/ansible/playbooks/simulations/README.md new file mode 100644 index 0000000..845e83f --- /dev/null +++ b/ansible/playbooks/simulations/README.md @@ -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. diff --git a/ansible/playbooks/simulations/iam_actor.yml b/ansible/playbooks/simulations/iam_actor.yml new file mode 100644 index 0000000..c7e5eda --- /dev/null +++ b/ansible/playbooks/simulations/iam_actor.yml @@ -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." diff --git a/ansible/playbooks/simulations/preflight.yml b/ansible/playbooks/simulations/preflight.yml new file mode 100644 index 0000000..10ad979 --- /dev/null +++ b/ansible/playbooks/simulations/preflight.yml @@ -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-." diff --git a/ansible/playbooks/simulations/rollback_cleanup.yml b/ansible/playbooks/simulations/rollback_cleanup.yml new file mode 100644 index 0000000..cd8600d --- /dev/null +++ b/ansible/playbooks/simulations/rollback_cleanup.yml @@ -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 }})" + - "==========================================================" diff --git a/ansible/playbooks/simulations/run_all.yml b/ansible/playbooks/simulations/run_all.yml new file mode 100644 index 0000000..55ea9bb --- /dev/null +++ b/ansible/playbooks/simulations/run_all.yml @@ -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] diff --git a/ansible/playbooks/simulations/vars.example.yml b/ansible/playbooks/simulations/vars.example.yml new file mode 100644 index 0000000..4d8b250 --- /dev/null +++ b/ansible/playbooks/simulations/vars.example.yml @@ -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: [] diff --git a/ansible/roles/portal_app/files/app.py b/ansible/roles/portal_app/files/app.py index 7cd1e23..310b227 100644 --- a/ansible/roles/portal_app/files/app.py +++ b/ansible/roles/portal_app/files/app.py @@ -12,7 +12,9 @@ import secrets import time LOG_FILE = os.environ.get("PORTAL_LOG_FILE", "/var/log/tesis-portal/app.log") -SESSION_SECRET_FILE = os.environ.get("PORTAL_SESSION_SECRET_FILE", "/opt/tesis-portal/session_secret") +SESSION_SECRET_FILE = os.environ.get( + "PORTAL_SESSION_SECRET_FILE", "/opt/tesis-portal/session_secret" +) LOCK_THRESHOLD = 5 LOCK_SECONDS = 300 EC_TZ = timezone(timedelta(hours=-5), name="America/Guayaquil") @@ -20,6 +22,7 @@ AFFECTED_SERVICE = "Portal de autenticacion corporativo" ASSET_NAME = os.environ.get("PORTAL_ASSET_NAME", "tesis-ir-portal-ec2") ASSET_TYPE = "EC2 web application" COMPANY_NAME = "Asteria Operaciones" +PORTAL_VERSION = "2.2.0" # Usuarios internos de la aplicacion. No son usuarios IAM reales de AWS. USERS = { @@ -38,6 +41,84 @@ USERS = { } FAILED_STATE = {} +SERVER_START_TIME = time.time() + +# Métricas en memoria para telemetría y tiempos de respuesta (TIC) +METRICS = { + "requests_total": 0, + "status_2xx": 0, + "status_3xx": 0, + "status_4xx": 0, + "status_5xx": 0, + "latencies_ms": [], + "recent_audit": [], +} + +# Iconografía minimalista en SVG vectorial (sin uso de emojis según el estándar formal del TIC) +SVG_ICONS = { + "shield": ( + '' + '' + ), + "pulse": ( + '' + '' + ), + "chart": ( + '' + '' + ), + "alert": ( + '' + ), + "sun": ( + '' + ), + "moon": ( + '' + ), + "logout": ( + '' + '' + ), + "user": ( + '' + '' + ), + "lock": ( + '' + '' + '' + ), + "arrow_right": ( + '' + '' + ), +} def now_ecuador(): @@ -52,6 +133,131 @@ def epoch_now(): return int(time.time()) +def get_uptime_seconds(): + return int(time.time() - SERVER_START_TIME) + + +def format_uptime(seconds): + days, rem = divmod(seconds, 86400) + hours, rem = divmod(rem, 3600) + minutes, secs = divmod(rem, 60) + if days > 0: + return f"{days}d {hours}h {minutes}m" + if hours > 0: + return f"{hours}h {minutes}m {secs}s" + return f"{minutes}m {secs}s" + + +def get_system_stats(): + try: + load1, load5, load15 = os.getloadavg() + except (AttributeError, OSError): + load1, load5, load15 = None, None, None + + mem_total_mb = None + mem_used_mb = None + mem_percent = None + try: + if os.path.exists("/proc/meminfo"): + meminfo = {} + with open("/proc/meminfo", "r") as f: + for line in f: + parts = line.split(":") + if len(parts) == 2: + key = parts[0].strip() + val = parts[1].strip().split()[0] + meminfo[key] = int(val) + total = meminfo["MemTotal"] + avail = meminfo["MemAvailable"] + used = total - avail + mem_total_mb = round(total / 1024) + mem_used_mb = round(used / 1024) + mem_percent = round((used / total) * 100, 1) + except (OSError, ValueError, KeyError, ZeroDivisionError): + pass + + return { + "load_1m": round(load1, 2) if load1 is not None else None, + "load_5m": round(load5, 2) if load5 is not None else None, + "load_15m": round(load15, 2) if load15 is not None else None, + "mem_used_mb": mem_used_mb, + "mem_total_mb": mem_total_mb, + "mem_percent": mem_percent, + } + + +def record_request_metric(status_code, latency_ms): + METRICS["requests_total"] += 1 + if 200 <= status_code < 300: + METRICS["status_2xx"] += 1 + elif 300 <= status_code < 400: + METRICS["status_3xx"] += 1 + elif 400 <= status_code < 500: + METRICS["status_4xx"] += 1 + elif status_code >= 500: + METRICS["status_5xx"] += 1 + + latencies = METRICS["latencies_ms"] + latencies.append(round(latency_ms, 2)) + if len(latencies) > 100: + latencies.pop(0) + + +def get_latency_stats(): + latencies = METRICS["latencies_ms"] + if not latencies: + return { + "last_ms": None, + "avg_ms": None, + "p50_ms": None, + "p95_ms": None, + "min_ms": None, + "max_ms": None, + "samples": 0, + "recent": [], + } + sorted_l = sorted(latencies) + p95_idx = (95 * len(sorted_l) + 99) // 100 - 1 + return { + "last_ms": latencies[-1], + "avg_ms": round(sum(latencies) / len(latencies), 2), + "p50_ms": sorted_l[(50 * len(sorted_l) + 99) // 100 - 1], + "p95_ms": sorted_l[p95_idx], + "min_ms": sorted_l[0], + "max_ms": sorted_l[-1], + "samples": len(latencies), + "recent": latencies[-12:], + } + + +def locked_ip_count(): + return len({ + key.split("|", 1)[0] + for key, value in FAILED_STATE.items() + if value.get("locked_until", 0) > epoch_now() + }) + + +def record_audit_event(event): + recent = METRICS["recent_audit"] + dt = datetime.now(EC_TZ).strftime("%H:%M:%S") + summary = { + "time": dt, + "timestamp_utc": event.get("timestamp_utc", now_utc()), + "event_type": event.get("event_type", "unknown"), + "username": event.get("username", "—"), + "source_ip": event.get("sourceIPAddress") or event.get("source_ip", "—"), + "result": event.get("result", "INFO"), + "severity": event.get("severity", "LOW"), + "reason": ( + event.get("failure_reason") or event.get("message") or "Operacion normal" + ), + } + recent.insert(0, summary) + if len(recent) > 30: + recent.pop() + + def get_session_secret(): if os.path.exists(SESSION_SECRET_FILE): with open(SESSION_SECRET_FILE, "rb") as f: @@ -80,8 +286,10 @@ def base_event(event): def write_event(event): + ev = base_event(event) + record_audit_event(ev) with open(LOG_FILE, "a", encoding="utf-8") as f: - f.write(json.dumps(base_event(event), ensure_ascii=False, separators=(",", ":")) + "\n") + f.write(json.dumps(ev, ensure_ascii=False, separators=(",", ":")) + "\n") def verify_password(username, password): @@ -104,7 +312,9 @@ def verify_signed_value(value): if not value or "." not in value: return None payload, sig = value.rsplit(".", 1) - expected = hmac.new(SESSION_SECRET, payload.encode("utf-8"), hashlib.sha256).hexdigest() + expected = hmac.new( + SESSION_SECRET, payload.encode("utf-8"), hashlib.sha256 + ).hexdigest() if hmac.compare_digest(sig, expected): return payload return None @@ -114,51 +324,338 @@ def html_escape(value): return html.escape(str(value if value is not None else "")) +def shared_styles(): + """Estilos y variables de diseño inspirados en Emil Kowalski: + Craft riguroso, micro-interacciones suaves, bordes sutiles con iluminación interna, + soporte completo para Modo Claro / Modo Oscuro, cero emojis e iconografía SVG vectorial. + """ + return """ + :root, [data-theme="dark"] { + --bg: #070a12; + --bg-surface: #0e1424; + --bg-elevated: #141c30; + --bg-subtle: #1b2640; + --border: rgba(255, 255, 255, 0.08); + --border-highlight: rgba(255, 255, 255, 0.16); + --border-focus: #38bdf8; + --text-main: #f8fafc; + --text-muted: #94a3b8; + --text-dim: #64748b; + --primary: #3b82f6; + --primary-hover: #2563eb; + --accent-cyan: #38bdf8; + --emerald: #10b981; + --emerald-bg: rgba(16, 185, 129, 0.12); + --amber: #f59e0b; + --amber-bg: rgba(245, 158, 11, 0.12); + --orange: #f97316; + --orange-bg: rgba(249, 115, 22, 0.12); + --red: #ef4444; + --red-bg: rgba(239, 68, 68, 0.12); + --shadow-card: inset 0 1px 0 rgba(255, 255, 255, 0.08), 0 12px 36px -8px rgba(0, 0, 0, 0.6); + --shadow-sm: inset 0 1px 0 rgba(255, 255, 255, 0.06), 0 2px 6px rgba(0, 0, 0, 0.4); + --nav-bg: rgba(7, 10, 18, 0.80); + --bg-gradient: radial-gradient(1200px circle at 50% -20%, rgba(30, 58, 138, 0.22), transparent 75%), #070a12; + --table-header-bg: #141c30; + --table-row-hover: rgba(255, 255, 255, 0.02); + --theme-sun-display: block; + --theme-moon-display: none; + } + [data-theme="light"] { + --bg: #f8fafc; + --bg-surface: #ffffff; + --bg-elevated: #f1f5f9; + --bg-subtle: #e2e8f0; + --border: rgba(15, 23, 42, 0.08); + --border-highlight: rgba(15, 23, 42, 0.18); + --border-focus: #0284c7; + --text-main: #0f172a; + --text-muted: #475569; + --text-dim: #64748b; + --primary: #2563eb; + --primary-hover: #1d4ed8; + --accent-cyan: #0284c7; + --emerald: #059669; + --emerald-bg: rgba(5, 150, 105, 0.10); + --amber: #d97706; + --amber-bg: rgba(217, 119, 6, 0.10); + --orange: #ea580c; + --orange-bg: rgba(234, 88, 12, 0.10); + --red: #dc2626; + --red-bg: rgba(220, 38, 38, 0.10); + --shadow-card: inset 0 1px 0 rgba(255, 255, 255, 0.9), 0 12px 32px -8px rgba(15, 23, 42, 0.08), 0 1px 3px rgba(15, 23, 42, 0.05); + --shadow-sm: inset 0 1px 0 rgba(255, 255, 255, 0.8), 0 1px 3px rgba(15, 23, 42, 0.06); + --nav-bg: rgba(255, 255, 255, 0.85); + --bg-gradient: radial-gradient(1200px circle at 50% -20%, rgba(219, 234, 254, 0.7), transparent 75%), #f8fafc; + --table-header-bg: #f8fafc; + --table-row-hover: rgba(15, 23, 42, 0.02); + --theme-sun-display: none; + --theme-moon-display: block; + } + :root { + --radius-sm: 8px; + --radius-md: 14px; + --radius-lg: 20px; + --ease-snappy: cubic-bezier(0.16, 1, 0.3, 1); + } + * { box-sizing: border-box; margin: 0; padding: 0; } + body { + min-height: 100vh; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Inter", sans-serif; + background: var(--bg-gradient); + color: var(--text-main); + line-height: 1.5; + -webkit-font-smoothing: antialiased; + overflow-x: hidden; + transition: background-color 0.2s var(--ease-snappy), color 0.2s var(--ease-snappy); + } + .num, .metric-value, .latency-val, .uptime-val { + font-variant-numeric: tabular-nums; + font-feature-settings: 'tnum' 1; + } + + /* Minimalist SVG Icon styles */ + .icon { + width: 16px; + height: 16px; + vertical-align: middle; + display: inline-block; + flex-shrink: 0; + } + .icon-alert { + width: 38px; + height: 38px; + color: var(--red); + } + + /* Micro-interactions & animations */ + button, .btn, .tab-btn, .pill-btn, .btn-theme { + transition: all 0.16s var(--ease-snappy); + cursor: pointer; + user-select: none; + } + button:active, .btn:active, .tab-btn:active, .pill-btn:active, .btn-theme:active { + transform: scale(0.98); + } + + /* Live Beacon Pulsing */ + .beacon { + width: 8px; + height: 8px; + border-radius: 50%; + background: var(--emerald); + display: inline-block; + position: relative; + } + .beacon::after { + content: ''; + position: absolute; + inset: -3px; + border-radius: 50%; + border: 2px solid var(--emerald); + animation: beacon-pulse 2.2s var(--ease-snappy) infinite; + } + @keyframes beacon-pulse { + 0% { transform: scale(0.8); opacity: 1; } + 100% { transform: scale(2.5); opacity: 0; } + } + + /* Badges & Severity Chips */ + .badge { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 3px 9px; + border-radius: 999px; + font-size: 11px; + font-weight: 700; + letter-spacing: 0.04em; + text-transform: uppercase; + font-variant-numeric: tabular-nums; + } + .badge.success { background: var(--emerald-bg); color: #10b981; border: 1px solid rgba(16, 185, 129, 0.25); } + .badge.info { background: rgba(56, 189, 248, 0.12); color: var(--accent-cyan); border: 1px solid rgba(56, 189, 248, 0.25); } + .badge.warning { background: var(--amber-bg); color: var(--amber); border: 1px solid rgba(245, 158, 11, 0.25); } + .badge.high { background: var(--orange-bg); color: var(--orange); border: 1px solid rgba(249, 115, 22, 0.25); } + .badge.critical { background: var(--red-bg); color: var(--red); border: 1px solid rgba(239, 68, 68, 0.25); } + + /* Header */ + .top-nav { + height: 64px; + display: flex; + align-items: center; + justify-content: space-between; + padding: 0 32px; + border-bottom: 1px solid var(--border); + background: var(--nav-bg); + backdrop-filter: blur(14px); + position: sticky; + top: 0; + z-index: 50; + transition: background-color 0.2s var(--ease-snappy), border-color 0.2s var(--ease-snappy); + } + .nav-brand { + display: flex; + align-items: center; + gap: 12px; + font-weight: 800; + font-size: 17px; + letter-spacing: -0.02em; + } + .nav-brand-icon { + width: 30px; + height: 30px; + border-radius: 8px; + background: linear-gradient(135deg, var(--primary), var(--accent-cyan)); + color: white; + display: grid; + place-items: center; + box-shadow: 0 2px 10px rgba(56, 189, 248, 0.35); + } + .nav-actions { + display: flex; + align-items: center; + gap: 12px; + } + .nav-user { + display: flex; + align-items: center; + gap: 8px; + background: var(--bg-surface); + border: 1px solid var(--border); + padding: 5px 12px; + border-radius: 999px; + font-size: 13px; + } + .nav-user-avatar { + width: 20px; + height: 20px; + border-radius: 50%; + background: var(--bg-elevated); + display: grid; + place-items: center; + font-size: 11px; + font-weight: 700; + color: var(--accent-cyan); + } + .btn-logout { + color: var(--text-muted); + text-decoration: none; + font-size: 12px; + font-weight: 600; + padding: 6px 12px; + border-radius: var(--radius-sm); + border: 1px solid var(--border); + background: transparent; + display: inline-flex; + align-items: center; + gap: 6px; + transition: all 0.16s var(--ease-snappy); + } + .btn-logout:hover { + color: var(--text-main); + border-color: var(--border-highlight); + background: var(--bg-surface); + } + .btn-theme { + width: 32px; + height: 32px; + display: grid; + place-items: center; + border-radius: var(--radius-sm); + border: 1px solid var(--border); + background: var(--bg-surface); + color: var(--text-muted); + padding: 0; + } + .btn-theme:hover { + color: var(--text-main); + border-color: var(--border-highlight); + background: var(--bg-elevated); + } + .icon-sun { display: var(--theme-sun-display); } + .icon-moon { display: var(--theme-moon-display); } + """ + + def page(title, content, authenticated=False, username=None): - session_area = "" + theme_btn_html = f""" + + """ + + session_html = "" if authenticated: - session_area = f"{html_escape(username)}Salir" + role = USERS.get(username, {}).get("display", "Usuario") + initial = (username[0] if username else "A").upper() + session_html = f""" + + """ + else: + session_html = f""" + + """ + return f""" - {html_escape(title)} + {html_escape(title)} — {COMPANY_NAME} + -
{COMPANY_NAME}
{session_area}
+
+ + {session_html} +
{content} """ class Handler(BaseHTTPRequestHandler): - server_version = "AsteriaPortal/1.0" + server_version = f"AsteriaPortal/{PORTAL_VERSION}" + + def handle_one_request(self): + self._req_start = time.perf_counter() + super().handle_one_request() def client_ip(self): forwarded = self.headers.get("X-Forwarded-For") @@ -184,11 +681,22 @@ class Handler(BaseHTTPRequestHandler): return None return None - def respond(self, status, body, content_type="text/html; charset=utf-8", headers=None): + def respond( + self, + status, + body, + content_type="text/html; charset=utf-8", + headers=None, + ): + elapsed_ms = (time.perf_counter() - self._req_start) * 1000 + record_request_metric(status, elapsed_ms) + encoded = body.encode("utf-8") self.send_response(status) self.send_header("Content-Type", content_type) self.send_header("Content-Length", str(len(encoded))) + self.send_header("X-Response-Time", f"{elapsed_ms:.2f}ms") + self.send_header("X-Server-Version", self.server_version) self.send_header("X-Frame-Options", "DENY") self.send_header("X-Content-Type-Options", "nosniff") self.send_header("Referrer-Policy", "no-referrer") @@ -200,8 +708,12 @@ class Handler(BaseHTTPRequestHandler): self.wfile.write(encoded) def redirect(self, location, headers=None): + elapsed_ms = (time.perf_counter() - self._req_start) * 1000 + record_request_metric(302, elapsed_ms) + self.send_response(302) self.send_header("Location", location) + self.send_header("X-Response-Time", f"{elapsed_ms:.2f}ms") self.send_header("Cache-Control", "no-store") if headers: for key, value in headers.items(): @@ -209,84 +721,1059 @@ class Handler(BaseHTTPRequestHandler): self.end_headers() def render_login(self, message=None, error=False): - alert = "" + alert_html = "" if message: - kind = "error" if error else "info" - alert = f"
{html_escape(message)}
" + kind = "critical" if error else "info" + alert_html = f""" +
+ {html_escape(message)} +
+ """ + + icon_shield = SVG_ICONS["shield"] + icon_user = SVG_ICONS["user"] + icon_lock = SVG_ICONS["lock"] + icon_arrow = SVG_ICONS["arrow_right"] + content = f""" -
-
-

Iniciar sesion

-

Acceda con sus credenciales corporativas.

- {alert} + + +
+ + + +
+
+
+ {icon_shield} +
+

Iniciar sesión

+

Portal seguro de operaciones & telemetría en tiempo real

+
+ + {alert_html} +
- - - - - +
+ +
+ +
+
+ +
+ +
+ +
+
+ +
+ +
+
Accesos de prueba rápidos
+
+ + + +
+
+ +
+ + Sesión protegida por HMAC-SHA256 • Telemetría Monotónica +
+ """ - self.respond(200, page("Inicio de sesion", content)) + self.respond(200, page("Iniciar sesión", content)) + + def render_access_denied(self, remaining): + icon_alert = SVG_ICONS["alert"] + content = f""" + +
+ +
+
{icon_alert}
+

Acceso bloqueado temporalmente

+

Se detectó un exceso de intentos fallidos. El sistema IR activó la ventana de contención defensiva.

+
+ Tiempo restante de enfriamiento: {remaining} segundos +
+ Volver al inicio +
+
+ + """ + self.respond(403, page("Acceso bloqueado", content)) def render_dashboard(self, username): role = USERS.get(username, {}).get("display", "Usuario") - content = f""" -
-
-
-

Panel principal

-

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

-
-

Solicitudes

12

En revision

-

Operaciones

98%

Disponibilidad

-

Cuenta

Activa

Sesion protegida

-
-
- """ - self.respond(200, page("Panel principal", content, authenticated=True, username=username)) + lat = get_latency_stats() + uptime_sec = get_uptime_seconds() + uptime_str = format_uptime(uptime_sec) + sys_stats = get_system_stats() + client_ip = self.client_ip() + + audit_rows_parts = [] + for ev in METRICS["recent_audit"][:10]: + ev_sev = ev["severity"].lower() + audit_rows_parts.append( + "" + + f"{html_escape(ev['time'])}" + + f"{html_escape(ev['event_type'])}" + + f"{html_escape(ev['username'])}" + + f"{html_escape(ev['source_ip'])}" + + f"{html_escape(ev['severity'])}" + + f"{html_escape(ev['result'])}" + + "{html_escape(ev['reason'])}" + "" + ) + audit_rows_html = ( + "".join(audit_rows_parts) + or "Sin eventos de seguridad" + " recientes" + ) - def render_access_denied(self, remaining): content = f""" -
-
", + ), + ) def do_POST(self): parsed = urlparse(self.path) if parsed.path != "/login": self.respond(404, "Not found", "text/plain") return + length = int(self.headers.get("Content-Length", "0")) body = self.rfile.read(length).decode("utf-8") form = parse_qs(body) @@ -295,46 +1782,64 @@ class Handler(BaseHTTPRequestHandler): source_ip = self.client_ip() user_agent = self.headers.get("User-Agent", "unknown")[:300] key = source_ip + "|" + username - state = FAILED_STATE.get(key, {"count": 0, "first": epoch_now(), "locked_until": 0}) + state = FAILED_STATE.get( + key, {"count": 0, "first": epoch_now(), "locked_until": 0} + ) if state.get("locked_until", 0) > epoch_now(): remaining = state["locked_until"] - epoch_now() - write_event({ - "event_type": "access_blocked", - "auth_method": "password", - "username": username or "unknown", - "source_ip": source_ip, - "sourceIPAddress": source_ip, - "affectedResource": "iam:user/" + (username or "unknown"), - "endpoint": "/login", - "result": "DENIED", - "failure_reason": "temporary_lockout", - "failed_attempts": state.get("count", 0), - "detection_window": "5 minutes", - "severity": "HIGH", - "severity_basis": "HIGH porque el usuario o la IP supero 5 intentos fallidos dentro de una ventana de 5 minutos.", - "user_agent": user_agent, - }) + write_event( + { + "event_type": "access_blocked", + "auth_method": "password", + "username": username or "unknown", + "source_ip": source_ip, + "sourceIPAddress": source_ip, + "affectedResource": "iam:user/" + (username or "unknown"), + "endpoint": "/login", + "result": "DENIED", + "failure_reason": "temporary_lockout", + "failed_attempts": state.get("count", 0), + "detection_window": "5 minutes", + "severity": "HIGH", + "severity_basis": ( + "HIGH porque el usuario o la IP supero 5 intentos fallidos" + " dentro de una ventana de 5 minutos." + ), + "user_agent": user_agent, + } + ) self.render_access_denied(remaining) return if verify_password(username, password): FAILED_STATE.pop(key, None) - write_event({ - "event_type": "login_success", - "auth_method": "password", - "username": username, - "source_ip": source_ip, - "sourceIPAddress": source_ip, - "affectedResource": "iam:user/" + username, - "endpoint": "/login", - "result": "SUCCESS", - "severity": "INFO", - "severity_basis": "INFO porque la autenticacion fue exitosa y no representa incidente por si sola.", - "user_agent": user_agent, - }) + write_event( + { + "event_type": "login_success", + "auth_method": "password", + "username": username, + "source_ip": source_ip, + "sourceIPAddress": source_ip, + "affectedResource": "iam:user/" + username, + "endpoint": "/login", + "result": "SUCCESS", + "severity": "INFO", + "severity_basis": ( + "INFO porque la autenticacion fue exitosa y no representa" + " incidente por si sola." + ), + "user_agent": user_agent, + } + ) cookie_value = sign_value(username + ":" + str(epoch_now())) - headers = {"Set-Cookie": "portal_session=" + cookie_value + "; Path=/; Max-Age=3600; HttpOnly; SameSite=Lax"} + headers = { + "Set-Cookie": ( + "portal_session=" + + cookie_value + + "; Path=/; Max-Age=3600; HttpOnly; SameSite=Lax" + ) + } self.redirect("/dashboard", headers=headers) return @@ -347,26 +1852,32 @@ class Handler(BaseHTTPRequestHandler): severity = "HIGH" if state["count"] >= LOCK_THRESHOLD else "LOW" severity_basis = ( - "HIGH porque se alcanzaron 5 o mas intentos fallidos de autenticacion en 5 minutos." - if severity == "HIGH" else - "LOW porque es un intento fallido aislado que aun no supera el umbral de incidente." + "HIGH porque se alcanzaron 5 o mas intentos fallidos de" + " autenticacion en 5 minutos." + if severity == "HIGH" + else ( + "LOW porque es un intento fallido aislado que aun no supera el" + " umbral de incidente." + ) + ) + write_event( + { + "event_type": "login_failed", + "auth_method": "password", + "username": username or "unknown", + "source_ip": source_ip, + "sourceIPAddress": source_ip, + "affectedResource": "iam:user/" + (username or "unknown"), + "endpoint": "/login", + "result": "FAILURE", + "failure_reason": "invalid_credentials", + "failed_attempts": state["count"], + "detection_window": "5 minutes", + "severity": severity, + "severity_basis": severity_basis, + "user_agent": user_agent, + } ) - write_event({ - "event_type": "login_failed", - "auth_method": "password", - "username": username or "unknown", - "source_ip": source_ip, - "sourceIPAddress": source_ip, - "affectedResource": "iam:user/" + (username or "unknown"), - "endpoint": "/login", - "result": "FAILURE", - "failure_reason": "invalid_credentials", - "failed_attempts": state["count"], - "detection_window": "5 minutes", - "severity": severity, - "severity_basis": severity_basis, - "user_agent": user_agent, - }) if state.get("locked_until", 0) > epoch_now(): self.render_access_denied(LOCK_SECONDS) @@ -378,14 +1889,18 @@ class Handler(BaseHTTPRequestHandler): if __name__ == "__main__": - write_event({ - "event_type": "portal_started", - "severity": "INFO", - "severity_basis": "INFO porque corresponde al inicio controlado del servicio web.", - "message": "Portal iniciado correctamente", - "source_ip": "127.0.0.1", - "sourceIPAddress": "127.0.0.1", - "endpoint": "systemd", - "result": "SUCCESS", - }) + write_event( + { + "event_type": "portal_started", + "severity": "INFO", + "severity_basis": ( + "INFO porque corresponde al inicio controlado del servicio web." + ), + "message": "Portal iniciado correctamente", + "source_ip": "127.0.0.1", + "sourceIPAddress": "127.0.0.1", + "endpoint": "systemd", + "result": "SUCCESS", + } + ) HTTPServer(("127.0.0.1", 8080), Handler).serve_forever() diff --git a/ansible/scripts/generate_simulation_vars.py b/ansible/scripts/generate_simulation_vars.py new file mode 100644 index 0000000..c3c783f --- /dev/null +++ b/ansible/scripts/generate_simulation_vars.py @@ -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()) diff --git a/tests/test_portal.py b/tests/test_portal.py index 3221343..d25c3ac 100644 --- a/tests/test_portal.py +++ b/tests/test_portal.py @@ -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"", data.decode(), re.S) + if "function updateTelemetry" in s) + _, _, data = self.request("GET", "/api/metrics") + metrics = json.loads(data) + payload = '' + 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(' {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("