feat: configurar portal y CloudWatch con Ansible y CI en Forgejo
This commit is contained in:
commit
a789257551
|
|
@ -0,0 +1,12 @@
|
||||||
|
## Resultado
|
||||||
|
|
||||||
|
Describe el problema y el comportamiento final.
|
||||||
|
|
||||||
|
Closes #<numero-del-issue>
|
||||||
|
|
||||||
|
## Validacion
|
||||||
|
|
||||||
|
- [ ] Issue y PR con el mismo milestone y una etiqueta `type::*` coherente.
|
||||||
|
- [ ] Rama `<tipo>/<issue>-slug` y destino `develop`.
|
||||||
|
- [ ] Checks `gitflow`, `ansible`, `terraform` y `secretos` aprobados sobre el HEAD final.
|
||||||
|
- [ ] Evidencia de pruebas y limites del despliegue descritos.
|
||||||
|
|
@ -1,10 +1,10 @@
|
||||||
name: Seguridad y Detección de Fuga de Secretos
|
name: Seguridad de main
|
||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [ main, develop ]
|
branches: [ main ]
|
||||||
pull_request:
|
pull_request:
|
||||||
branches: [ main, develop ]
|
branches: [ main ]
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
security-audit:
|
security-audit:
|
||||||
|
|
@ -34,7 +34,7 @@ jobs:
|
||||||
fi
|
fi
|
||||||
|
|
||||||
echo "Ejecutando escaneo profundo de secretos en código e historial..."
|
echo "Ejecutando escaneo profundo de secretos en código e historial..."
|
||||||
gitleaks detect --source . --verbose --config .gitleaks.toml
|
gitleaks detect --source . --redact --config .gitleaks.toml
|
||||||
|
|
||||||
- name: Validar Metadata de Pull Request
|
- name: Validar Metadata de Pull Request
|
||||||
if: github.event_name == 'pull_request'
|
if: github.event_name == 'pull_request'
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,113 @@
|
||||||
|
name: Validacion
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
branches: [develop]
|
||||||
|
push:
|
||||||
|
branches: [develop]
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
gitflow:
|
||||||
|
name: gitflow
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: https://github.com/actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
ref: ${{ github.event.pull_request.head.sha || github.sha }}
|
||||||
|
persist-credentials: false
|
||||||
|
github-server-url: https://git.bryan-bano.com
|
||||||
|
- uses: https://github.com/astral-sh/setup-uv@v6
|
||||||
|
with:
|
||||||
|
github-token: ''
|
||||||
|
enable-cache: false
|
||||||
|
- name: Validar rama, issue, milestone, etiquetas y commits
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
GITHUB_SERVER_URL: https://git.bryan-bano.com
|
||||||
|
run: uv run --no-project --python 3.12 python scripts/check_gitflow.py
|
||||||
|
|
||||||
|
ansible:
|
||||||
|
name: ansible
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: https://github.com/actions/checkout@v4
|
||||||
|
with:
|
||||||
|
ref: ${{ github.event.pull_request.head.sha || github.sha }}
|
||||||
|
persist-credentials: false
|
||||||
|
github-server-url: https://git.bryan-bano.com
|
||||||
|
- uses: https://github.com/astral-sh/setup-uv@v6
|
||||||
|
with:
|
||||||
|
github-token: ''
|
||||||
|
enable-cache: false
|
||||||
|
- name: Instalar dependencias y coleccion AWS
|
||||||
|
run: |
|
||||||
|
uv venv --python 3.12 .venv
|
||||||
|
uv pip install --python .venv/bin/python -r ansible/requirements.txt
|
||||||
|
echo "$PWD/.venv/bin" >> "$GITHUB_PATH"
|
||||||
|
export PATH="$PWD/.venv/bin:$PATH"
|
||||||
|
ansible-galaxy collection install -r ansible/requirements.yml
|
||||||
|
- name: Validar sintaxis y buenas practicas
|
||||||
|
working-directory: ansible
|
||||||
|
run: |
|
||||||
|
ansible-playbook -i inventory/hosts.example.yml playbook.yml --syntax-check
|
||||||
|
ansible-lint playbook.yml
|
||||||
|
- name: Probar autenticacion, eventos, inventario y reglas de integracion
|
||||||
|
run: python -m unittest discover -s tests -v
|
||||||
|
|
||||||
|
terraform:
|
||||||
|
name: terraform
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: https://github.com/actions/checkout@v4
|
||||||
|
with:
|
||||||
|
ref: ${{ github.event.pull_request.head.sha || github.sha }}
|
||||||
|
persist-credentials: false
|
||||||
|
github-server-url: https://git.bryan-bano.com
|
||||||
|
- uses: https://github.com/hashicorp/setup-terraform@v3
|
||||||
|
with:
|
||||||
|
terraform_version: '1.15.9'
|
||||||
|
terraform_wrapper: false
|
||||||
|
- name: Validar infraestructura sin credenciales AWS
|
||||||
|
working-directory: terraform-tesis-ir-secure-portal
|
||||||
|
run: |
|
||||||
|
terraform fmt -check -diff
|
||||||
|
terraform init -backend=false -input=false
|
||||||
|
terraform validate -no-color
|
||||||
|
|
||||||
|
secretos:
|
||||||
|
name: secretos
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: https://github.com/actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
ref: ${{ github.event.pull_request.head.sha || github.sha }}
|
||||||
|
persist-credentials: false
|
||||||
|
github-server-url: https://git.bryan-bano.com
|
||||||
|
- name: Descargar Gitleaks y verificar checksum
|
||||||
|
run: |
|
||||||
|
set -eu
|
||||||
|
mkdir -p /tmp/tesis-gitleaks
|
||||||
|
cd /tmp/tesis-gitleaks
|
||||||
|
base=https://github.com/gitleaks/gitleaks/releases/download/v8.24.3
|
||||||
|
case "$(uname -m)" in
|
||||||
|
x86_64) archive=gitleaks_8.24.3_linux_x64.tar.gz ;;
|
||||||
|
aarch64|arm64) archive=gitleaks_8.24.3_linux_arm64.tar.gz ;;
|
||||||
|
*) echo "Arquitectura no soportada" >&2; exit 1 ;;
|
||||||
|
esac
|
||||||
|
curl -fsSLO "$base/$archive"
|
||||||
|
curl -fsSLO "$base/gitleaks_8.24.3_checksums.txt"
|
||||||
|
sha256sum --check --ignore-missing gitleaks_8.24.3_checksums.txt
|
||||||
|
tar -xzf "$archive" gitleaks
|
||||||
|
- name: Buscar secretos en los commits del cambio
|
||||||
|
env:
|
||||||
|
BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.before }}
|
||||||
|
run: |
|
||||||
|
set -eu
|
||||||
|
if [ -n "$BASE_SHA" ] && git cat-file -e "$BASE_SHA^{commit}" 2>/dev/null; then
|
||||||
|
/tmp/tesis-gitleaks/gitleaks git --redact --no-banner --log-opts="$BASE_SHA..HEAD" .
|
||||||
|
else
|
||||||
|
/tmp/tesis-gitleaks/gitleaks git --redact --no-banner --log-opts=-1 .
|
||||||
|
fi
|
||||||
|
|
@ -5,6 +5,8 @@
|
||||||
.terraform.lock.hcl
|
.terraform.lock.hcl
|
||||||
terraform.tfvars
|
terraform.tfvars
|
||||||
terraform.tfvars.json
|
terraform.tfvars.json
|
||||||
|
tfplan
|
||||||
|
*.tfplan
|
||||||
|
|
||||||
# Lambda build artifacts
|
# Lambda build artifacts
|
||||||
*.zip
|
*.zip
|
||||||
|
|
@ -23,3 +25,11 @@ __pycache__/
|
||||||
# Backups and logs
|
# Backups and logs
|
||||||
*.log
|
*.log
|
||||||
backup_*/
|
backup_*/
|
||||||
|
|
||||||
|
# Ansible: inventario local, secretos y dependencias
|
||||||
|
ansible/inventory/hosts.yml
|
||||||
|
ansible/inventory/hosts.json
|
||||||
|
.venv/
|
||||||
|
.ansible/
|
||||||
|
*.retry
|
||||||
|
ansible/**/vault*.yml
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,7 @@
|
||||||
|
# Conservar las reglas oficiales al agregar exclusiones del repositorio.
|
||||||
|
[extend]
|
||||||
|
useDefault = true
|
||||||
|
|
||||||
# Configuración de Gitleaks para exclusión de archivos locales de infraestructura
|
# Configuración de Gitleaks para exclusión de archivos locales de infraestructura
|
||||||
[allowlist]
|
[allowlist]
|
||||||
description = "Exclusiones de archivos locales ignorados por git y falsos positivos"
|
description = "Exclusiones de archivos locales ignorados por git y falsos positivos"
|
||||||
|
|
|
||||||
14
README.md
14
README.md
|
|
@ -91,6 +91,8 @@ El sistema implementa 5 playbooks de detección y respuesta automatizada estanda
|
||||||
|
|
||||||
```text
|
```text
|
||||||
localstack-tesis/
|
localstack-tesis/
|
||||||
|
├── ansible/ ← Portal, Nginx y CloudWatch Agent por SSM/SSH
|
||||||
|
├── .forgejo/workflows/validate.yml ← Validacion de PR hacia develop
|
||||||
├── docs/ ← Documentación técnica integral de tesis
|
├── docs/ ← Documentación técnica integral de tesis
|
||||||
│ ├── README.md ← Índice general y mapa de navegación
|
│ ├── README.md ← Índice general y mapa de navegación
|
||||||
│ ├── 01-contexto-tesis-y-roles.md ← Marco académico, roles A/B/C y contratos
|
│ ├── 01-contexto-tesis-y-roles.md ← Marco académico, roles A/B/C y contratos
|
||||||
|
|
@ -156,6 +158,18 @@ terraform init
|
||||||
terraform apply -auto-approve
|
terraform apply -auto-approve
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Paso 3: Configurar el Portal con Ansible
|
||||||
|
|
||||||
|
Instala las dependencias siguiendo [la guia operativa de Ansible](ansible/README.md). Desde la raiz:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python ansible/scripts/generate_inventory.py
|
||||||
|
cd ansible
|
||||||
|
ansible-playbook playbook.yml
|
||||||
|
```
|
||||||
|
|
||||||
|
El primer cambio de `user_data` puede reemplazar EC2; revisa el plan antes de aplicar. Los checks y la proteccion de `develop` se describen en [Forgejo Actions](docs/11-forgejo-actions-y-proteccion-develop.md).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 7. Ejecución de Pruebas de Incidentes
|
## 7. Ejecución de Pruebas de Incidentes
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,105 @@
|
||||||
|
# Configuracion del portal EC2
|
||||||
|
|
||||||
|
Terraform crea AWS; Ansible instala y mantiene el software en Amazon Linux 2023. Los roles `common`, `portal_app`, `nginx` y `cloudwatch_agent` conservan los eventos que consume el detector. Python escucha en `127.0.0.1:8080`; Nginx atiende el puerto 80 y sobrescribe la IP reenviada para impedir suplantaciones.
|
||||||
|
|
||||||
|
## Preparacion
|
||||||
|
|
||||||
|
Desde la raiz, con Python 3.12 o 3.13, Terraform y AWS CLI disponibles:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3.12 -m venv .venv
|
||||||
|
source .venv/bin/activate
|
||||||
|
python -m pip install -r ansible/requirements.txt
|
||||||
|
ansible-galaxy collection install -r ansible/requirements.yml
|
||||||
|
aws sts get-caller-identity
|
||||||
|
```
|
||||||
|
|
||||||
|
Para SSM instala [Session Manager plugin](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html). Las credenciales provienen del perfil AWS local (`AWS_PROFILE` si usas uno con nombre); no se copian al inventario ni al portal.
|
||||||
|
|
||||||
|
## Despliegue
|
||||||
|
|
||||||
|
```bash
|
||||||
|
terraform -chdir=terraform-tesis-ir-secure-portal init
|
||||||
|
terraform -chdir=terraform-tesis-ir-secure-portal plan -out=tfplan
|
||||||
|
terraform -chdir=terraform-tesis-ir-secure-portal apply tfplan
|
||||||
|
python ansible/scripts/generate_inventory.py
|
||||||
|
cd ansible
|
||||||
|
ansible-inventory --graph
|
||||||
|
ansible-playbook playbook.yml
|
||||||
|
# Verificar idempotencia: sin deriva, la segunda ejecucion debe dar changed=0.
|
||||||
|
ansible-playbook playbook.yml
|
||||||
|
```
|
||||||
|
|
||||||
|
El generador lee exclusivamente `terraform output -json ansible_portal`; no exporta el estado ni salidas sensibles. El inventario local se excluye de Git. Regeneralo tras reemplazar EC2 o cambiar region/proyecto. La IP publica puede cambiar al detener/iniciar la instancia.
|
||||||
|
|
||||||
|
El playbook espera la conexion y cloud-init, comprueba Amazon Linux 2023, instala los servicios y verifica `/health` a traves de Nginx. Los cambios posteriores se aplican repitiendo Ansible, sin reemplazar EC2. El secreto de sesion se crea solo una vez; el codigo pertenece a root y el servicio solo escribe en su directorio de logs.
|
||||||
|
|
||||||
|
### SSM (predeterminado)
|
||||||
|
|
||||||
|
No requiere llave SSH. EC2 debe aparecer `Online` en Systems Manager y tener salida HTTPS a SSM, `ssmmessages` y S3. El bootstrap inicia `amazon-ssm-agent`; Terraform ya asocia `AmazonSSMManagedInstanceCore`. Elegir SSM no modifica la regla SSH existente del Security Group.
|
||||||
|
|
||||||
|
El plugin [amazon.aws.aws_ssm](https://docs.ansible.com/projects/ansible/latest/collections/amazon/aws/aws_ssm_connection.html) transfiere modulos por S3 con URLs prefirmadas. Terraform crea `${project_name}-ansible-${account_id}-${region}`, separado de evidencia, con bloqueo publico, ACL desactivadas, SSE-S3 y expiracion de un dia como respaldo a la eliminacion del plugin. No habilites versionado: los modulos pueden contener datos sensibles. Almacenamiento y solicitudes generan cargos segun uso ([precios S3](https://aws.amazon.com/s3/pricing/)).
|
||||||
|
|
||||||
|
El operador necesita permisos de sesiones SSM sobre la instancia (`ssm:StartSession`, `ssm:ResumeSession`, `ssm:TerminateSession` y el documento de sesion usado), y `s3:GetObject`, `s3:PutObject`, `s3:DeleteObject`, `s3:ListBucket`, `s3:GetBucketLocation` limitados al bucket de transferencias. EC2 usa las URLs prefirmadas y no necesita permisos S3 adicionales. El rol del portal no se amplia.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
aws ssm describe-instance-information --region us-east-2
|
||||||
|
aws ssm start-session --target INSTANCE_ID --region us-east-2
|
||||||
|
```
|
||||||
|
|
||||||
|
### SSH alternativo
|
||||||
|
|
||||||
|
Define `key_name` en Terraform con una key pair existente y `ssh_allowed_cidr` con la IP del controlador `/32`. Conserva la llave privada fuera del repositorio. Verifica la huella del host por un canal confiable, por ejemplo SSM, y registrala en `~/.ssh/known_hosts`; la comprobacion de claves de host permanece activa.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python ansible/scripts/generate_inventory.py --connection ssh --private-key ~/.ssh/tesis.pem
|
||||||
|
cd ansible
|
||||||
|
ansible-playbook playbook.yml
|
||||||
|
```
|
||||||
|
|
||||||
|
Puedes omitir `--private-key` si usas `ssh-agent`. Para inventario manual usa `inventory/hosts.example.yml` como referencia y seleccionalo con `-i`.
|
||||||
|
|
||||||
|
## Migracion desde user_data
|
||||||
|
|
||||||
|
El script anterior instalaba todo; ahora solo prepara Python, curl y SSM. Con `user_data_replace_on_change=true`, **el primer plan de esta migracion propone reemplazar EC2**: revisa el plan, programa la interrupcion y conserva los logs locales necesarios. La instancia nueva no tendra portal hasta ejecutar Ansible. Los logs ya enviados a CloudWatch permanecen en su grupo administrado por Terraform.
|
||||||
|
|
||||||
|
Puedes configurar primero una EC2 existente usando un inventario manual por SSH, o SSM con un bucket de transferencias ya preparado. Ansible conserva el `session_secret` existente. No cambies la politica de reemplazo para ocultar el efecto de la migracion sin revisar el ciclo de vida de la instancia.
|
||||||
|
|
||||||
|
## Operacion y evidencia
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Desde ansible/, sobre una instancia ya configurada:
|
||||||
|
ansible-playbook playbook.yml --check --diff
|
||||||
|
ansible portal -b -m ansible.builtin.command -a 'systemctl status tesis-portal nginx amazon-cloudwatch-agent --no-pager'
|
||||||
|
ansible portal -b -m ansible.builtin.command -a 'journalctl -u tesis-portal -n 30 --no-pager'
|
||||||
|
ansible portal -b -m ansible.builtin.command -a 'tail -n 10 /var/log/tesis-portal/app.log'
|
||||||
|
```
|
||||||
|
|
||||||
|
`--check` revisa deriva en hosts existentes; no sustituye el primer despliegue donde faltan usuarios, archivos y servicios. La actualizacion global de paquetes es optativa: `ansible-playbook playbook.yml -e common_upgrade_packages=true`; revisa si despues se requiere reiniciar EC2.
|
||||||
|
|
||||||
|
La rotacion local es diaria, conserva siete archivos y evalua el limite de 10 MB al ejecutarse logrotate. CloudWatch envia `{instance_id}/app`, `/nginx-access` y `/nginx-error` al grupo exportado por Terraform. La [configuracion del agente](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Agent-Configuration-File-Details.html) contiene solo logs; la retencion del grupo sigue en Terraform.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Desde la raiz; ajustar --region al output region.
|
||||||
|
PORTAL_IP=$(terraform -chdir=terraform-tesis-ir-secure-portal output -raw portal_public_ip)
|
||||||
|
curl --fail "http://$PORTAL_IP/health"
|
||||||
|
LOG_GROUP=$(terraform -chdir=terraform-tesis-ir-secure-portal output -raw ec2_app_log_group)
|
||||||
|
aws logs tail "$LOG_GROUP" --since 10m --follow --region us-east-2
|
||||||
|
```
|
||||||
|
|
||||||
|
Para verificar la cadena completa sigue [las pruebas de incidentes](../terraform-tesis-ir-secure-portal/GUIA_PRUEBAS_INCIDENTES.md) y conserva evidencia de CloudWatch, Lambda, SQS y mitigacion. La fuerza bruta puede bloquear la IP de prueba en la NACL.
|
||||||
|
|
||||||
|
## Validacion sin AWS
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd ansible
|
||||||
|
ansible-playbook -i inventory/hosts.example.yml playbook.yml --syntax-check
|
||||||
|
ansible-lint playbook.yml
|
||||||
|
cd ..
|
||||||
|
python -m unittest discover -s tests -v
|
||||||
|
terraform -chdir=terraform-tesis-ir-secure-portal fmt -check
|
||||||
|
terraform -chdir=terraform-tesis-ir-secure-portal init -backend=false -input=false
|
||||||
|
terraform -chdir=terraform-tesis-ir-secure-portal validate
|
||||||
|
```
|
||||||
|
|
||||||
|
CI comprueba sintaxis, lint, contrato HTTP/eventos, inventario, reglas de PR, Terraform y secretos. La idempotencia remota y la entrega real a CloudWatch se verifican con las ejecuciones operativas anteriores.
|
||||||
|
|
@ -0,0 +1,10 @@
|
||||||
|
[defaults]
|
||||||
|
inventory = inventory/hosts.yml
|
||||||
|
roles_path = roles
|
||||||
|
interpreter_python = /usr/bin/python3
|
||||||
|
host_key_checking = True
|
||||||
|
timeout = 30
|
||||||
|
retry_files_enabled = False
|
||||||
|
|
||||||
|
[ssh_connection]
|
||||||
|
pipelining = True
|
||||||
|
|
@ -0,0 +1,8 @@
|
||||||
|
---
|
||||||
|
portal_app_user: tesisportal
|
||||||
|
portal_app_dir: /opt/tesis-portal
|
||||||
|
portal_app_log_dir: /var/log/tesis-portal
|
||||||
|
portal_app_asset_name: tesis-ir-portal-ec2
|
||||||
|
cloudwatch_agent_region: us-east-2
|
||||||
|
cloudwatch_agent_log_group: /aws/ec2/tesis-ir-portal-app
|
||||||
|
common_upgrade_packages: false
|
||||||
|
|
@ -0,0 +1,14 @@
|
||||||
|
---
|
||||||
|
all:
|
||||||
|
children:
|
||||||
|
portal:
|
||||||
|
hosts:
|
||||||
|
portal_ec2:
|
||||||
|
ansible_host: 192.0.2.10
|
||||||
|
ansible_connection: ssh
|
||||||
|
ansible_user: ec2-user
|
||||||
|
ansible_ssh_private_key_file: ~/.ssh/tesis.pem
|
||||||
|
vars:
|
||||||
|
portal_app_asset_name: tesis-ir-portal-ec2
|
||||||
|
cloudwatch_agent_region: us-east-2
|
||||||
|
cloudwatch_agent_log_group: /aws/ec2/tesis-ir-portal-app
|
||||||
|
|
@ -0,0 +1,44 @@
|
||||||
|
---
|
||||||
|
- name: Configurar portal de laboratorio y telemetria
|
||||||
|
hosts: portal
|
||||||
|
become: true
|
||||||
|
gather_facts: false
|
||||||
|
pre_tasks:
|
||||||
|
- name: Esperar la conexion con EC2
|
||||||
|
ansible.builtin.wait_for_connection:
|
||||||
|
timeout: 600
|
||||||
|
|
||||||
|
- name: Esperar que termine el bootstrap de cloud-init
|
||||||
|
ansible.builtin.command: cloud-init status --wait
|
||||||
|
changed_when: false
|
||||||
|
when: not ansible_check_mode
|
||||||
|
|
||||||
|
- name: Recopilar datos del sistema operativo
|
||||||
|
ansible.builtin.setup:
|
||||||
|
|
||||||
|
- name: Verificar Amazon Linux 2023
|
||||||
|
ansible.builtin.assert:
|
||||||
|
that:
|
||||||
|
- ansible_facts.distribution == 'Amazon'
|
||||||
|
- ansible_facts.distribution_major_version == '2023'
|
||||||
|
fail_msg: Este playbook requiere Amazon Linux 2023.
|
||||||
|
|
||||||
|
roles:
|
||||||
|
- common
|
||||||
|
- portal_app
|
||||||
|
- nginx
|
||||||
|
- cloudwatch_agent
|
||||||
|
|
||||||
|
post_tasks:
|
||||||
|
- name: Aplicar los cambios de servicios antes de verificar
|
||||||
|
ansible.builtin.meta: flush_handlers
|
||||||
|
|
||||||
|
- name: Verificar el portal a traves de Nginx
|
||||||
|
ansible.builtin.uri:
|
||||||
|
url: http://127.0.0.1/health
|
||||||
|
return_content: true
|
||||||
|
register: portal_health
|
||||||
|
until: portal_health.status == 200 and portal_health.json.status == 'ok'
|
||||||
|
retries: 10
|
||||||
|
delay: 3
|
||||||
|
when: not ansible_check_mode
|
||||||
|
|
@ -0,0 +1,3 @@
|
||||||
|
ansible-core==2.19.9
|
||||||
|
ansible-lint==26.10.0
|
||||||
|
boto3>=1.34.0,<2.0
|
||||||
|
|
@ -0,0 +1,4 @@
|
||||||
|
---
|
||||||
|
collections:
|
||||||
|
- name: amazon.aws
|
||||||
|
version: 11.5.1
|
||||||
|
|
@ -0,0 +1,14 @@
|
||||||
|
---
|
||||||
|
- name: Aplicar configuracion CloudWatch Agent
|
||||||
|
ansible.builtin.command:
|
||||||
|
argv:
|
||||||
|
- /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl
|
||||||
|
- -a
|
||||||
|
- fetch-config
|
||||||
|
- -m
|
||||||
|
- ec2
|
||||||
|
- -s
|
||||||
|
- -c
|
||||||
|
- file:/opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.json
|
||||||
|
changed_when: true
|
||||||
|
when: not ansible_check_mode
|
||||||
|
|
@ -0,0 +1,25 @@
|
||||||
|
---
|
||||||
|
- name: Instalar CloudWatch Agent
|
||||||
|
ansible.builtin.dnf:
|
||||||
|
name: amazon-cloudwatch-agent
|
||||||
|
state: present
|
||||||
|
notify: Aplicar configuracion CloudWatch Agent
|
||||||
|
|
||||||
|
- name: Configurar envio de eventos y logs Nginx
|
||||||
|
ansible.builtin.template:
|
||||||
|
src: config.json.j2
|
||||||
|
dest: /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.json
|
||||||
|
owner: root
|
||||||
|
group: root
|
||||||
|
mode: '0644'
|
||||||
|
validate: /usr/bin/python3 -m json.tool %s
|
||||||
|
notify: Aplicar configuracion CloudWatch Agent
|
||||||
|
|
||||||
|
- name: Aplicar configuracion antes de iniciar el agente
|
||||||
|
ansible.builtin.meta: flush_handlers
|
||||||
|
|
||||||
|
- name: Habilitar e iniciar CloudWatch Agent
|
||||||
|
ansible.builtin.systemd_service:
|
||||||
|
name: amazon-cloudwatch-agent
|
||||||
|
enabled: true
|
||||||
|
state: started
|
||||||
|
|
@ -0,0 +1,32 @@
|
||||||
|
{
|
||||||
|
"agent": {
|
||||||
|
"region": {{ cloudwatch_agent_region | to_json }},
|
||||||
|
"run_as_user": "root"
|
||||||
|
},
|
||||||
|
"logs": {
|
||||||
|
"logs_collected": {
|
||||||
|
"files": {
|
||||||
|
"collect_list": [
|
||||||
|
{
|
||||||
|
"file_path": "/var/log/nginx/access.log",
|
||||||
|
"log_group_name": {{ cloudwatch_agent_log_group | to_json }},
|
||||||
|
"log_stream_name": "{instance_id}/nginx-access",
|
||||||
|
"timezone": "UTC"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file_path": "/var/log/nginx/error.log",
|
||||||
|
"log_group_name": {{ cloudwatch_agent_log_group | to_json }},
|
||||||
|
"log_stream_name": "{instance_id}/nginx-error",
|
||||||
|
"timezone": "UTC"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file_path": {{ (portal_app_log_dir ~ '/app.log') | to_json }},
|
||||||
|
"log_group_name": {{ cloudwatch_agent_log_group | to_json }},
|
||||||
|
"log_stream_name": "{instance_id}/app",
|
||||||
|
"timezone": "UTC"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,54 @@
|
||||||
|
---
|
||||||
|
- name: Actualizar paquetes si se solicito mantenimiento # noqa: package-latest
|
||||||
|
ansible.builtin.dnf:
|
||||||
|
name: '*'
|
||||||
|
state: latest
|
||||||
|
when: common_upgrade_packages | bool
|
||||||
|
|
||||||
|
- name: Instalar dependencias base
|
||||||
|
ansible.builtin.dnf:
|
||||||
|
name:
|
||||||
|
- python3
|
||||||
|
- curl
|
||||||
|
- logrotate
|
||||||
|
state: present
|
||||||
|
|
||||||
|
- name: Crear grupo del portal
|
||||||
|
ansible.builtin.group:
|
||||||
|
name: '{{ portal_app_user }}'
|
||||||
|
system: true
|
||||||
|
|
||||||
|
- name: Crear usuario sin acceso interactivo
|
||||||
|
ansible.builtin.user:
|
||||||
|
name: '{{ portal_app_user }}'
|
||||||
|
group: '{{ portal_app_user }}'
|
||||||
|
home: '{{ portal_app_dir }}'
|
||||||
|
shell: /sbin/nologin
|
||||||
|
system: true
|
||||||
|
create_home: false
|
||||||
|
|
||||||
|
- name: Crear directorio de aplicacion protegido contra escritura del servicio
|
||||||
|
ansible.builtin.file:
|
||||||
|
path: '{{ portal_app_dir }}'
|
||||||
|
state: directory
|
||||||
|
owner: root
|
||||||
|
group: '{{ portal_app_user }}'
|
||||||
|
mode: '0750'
|
||||||
|
|
||||||
|
- name: Crear directorio de eventos
|
||||||
|
ansible.builtin.file:
|
||||||
|
path: '{{ portal_app_log_dir }}'
|
||||||
|
state: directory
|
||||||
|
owner: '{{ portal_app_user }}'
|
||||||
|
group: '{{ portal_app_user }}'
|
||||||
|
mode: '0750'
|
||||||
|
|
||||||
|
- name: Crear archivo de eventos sin truncar el contenido
|
||||||
|
ansible.builtin.file:
|
||||||
|
path: '{{ portal_app_log_dir }}/app.log'
|
||||||
|
state: touch
|
||||||
|
owner: '{{ portal_app_user }}'
|
||||||
|
group: '{{ portal_app_user }}'
|
||||||
|
mode: '0640'
|
||||||
|
access_time: preserve
|
||||||
|
modification_time: preserve
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
---
|
||||||
|
- name: Validar Nginx antes de recargar
|
||||||
|
ansible.builtin.command: /usr/sbin/nginx -t
|
||||||
|
changed_when: false
|
||||||
|
listen: Recargar Nginx
|
||||||
|
when: not ansible_check_mode
|
||||||
|
|
||||||
|
- name: Recargar Nginx
|
||||||
|
ansible.builtin.systemd_service:
|
||||||
|
name: nginx
|
||||||
|
state: reloaded
|
||||||
|
|
@ -0,0 +1,34 @@
|
||||||
|
---
|
||||||
|
- name: Instalar Nginx
|
||||||
|
ansible.builtin.dnf:
|
||||||
|
name: nginx
|
||||||
|
state: present
|
||||||
|
|
||||||
|
- name: Retirar virtual host predeterminado si existe
|
||||||
|
ansible.builtin.file:
|
||||||
|
path: /etc/nginx/conf.d/default.conf
|
||||||
|
state: absent
|
||||||
|
notify: Recargar Nginx
|
||||||
|
|
||||||
|
- name: Configurar Nginx y proxy del portal
|
||||||
|
ansible.builtin.template:
|
||||||
|
src: '{{ item }}.j2'
|
||||||
|
dest: '/etc/nginx/{{ item }}'
|
||||||
|
owner: root
|
||||||
|
group: root
|
||||||
|
mode: '0644'
|
||||||
|
loop:
|
||||||
|
- nginx.conf
|
||||||
|
- conf.d/tesis-portal.conf
|
||||||
|
notify: Recargar Nginx
|
||||||
|
|
||||||
|
- name: Validar configuracion antes de iniciar Nginx
|
||||||
|
ansible.builtin.command: /usr/sbin/nginx -t
|
||||||
|
changed_when: false
|
||||||
|
when: not ansible_check_mode
|
||||||
|
|
||||||
|
- name: Habilitar e iniciar Nginx
|
||||||
|
ansible.builtin.systemd_service:
|
||||||
|
name: nginx
|
||||||
|
enabled: true
|
||||||
|
state: started
|
||||||
|
|
@ -0,0 +1,19 @@
|
||||||
|
server {
|
||||||
|
listen 80 default_server;
|
||||||
|
server_name _;
|
||||||
|
access_log /var/log/nginx/access.log portal_json;
|
||||||
|
error_log /var/log/nginx/error.log;
|
||||||
|
|
||||||
|
add_header X-Frame-Options "DENY" always;
|
||||||
|
add_header X-Content-Type-Options "nosniff" always;
|
||||||
|
add_header Referrer-Policy "no-referrer" always;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass http://127.0.0.1:8080;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
# Sobrescribir la cabecera evita que el cliente falsifique el origen.
|
||||||
|
proxy_set_header X-Forwarded-For $remote_addr;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,25 @@
|
||||||
|
user nginx;
|
||||||
|
worker_processes auto;
|
||||||
|
error_log /var/log/nginx/error.log warn;
|
||||||
|
pid /run/nginx.pid;
|
||||||
|
include /usr/share/nginx/modules/*.conf;
|
||||||
|
|
||||||
|
events {
|
||||||
|
worker_connections 1024;
|
||||||
|
}
|
||||||
|
|
||||||
|
http {
|
||||||
|
include /etc/nginx/mime.types;
|
||||||
|
default_type application/octet-stream;
|
||||||
|
server_tokens off;
|
||||||
|
sendfile on;
|
||||||
|
keepalive_timeout 30;
|
||||||
|
client_max_body_size 16k;
|
||||||
|
|
||||||
|
log_format portal_json escape=json
|
||||||
|
'{"timestamp":"$time_iso8601","source_ip":"$remote_addr",'
|
||||||
|
'"method":"$request_method","uri":"$uri",'
|
||||||
|
'"status":$status,"bytes":$body_bytes_sent,"request_time":$request_time}';
|
||||||
|
|
||||||
|
include /etc/nginx/conf.d/*.conf;
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,391 @@
|
||||||
|
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||||
|
from urllib.parse import parse_qs, urlparse
|
||||||
|
from http import cookies
|
||||||
|
from datetime import datetime, timezone, timedelta
|
||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
import html
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
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")
|
||||||
|
LOCK_THRESHOLD = 5
|
||||||
|
LOCK_SECONDS = 300
|
||||||
|
EC_TZ = timezone(timedelta(hours=-5), name="America/Guayaquil")
|
||||||
|
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"
|
||||||
|
|
||||||
|
# Usuarios internos de la aplicacion. No son usuarios IAM reales de AWS.
|
||||||
|
USERS = {
|
||||||
|
"admin.demo": {
|
||||||
|
"display": "Administrador",
|
||||||
|
"hash": "VpqSvQMFATBEs7T3ZU/BSA==:xioUwz95jf3bZ1gsUHqTc3H6cTcU6upr0fZiFuoU9ZY=",
|
||||||
|
},
|
||||||
|
"soc.demo": {
|
||||||
|
"display": "Analista SOC",
|
||||||
|
"hash": "9lkouWYrd54ObTxyAsNSUw==:UPSlJBYvlF2uIdpzV9LVmqMUuMNsLwXFDX+f5dedX04=",
|
||||||
|
},
|
||||||
|
"usuario.demo": {
|
||||||
|
"display": "Usuario operativo",
|
||||||
|
"hash": "n33eTr4zUj6AkGU1EfAx8A==:C3Bu/CHMnuT3SPOvBTvp0H0qpmCFJvpOjtnv7YKD9yQ=",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
FAILED_STATE = {}
|
||||||
|
|
||||||
|
|
||||||
|
def now_ecuador():
|
||||||
|
return datetime.now(EC_TZ).isoformat()
|
||||||
|
|
||||||
|
|
||||||
|
def now_utc():
|
||||||
|
return datetime.now(timezone.utc).isoformat()
|
||||||
|
|
||||||
|
|
||||||
|
def epoch_now():
|
||||||
|
return int(time.time())
|
||||||
|
|
||||||
|
|
||||||
|
def get_session_secret():
|
||||||
|
if os.path.exists(SESSION_SECRET_FILE):
|
||||||
|
with open(SESSION_SECRET_FILE, "rb") as f:
|
||||||
|
return f.read().strip()
|
||||||
|
secret = base64.urlsafe_b64encode(secrets.token_bytes(48))
|
||||||
|
with open(SESSION_SECRET_FILE, "wb") as f:
|
||||||
|
f.write(secret)
|
||||||
|
os.chmod(SESSION_SECRET_FILE, 0o600)
|
||||||
|
return secret
|
||||||
|
|
||||||
|
|
||||||
|
SESSION_SECRET = get_session_secret()
|
||||||
|
|
||||||
|
|
||||||
|
def base_event(event):
|
||||||
|
clean = dict(event)
|
||||||
|
clean.pop("password", None)
|
||||||
|
clean.setdefault("timestamp", now_ecuador())
|
||||||
|
clean.setdefault("timestamp_utc", now_utc())
|
||||||
|
clean.setdefault("timezone", "America/Guayaquil")
|
||||||
|
clean.setdefault("affected_service", AFFECTED_SERVICE)
|
||||||
|
clean.setdefault("asset_name", ASSET_NAME)
|
||||||
|
clean.setdefault("asset_type", ASSET_TYPE)
|
||||||
|
clean.setdefault("service_owner", COMPANY_NAME)
|
||||||
|
return clean
|
||||||
|
|
||||||
|
|
||||||
|
def write_event(event):
|
||||||
|
with open(LOG_FILE, "a", encoding="utf-8") as f:
|
||||||
|
f.write(json.dumps(base_event(event), ensure_ascii=False, separators=(",", ":")) + "\n")
|
||||||
|
|
||||||
|
|
||||||
|
def verify_password(username, password):
|
||||||
|
user = USERS.get(username)
|
||||||
|
if not user:
|
||||||
|
return False
|
||||||
|
salt_b64, hash_b64 = user["hash"].split(":", 1)
|
||||||
|
salt = base64.b64decode(salt_b64)
|
||||||
|
expected = base64.b64decode(hash_b64)
|
||||||
|
candidate = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, 120000)
|
||||||
|
return hmac.compare_digest(candidate, expected)
|
||||||
|
|
||||||
|
|
||||||
|
def sign_value(value):
|
||||||
|
sig = hmac.new(SESSION_SECRET, value.encode("utf-8"), hashlib.sha256).hexdigest()
|
||||||
|
return value + "." + sig
|
||||||
|
|
||||||
|
|
||||||
|
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()
|
||||||
|
if hmac.compare_digest(sig, expected):
|
||||||
|
return payload
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def html_escape(value):
|
||||||
|
return html.escape(str(value if value is not None else ""))
|
||||||
|
|
||||||
|
|
||||||
|
def page(title, content, authenticated=False, username=None):
|
||||||
|
session_area = ""
|
||||||
|
if authenticated:
|
||||||
|
session_area = f"<span>{html_escape(username)}</span><a href='/logout'>Salir</a>"
|
||||||
|
return f"""<!DOCTYPE html>
|
||||||
|
<html lang='es'>
|
||||||
|
<head>
|
||||||
|
<meta charset='UTF-8'>
|
||||||
|
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
|
||||||
|
<title>{html_escape(title)}</title>
|
||||||
|
<style>
|
||||||
|
:root {{ --bg:#0b1120; --panel:#ffffff; --muted:#64748b; --text:#0f172a; --blue:#1d4ed8; --red:#b91c1c; --border:#e2e8f0; }}
|
||||||
|
* {{ box-sizing:border-box; }}
|
||||||
|
body {{ margin:0; min-height:100vh; font-family:Inter, Segoe UI, Roboto, Arial, sans-serif; background:linear-gradient(135deg,#0f172a,#1e3a8a); color:var(--text); }}
|
||||||
|
.header {{ height:68px; display:flex; align-items:center; justify-content:space-between; padding:0 34px; color:white; }}
|
||||||
|
.brand {{ font-weight:800; letter-spacing:.2px; font-size:19px; }}
|
||||||
|
.session a {{ margin-left:16px; color:white; text-decoration:none; border:1px solid rgba(255,255,255,.35); border-radius:999px; padding:8px 13px; font-weight:700; }}
|
||||||
|
.login-wrap {{ min-height:calc(100vh - 68px); display:grid; place-items:center; padding:30px; }}
|
||||||
|
.login-card {{ width:100%; max-width:430px; background:var(--panel); border:1px solid var(--border); border-radius:26px; padding:34px; box-shadow:0 24px 70px rgba(0,0,0,.30); }}
|
||||||
|
h1 {{ margin:0 0 8px; font-size:29px; }}
|
||||||
|
p {{ color:var(--muted); line-height:1.55; }}
|
||||||
|
label {{ display:block; font-weight:750; margin:16px 0 7px; }}
|
||||||
|
input {{ width:100%; padding:14px 14px; border:1px solid #cbd5e1; border-radius:13px; font-size:15px; outline:none; }}
|
||||||
|
input:focus {{ border-color:var(--blue); box-shadow:0 0 0 4px #dbeafe; }}
|
||||||
|
button,.btn {{ width:100%; display:inline-block; text-align:center; border:0; background:var(--blue); color:white; padding:13px 16px; border-radius:13px; font-weight:800; text-decoration:none; cursor:pointer; margin-top:20px; }}
|
||||||
|
.alert {{ border-radius:14px; padding:13px 15px; margin:16px 0; font-weight:650; }}
|
||||||
|
.alert.error {{ background:#fee2e2; color:#7f1d1d; border:1px solid #fecaca; }}
|
||||||
|
.alert.info {{ background:#eff6ff; color:#1e3a8a; border:1px solid #bfdbfe; }}
|
||||||
|
.app {{ background:#f8fafc; min-height:calc(100vh - 68px); padding:34px; }}
|
||||||
|
.grid {{ max-width:980px; margin:0 auto; display:grid; grid-template-columns:repeat(3,1fr); gap:18px; }}
|
||||||
|
.card {{ background:#fff; border:1px solid var(--border); border-radius:22px; padding:24px; box-shadow:0 14px 32px rgba(15,23,42,.08); }}
|
||||||
|
.wide {{ grid-column:1 / -1; }}
|
||||||
|
.metric {{ font-size:30px; font-weight:850; margin:10px 0 2px; }}
|
||||||
|
@media(max-width:820px){{ .grid {{ grid-template-columns:1fr; }} .header {{ padding:0 18px; }} }}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class='header'><div class='brand'>{COMPANY_NAME}</div><div class='session'>{session_area}</div></div>
|
||||||
|
{content}
|
||||||
|
</body>
|
||||||
|
</html>"""
|
||||||
|
|
||||||
|
|
||||||
|
class Handler(BaseHTTPRequestHandler):
|
||||||
|
server_version = "AsteriaPortal/1.0"
|
||||||
|
|
||||||
|
def client_ip(self):
|
||||||
|
forwarded = self.headers.get("X-Forwarded-For")
|
||||||
|
if forwarded:
|
||||||
|
return forwarded.split(",")[0].strip()
|
||||||
|
return self.client_address[0]
|
||||||
|
|
||||||
|
def get_session_user(self):
|
||||||
|
raw_cookie = self.headers.get("Cookie")
|
||||||
|
if not raw_cookie:
|
||||||
|
return None
|
||||||
|
jar = cookies.SimpleCookie(raw_cookie)
|
||||||
|
if "portal_session" not in jar:
|
||||||
|
return None
|
||||||
|
payload = verify_signed_value(jar["portal_session"].value)
|
||||||
|
if not payload:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
username, issued = payload.split(":", 1)
|
||||||
|
if username in USERS and epoch_now() - int(issued) < 3600:
|
||||||
|
return username
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
return None
|
||||||
|
|
||||||
|
def respond(self, status, body, content_type="text/html; charset=utf-8", headers=None):
|
||||||
|
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-Frame-Options", "DENY")
|
||||||
|
self.send_header("X-Content-Type-Options", "nosniff")
|
||||||
|
self.send_header("Referrer-Policy", "no-referrer")
|
||||||
|
self.send_header("Cache-Control", "no-store")
|
||||||
|
if headers:
|
||||||
|
for key, value in headers.items():
|
||||||
|
self.send_header(key, value)
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(encoded)
|
||||||
|
|
||||||
|
def redirect(self, location, headers=None):
|
||||||
|
self.send_response(302)
|
||||||
|
self.send_header("Location", location)
|
||||||
|
self.send_header("Cache-Control", "no-store")
|
||||||
|
if headers:
|
||||||
|
for key, value in headers.items():
|
||||||
|
self.send_header(key, value)
|
||||||
|
self.end_headers()
|
||||||
|
|
||||||
|
def render_login(self, message=None, error=False):
|
||||||
|
alert = ""
|
||||||
|
if message:
|
||||||
|
kind = "error" if error else "info"
|
||||||
|
alert = f"<div class='alert {kind}'>{html_escape(message)}</div>"
|
||||||
|
content = f"""
|
||||||
|
<main class='login-wrap'>
|
||||||
|
<section class='login-card'>
|
||||||
|
<h1>Iniciar sesion</h1>
|
||||||
|
<p>Acceda con sus credenciales corporativas.</p>
|
||||||
|
{alert}
|
||||||
|
<form method='POST' action='/login' autocomplete='off'>
|
||||||
|
<label for='username'>Usuario</label>
|
||||||
|
<input id='username' name='username' required maxlength='64' autocomplete='username'>
|
||||||
|
<label for='password'>Contrasena</label>
|
||||||
|
<input id='password' name='password' type='password' required maxlength='128' autocomplete='current-password'>
|
||||||
|
<button type='submit'>Ingresar</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
"""
|
||||||
|
self.respond(200, page("Inicio de sesion", content))
|
||||||
|
|
||||||
|
def render_dashboard(self, username):
|
||||||
|
role = USERS.get(username, {}).get("display", "Usuario")
|
||||||
|
content = f"""
|
||||||
|
<main class='app'>
|
||||||
|
<section class='grid'>
|
||||||
|
<div class='card wide'>
|
||||||
|
<h1>Panel principal</h1>
|
||||||
|
<p>Bienvenido, {html_escape(username)}. Perfil asignado: {html_escape(role)}.</p>
|
||||||
|
</div>
|
||||||
|
<div class='card'><p>Solicitudes</p><div class='metric'>12</div><p>En revision</p></div>
|
||||||
|
<div class='card'><p>Operaciones</p><div class='metric'>98%</div><p>Disponibilidad</p></div>
|
||||||
|
<div class='card'><p>Cuenta</p><div class='metric'>Activa</div><p>Sesion protegida</p></div>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
"""
|
||||||
|
self.respond(200, page("Panel principal", content, authenticated=True, username=username))
|
||||||
|
|
||||||
|
def render_access_denied(self, remaining):
|
||||||
|
content = f"""
|
||||||
|
<main class='login-wrap'>
|
||||||
|
<section class='login-card'>
|
||||||
|
<h1>Acceso temporalmente restringido</h1>
|
||||||
|
<p>Se detectaron demasiados intentos incorrectos. Intente nuevamente en unos minutos.</p>
|
||||||
|
<div class='alert error'>Tiempo restante aproximado: {remaining} segundos</div>
|
||||||
|
<a class='btn' href='/login'>Volver</a>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
"""
|
||||||
|
self.respond(403, page("Acceso restringido", content))
|
||||||
|
|
||||||
|
def do_GET(self):
|
||||||
|
parsed = urlparse(self.path)
|
||||||
|
username = self.get_session_user()
|
||||||
|
if parsed.path == "/health":
|
||||||
|
self.respond(200, json.dumps({"status": "ok", "time": now_ecuador(), "timezone": "America/Guayaquil"}), "application/json")
|
||||||
|
return
|
||||||
|
if parsed.path in ["/", "/login"]:
|
||||||
|
self.redirect("/dashboard") if username else self.render_login()
|
||||||
|
return
|
||||||
|
if parsed.path == "/dashboard":
|
||||||
|
if not username:
|
||||||
|
self.redirect("/login")
|
||||||
|
return
|
||||||
|
self.render_dashboard(username)
|
||||||
|
return
|
||||||
|
if parsed.path == "/logout":
|
||||||
|
headers = {"Set-Cookie": "portal_session=deleted; Path=/; Max-Age=0; HttpOnly; SameSite=Lax"}
|
||||||
|
self.redirect("/login", headers=headers)
|
||||||
|
return
|
||||||
|
self.respond(404, page("No encontrado", "<main class='login-wrap'><section class='login-card'><h1>404</h1><p>Pagina no encontrada.</p></section></main>"))
|
||||||
|
|
||||||
|
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)
|
||||||
|
username = form.get("username", [""])[0].strip().lower()
|
||||||
|
password = form.get("password", [""])[0]
|
||||||
|
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})
|
||||||
|
|
||||||
|
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,
|
||||||
|
})
|
||||||
|
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,
|
||||||
|
})
|
||||||
|
cookie_value = sign_value(username + ":" + str(epoch_now()))
|
||||||
|
headers = {"Set-Cookie": "portal_session=" + cookie_value + "; Path=/; Max-Age=3600; HttpOnly; SameSite=Lax"}
|
||||||
|
self.redirect("/dashboard", headers=headers)
|
||||||
|
return
|
||||||
|
|
||||||
|
if epoch_now() - int(state.get("first", epoch_now())) > 300:
|
||||||
|
state = {"count": 0, "first": epoch_now(), "locked_until": 0}
|
||||||
|
state["count"] = int(state.get("count", 0)) + 1
|
||||||
|
if state["count"] >= LOCK_THRESHOLD:
|
||||||
|
state["locked_until"] = epoch_now() + LOCK_SECONDS
|
||||||
|
FAILED_STATE[key] = state
|
||||||
|
|
||||||
|
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."
|
||||||
|
)
|
||||||
|
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)
|
||||||
|
else:
|
||||||
|
self.render_login("Credenciales incorrectas.", error=True)
|
||||||
|
|
||||||
|
def log_message(self, format, *args):
|
||||||
|
return
|
||||||
|
|
||||||
|
|
||||||
|
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",
|
||||||
|
})
|
||||||
|
HTTPServer(("127.0.0.1", 8080), Handler).serve_forever()
|
||||||
|
|
@ -0,0 +1,5 @@
|
||||||
|
---
|
||||||
|
- name: Reiniciar portal
|
||||||
|
ansible.builtin.systemd_service:
|
||||||
|
name: tesis-portal
|
||||||
|
state: restarted
|
||||||
|
|
@ -0,0 +1,53 @@
|
||||||
|
---
|
||||||
|
- name: Desplegar la aplicacion del portal
|
||||||
|
ansible.builtin.copy:
|
||||||
|
src: app.py
|
||||||
|
dest: '{{ portal_app_dir }}/app.py'
|
||||||
|
owner: root
|
||||||
|
group: '{{ portal_app_user }}'
|
||||||
|
mode: '0640'
|
||||||
|
notify: Reiniciar portal
|
||||||
|
|
||||||
|
- name: Crear secreto de sesion solo si no existe
|
||||||
|
ansible.builtin.command:
|
||||||
|
argv:
|
||||||
|
- /usr/bin/python3
|
||||||
|
- -c
|
||||||
|
- >-
|
||||||
|
import os, secrets;
|
||||||
|
fd = os.open({{ (portal_app_dir ~ '/session_secret') | to_json }}, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600);
|
||||||
|
os.write(fd, secrets.token_urlsafe(48).encode()); os.close(fd)
|
||||||
|
creates: '{{ portal_app_dir }}/session_secret'
|
||||||
|
no_log: true
|
||||||
|
notify: Reiniciar portal
|
||||||
|
|
||||||
|
- name: Proteger el secreto de sesion
|
||||||
|
ansible.builtin.file:
|
||||||
|
path: '{{ portal_app_dir }}/session_secret'
|
||||||
|
owner: root
|
||||||
|
group: '{{ portal_app_user }}'
|
||||||
|
mode: '0640'
|
||||||
|
|
||||||
|
- name: Instalar unidad systemd
|
||||||
|
ansible.builtin.template:
|
||||||
|
src: tesis-portal.service.j2
|
||||||
|
dest: /etc/systemd/system/tesis-portal.service
|
||||||
|
owner: root
|
||||||
|
group: root
|
||||||
|
mode: '0644'
|
||||||
|
notify: Reiniciar portal
|
||||||
|
|
||||||
|
- name: Configurar rotacion de eventos
|
||||||
|
ansible.builtin.template:
|
||||||
|
src: logrotate.j2
|
||||||
|
dest: /etc/logrotate.d/tesis-portal
|
||||||
|
owner: root
|
||||||
|
group: root
|
||||||
|
mode: '0644'
|
||||||
|
|
||||||
|
- name: Habilitar e iniciar portal
|
||||||
|
ansible.builtin.systemd_service:
|
||||||
|
name: tesis-portal
|
||||||
|
enabled: true
|
||||||
|
state: started
|
||||||
|
daemon_reload: true
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
{{ portal_app_log_dir }}/app.log {
|
||||||
|
daily
|
||||||
|
maxsize 10M
|
||||||
|
rotate 7
|
||||||
|
compress
|
||||||
|
delaycompress
|
||||||
|
missingok
|
||||||
|
notifempty
|
||||||
|
create 0640 {{ portal_app_user }} {{ portal_app_user }}
|
||||||
|
su {{ portal_app_user }} {{ portal_app_user }}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,25 @@
|
||||||
|
[Unit]
|
||||||
|
Description=Portal corporativo de autenticacion de laboratorio
|
||||||
|
After=network.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
WorkingDirectory={{ portal_app_dir }}
|
||||||
|
Environment={{ ('PORTAL_LOG_FILE=' ~ portal_app_log_dir ~ '/app.log') | to_json }}
|
||||||
|
Environment={{ ('PORTAL_SESSION_SECRET_FILE=' ~ portal_app_dir ~ '/session_secret') | to_json }}
|
||||||
|
Environment={{ ('PORTAL_ASSET_NAME=' ~ portal_app_asset_name) | to_json }}
|
||||||
|
Environment=PYTHONDONTWRITEBYTECODE=1
|
||||||
|
ExecStart=/usr/bin/python3 {{ portal_app_dir }}/app.py
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=3
|
||||||
|
User={{ portal_app_user }}
|
||||||
|
Group={{ portal_app_user }}
|
||||||
|
UMask=0027
|
||||||
|
NoNewPrivileges=true
|
||||||
|
PrivateTmp=true
|
||||||
|
ProtectSystem=strict
|
||||||
|
ProtectHome=true
|
||||||
|
ReadWritePaths={{ portal_app_log_dir }}
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
|
@ -0,0 +1,70 @@
|
||||||
|
"""Genera un inventario YAML (JSON compatible) desde un unico output de Terraform."""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
|
||||||
|
|
||||||
|
def build_inventory(values, connection="ssm", private_key=None):
|
||||||
|
required = ["instance_id", "region", "asset_name", "log_group"]
|
||||||
|
required += ["ssm_bucket"] if connection == "ssm" else ["public_ip", "ssh_key"]
|
||||||
|
for key in required:
|
||||||
|
if not isinstance(values.get(key), str) or not values[key].strip():
|
||||||
|
raise ValueError(f"Output ansible_portal sin {key}; aplica Terraform y revisa la conexion elegida.")
|
||||||
|
host = {"ansible_python_interpreter": "/usr/bin/python3"}
|
||||||
|
if connection == "ssm":
|
||||||
|
host.update(
|
||||||
|
ansible_host=values["instance_id"],
|
||||||
|
ansible_connection="amazon.aws.aws_ssm",
|
||||||
|
ansible_aws_ssm_region=values["region"],
|
||||||
|
ansible_aws_ssm_bucket_name=values["ssm_bucket"],
|
||||||
|
ansible_aws_ssm_bucket_sse_mode="AES256",
|
||||||
|
ansible_aws_ssm_s3_addressing_style="virtual",
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
host.update(ansible_host=values["public_ip"], ansible_connection="ssh", ansible_user="ec2-user")
|
||||||
|
if private_key:
|
||||||
|
host["ansible_ssh_private_key_file"] = str(Path(private_key).expanduser().resolve())
|
||||||
|
return {
|
||||||
|
"all": {
|
||||||
|
"children": {
|
||||||
|
"portal": {
|
||||||
|
"hosts": {"portal_ec2": host},
|
||||||
|
"vars": {
|
||||||
|
"portal_app_asset_name": values["asset_name"],
|
||||||
|
"cloudwatch_agent_region": values["region"],
|
||||||
|
"cloudwatch_agent_log_group": values["log_group"],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
root = Path(__file__).resolve().parents[2]
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("--terraform-dir", type=Path, default=root / "terraform-tesis-ir-secure-portal")
|
||||||
|
parser.add_argument("--connection", choices=["ssm", "ssh"], default="ssm")
|
||||||
|
parser.add_argument("--private-key")
|
||||||
|
parser.add_argument("--output", type=Path, default=root / "ansible/inventory/hosts.yml")
|
||||||
|
args = parser.parse_args()
|
||||||
|
try:
|
||||||
|
result = subprocess.run(
|
||||||
|
["terraform", f"-chdir={args.terraform_dir.resolve()}", "output", "-json", "ansible_portal"],
|
||||||
|
check=True, capture_output=True, text=True,
|
||||||
|
)
|
||||||
|
inventory = build_inventory(json.loads(result.stdout), args.connection, args.private_key)
|
||||||
|
# La validacion termina antes de tocar un inventario existente.
|
||||||
|
args.output.write_text(json.dumps(inventory, indent=2) + "\n")
|
||||||
|
except (OSError, ValueError, subprocess.CalledProcessError) as exc:
|
||||||
|
print(f"No se genero el inventario: {exc}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
print(f"Inventario {args.connection}: {args.output}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
|
|
@ -1,5 +1,7 @@
|
||||||
# 09. Integración de Ansible para Gestión de Configuración (CM)
|
# 09. Integración de Ansible para Gestión de Configuración (CM)
|
||||||
|
|
||||||
|
> **Implementado:** los cuatro roles, inventario desde Terraform y bootstrap minimo estan en [`ansible/`](../ansible/README.md). Esa guia contiene los comandos vigentes, requisitos SSM/SSH, permisos, idempotencia y reemplazo inicial de EC2. El contenido siguiente conserva la justificacion y diseño original. El plugin actual es `amazon.aws.aws_ssm`; las actualizaciones globales se solicitan expresamente y el secreto de sesion se conserva.
|
||||||
|
|
||||||
## 1. Justificación Técnica y Académica para la Tesis
|
## 1. Justificación Técnica y Académica para la Tesis
|
||||||
|
|
||||||
En la arquitectura inicial del proyecto, el aprovisionamiento de la instancia EC2 y todo el software del portal web corporativo se concentraba en un script Bash monolítico dentro de [`terraform-tesis-ir-secure-portal/scripts/user_data.sh.tpl`](file:///home/bryan/Projects/LOCALSTACK/localstack-tesis/terraform-tesis-ir-secure-portal/scripts/user_data.sh.tpl) de más de 500 líneas.
|
En la arquitectura inicial del proyecto, el aprovisionamiento de la instancia EC2 y todo el software del portal web corporativo se concentraba en un script Bash monolítico dentro de [`terraform-tesis-ir-secure-portal/scripts/user_data.sh.tpl`](file:///home/bryan/Projects/LOCALSTACK/localstack-tesis/terraform-tesis-ir-secure-portal/scripts/user_data.sh.tpl) de más de 500 líneas.
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,44 @@
|
||||||
|
# Forgejo Actions y proteccion de develop
|
||||||
|
|
||||||
|
Ansible se entrega desde `feature/1-ansible-portal-cloudwatch`, asociada al Issue #1 en Forgejo, hacia `develop`. No se hace push directo a `develop` o `main`.
|
||||||
|
|
||||||
|
El workflow [validate.yml](../.forgejo/workflows/validate.yml) usa un runner `ubuntu-latest`, Linux x86_64 o ARM64 con Node compatible con Actions y acceso HTTPS a GitHub, PyPI, Galaxy y los registros Terraform:
|
||||||
|
|
||||||
|
| Job | Comprobacion |
|
||||||
|
|---|---|
|
||||||
|
| `gitflow` | Rama, destino `develop`, `Closes #issue`, milestone y etiqueta de tipo iguales en Issue/PR; todos los asuntos de commits entre base y HEAD de 10 a 72 caracteres. |
|
||||||
|
| `ansible` | Coleccion AWS, syntax-check, ansible-lint y pruebas de autenticacion, bloqueo, eventos, inventario y reglas de integracion. |
|
||||||
|
| `terraform` | Formato, inicializacion sin backend y validacion, sin plan/apply ni credenciales AWS. |
|
||||||
|
| `secretos` | Gitleaks con reglas oficiales y exclusiones locales sobre commits nuevos, con salida redactada. |
|
||||||
|
|
||||||
|
Los PR se validan sobre el SHA de origen. Los pushes a `develop` vuelven a comprobar el codigo integrado; la comprobacion de metadatos requiere el PR. No hay filtros por archivos que dejen checks obligatorios sin ejecutar.
|
||||||
|
|
||||||
|
## Configuracion
|
||||||
|
|
||||||
|
En **Settings → Repository → Advanced Settings** habilita Actions. En **Settings → Actions → Runners** debe haber un runner conectado con etiqueta `ubuntu-latest`. Si usa otra etiqueta, ajusta `runs-on` o agrega la etiqueta equivalente al runner. Referencia: [Forgejo Actions 1.21](https://forgejo.org/docs/v1.21/user/actions/).
|
||||||
|
|
||||||
|
En **Settings → Branches**, protege `develop`:
|
||||||
|
|
||||||
|
- Deshabilitar push directo y force push.
|
||||||
|
- Exigir los cuatro contextos del evento `pull_request` del workflow.
|
||||||
|
- Bloquear merge con rama desactualizada o revisiones que soliciten cambios.
|
||||||
|
- Descartar aprobaciones obsoletas.
|
||||||
|
|
||||||
|
Los contextos obligatorios configurados son `Validacion / gitflow (pull_request)`, `Validacion / ansible (pull_request)`, `Validacion / terraform (pull_request)` y `Validacion / secretos (pull_request)`. La proteccion se configura en Forgejo: el YAML por si solo no bloquea merges. Los administradores conservan las facultades del servidor; el flujo ordinario debe respetar checks y PR. Protege tambien `main` contra push directo; los cortes de version siguen el flujo de release documentado.
|
||||||
|
|
||||||
|
## Uso diario
|
||||||
|
|
||||||
|
1. Crear Issue con milestone y una etiqueta `type::feature`, `type::bug` o `type::chore`.
|
||||||
|
2. Crear desde `forgejo/develop` la rama `<feature|bugfix|chore>/<issue>-slug`.
|
||||||
|
3. Usar asuntos de commits descriptivos de 10 a 72 caracteres.
|
||||||
|
4. Publicar en `forgejo` y abrir PR hacia `develop` con `Closes #issue`.
|
||||||
|
5. Asignar el mismo milestone y etiqueta de tipo, y solicitar revisor cuando exista otro colaborador.
|
||||||
|
6. Esperar los cuatro checks del ultimo commit y revisar el diff antes de integrar.
|
||||||
|
|
||||||
|
En Forgejo 1.21, editar etiquetas o milestone puede no iniciar otra ejecucion. Completa los metadatos al crear el PR o relanza el workflow tras editarlos. No se publican comentarios automaticos ni se almacenan tokens personales o credenciales AWS en el YAML; el token efimero solo lee metadatos.
|
||||||
|
|
||||||
|
El runner anuncia internamente `http://forgejo:3000`, que no resuelve desde los contenedores de jobs. El checkout y las consultas de metadatos usan explicitamente `https://git.bryan-bano.com`; el runner debe poder alcanzar esa URL. No se desactiva la verificacion TLS.
|
||||||
|
|
||||||
|
El runner disponible es ARM64 con imagen `node:22-bookworm`. Se usa `setup-uv` y un entorno Python 3.12 aislado para no depender de las distribuciones Ubuntu admitidas por `setup-python`. Gitleaks selecciona el archivo x64/ARM64 segun la arquitectura real.
|
||||||
|
|
||||||
|
El workflow `security.yml` anterior se conserva para pushes/PR de `main`, con salida redactada. `validate.yml` atiende el circuito de `develop`, evitando duplicar el escaneo en el mismo PR.
|
||||||
|
|
@ -1,5 +1,7 @@
|
||||||
# Documentación Técnica del Sistema de Detección y Respuesta Automatizada ante Incidentes en AWS
|
# Documentación Técnica del Sistema de Detección y Respuesta Automatizada ante Incidentes en AWS
|
||||||
|
|
||||||
|
La gestion de configuracion ya esta implementada: [Ansible y despliegue del portal](../ansible/README.md), [Forgejo Actions y proteccion de develop](11-forgejo-actions-y-proteccion-develop.md).
|
||||||
|
|
||||||
**Trabajo de Integración Curricular (Tesis de Grado)**
|
**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)
|
||||||
**Autor Principal (Componente C - Automatización de Respuesta):** Bryan Baño
|
**Autor Principal (Componente C - Automatización de Respuesta):** Bryan Baño
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,74 @@
|
||||||
|
"""Valida el PR de Forgejo y todos sus commits antes de permitir integracion."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
|
||||||
|
def check_pr(pr, issue, subjects):
|
||||||
|
if issue.get("pull_request"):
|
||||||
|
raise ValueError("La referencia debe apuntar a un issue, no a otro PR.")
|
||||||
|
match = re.fullmatch(r"(feature|bugfix|chore)/(\d+)-[a-z0-9]+(?:-[a-z0-9]+)*", pr["head"]["ref"])
|
||||||
|
if not match:
|
||||||
|
raise ValueError("La rama debe usar <feature|bugfix|chore>/<issue>-slug.")
|
||||||
|
kind, number = match.groups()
|
||||||
|
if pr["base"]["ref"] != "develop":
|
||||||
|
raise ValueError("Las ramas de trabajo deben apuntar a develop.")
|
||||||
|
if not re.search(rf"\b(?:Closes|Fixes|Resolves)\s+#{number}(?!\d)\b", pr.get("body") or "", re.I):
|
||||||
|
raise ValueError(f"El cuerpo debe incluir Closes #{number}.")
|
||||||
|
expected_label = "type::" + {"feature": "feature", "bugfix": "bug", "chore": "chore"}[kind]
|
||||||
|
for obj in (pr, issue):
|
||||||
|
labels = [label["name"] for label in obj.get("labels", []) if label["name"].startswith("type::")]
|
||||||
|
if labels != [expected_label]:
|
||||||
|
raise ValueError(f"Issue y PR deben tener solo la etiqueta de tipo {expected_label}.")
|
||||||
|
if not issue.get("milestone") or not pr.get("milestone") or issue["milestone"]["id"] != pr["milestone"]["id"]:
|
||||||
|
raise ValueError("Issue y PR deben compartir un milestone.")
|
||||||
|
if issue.get("state") != "open":
|
||||||
|
raise ValueError("El issue debe estar abierto durante la revision.")
|
||||||
|
if not subjects:
|
||||||
|
raise ValueError("No hay commits nuevos para validar.")
|
||||||
|
for subject in subjects:
|
||||||
|
if not 10 <= len(subject) <= 72 or re.fullmatch(
|
||||||
|
r"(?:wip|todo|test|prueba|pruebas|cambios|arreglos|update|fix|fixes|minor|varios|\.+)", subject.strip(), re.I
|
||||||
|
):
|
||||||
|
raise ValueError(f"Asunto de commit invalido: {subject!r}")
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
if os.environ.get("GITHUB_EVENT_NAME") != "pull_request":
|
||||||
|
print("La validacion de metadatos aplica al pull request hacia develop.")
|
||||||
|
return
|
||||||
|
event = json.loads(Path(os.environ["GITHUB_EVENT_PATH"]).read_text())
|
||||||
|
pr = event["pull_request"]
|
||||||
|
branch = pr["head"]["ref"]
|
||||||
|
match = re.match(r"(?:feature|bugfix|chore)/(\d+)-", branch)
|
||||||
|
if not match:
|
||||||
|
raise ValueError("Nombre de rama invalido.")
|
||||||
|
api = os.environ["GITHUB_SERVER_URL"].rstrip("/") + "/api/v1/repos/" + os.environ["GITHUB_REPOSITORY"]
|
||||||
|
headers = {"Authorization": "token " + os.environ["GITHUB_TOKEN"], "Accept": "application/json"}
|
||||||
|
# Leer metadatos actuales permite relanzar CI tras editar etiquetas o milestone.
|
||||||
|
def get(path):
|
||||||
|
request = urllib.request.Request(api + path, headers=headers)
|
||||||
|
with urllib.request.urlopen(request, timeout=30) as response:
|
||||||
|
return json.load(response)
|
||||||
|
current = get(f"/pulls/{pr['number']}")
|
||||||
|
if current["head"]["sha"] != pr["head"]["sha"]:
|
||||||
|
raise ValueError("La rama cambio durante la ejecucion; validar el HEAD mas reciente.")
|
||||||
|
issue = get(f"/issues/{match.group(1)}")
|
||||||
|
subjects = subprocess.check_output(
|
||||||
|
["git", "log", "--format=%s", f"{pr['base']['sha']}..{pr['head']['sha']}"], text=True
|
||||||
|
).splitlines()
|
||||||
|
check_pr(current, issue, subjects)
|
||||||
|
print(f"Gitflow valido: {branch} -> develop; issue #{match.group(1)}; {len(subjects)} commit(s).")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
try:
|
||||||
|
main()
|
||||||
|
except (ValueError, OSError, subprocess.CalledProcessError) as exc:
|
||||||
|
print(str(exc), file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
@ -59,6 +59,8 @@ Activa `enable_s3_data_events=true` solo cuando vayas a probar EXFILTRATION. Act
|
||||||
|
|
||||||
## Uso
|
## Uso
|
||||||
|
|
||||||
|
Terraform aprovisiona AWS y despues [Ansible](../ansible/README.md) instala el portal, Nginx y CloudWatch Agent. Tras `terraform apply`, genera el inventario y ejecuta `ansible/playbook.yml` antes de probar el portal. La migracion desde el `user_data` anterior puede reemplazar EC2; revisa el plan.
|
||||||
|
|
||||||
Copia el ejemplo:
|
Copia el ejemplo:
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,73 @@
|
||||||
|
# Transferencias temporales del plugin amazon.aws.aws_ssm. No mezclar con evidencia.
|
||||||
|
resource "aws_s3_bucket" "ansible_transfer" {
|
||||||
|
bucket = "${var.project_name}-ansible-${local.account_id}-${var.aws_region}"
|
||||||
|
force_destroy = var.force_destroy_buckets
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "aws_s3_bucket_public_access_block" "ansible_transfer" {
|
||||||
|
bucket = aws_s3_bucket.ansible_transfer.id
|
||||||
|
block_public_acls = true
|
||||||
|
block_public_policy = true
|
||||||
|
ignore_public_acls = true
|
||||||
|
restrict_public_buckets = true
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "aws_s3_bucket_ownership_controls" "ansible_transfer" {
|
||||||
|
bucket = aws_s3_bucket.ansible_transfer.id
|
||||||
|
rule {
|
||||||
|
object_ownership = "BucketOwnerEnforced"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "aws_s3_bucket_policy" "ansible_transfer" {
|
||||||
|
bucket = aws_s3_bucket.ansible_transfer.id
|
||||||
|
policy = jsonencode({
|
||||||
|
Version = "2012-10-17"
|
||||||
|
Statement = [{
|
||||||
|
Sid = "DenyInsecureTransport"
|
||||||
|
Effect = "Deny"
|
||||||
|
Principal = "*"
|
||||||
|
Action = "s3:*"
|
||||||
|
Resource = [aws_s3_bucket.ansible_transfer.arn, "${aws_s3_bucket.ansible_transfer.arn}/*"]
|
||||||
|
Condition = { Bool = { "aws:SecureTransport" = "false" } }
|
||||||
|
}]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "aws_s3_bucket_server_side_encryption_configuration" "ansible_transfer" {
|
||||||
|
bucket = aws_s3_bucket.ansible_transfer.id
|
||||||
|
rule {
|
||||||
|
apply_server_side_encryption_by_default {
|
||||||
|
sse_algorithm = "AES256"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Sin versionado: los modulos pueden transportar secretos y deben poder eliminarse.
|
||||||
|
resource "aws_s3_bucket_lifecycle_configuration" "ansible_transfer" {
|
||||||
|
bucket = aws_s3_bucket.ansible_transfer.id
|
||||||
|
rule {
|
||||||
|
id = "expire-transfers"
|
||||||
|
status = "Enabled"
|
||||||
|
filter {}
|
||||||
|
expiration {
|
||||||
|
days = 1
|
||||||
|
}
|
||||||
|
abort_incomplete_multipart_upload {
|
||||||
|
days_after_initiation = 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
output "ansible_portal" {
|
||||||
|
description = "Parametros no secretos para generar el inventario de Ansible."
|
||||||
|
value = {
|
||||||
|
instance_id = aws_instance.portal.id
|
||||||
|
public_ip = aws_instance.portal.public_ip
|
||||||
|
region = var.aws_region
|
||||||
|
asset_name = "${var.project_name}-portal-ec2"
|
||||||
|
log_group = aws_cloudwatch_log_group.ec2_app.name
|
||||||
|
ssm_bucket = aws_s3_bucket.ansible_transfer.id
|
||||||
|
ssh_key = var.key_name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -65,7 +65,7 @@ locals {
|
||||||
sensitive_bucket_name = "${var.project_name}-sensitive-data-${local.account_id}-${var.aws_region}"
|
sensitive_bucket_name = "${var.project_name}-sensitive-data-${local.account_id}-${var.aws_region}"
|
||||||
|
|
||||||
authorized_ip_cidrs = length(var.authorized_ip_cidrs) > 0 ? var.authorized_ip_cidrs : [var.ssh_allowed_cidr]
|
authorized_ip_cidrs = length(var.authorized_ip_cidrs) > 0 ? var.authorized_ip_cidrs : [var.ssh_allowed_cidr]
|
||||||
portal_http_cidrs = length(var.http_allowed_cidrs) > 0 ? var.http_allowed_cidrs : [var.ssh_allowed_cidr]
|
portal_http_cidrs = length(var.http_allowed_cidrs) > 0 ? var.http_allowed_cidrs : [var.ssh_allowed_cidr]
|
||||||
|
|
||||||
common_log_groups = {
|
common_log_groups = {
|
||||||
cloudtrail = "/aws/cloudtrail/${var.project_name}-management"
|
cloudtrail = "/aws/cloudtrail/${var.project_name}-management"
|
||||||
|
|
@ -537,9 +537,9 @@ resource "aws_iam_role" "ec2" {
|
||||||
Version = "2012-10-17"
|
Version = "2012-10-17"
|
||||||
Statement = [
|
Statement = [
|
||||||
{
|
{
|
||||||
Effect = "Allow"
|
Effect = "Allow"
|
||||||
Principal = { Service = "ec2.amazonaws.com" }
|
Principal = { Service = "ec2.amazonaws.com" }
|
||||||
Action = "sts:AssumeRole"
|
Action = "sts:AssumeRole"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
|
|
@ -594,10 +594,7 @@ resource "aws_instance" "portal" {
|
||||||
iam_instance_profile = aws_iam_instance_profile.ec2.name
|
iam_instance_profile = aws_iam_instance_profile.ec2.name
|
||||||
key_name = var.key_name != "" ? var.key_name : null
|
key_name = var.key_name != "" ? var.key_name : null
|
||||||
|
|
||||||
user_data_base64 = base64gzip(templatefile("${path.module}/scripts/user_data.sh.tpl", {
|
user_data_base64 = base64gzip(file("${path.module}/scripts/user_data.sh.tpl"))
|
||||||
app_log_group = aws_cloudwatch_log_group.ec2_app.name
|
|
||||||
project_name = var.project_name
|
|
||||||
}))
|
|
||||||
|
|
||||||
user_data_replace_on_change = true
|
user_data_replace_on_change = true
|
||||||
|
|
||||||
|
|
@ -635,9 +632,9 @@ resource "aws_iam_role" "vpc_flowlogs" {
|
||||||
Version = "2012-10-17"
|
Version = "2012-10-17"
|
||||||
Statement = [
|
Statement = [
|
||||||
{
|
{
|
||||||
Effect = "Allow"
|
Effect = "Allow"
|
||||||
Principal = { Service = "vpc-flow-logs.amazonaws.com" }
|
Principal = { Service = "vpc-flow-logs.amazonaws.com" }
|
||||||
Action = "sts:AssumeRole"
|
Action = "sts:AssumeRole"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
|
|
@ -697,9 +694,9 @@ resource "aws_iam_role" "cloudtrail_cloudwatch" {
|
||||||
Version = "2012-10-17"
|
Version = "2012-10-17"
|
||||||
Statement = [
|
Statement = [
|
||||||
{
|
{
|
||||||
Effect = "Allow"
|
Effect = "Allow"
|
||||||
Principal = { Service = "cloudtrail.amazonaws.com" }
|
Principal = { Service = "cloudtrail.amazonaws.com" }
|
||||||
Action = "sts:AssumeRole"
|
Action = "sts:AssumeRole"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
|
|
@ -773,9 +770,9 @@ resource "aws_iam_role" "config" {
|
||||||
Version = "2012-10-17"
|
Version = "2012-10-17"
|
||||||
Statement = [
|
Statement = [
|
||||||
{
|
{
|
||||||
Effect = "Allow"
|
Effect = "Allow"
|
||||||
Principal = { Service = "config.amazonaws.com" }
|
Principal = { Service = "config.amazonaws.com" }
|
||||||
Action = "sts:AssumeRole"
|
Action = "sts:AssumeRole"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
|
|
@ -1065,9 +1062,9 @@ resource "aws_iam_role" "lambda_detector" {
|
||||||
Version = "2012-10-17"
|
Version = "2012-10-17"
|
||||||
Statement = [
|
Statement = [
|
||||||
{
|
{
|
||||||
Effect = "Allow"
|
Effect = "Allow"
|
||||||
Principal = { Service = "lambda.amazonaws.com" }
|
Principal = { Service = "lambda.amazonaws.com" }
|
||||||
Action = "sts:AssumeRole"
|
Action = "sts:AssumeRole"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
|
|
@ -1156,17 +1153,17 @@ resource "aws_lambda_function" "detector" {
|
||||||
|
|
||||||
environment {
|
environment {
|
||||||
variables = {
|
variables = {
|
||||||
INCIDENTS_TABLE = aws_dynamodb_table.incidents.name
|
INCIDENTS_TABLE = aws_dynamodb_table.incidents.name
|
||||||
STATE_TABLE = aws_dynamodb_table.state.name
|
STATE_TABLE = aws_dynamodb_table.state.name
|
||||||
EVIDENCE_BUCKET = aws_s3_bucket.evidence.bucket
|
EVIDENCE_BUCKET = aws_s3_bucket.evidence.bucket
|
||||||
SNS_TOPIC_ARN = aws_sns_topic.alerts.arn
|
SNS_TOPIC_ARN = aws_sns_topic.alerts.arn
|
||||||
CONFIG_KEY = aws_s3_object.detector_config.key
|
CONFIG_KEY = aws_s3_object.detector_config.key
|
||||||
INCIDENT_QUEUE_URL = aws_sqs_queue.incident_queue.url
|
INCIDENT_QUEUE_URL = aws_sqs_queue.incident_queue.url
|
||||||
PLAYBOOK_NOTIFY_QUEUE_URL = aws_sqs_queue.playbook_notify_queue.url
|
PLAYBOOK_NOTIFY_QUEUE_URL = aws_sqs_queue.playbook_notify_queue.url
|
||||||
PLAYBOOK_BLOCK_IP_QUEUE_URL = aws_sqs_queue.playbook_block_ip_queue.url
|
PLAYBOOK_BLOCK_IP_QUEUE_URL = aws_sqs_queue.playbook_block_ip_queue.url
|
||||||
PLAYBOOK_REVOKE_CREDENTIALS_QUEUE_URL = aws_sqs_queue.playbook_revoke_credentials_queue.url
|
PLAYBOOK_REVOKE_CREDENTIALS_QUEUE_URL = aws_sqs_queue.playbook_revoke_credentials_queue.url
|
||||||
VPC_ID = aws_vpc.this.id
|
VPC_ID = aws_vpc.this.id
|
||||||
PORTAL_INSTANCE_ID = aws_instance.portal.id
|
PORTAL_INSTANCE_ID = aws_instance.portal.id
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1271,9 +1268,9 @@ resource "aws_iam_role" "playbook_notify" {
|
||||||
Version = "2012-10-17"
|
Version = "2012-10-17"
|
||||||
Statement = [
|
Statement = [
|
||||||
{
|
{
|
||||||
Effect = "Allow"
|
Effect = "Allow"
|
||||||
Principal = { Service = "lambda.amazonaws.com" }
|
Principal = { Service = "lambda.amazonaws.com" }
|
||||||
Action = "sts:AssumeRole"
|
Action = "sts:AssumeRole"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
|
|
@ -1286,9 +1283,9 @@ resource "aws_iam_role" "playbook_block_ip" {
|
||||||
Version = "2012-10-17"
|
Version = "2012-10-17"
|
||||||
Statement = [
|
Statement = [
|
||||||
{
|
{
|
||||||
Effect = "Allow"
|
Effect = "Allow"
|
||||||
Principal = { Service = "lambda.amazonaws.com" }
|
Principal = { Service = "lambda.amazonaws.com" }
|
||||||
Action = "sts:AssumeRole"
|
Action = "sts:AssumeRole"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
|
|
@ -1328,9 +1325,9 @@ resource "aws_iam_role_policy" "playbook_notify" {
|
||||||
Resource = aws_sns_topic.alerts.arn
|
Resource = aws_sns_topic.alerts.arn
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Sid = "SendSESEmail"
|
Sid = "SendSESEmail"
|
||||||
Effect = "Allow"
|
Effect = "Allow"
|
||||||
Action = [
|
Action = [
|
||||||
"ses:SendEmail",
|
"ses:SendEmail",
|
||||||
"ses:SendRawEmail"
|
"ses:SendRawEmail"
|
||||||
]
|
]
|
||||||
|
|
@ -1390,9 +1387,9 @@ resource "aws_iam_role_policy" "playbook_block_ip" {
|
||||||
Resource = aws_sns_topic.alerts.arn
|
Resource = aws_sns_topic.alerts.arn
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Sid = "SendSESEmail"
|
Sid = "SendSESEmail"
|
||||||
Effect = "Allow"
|
Effect = "Allow"
|
||||||
Action = [
|
Action = [
|
||||||
"ses:SendEmail",
|
"ses:SendEmail",
|
||||||
"ses:SendRawEmail"
|
"ses:SendRawEmail"
|
||||||
]
|
]
|
||||||
|
|
@ -1510,9 +1507,9 @@ resource "aws_iam_role" "playbook_revoke_credentials" {
|
||||||
Version = "2012-10-17"
|
Version = "2012-10-17"
|
||||||
Statement = [
|
Statement = [
|
||||||
{
|
{
|
||||||
Effect = "Allow"
|
Effect = "Allow"
|
||||||
Principal = { Service = "lambda.amazonaws.com" }
|
Principal = { Service = "lambda.amazonaws.com" }
|
||||||
Action = "sts:AssumeRole"
|
Action = "sts:AssumeRole"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
|
|
@ -1566,9 +1563,9 @@ resource "aws_iam_role_policy" "playbook_revoke_credentials" {
|
||||||
Resource = aws_sns_topic.alerts.arn
|
Resource = aws_sns_topic.alerts.arn
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Sid = "SendSESEmail"
|
Sid = "SendSESEmail"
|
||||||
Effect = "Allow"
|
Effect = "Allow"
|
||||||
Action = [
|
Action = [
|
||||||
"ses:SendEmail",
|
"ses:SendEmail",
|
||||||
"ses:SendRawEmail"
|
"ses:SendRawEmail"
|
||||||
]
|
]
|
||||||
|
|
|
||||||
|
|
@ -1,502 +1,6 @@
|
||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
# Portal corporativo de laboratorio.
|
# Solo bootstrap: la configuracion del portal pertenece a Ansible.
|
||||||
# La aplicacion NO usa credenciales AWS ni llama servicios AWS.
|
dnf install -y python3 curl amazon-ssm-agent
|
||||||
# Solo escribe eventos JSON locales en /var/log/tesis-portal/app.log.
|
systemctl enable --now amazon-ssm-agent
|
||||||
# CloudWatch Agent transporta esos logs a CloudWatch Logs.
|
|
||||||
|
|
||||||
dnf update -y
|
|
||||||
dnf install -y nginx python3 amazon-cloudwatch-agent
|
|
||||||
|
|
||||||
useradd --system --home-dir /opt/tesis-portal --shell /sbin/nologin tesisportal || true
|
|
||||||
|
|
||||||
mkdir -p /opt/tesis-portal /var/log/tesis-portal
|
|
||||||
touch /var/log/tesis-portal/app.log
|
|
||||||
chown -R tesisportal:tesisportal /opt/tesis-portal /var/log/tesis-portal
|
|
||||||
chmod 750 /opt/tesis-portal /var/log/tesis-portal
|
|
||||||
chmod 640 /var/log/tesis-portal/app.log
|
|
||||||
|
|
||||||
cat > /opt/tesis-portal/app.py << 'PYAPP'
|
|
||||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
||||||
from urllib.parse import parse_qs, urlparse
|
|
||||||
from http import cookies
|
|
||||||
from datetime import datetime, timezone, timedelta
|
|
||||||
import base64
|
|
||||||
import hashlib
|
|
||||||
import hmac
|
|
||||||
import html
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import secrets
|
|
||||||
import time
|
|
||||||
|
|
||||||
LOG_FILE = "/var/log/tesis-portal/app.log"
|
|
||||||
SESSION_SECRET_FILE = "/opt/tesis-portal/session_secret"
|
|
||||||
LOCK_THRESHOLD = 5
|
|
||||||
LOCK_SECONDS = 300
|
|
||||||
EC_TZ = timezone(timedelta(hours=-5), name="America/Guayaquil")
|
|
||||||
AFFECTED_SERVICE = "Portal de autenticacion corporativo"
|
|
||||||
ASSET_NAME = "${project_name}-portal-ec2"
|
|
||||||
ASSET_TYPE = "EC2 web application"
|
|
||||||
COMPANY_NAME = "Asteria Operaciones"
|
|
||||||
|
|
||||||
# Usuarios internos de la aplicacion. No son usuarios IAM reales de AWS.
|
|
||||||
USERS = {
|
|
||||||
"admin.demo": {
|
|
||||||
"display": "Administrador",
|
|
||||||
"hash": "VpqSvQMFATBEs7T3ZU/BSA==:xioUwz95jf3bZ1gsUHqTc3H6cTcU6upr0fZiFuoU9ZY=",
|
|
||||||
},
|
|
||||||
"soc.demo": {
|
|
||||||
"display": "Analista SOC",
|
|
||||||
"hash": "9lkouWYrd54ObTxyAsNSUw==:UPSlJBYvlF2uIdpzV9LVmqMUuMNsLwXFDX+f5dedX04=",
|
|
||||||
},
|
|
||||||
"usuario.demo": {
|
|
||||||
"display": "Usuario operativo",
|
|
||||||
"hash": "n33eTr4zUj6AkGU1EfAx8A==:C3Bu/CHMnuT3SPOvBTvp0H0qpmCFJvpOjtnv7YKD9yQ=",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
FAILED_STATE = {}
|
|
||||||
|
|
||||||
|
|
||||||
def now_ecuador():
|
|
||||||
return datetime.now(EC_TZ).isoformat()
|
|
||||||
|
|
||||||
|
|
||||||
def now_utc():
|
|
||||||
return datetime.now(timezone.utc).isoformat()
|
|
||||||
|
|
||||||
|
|
||||||
def epoch_now():
|
|
||||||
return int(time.time())
|
|
||||||
|
|
||||||
|
|
||||||
def get_session_secret():
|
|
||||||
if os.path.exists(SESSION_SECRET_FILE):
|
|
||||||
with open(SESSION_SECRET_FILE, "rb") as f:
|
|
||||||
return f.read().strip()
|
|
||||||
secret = base64.urlsafe_b64encode(secrets.token_bytes(48))
|
|
||||||
with open(SESSION_SECRET_FILE, "wb") as f:
|
|
||||||
f.write(secret)
|
|
||||||
os.chmod(SESSION_SECRET_FILE, 0o600)
|
|
||||||
return secret
|
|
||||||
|
|
||||||
|
|
||||||
SESSION_SECRET = get_session_secret()
|
|
||||||
|
|
||||||
|
|
||||||
def base_event(event):
|
|
||||||
clean = dict(event)
|
|
||||||
clean.pop("password", None)
|
|
||||||
clean.setdefault("timestamp", now_ecuador())
|
|
||||||
clean.setdefault("timestamp_utc", now_utc())
|
|
||||||
clean.setdefault("timezone", "America/Guayaquil")
|
|
||||||
clean.setdefault("affected_service", AFFECTED_SERVICE)
|
|
||||||
clean.setdefault("asset_name", ASSET_NAME)
|
|
||||||
clean.setdefault("asset_type", ASSET_TYPE)
|
|
||||||
clean.setdefault("service_owner", COMPANY_NAME)
|
|
||||||
return clean
|
|
||||||
|
|
||||||
|
|
||||||
def write_event(event):
|
|
||||||
with open(LOG_FILE, "a", encoding="utf-8") as f:
|
|
||||||
f.write(json.dumps(base_event(event), ensure_ascii=False, separators=(",", ":")) + "\n")
|
|
||||||
|
|
||||||
|
|
||||||
def verify_password(username, password):
|
|
||||||
user = USERS.get(username)
|
|
||||||
if not user:
|
|
||||||
return False
|
|
||||||
salt_b64, hash_b64 = user["hash"].split(":", 1)
|
|
||||||
salt = base64.b64decode(salt_b64)
|
|
||||||
expected = base64.b64decode(hash_b64)
|
|
||||||
candidate = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, 120000)
|
|
||||||
return hmac.compare_digest(candidate, expected)
|
|
||||||
|
|
||||||
|
|
||||||
def sign_value(value):
|
|
||||||
sig = hmac.new(SESSION_SECRET, value.encode("utf-8"), hashlib.sha256).hexdigest()
|
|
||||||
return value + "." + sig
|
|
||||||
|
|
||||||
|
|
||||||
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()
|
|
||||||
if hmac.compare_digest(sig, expected):
|
|
||||||
return payload
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def html_escape(value):
|
|
||||||
return html.escape(str(value if value is not None else ""))
|
|
||||||
|
|
||||||
|
|
||||||
def page(title, content, authenticated=False, username=None):
|
|
||||||
session_area = ""
|
|
||||||
if authenticated:
|
|
||||||
session_area = f"<span>{html_escape(username)}</span><a href='/logout'>Salir</a>"
|
|
||||||
return f"""<!DOCTYPE html>
|
|
||||||
<html lang='es'>
|
|
||||||
<head>
|
|
||||||
<meta charset='UTF-8'>
|
|
||||||
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
|
|
||||||
<title>{html_escape(title)}</title>
|
|
||||||
<style>
|
|
||||||
:root {{ --bg:#0b1120; --panel:#ffffff; --muted:#64748b; --text:#0f172a; --blue:#1d4ed8; --red:#b91c1c; --border:#e2e8f0; }}
|
|
||||||
* {{ box-sizing:border-box; }}
|
|
||||||
body {{ margin:0; min-height:100vh; font-family:Inter, Segoe UI, Roboto, Arial, sans-serif; background:linear-gradient(135deg,#0f172a,#1e3a8a); color:var(--text); }}
|
|
||||||
.header {{ height:68px; display:flex; align-items:center; justify-content:space-between; padding:0 34px; color:white; }}
|
|
||||||
.brand {{ font-weight:800; letter-spacing:.2px; font-size:19px; }}
|
|
||||||
.session a {{ margin-left:16px; color:white; text-decoration:none; border:1px solid rgba(255,255,255,.35); border-radius:999px; padding:8px 13px; font-weight:700; }}
|
|
||||||
.login-wrap {{ min-height:calc(100vh - 68px); display:grid; place-items:center; padding:30px; }}
|
|
||||||
.login-card {{ width:100%; max-width:430px; background:var(--panel); border:1px solid var(--border); border-radius:26px; padding:34px; box-shadow:0 24px 70px rgba(0,0,0,.30); }}
|
|
||||||
h1 {{ margin:0 0 8px; font-size:29px; }}
|
|
||||||
p {{ color:var(--muted); line-height:1.55; }}
|
|
||||||
label {{ display:block; font-weight:750; margin:16px 0 7px; }}
|
|
||||||
input {{ width:100%; padding:14px 14px; border:1px solid #cbd5e1; border-radius:13px; font-size:15px; outline:none; }}
|
|
||||||
input:focus {{ border-color:var(--blue); box-shadow:0 0 0 4px #dbeafe; }}
|
|
||||||
button,.btn {{ width:100%; display:inline-block; text-align:center; border:0; background:var(--blue); color:white; padding:13px 16px; border-radius:13px; font-weight:800; text-decoration:none; cursor:pointer; margin-top:20px; }}
|
|
||||||
.alert {{ border-radius:14px; padding:13px 15px; margin:16px 0; font-weight:650; }}
|
|
||||||
.alert.error {{ background:#fee2e2; color:#7f1d1d; border:1px solid #fecaca; }}
|
|
||||||
.alert.info {{ background:#eff6ff; color:#1e3a8a; border:1px solid #bfdbfe; }}
|
|
||||||
.app {{ background:#f8fafc; min-height:calc(100vh - 68px); padding:34px; }}
|
|
||||||
.grid {{ max-width:980px; margin:0 auto; display:grid; grid-template-columns:repeat(3,1fr); gap:18px; }}
|
|
||||||
.card {{ background:#fff; border:1px solid var(--border); border-radius:22px; padding:24px; box-shadow:0 14px 32px rgba(15,23,42,.08); }}
|
|
||||||
.wide {{ grid-column:1 / -1; }}
|
|
||||||
.metric {{ font-size:30px; font-weight:850; margin:10px 0 2px; }}
|
|
||||||
@media(max-width:820px){{ .grid {{ grid-template-columns:1fr; }} .header {{ padding:0 18px; }} }}
|
|
||||||
</style>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<div class='header'><div class='brand'>{COMPANY_NAME}</div><div class='session'>{session_area}</div></div>
|
|
||||||
{content}
|
|
||||||
</body>
|
|
||||||
</html>"""
|
|
||||||
|
|
||||||
|
|
||||||
class Handler(BaseHTTPRequestHandler):
|
|
||||||
server_version = "AsteriaPortal/1.0"
|
|
||||||
|
|
||||||
def client_ip(self):
|
|
||||||
forwarded = self.headers.get("X-Forwarded-For")
|
|
||||||
if forwarded:
|
|
||||||
return forwarded.split(",")[0].strip()
|
|
||||||
return self.client_address[0]
|
|
||||||
|
|
||||||
def get_session_user(self):
|
|
||||||
raw_cookie = self.headers.get("Cookie")
|
|
||||||
if not raw_cookie:
|
|
||||||
return None
|
|
||||||
jar = cookies.SimpleCookie(raw_cookie)
|
|
||||||
if "portal_session" not in jar:
|
|
||||||
return None
|
|
||||||
payload = verify_signed_value(jar["portal_session"].value)
|
|
||||||
if not payload:
|
|
||||||
return None
|
|
||||||
try:
|
|
||||||
username, issued = payload.split(":", 1)
|
|
||||||
if username in USERS and epoch_now() - int(issued) < 3600:
|
|
||||||
return username
|
|
||||||
except Exception:
|
|
||||||
return None
|
|
||||||
return None
|
|
||||||
|
|
||||||
def respond(self, status, body, content_type="text/html; charset=utf-8", headers=None):
|
|
||||||
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-Frame-Options", "DENY")
|
|
||||||
self.send_header("X-Content-Type-Options", "nosniff")
|
|
||||||
self.send_header("Referrer-Policy", "no-referrer")
|
|
||||||
self.send_header("Cache-Control", "no-store")
|
|
||||||
if headers:
|
|
||||||
for key, value in headers.items():
|
|
||||||
self.send_header(key, value)
|
|
||||||
self.end_headers()
|
|
||||||
self.wfile.write(encoded)
|
|
||||||
|
|
||||||
def redirect(self, location, headers=None):
|
|
||||||
self.send_response(302)
|
|
||||||
self.send_header("Location", location)
|
|
||||||
self.send_header("Cache-Control", "no-store")
|
|
||||||
if headers:
|
|
||||||
for key, value in headers.items():
|
|
||||||
self.send_header(key, value)
|
|
||||||
self.end_headers()
|
|
||||||
|
|
||||||
def render_login(self, message=None, error=False):
|
|
||||||
alert = ""
|
|
||||||
if message:
|
|
||||||
kind = "error" if error else "info"
|
|
||||||
alert = f"<div class='alert {kind}'>{html_escape(message)}</div>"
|
|
||||||
content = f"""
|
|
||||||
<main class='login-wrap'>
|
|
||||||
<section class='login-card'>
|
|
||||||
<h1>Iniciar sesion</h1>
|
|
||||||
<p>Acceda con sus credenciales corporativas.</p>
|
|
||||||
{alert}
|
|
||||||
<form method='POST' action='/login' autocomplete='off'>
|
|
||||||
<label for='username'>Usuario</label>
|
|
||||||
<input id='username' name='username' required maxlength='64' autocomplete='username'>
|
|
||||||
<label for='password'>Contrasena</label>
|
|
||||||
<input id='password' name='password' type='password' required maxlength='128' autocomplete='current-password'>
|
|
||||||
<button type='submit'>Ingresar</button>
|
|
||||||
</form>
|
|
||||||
</section>
|
|
||||||
</main>
|
|
||||||
"""
|
|
||||||
self.respond(200, page("Inicio de sesion", content))
|
|
||||||
|
|
||||||
def render_dashboard(self, username):
|
|
||||||
role = USERS.get(username, {}).get("display", "Usuario")
|
|
||||||
content = f"""
|
|
||||||
<main class='app'>
|
|
||||||
<section class='grid'>
|
|
||||||
<div class='card wide'>
|
|
||||||
<h1>Panel principal</h1>
|
|
||||||
<p>Bienvenido, {html_escape(username)}. Perfil asignado: {html_escape(role)}.</p>
|
|
||||||
</div>
|
|
||||||
<div class='card'><p>Solicitudes</p><div class='metric'>12</div><p>En revision</p></div>
|
|
||||||
<div class='card'><p>Operaciones</p><div class='metric'>98%</div><p>Disponibilidad</p></div>
|
|
||||||
<div class='card'><p>Cuenta</p><div class='metric'>Activa</div><p>Sesion protegida</p></div>
|
|
||||||
</section>
|
|
||||||
</main>
|
|
||||||
"""
|
|
||||||
self.respond(200, page("Panel principal", content, authenticated=True, username=username))
|
|
||||||
|
|
||||||
def render_access_denied(self, remaining):
|
|
||||||
content = f"""
|
|
||||||
<main class='login-wrap'>
|
|
||||||
<section class='login-card'>
|
|
||||||
<h1>Acceso temporalmente restringido</h1>
|
|
||||||
<p>Se detectaron demasiados intentos incorrectos. Intente nuevamente en unos minutos.</p>
|
|
||||||
<div class='alert error'>Tiempo restante aproximado: {remaining} segundos</div>
|
|
||||||
<a class='btn' href='/login'>Volver</a>
|
|
||||||
</section>
|
|
||||||
</main>
|
|
||||||
"""
|
|
||||||
self.respond(403, page("Acceso restringido", content))
|
|
||||||
|
|
||||||
def do_GET(self):
|
|
||||||
parsed = urlparse(self.path)
|
|
||||||
username = self.get_session_user()
|
|
||||||
if parsed.path == "/health":
|
|
||||||
self.respond(200, json.dumps({"status": "ok", "time": now_ecuador(), "timezone": "America/Guayaquil"}), "application/json")
|
|
||||||
return
|
|
||||||
if parsed.path in ["/", "/login"]:
|
|
||||||
self.redirect("/dashboard") if username else self.render_login()
|
|
||||||
return
|
|
||||||
if parsed.path == "/dashboard":
|
|
||||||
if not username:
|
|
||||||
self.redirect("/login")
|
|
||||||
return
|
|
||||||
self.render_dashboard(username)
|
|
||||||
return
|
|
||||||
if parsed.path == "/logout":
|
|
||||||
headers = {"Set-Cookie": "portal_session=deleted; Path=/; Max-Age=0; HttpOnly; SameSite=Lax"}
|
|
||||||
self.redirect("/login", headers=headers)
|
|
||||||
return
|
|
||||||
self.respond(404, page("No encontrado", "<main class='login-wrap'><section class='login-card'><h1>404</h1><p>Pagina no encontrada.</p></section></main>"))
|
|
||||||
|
|
||||||
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)
|
|
||||||
username = form.get("username", [""])[0].strip().lower()
|
|
||||||
password = form.get("password", [""])[0]
|
|
||||||
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})
|
|
||||||
|
|
||||||
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,
|
|
||||||
})
|
|
||||||
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,
|
|
||||||
})
|
|
||||||
cookie_value = sign_value(username + ":" + str(epoch_now()))
|
|
||||||
headers = {"Set-Cookie": "portal_session=" + cookie_value + "; Path=/; Max-Age=3600; HttpOnly; SameSite=Lax"}
|
|
||||||
self.redirect("/dashboard", headers=headers)
|
|
||||||
return
|
|
||||||
|
|
||||||
if epoch_now() - int(state.get("first", epoch_now())) > 300:
|
|
||||||
state = {"count": 0, "first": epoch_now(), "locked_until": 0}
|
|
||||||
state["count"] = int(state.get("count", 0)) + 1
|
|
||||||
if state["count"] >= LOCK_THRESHOLD:
|
|
||||||
state["locked_until"] = epoch_now() + LOCK_SECONDS
|
|
||||||
FAILED_STATE[key] = state
|
|
||||||
|
|
||||||
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."
|
|
||||||
)
|
|
||||||
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)
|
|
||||||
else:
|
|
||||||
self.render_login("Credenciales incorrectas.", error=True)
|
|
||||||
|
|
||||||
def log_message(self, format, *args):
|
|
||||||
return
|
|
||||||
|
|
||||||
|
|
||||||
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",
|
|
||||||
})
|
|
||||||
HTTPServer(("127.0.0.1", 8080), Handler).serve_forever()
|
|
||||||
PYAPP
|
|
||||||
|
|
||||||
cat > /etc/systemd/system/tesis-portal.service << 'SYSTEMD'
|
|
||||||
[Unit]
|
|
||||||
Description=Portal corporativo de autenticacion
|
|
||||||
After=network.target
|
|
||||||
|
|
||||||
[Service]
|
|
||||||
Type=simple
|
|
||||||
WorkingDirectory=/opt/tesis-portal
|
|
||||||
ExecStart=/usr/bin/python3 /opt/tesis-portal/app.py
|
|
||||||
Restart=always
|
|
||||||
RestartSec=3
|
|
||||||
User=tesisportal
|
|
||||||
Group=tesisportal
|
|
||||||
NoNewPrivileges=true
|
|
||||||
PrivateTmp=true
|
|
||||||
ProtectSystem=full
|
|
||||||
ProtectHome=true
|
|
||||||
ReadWritePaths=/var/log/tesis-portal /opt/tesis-portal
|
|
||||||
|
|
||||||
[Install]
|
|
||||||
WantedBy=multi-user.target
|
|
||||||
SYSTEMD
|
|
||||||
|
|
||||||
cat > /etc/nginx/conf.d/tesis-portal.conf << 'NGINX'
|
|
||||||
server {
|
|
||||||
listen 80 default_server;
|
|
||||||
server_name _;
|
|
||||||
|
|
||||||
access_log /var/log/nginx/access.log;
|
|
||||||
error_log /var/log/nginx/error.log;
|
|
||||||
|
|
||||||
add_header X-Frame-Options "DENY" always;
|
|
||||||
add_header X-Content-Type-Options "nosniff" always;
|
|
||||||
add_header Referrer-Policy "no-referrer" always;
|
|
||||||
|
|
||||||
location / {
|
|
||||||
proxy_pass http://127.0.0.1:8080;
|
|
||||||
proxy_http_version 1.1;
|
|
||||||
proxy_set_header Host $host;
|
|
||||||
proxy_set_header X-Forwarded-For $remote_addr;
|
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
NGINX
|
|
||||||
|
|
||||||
rm -f /etc/nginx/conf.d/default.conf || true
|
|
||||||
|
|
||||||
cat > /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.json << 'CWAGENT'
|
|
||||||
{
|
|
||||||
"logs": {
|
|
||||||
"logs_collected": {
|
|
||||||
"files": {
|
|
||||||
"collect_list": [
|
|
||||||
{
|
|
||||||
"file_path": "/var/log/nginx/access.log",
|
|
||||||
"log_group_name": "${app_log_group}",
|
|
||||||
"log_stream_name": "{instance_id}/nginx-access",
|
|
||||||
"timezone": "UTC"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"file_path": "/var/log/nginx/error.log",
|
|
||||||
"log_group_name": "${app_log_group}",
|
|
||||||
"log_stream_name": "{instance_id}/nginx-error",
|
|
||||||
"timezone": "UTC"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"file_path": "/var/log/tesis-portal/app.log",
|
|
||||||
"log_group_name": "${app_log_group}",
|
|
||||||
"log_stream_name": "{instance_id}/app",
|
|
||||||
"timezone": "UTC"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
CWAGENT
|
|
||||||
|
|
||||||
systemctl daemon-reload
|
|
||||||
systemctl enable tesis-portal
|
|
||||||
systemctl restart tesis-portal
|
|
||||||
systemctl enable nginx
|
|
||||||
systemctl restart nginx
|
|
||||||
|
|
||||||
/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl \
|
|
||||||
-a fetch-config \
|
|
||||||
-m ec2 \
|
|
||||||
-c file:/opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.json \
|
|
||||||
-s
|
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,36 @@
|
||||||
|
import copy
|
||||||
|
import importlib.util
|
||||||
|
from pathlib import Path
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
spec = importlib.util.spec_from_file_location("gitflow", Path(__file__).resolve().parents[1] / "scripts/check_gitflow.py")
|
||||||
|
gitflow = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(gitflow)
|
||||||
|
|
||||||
|
|
||||||
|
class GitflowTest(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.pr = {
|
||||||
|
"head": {"ref": "feature/1-ansible-portal"}, "base": {"ref": "develop"},
|
||||||
|
"body": "Implementar portal. Closes #1", "labels": [{"name": "type::feature"}], "milestone": {"id": 2},
|
||||||
|
}
|
||||||
|
self.issue = {"state": "open", "labels": [{"name": "type::feature"}], "milestone": {"id": 2}, "pull_request": None}
|
||||||
|
|
||||||
|
def test_valid_pr(self):
|
||||||
|
gitflow.check_pr(self.pr, self.issue, ["feat: configurar portal con Ansible"])
|
||||||
|
|
||||||
|
def test_rejects_a_pull_request_used_as_issue(self):
|
||||||
|
with self.assertRaisesRegex(ValueError, "issue, no a otro PR"):
|
||||||
|
gitflow.check_pr(self.pr, {**self.issue, "pull_request": {"url": "/pulls/1"}}, ["feat: configurar portal con Ansible"])
|
||||||
|
|
||||||
|
def test_rejects_invalid_metadata_and_commits(self):
|
||||||
|
for mutation in [
|
||||||
|
{"base": {"ref": "main"}}, {"head": {"ref": "feature/ansible"}},
|
||||||
|
{"body": "Closes #12"}, {"milestone": None}, {"labels": []},
|
||||||
|
{"labels": [{"name": "type::feature"}, {"name": "type::chore"}]},
|
||||||
|
]:
|
||||||
|
with self.subTest(mutation=mutation), self.assertRaises(ValueError):
|
||||||
|
gitflow.check_pr({**copy.deepcopy(self.pr), **mutation}, self.issue, ["feat: configurar portal con Ansible"])
|
||||||
|
for subjects in [[], ["wip"], ["x" * 73]]:
|
||||||
|
with self.subTest(subjects=subjects), self.assertRaises(ValueError):
|
||||||
|
gitflow.check_pr(self.pr, self.issue, subjects)
|
||||||
|
|
@ -0,0 +1,35 @@
|
||||||
|
import importlib.util
|
||||||
|
from pathlib import Path
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
spec = importlib.util.spec_from_file_location(
|
||||||
|
"inventory", Path(__file__).resolve().parents[1] / "ansible/scripts/generate_inventory.py"
|
||||||
|
)
|
||||||
|
inventory = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(inventory)
|
||||||
|
|
||||||
|
|
||||||
|
class InventoryTest(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.values = dict(instance_id="i-0123456789abcdef0", public_ip="192.0.2.10", region="us-east-2",
|
||||||
|
asset_name="custom-portal", log_group="/aws/ec2/custom", ssm_bucket="custom-transfer", ssh_key="")
|
||||||
|
|
||||||
|
def test_ssm_preserves_terraform_parameters_without_ssh_key(self):
|
||||||
|
group = inventory.build_inventory(self.values)["all"]["children"]["portal"]
|
||||||
|
host = group["hosts"]["portal_ec2"]
|
||||||
|
self.assertEqual(host["ansible_host"], self.values["instance_id"])
|
||||||
|
self.assertEqual(host["ansible_aws_ssm_bucket_name"], self.values["ssm_bucket"])
|
||||||
|
self.assertEqual(group["vars"]["cloudwatch_agent_log_group"], self.values["log_group"])
|
||||||
|
|
||||||
|
def test_ssh_requires_key_pair_and_uses_public_address(self):
|
||||||
|
with self.assertRaisesRegex(ValueError, "ssh_key"):
|
||||||
|
inventory.build_inventory(self.values, "ssh")
|
||||||
|
self.values["ssh_key"] = "tesis"
|
||||||
|
host = inventory.build_inventory(self.values, "ssh")["all"]["children"]["portal"]["hosts"]["portal_ec2"]
|
||||||
|
self.assertEqual(host["ansible_host"], self.values["public_ip"])
|
||||||
|
self.assertEqual(host["ansible_connection"], "ssh")
|
||||||
|
|
||||||
|
def test_incomplete_output_fails_before_generating_inventory(self):
|
||||||
|
for key in ["instance_id", "region", "asset_name", "log_group", "ssm_bucket"]:
|
||||||
|
with self.subTest(key=key), self.assertRaises(ValueError):
|
||||||
|
inventory.build_inventory({**self.values, key: ""})
|
||||||
|
|
@ -0,0 +1,99 @@
|
||||||
|
"""Contrato HTTP y eventos que consume el detector, sin AWS ni dependencias."""
|
||||||
|
|
||||||
|
import http.client
|
||||||
|
from http.server import HTTPServer
|
||||||
|
import importlib.util
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import tempfile
|
||||||
|
import threading
|
||||||
|
import unittest
|
||||||
|
from urllib.parse import urlencode
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
|
||||||
|
|
||||||
|
class PortalTest(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.tmp = tempfile.TemporaryDirectory()
|
||||||
|
self.addCleanup(self.tmp.cleanup)
|
||||||
|
self.log = Path(self.tmp.name) / "app.log"
|
||||||
|
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.start()
|
||||||
|
self.addCleanup(env.stop)
|
||||||
|
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)
|
||||||
|
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
|
||||||
|
self.thread.start()
|
||||||
|
self.addCleanup(self.stop_server)
|
||||||
|
|
||||||
|
def stop_server(self):
|
||||||
|
self.server.shutdown()
|
||||||
|
self.server.server_close()
|
||||||
|
self.thread.join(timeout=5)
|
||||||
|
|
||||||
|
def request(self, method, path, body=None, headers=None):
|
||||||
|
conn = http.client.HTTPConnection(*self.server.server_address, timeout=5)
|
||||||
|
try:
|
||||||
|
conn.request(method, path, body, headers or {})
|
||||||
|
response = conn.getresponse()
|
||||||
|
return response.status, dict(response.getheaders()), response.read()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
def test_health_and_private_dashboard(self):
|
||||||
|
status, _, data = self.request("GET", "/health")
|
||||||
|
self.assertEqual(status, 200)
|
||||||
|
self.assertEqual(json.loads(data)["status"], "ok")
|
||||||
|
status, headers, _ = self.request("GET", "/dashboard")
|
||||||
|
self.assertEqual(status, 302)
|
||||||
|
self.assertEqual(headers["Location"], "/login")
|
||||||
|
|
||||||
|
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"}
|
||||||
|
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)
|
||||||
|
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)
|
||||||
|
self.assertEqual(failed[-1]["failed_attempts"], 5)
|
||||||
|
self.assertEqual(failed[-1]["severity"], "HIGH")
|
||||||
|
self.assertEqual(events[-1]["event_type"], "access_blocked")
|
||||||
|
for event in events:
|
||||||
|
self.assertEqual(event["sourceIPAddress"], "198.51.100.8")
|
||||||
|
self.assertEqual(event["asset_name"], "custom-portal-ec2")
|
||||||
|
self.assertIn("timestamp_utc", event)
|
||||||
|
self.assertNotIn("password", event)
|
||||||
|
self.assertNotIn(password, self.log.read_text())
|
||||||
|
|
||||||
|
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(),
|
||||||
|
}
|
||||||
|
status, headers, _ = self.request(
|
||||||
|
"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.secret.read_bytes(), b"local-test-session-value")
|
||||||
|
self.assertEqual(json.loads(self.log.read_text().splitlines()[0])["event_type"], "login_success")
|
||||||
|
|
@ -0,0 +1,26 @@
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from jinja2 import Environment, FileSystemLoader, StrictUndefined
|
||||||
|
import yaml
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1] / "ansible"
|
||||||
|
|
||||||
|
|
||||||
|
class TemplatesTest(unittest.TestCase):
|
||||||
|
def test_all_templates_render_and_cloudwatch_uses_inventory_values(self):
|
||||||
|
values = yaml.safe_load((ROOT / "inventory/group_vars/all.yml").read_text())
|
||||||
|
values.update(cloudwatch_agent_region="eu-west-1", cloudwatch_agent_log_group="/custom/portal")
|
||||||
|
rendered = {}
|
||||||
|
for directory in (ROOT / "roles").glob("*/templates"):
|
||||||
|
env = Environment(loader=FileSystemLoader(directory), undefined=StrictUndefined)
|
||||||
|
env.filters["to_json"] = json.dumps
|
||||||
|
for name in env.list_templates():
|
||||||
|
rendered[name] = env.get_template(name).render(values)
|
||||||
|
config = json.loads(rendered["config.json.j2"])
|
||||||
|
self.assertEqual(config["agent"]["region"], "eu-west-1")
|
||||||
|
logs = config["logs"]["logs_collected"]["files"]["collect_list"]
|
||||||
|
self.assertEqual(len({entry["log_stream_name"] for entry in logs}), len(logs))
|
||||||
|
self.assertTrue(all(entry["log_group_name"] == "/custom/portal" for entry in logs))
|
||||||
|
self.assertIn("/var/log/tesis-portal/app.log", [entry["file_path"] for entry in logs])
|
||||||
Loading…
Reference in New Issue