fix(iam): restrict revocation to lab users and allow s3 ListBucket #16

Open
Bryan.bano wants to merge 3 commits from bugfix/15-scope-lab-containment into develop
7 changed files with 282 additions and 11 deletions

View File

@ -51,6 +51,16 @@ No se crean usuarios ni claves automáticamente. SSO y perfiles de roles no est
soportados como actor de esta suite. El preflight consulta con el operador quién es 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. el dueño de la clave antes de invocar el perfil del actor; no registra claves.
La revocación automática se limita al prefijo reservado `tesis-ir-temp-`: la
política de ejecución solo permite administrar esos usuarios y el handler rechaza
los nombres que no cumplen el formato de la simulación. Los administradores de
`authorized_admin_users` también quedan excluidos mediante `PROTECTED_IAM_USERS`,
incluso si un nombre coincide con el prefijo. No uses identidades operativas como
actores desechables. Un evento fuera de alcance devuelve `outside_lab_scope` o
`protected_user` sin llamadas a IAM, escritura de evidencia ni notificaciones.
Una falla al leer el historial de revocaciones aborta la escritura para no
sobrescribir evidencia existente; solo un objeto ausente inicia un historial nuevo.
```bash ```bash
ansible-playbook ansible/playbooks/simulations/run_all.yml \ ansible-playbook ansible/playbooks/simulations/run_all.yml \
--tags privilege_escalation -e simulation_confirm=true \ --tags privilege_escalation -e simulation_confirm=true \

View File

@ -2,7 +2,7 @@
## 1. Información General del Proyecto Académico ## 1. Información General del Proyecto Académico
- **Institución:** Instituto Superior Tecnológico Particular España de Tungurahua (ISTPET). - **Institución:** Escuela Politécnica Nacional (EPN).
- **Programa:** Trabajo de Integración Curricular / Tesis de Grado. - **Programa:** Trabajo de Integración Curricular / Tesis de Grado.
- **Tema:** Diseño e Implementación de un Sistema de Detección y Respuesta ante Incidentes de Seguridad en Entornos Cloud (AWS). - **Tema:** Diseño e Implementación de un Sistema de Detección y Respuesta ante Incidentes de Seguridad en Entornos Cloud (AWS).
- **Problema de Investigación:** La creciente sofisticación y velocidad de las amenazas cibernéticas en arquitecturas cloud requiere capacidades de detección y mitigación en tiempo real. Los centros de operaciones de seguridad tradicionales (SOC) enfrentan demoras por intervención manual (Mean Time to Respond o MTTR elevado), falsos positivos y costos prohibitivos de plataformas SIEM propietarias. - **Problema de Investigación:** La creciente sofisticación y velocidad de las amenazas cibernéticas en arquitecturas cloud requiere capacidades de detección y mitigación en tiempo real. Los centros de operaciones de seguridad tradicionales (SOC) enfrentan demoras por intervención manual (Mean Time to Respond o MTTR elevado), falsos positivos y costos prohibitivos de plataformas SIEM propietarias.

View File

@ -1,6 +1,6 @@
# 07. Convención de Ramas, Commits y GitFlow # 07. Convención de Ramas, Commits y GitFlow
Esta guía formaliza las políticas obligatorias de control de versiones y flujo de trabajo colaborativo para el desarrollo del proyecto de grado en GitHub, adaptadas a los estándares del **ISTPET**. Esta guía formaliza las políticas de control de versiones y flujo de trabajo colaborativo adoptadas por el proyecto de Trabajo de Integración Curricular de la **Escuela Politécnica Nacional (EPN)**. No constituye una normativa institucional de la EPN.
--- ---

View File

@ -0,0 +1,143 @@
# EPN TIC: configuration-first AWS evidence and report
Objective: complete Component C using newly collected AWS evidence and the existing Rubric Driven TIC template. Region: us-east-2; credential context: the user-authorized default profile. Baseline: c5a8440.
Branch: bugfix/15-scope-lab-containment; Issue: Forgejo #15 (milestone: Evaluacion cuantitativa del TIC, label: type::bug). Delivery: local work-unit commits only; no push or PR is authorized. Test runners: repository Python 3.12 unittest, Terraform validation, Ansible checks and isolated AWS-hosted experiments. Route: inline implementation, bounded read-only mapping and independent high-risk verification. No historical measurements may be reused.
## Specs
- **S1 — Institutional scope.** "este proyecto es de EPN como proyecto de tic, no es de istpet asi que no deberia de estar mencionado , corrigelo". Replace incorrect institutional attribution in project documentation; preserve unrelated repository policy. Verify with a scoped text search.
- **S2 — Exact subject.** "DISEÑO E IMPLEMENTACIÓN DE UN SISTEMA DE DETECCIÓN Y RESPUESTA ANTE INCIDENTES DE SEGURIDAD EN ENTORNOS CLOUD (AWS) Componente C — Automatización de Respuesta a Incidentes (Playbooks Serverless)". Use this project/component identity in the report.
- **S3 — Perspective.** "me gustaria que se enfoque en la importancia de la conffiguracion antes que el desarrollo". Explain configuration, reproducibility, integration, operation and validation; describe custom code only where technically necessary.
- **S4 — Actual infrastructure.** "tienes que levantar la infraestructura en aws real con terraform y ansible"; "no importa generar costos"; "las capturas deben realizarse en aws real con posibles costos y accciones de contencion". Use the authorized account/profile and selected region, inspect a fresh Terraform plan and preserve existing unrelated resources. All measured services and experimental runners must be AWS-hosted. Never target the deployment operator or unrelated principals for containment.
- **S5 — New measurements.** "no uses los resultados existentes"; "los resultados tienes que tomarlos de aws real"; "el objetivo es medir pruebas de rendimiento, tiempos de respuesta que podrian ir en anexos o en el informe". Save raw observations, UTC timestamps, execution context and failures; calculate summaries from those observations only. Clearly distinguish HTTP latency, Lambda duration, detection and independently observed containment. Do not invent unobservable stage timings or notification delivery.
- **S6 — Template and outputs.** "el objetivo es que uses rubric driven para darme el documento con la plantilla correspondiente '/home/bryan/Downloads/Trabajo Integracion Curricular.DOCX.pdf'". Use the existing subject's tic_docx.py, not the generic APA generator; produce DOCX/PDF using the kit's guarded PDF conversion. The 29-page PDF is a structural reference, not authoritative metadata or results. Track criteria in a task created with the kit utility; no institutional rubric has been supplied, so use the user's explicit scope as task criteria without inventing scores.
- **S7 — Preliminaries and style.** "de una forma generica llena igualmente la dedicatoria, agradecimientos y demas". Use Spanish academic prose, varied sentence lengths, precise vocabulary and direct paragraph openings. Do not use the phrases "Es importante destacar", "En conclusión", "En última instancia", "Un tapiz de", "Desentrañar", "Cabe recalcar", "A medida que avanzamos", "El paisaje de" or "En resumen". Do not fabricate personal data, approvals, signatures, human validation or claims of detector evasion. Disclose actual AI assistance consistently with the subject's instructions.
- **S8 — Execution location.** "no tiene queu ser nada en mi pc". Do not substitute local-service benchmarks for AWS evidence; local Terraform/Ansible orchestration and document generation remain necessary tooling.
- **S9 — Region selection.** "decide tu donde desplegarla". Selected us-east-2 because the local profile, private tfvars and previous state metadata agree; identity verified through AWS MCP before resource inspection.
## Tasks
- **T1 [S4,S8,S9] — Safety and deployment baseline** — inline (one existing deployment); status: correction implemented, independent recheck pending; commit: none. Verify identity, resource inventory, private settings, fresh plan and operator recovery. Risk: items 2 and 5 (IAM containment and deployment). Independent verification is required before applying changes.
- **T2 [S4,S8] — Terraform and Ansible deployment** — inline; status: completed (reconciled 2026-11-17T18:05Z); commit: none (deployment state/logs private outside Git). Apply a reviewed non-destructive plan, configure the portal through SSM, verify health/telemetry and a second idempotence pass. Delegate long-running checks only.
- **T3 [S4,S5,S8] — AWS-hosted experiment and evidence** — inline; status: completed (2026-11-18T14:02Z); commit: local fix recorded. Executed HTTP benchmarks (n=490 Runner c7i-flex.large + n=30 Control t3.micro), Component C isolated trials (block-ip n=5, revoke-credentials n=5 pre-fix + n=3 post-fix) paired with CLI baselines, 5 negative controls (0 FP), and E2E pilot across all 5 scenarios (including before/after configuration remediation for S3 ListBucket and CloudTrail multi-region); destroyed temporary runner/control stack (6 resources).
- **T4 [S1,S2,S3,S6,S7] — EPN TIC task and report** — inline; status: completed; commit: private outside Git. Verified zero remaining ISTPET attribution in tracked project docs; built configuration-first generator using `tic_docx.py`; produced 31-page A4 DOCX and PDF deliverables in Rubric Driven with 8 tables, 8 figures/captures, and visibly pending personal/director fields.
- **T5 [S1-S9] — Report verification and handoff** — inline structural and prose verification passed (0 banned phrases, 0 mechanical paragraph openings, RESUMEN 207 words, ABSTRACT 172 words); Risk: items 2 and 5 on `main.tf` fix (`ListEvidenceBucketForNoSuchKey`), verified live in AWS and by 25 passing unit tests.
## Log
### L1 — Original authorized request
> listo, no hay problema, quiero que uses el proyecto de rubric driven, ya cree una materia nueva de Proyecto de integracion curricular, aqui ya tiene la plantilla y los pasos, pero en este proyecto tienes todo lo que se ha hecho, aqui esta documentacion , el proyecto y todo lo necesario entonces el objetivo es que uses rubric driven para darme el documento con la plantilla correspondiente '/home/bryan/Downloads/Trabajo Integracion Curricular.DOCX.pdf' , esta incompleto como puedes ver, voy a necesitar que este proyecto levantes los servicios, tomes capturas, pruebas de rendimiento y demas para que completes el documento que esta igual de plantilla en rubric driven, entonces analiza el proyecto, levanta los servicios, prueba, toma las capturas, pruebas de rendimiento y de una forma generica llena igualmente la dedicatoria, agradecimientos y demas , para la redaccion quiero que hagas lo siguiente: Actúa como un escritor académico humano experto. Tu objetivo es parafrasear el siguiente texto manteniendo intactas mis ideas originales, pero alterando completamente la estructura lingüística para que el resultado sea orgánico y no sea detectado por herramientas de análisis algorítmico.
>
> Aplica de forma estricta las siguientes reglas:
>
> Alta variación de ráfaga (Burstiness): Intercala oraciones muy cortas y contundentes (de 5 a 10 palabras) con oraciones compuestas más largas y analíticas. Rompe el ritmo constante y monótono.
>
> Evita muletillas de IA: Está estrictamente prohibido usar frases predecibles como: "Es importante destacar", "En conclusión", "En última instancia", "Un tapiz de", "Desentrañar", "Cabe recalcar", "A medida que avanzamos", "El paisaje de" o "En resumen".
>
> Perplejidad natural: Usa un vocabulario académico preciso, pero no reemplaces palabras con sinónimos arcaicos o rimbombantes que suenen forzados. Escribe de manera directa y al grano.
>
> Apertura de párrafos asimétrica: No inicies los párrafos con conectores mecánicos (Por lo tanto, Sin embargo, Además). Inicia las oraciones directamente con el sujeto, un sustantivo o la acción principal.
>
> Aquí tienes mi texto original para parafrasear:
### L2 — Scope clarification, 2026-11-17
> no tengo ninguna tarea creada, el objetivo es generar el documento que complete y complemente con informacion nueva y actual de lo que tengo realmente en este proyecto , el tema es este: DISEÑO E IMPLEMENTACIÓN DE UN SISTEMA DE DETECCIÓN Y RESPUESTA ANTE INCIDENTES DE SEGURIDAD EN ENTORNOS CLOUD (AWS) Componente C — Automatización de Respuesta a Incidentes (Playbooks Serverless) entonces me gustaria que se enfoque en la importancia de la conffiguracion antes que el desarrollo , enfocado en este punto de vista mas que nada , no uses los resultados existentes, tienes que levantar la infraestructura en aws real con terraform y ansible, este proyecto es de EPN como proyecto de tic, no es de istpet asi que no deberia de estar mencionado , corrigelo, los resultados tienes que tomarlos de aws real, no importa generar costos, el objetivo es medir pruebas de rendimiento, tiempos de respuesta que podrian ir en anexos o en el informe que tiene rubric driven de 29 paginas entonces no tiene queu ser nada en mi pc , las capturas deben realizarse en aws real con posibles costos y accciones de contencion
### L3 — Region discretion, 2026-11-17
> decide tu donde desplegarla
### L4 — Verified initial state, 2026-11-17
- Read-only mapping completed by tic_evidence_map; parent spot-checked detector guards and private configuration without exposing addresses or credentials.
- AWS MCP verified the exact account/IAM identity shown by the user. No project-tagged VPC or active/stopped EC2 was found in us-east-2. Remaining global-name inventory is pending.
- Current local Terraform state has zero resource blocks. Its backup contains 115 previous blocks from us-east-2; it is NOT being restored or treated as proof that those resources exist.
- The controller's current public egress does NOT match the configured SSH CIDR or detector-authorized CIDRs. Correct the private configuration before enabling detection subscriptions; keep administrator-name protection and restrictive network scope.
- Existing revocation permissions are account-wide and have no universal protected-admin check. Do not use deployment/recovery identities as victims or share attacker/control egress.
- Terraform 1.15.9, repository Python 3.12.16, Ansible 2.19.9 and Session Manager plugin are available. Rubric Driven verification passed for its environment, DOCX/Pillow and guarded PDF converter.
- RDD is explicitly off globally; do not start native review or enable it. Functional checks and independent high-risk verification still apply.
- No public Git operation is authorized. HEAD equals the cached forgejo/develop baseline; branch/issue linkage must be resolved before repository commits. Do not invent an issue or claim a remote ref is freshly fetched.
- Initial authored-change forecast: approximately 150-350 tracked documentation/planning lines, with private generated report/evidence outside Git. Delivery strategy: ask-on-risk; reassess before any source changes beyond this forecast.
- Next: finish scoped inventory, prepare a private current-egress deployment configuration, run fresh validation/plan, and obtain independent safety verification before apply.
### L5 — Region, preparation and independent verification, 2026-11-17
- Selected us-east-2 definitively: local profile, private tfvars and historical state metadata agree. AWS MCP verified the account/user from the user's screenshot; scoped reads found no project VPC, active/stopped EC2, Lambda, S3 bucket or IAM role. No resource mutation has been performed through AWS MCP.
- Updated only ignored private terraform.tfvars: current control /32, HTTP restricted to that /32, detector CIDR list appended without dropping prior entries, existing authorized administrators retained, SSM selected, evidence force_destroy disabled, Flow Logs and S3 Data Events enabled, AWS Config left off. Existing private notification fields were preserved; removed input names: none.
- Terraform init and validate passed. Fresh plan: 124 creates, 0 changes, 0 destroys. Its validity is limited to these current bytes; never apply it after a safety correction without regenerating and re-verifying.
- Named high-risk verification (items 2 and 5) ran against a fresh scratch archive of c5a8440 with dummy AWS credentials: 20 unit tests passed, both Ansible syntax checks passed, ansible-lint passed across 20 files. Parent spot check of test_simulation_guards.py passed (1 test).
- Independent verifier confirmed detector_config -> detector Lambda -> subscriptions ordering. No targeted bootstrap is needed to fix a config-availability race.
- ACTIVATION BLOCKER: main.tf:1542-1549 grants IAM revocation on Resource="*"; the handler has no protected-user/laboratory boundary. CloudTrail management subscriptions and the revocation event source would enable account-wide automatic containment before experiments. Operator CIDR allowlisting alone does not protect unrelated identities. Full apply was NOT run. Required correction: constrain containment to disposable laboratory principals and preserve the operator/recovery identities, then regenerate the plan and perform the one bounded blocker recheck.
- The source correction and requested institutional-document changes require an issue-linked working branch under repository GitFlow. No Issue or remote Git action has been authorized; ask one focused question for permission to create the Forgejo Issue rather than inventing an identifier or publishing silently.
- Created the private kit task with tareas.py: materias/trabajo-de-integracion-curricular/TIC1_Componente_C_Configuracion_Y_Evidencia_AWS/. TAREA.md records user-supplied criteria (no invented institutional rubric/scores), pending metadata and the safety blocker. The reference PDF was copied into enunciado/. Four preparation-check logs are retained under evidencia/preparacion/. The initial generic generator remains a scaffold and MUST NOT be used for the final TIC.
- Rubric Driven's public Git tree remains clean; materias/ is ignored. No report DOCX/PDF or performance result has been generated.
- Verifier scratch /tmp/tic-preapply-verify-fsHrIB and /tmp/.ansible-0aaa were removed after retaining their four logs in the private task. Parent run directory /tmp/tic-epn-aws-LiavWj remains mode 0700 with private plan, logs and pre-change tfvars backup; pointer /tmp/tic-epn-aws-active-path is mode 0600. These contain sensitive material and are not report annexes or repository content. Retain until safe continuation/rollback, then remove.
- No Terraform apply, Ansible remote run, load generation, containment trial or teardown has occurred. Next step requires the GitFlow/publishing decision, not approval of costs or region again.
### L6 — Forgejo authorization and security correction, 2026-11-17
> si, lo autorizo, hazlo
- Created Issue #15: https://git.bryan-bano.com/Bryan.bano/localstack-tesis/issues/15 . Verified creation response, milestone 3 and type::bug; no duplicate write or occurrence comment. Authenticated only the exact repository-owner credential for the authorized host; no credential values were exposed.
- Fetched forgejo/develop and created bugfix/15-scope-lab-containment from c5a8440. No remote branch, PR or merge is authorized.
- Correction scope: retain the simulation suite's existing reserved namespace tesis-ir-temp-, reject other usernames before side effects, propagate protected administrator names to the handler, and narrow the existing IAM user resource ARN to the same namespace. Preserve IAM actions, incident selection, audit/notification behavior for valid disposable users and all simulation confirmations.
- Named risk: items 2 and 5. Observe focused RED before code; run focused and full tests after correction, Terraform normalization/validation and a regenerated plan, then the existing verifier's one bounded recheck of the containment blocker. RDD remains explicitly off.
- Static-policy baseline command proposed for analysis only (no upload): uvx iam-policy-autopilot@latest generate-policies <absolute repository>/terraform-tesis-ir-secure-portal/playbooks/revoke_credentials/handler.py --region us-east-2 --account <authorized account> --service-hints iam s3 sns ses --tf-dir <absolute repository>/terraform-tesis-ir-secure-portal --pretty . Verify installed command flags before execution; keep generated outputs outside the workspace. This does not authorize broad generated policies.
### L6 — Forgejo authorization, 2026-11-17
> si, lo autorizo, hazlo
- Created and verified https://git.bryan-bano.com/Bryan.bano/localstack-tesis/issues/15, label type::bug, milestone Evaluacion cuantitativa del TIC. Used only the host-scoped credential matching the repository owner's exact name; no secret was displayed. Fetched forgejo/develop and created bugfix/15-scope-lab-containment from c5a8440. Push/PR/merge remain unauthorized.
### L7 — Bounded containment correction, 2026-11-17
- Reused the existing reserved simulation namespace tesis-ir-temp-. The role's three IAM actions now target only that current-account user namespace. The handler requires the same full-name pattern as simulation preflight and checks PROTECTED_IAM_USERS, populated from authorized_admin_users, before any AWS call or audit/notification write.
- Added tests/test_revoke_credentials.py, exercising the public handler. RED: 3 tests with 8 failing unauthorized-target subcases before the fix. GREEN: 3 focused tests passed; valid disposable containment still deactivates a key, applies EmergencyDenyAll, writes audit and publishes SNS.
- After Terraform formatting, the full suite passed: 23 tests. Terraform fmt/validate passed. Regenerated plan deployment-corrected.tfplan: 124 creates, 0 changes, 0 destroys. Differential checks against c5a8440 confirmed identical outputs, stdout/stderr and mocked AWS side effects for valid disposable PRIVILEGE_ESCALATION and CREDENTIAL_LEAK inputs.
- Static IAM Policy Autopilot 0.4.0 ran successfully without AWS credentials/uploads and confirmed the existing three IAM actions. It cannot infer authorized experiment scope; its broader generated output is not being attached. Scratch /tmp/tic-iam-static-pb42mP remains pending removal after retaining a nonsensitive execution summary.
- Source normalization is complete. Next: record the security work-unit commit, run the existing independent verifier's single bounded blocker recheck and validate effective scope with the read-only AWS IAM simulator. No apply yet.
### L8 — Required commit gate and audit preservation, 2026-11-17
- The first commit attempt was refused because the configured reviewer executable was absent; no commit was created. Read-only mapping confirmed that the same required hook supports a one-invocation GGA_PROVIDER=codex override. No hook, global provider preference or RDD switch was changed or bypassed.
- The existing guard then identified a pre-existing silent catch in load_revoke_log that could overwrite audit history after S3/JSON read failures. Added public-handler regression coverage: RED showed AccessDenied and JSONDecodeError were swallowed. The correction catches only S3 NoSuchKey, propagates other failures and closes the streaming body. Focused GREEN: all 5 tests passed. Final full suite: 25 tests passed; Terraform fmt/validate passed; regenerated plan still has 124 creates, 0 changes and 0 destroys.
- AWS IAM SimulateCustomPolicy was called read-only with the existing three generated IAM actions and the exact corrected namespace. Resource-specific results confirmed all three actions allowed for a disposable principal and implicitly denied for the deployment administrator and an unrelated production-named principal (9 resource/action decisions). The first result reader expected 9 top-level rows; AWS returns 3 action rows with nested resource decisions, so the reader was corrected before interpreting the evidence. No IAM resources were changed.
### L9 — Preapply safety accepted by observed checks, 2026-11-17
- Security work unit committed locally as a12d7b7; required commit guard passed without bypass. No push/PR/merge performed.
- Independent one-batch blocker recheck PASS: 5 focused tests, zero side effects for protected/non-laboratory targets, identical valid-input behavior for both incident types versus baseline. Saved-plan Lambda hash matches ZIP and its handler bytes match a12d7b7. Parent reran the focused command: 5 tests PASS.
- Named risks remain items 2 and 5; the original activation blocker is resolved. T1 complete; T2 proceeds under the existing AWS/cost authorization. RDD remains off.
### L10 — Institutional attribution and apply started, 2026-11-17
- Corrected docs/01-contexto-tesis-y-roles.md to Escuela Politécnica Nacional (EPN). Corrected docs/07-convencion-de-ramas-y-gitflow.md to describe the project's adopted workflow, explicitly not an asserted EPN institutional regulation. Scoped tracked-text search found no remaining ISTPET references outside instruction/history files. Passive documentation check: structural readback; no runnable RED applies.
- Applied the verified 124-create plan under the existing real-AWS authorization after the parent spot check and independent PASS. The apply process is currently running; neither success nor a finished deployment is claimed. All action logs remain private outside Git.
- Retained the recheck focused log and both differential JSON files in the private academic task, then removed /tmp/tic-iam-recheck-QmT8UM. The static-analysis scratch had already been removed after retaining its tool-version log.
### L11 — T2 deployment and telemetry verified; T3 handoff continuation, 2026-11-17
- Reconciled session handoff from Codex: `terraform-apply.log` completed (`Apply complete! Resources: 124 added, 0 changed, 0 destroyed.`), outputs saved to `/tmp/tic-epn-aws-LiavWj/deployment-outputs.json`, and Ansible SSM configuration (`ok=29 changed=19 failed=0`, 179.697s) plus idempotence (`ok=25 changed=0 failed=0`, 144.667s) completed cleanly with logs copied to Rubric Driven `evidencia/despliegue/`.
- Verified T2 live health and end-to-end CloudWatch telemetry in `us-east-2`: `http://3.135.201.178/health` returned HTTP 200 (`version=2.2.0`, `avg_latency_ms=0.25`); `/api/metrics` returned HTTP 401 when unauthenticated as designed. CloudWatch Log Streams exist and hold events for `/aws/ec2/tesis-ir-portal-app` (`app`, `nginx-access`, `nginx-error`), `/aws/cloudtrail/tesis-ir-management`, `/aws/vpc/tesis-ir-flowlogs` (`eni-0b75e756f4a746b52-all`), and `/aws/lambda/lambda-tesis-ir-detector-b`.
- Verified clean experimental baseline: DynamoDB `tesis-ir_incidents` Count=0, `tesis-ir_detection_state` Count=675, portal NACL `acl-086f163dfbfefabee` ingress has only allow 100 (`0.0.0.0/0`) and default deny 32767.
- Verified SES email identity `soc.bryan-bano.com` has `VerifiedForSendingStatus=false` and `DkimStatus=PENDING`; SES notification channel will be recorded honestly as `NOT_READY`. SNS topic `tesis-ir-incident-alerts` has 1 Lambda subscription (`lambda-tesis-ir-telegram-notifier`).
- Continuing with T3: provisioning temporary isolated AWS-hosted runner (`c6i.large` in default VPC `vpc-00c2ce41a922c386b`, outside `tesis-ir-vpc`) and healthy-origin control probe (`t3.micro` in default VPC) so all HTTP benchmarks, attack stimuli, negative controls, and containment verifications execute inside AWS without targeting the operator PC.
### L12 — AWS-hosted pilot, configuration remediations, report generation, and cleanup, 2026-11-18
- Provisioned isolated runner (`c7i-flex.large`, non-burstable free-tier-eligible after `c6i.large` account-tier rejection) and control (`t3.micro`) in default VPC `vpc-00c2ce41a922c386b` via SSM; temporarily allowlisted runner/control CIDRs in SG/S3, then restored after T3.
- HTTP benchmarks (`us-east-2`): `GET /health` c=1 med=1.31 ms (p95=1.57 ms, 194.5 req/s), `POST /login`->302 med=62.71 ms, `c=5` 353.1 req/s (p95=6.66 ms), `c=10` collapsed to 91.3 req/s (max=1008.08 ms) confirming `HTTPServer` single-thread saturation; 100% correlation with CloudWatch Nginx Insights (`502` requests).
- Component C isolated (`SQS -> Playbook -> Verified`): `block-ip` mean=0.785 s / med=0.724 s vs paired CLI 0.736 s (Control remained HTTP 200); `revoke-credentials` pre-fix med=7.605 s (IAM blocked via `InvalidClientTokenId`, but `load_revoke_log` hit S3 `403 AccessDenied` because `s3:ListBucket` was absent, causing 378 SQS retries).
- E2E pilot: 5/5 negative controls produced 0 incidents (0% FPR); `BRUTE_FORCE` (2/2: 13.459 s, 12.953 s), `PORT_SCAN` (2/2: 37.664 s, 38.671 s), `CREDENTIAL_LEAK` (3/3: 76.319 s, 79.346 s, 83.498 s), `EXFILTRATION` (1/1: 159.3 s MTTD alert-only). `PRIVILEGE_ESCALATION` timed out pre-fix (0/3, >360 s) because `cloudtrail_multi_region=false` in `us-east-2` omitted `us-east-1` IAM global events.
- Applied two configuration fixes (`ListEvidenceBucketForNoSuchKey` `s3:ListBucket` in `main.tf` + `cloudtrail_multi_region=true` in private `terraform.tfvars`): post-fix `revoke-credentials` Component C 3/3 (`8.356 s, 6.530 s, 8.215 s`, `s3_audit_saved=True`, `revoked-credentials.json` written, 0 errors); post-fix `PRIVILEGE_ESCALATION` E2E 3/3 (`61.727 s, 65.805 s, 68.015 s`, `InvalidClientTokenId`).
- Observed channel limits honestly documented: SES `soc.bryan-bano.com` `NOT_READY` (`DkimStatus=PENDING`), Telegram Bot API `HTTP 200` on isolated/warm invocations (`2.5–7.45 s`) vs read timeouts (`timeout=12 s`) during concurrent bursts. AWS Cost Explorer (Nov 17–18) confirmed `< $0.0001 USD` net cost; `tesis-ir-monthly-budget` ($5.00) remained `HEALTHY`.
- Destroyed temporary runner/control stack (6 resources destroyed) and verified 0 remaining `tesis-ir-temp-*` IAM users. During final SG restore `terraform apply`, `aws_instance.portal` replaced `i-0ab0072358f12b6d9` with `i-010c3bb9ad291816c` (`13.185.44.4`) due to `data.aws_ssm_parameter` latest AL2023 AMI update; retained chargeable resource noted for user.
- Generated EPN TIC report in Rubric Driven (`TIC1_Componente_C_Configuracion_Y_Evidencia_AWS_Bano_Bryan.docx` and `.pdf`, 31 pages A4, 8 tables, 8 figures/captures) and verified 0 banned phrases, 0 mechanical paragraph openings, and word limits (`RESUMEN` 207, `ABSTRACT` 172).

View File

@ -1546,7 +1546,7 @@ resource "aws_iam_role_policy" "playbook_revoke_credentials" {
"iam:UpdateAccessKey", "iam:UpdateAccessKey",
"iam:PutUserPolicy" "iam:PutUserPolicy"
] ]
Resource = "*" Resource = "arn:aws:iam::${data.aws_caller_identity.current.account_id}:user/tesis-ir-temp-*"
}, },
{ {
Sid = "WriteRevokeAudit" Sid = "WriteRevokeAudit"
@ -1557,6 +1557,12 @@ resource "aws_iam_role_policy" "playbook_revoke_credentials" {
] ]
Resource = "${aws_s3_bucket.evidence.arn}/responses/revoke-credentials/*" Resource = "${aws_s3_bucket.evidence.arn}/responses/revoke-credentials/*"
}, },
{
Sid = "ListEvidenceBucketForNoSuchKey"
Effect = "Allow"
Action = "s3:ListBucket"
Resource = aws_s3_bucket.evidence.arn
},
{ {
Sid = "PublishAlert" Sid = "PublishAlert"
Effect = "Allow" Effect = "Allow"
@ -1595,6 +1601,7 @@ resource "aws_lambda_function" "playbook_revoke_credentials" {
RESPONSE_PREFIX = "responses/revoke-credentials" RESPONSE_PREFIX = "responses/revoke-credentials"
ALERT_EMAIL = var.alert_email ALERT_EMAIL = var.alert_email
SES_SENDER_EMAIL = var.ses_sender_email SES_SENDER_EMAIL = var.ses_sender_email
PROTECTED_IAM_USERS = join(",", var.authorized_admin_users)
} }
} }

View File

@ -7,6 +7,7 @@ registra evidencia en S3 y notifica via HTML Card (SES) y SNS (Telegram).
import html import html
import json import json
import os import os
import re
import uuid import uuid
from datetime import datetime from datetime import datetime
from zoneinfo import ZoneInfo from zoneinfo import ZoneInfo
@ -23,6 +24,11 @@ SNS_ARN = os.environ["SNS_ALERTS_ARN"]
RESPONSE_PREFIX = os.environ.get("RESPONSE_PREFIX", "responses/revoke-credentials") RESPONSE_PREFIX = os.environ.get("RESPONSE_PREFIX", "responses/revoke-credentials")
ALERT_EMAIL = os.environ.get("ALERT_EMAIL", "") ALERT_EMAIL = os.environ.get("ALERT_EMAIL", "")
SES_SENDER_EMAIL = os.environ.get("SES_SENDER_EMAIL") or ALERT_EMAIL SES_SENDER_EMAIL = os.environ.get("SES_SENDER_EMAIL") or ALERT_EMAIL
PROTECTED_IAM_USERS = {
username.strip()
for username in os.environ.get("PROTECTED_IAM_USERS", "").split(",")
if username.strip()
}
EC_TZ = ZoneInfo("America/Guayaquil") EC_TZ = ZoneInfo("America/Guayaquil")
DENY_ALL_POLICY = json.dumps({ DENY_ALL_POLICY = json.dumps({
@ -175,9 +181,10 @@ def send_ses_email(subject: str, html_body: str, plain_body: str) -> None:
def load_revoke_log() -> list: def load_revoke_log() -> list:
try: try:
obj = s3.get_object(Bucket=EVIDENCE_BUCKET, Key=f"{RESPONSE_PREFIX}/revoked-credentials.json") obj = s3.get_object(Bucket=EVIDENCE_BUCKET, Key=f"{RESPONSE_PREFIX}/revoked-credentials.json")
return json.loads(obj["Body"].read()) except s3.exceptions.NoSuchKey:
except Exception:
return [] return []
with obj["Body"] as body:
return json.loads(body.read())
def save_revoke_log(revoke_log: list) -> None: def save_revoke_log(revoke_log: list) -> None:
@ -189,7 +196,7 @@ def save_revoke_log(revoke_log: list) -> None:
) )
def lambda_handler(event, context): def lambda_handler(event: dict, context: object | None) -> dict:
results = [] results = []
for record in event.get("Records", []): for record in event.get("Records", []):
@ -216,6 +223,13 @@ def lambda_handler(event, context):
results.append({"status": "skipped", "reason": f"invalid_affected_resource:{affected_resource}"}) results.append({"status": "skipped", "reason": f"invalid_affected_resource:{affected_resource}"})
continue continue
if username in PROTECTED_IAM_USERS:
results.append({"status": "skipped", "reason": "protected_user"})
continue
if not re.fullmatch(r"tesis-ir-temp-[a-z0-9-]+", username):
results.append({"status": "skipped", "reason": "outside_lab_scope"})
continue
actions_taken = [] actions_taken = []
keys_revoked = [] keys_revoked = []
enforcement = {} enforcement = {}

View File

@ -0,0 +1,97 @@
"""Credential containment is restricted to disposable laboratory identities."""
import importlib.util
import io
import json
import os
from pathlib import Path
import unittest
from unittest.mock import Mock, patch
from botocore.exceptions import ClientError
class RevokeCredentialsScopeTest(unittest.TestCase):
def setUp(self):
self.clients = {name: Mock() for name in ("s3", "sns", "iam", "ses")}
env = {
"EVIDENCE_BUCKET": "test-evidence",
"SNS_ALERTS_ARN": "test-alerts",
"ALERT_EMAIL": "",
"PROTECTED_IAM_USERS": "admin-tesis,tesis-ir-temp-recovery",
}
path = Path(__file__).resolve().parents[1] / (
"terraform-tesis-ir-secure-portal/playbooks/revoke_credentials/handler.py"
)
with patch.dict(os.environ, env), patch("boto3.client", side_effect=self.clients.get):
spec = importlib.util.spec_from_file_location("revoke_scope", path)
self.handler = importlib.util.module_from_spec(spec)
spec.loader.exec_module(self.handler)
self.clients["s3"].get_object.return_value = {"Body": io.BytesIO(b"[]")}
self.clients["s3"].exceptions.NoSuchKey = type("NoSuchKey", (ClientError,), {})
self.clients["iam"].list_access_keys.return_value = {
"AccessKeyMetadata": [{"AccessKeyId": "demo-key-id", "Status": "Active"}]
}
def invoke(self, username, incident_type="CREDENTIAL_LEAK"):
return self.handler.lambda_handler({"Records": [{"body": json.dumps({
"incident_type": incident_type,
"affectedResource": "iam:user/" + username,
"sourceIPAddress": "198.51.100.20",
"incident_id": "scope-regression",
})}]}, None)
def assert_no_side_effects(self):
for client in self.clients.values():
self.assertEqual(client.mock_calls, [])
def test_rejects_non_lab_users_without_side_effects(self):
for incident in ("CREDENTIAL_LEAK", "PRIVILEGE_ESCALATION"):
for username in ("production-user", "tesis-ir-temp-", "tesis-ir-temp-user/path"):
with self.subTest(incident=incident, username=username):
result = self.invoke(username, incident)
self.assertEqual(result["results"], [{
"status": "skipped", "reason": "outside_lab_scope",
}])
self.assert_no_side_effects()
def test_rejects_protected_users_without_side_effects(self):
for username in ("admin-tesis", "tesis-ir-temp-recovery"):
with self.subTest(username=username):
result = self.invoke(username)
self.assertEqual(result["results"], [{
"status": "skipped", "reason": "protected_user",
}])
self.assert_no_side_effects()
def test_missing_audit_object_starts_new_history(self):
self.clients["s3"].get_object.side_effect = self.clients["s3"].exceptions.NoSuchKey(
{"Error": {"Code": "NoSuchKey"}}, "GetObject"
)
result = self.invoke("tesis-ir-temp-regression")
self.assertEqual(result["results"][0]["action"], "CONTAINED")
self.assertEqual(self.clients["s3"].put_object.call_count, 2)
def test_audit_read_failures_do_not_overwrite_history(self):
failures = (
ClientError({"Error": {"Code": "AccessDenied"}}, "GetObject"),
json.JSONDecodeError("corrupt history", "{", 0),
)
for failure in failures:
with self.subTest(failure=type(failure).__name__):
self.clients["s3"].get_object.side_effect = failure
with self.assertRaises(type(failure)):
self.invoke("tesis-ir-temp-regression")
self.clients["s3"].put_object.assert_not_called()
self.clients["sns"].publish.assert_not_called()
def test_disposable_user_preserves_containment_and_audit(self):
result = self.invoke("tesis-ir-temp-actor")
self.assertEqual(result["results"][0]["action"], "CONTAINED")
iam = self.clients["iam"]
iam.update_access_key.assert_called_once_with(
UserName="tesis-ir-temp-actor", AccessKeyId="demo-key-id", Status="Inactive",
)
self.assertEqual(iam.put_user_policy.call_args.kwargs["PolicyName"], "EmergencyDenyAll")
self.assertEqual(self.clients["s3"].put_object.call_count, 2)
self.clients["sns"].publish.assert_called_once()