diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d91b87c --- /dev/null +++ b/.gitignore @@ -0,0 +1,25 @@ +# Terraform +.terraform/ +*.tfstate +*.tfstate.* +.terraform.lock.hcl +terraform.tfvars +terraform.tfvars.json + +# Lambda build artifacts +*.zip + +# Python cache +__pycache__/ +*.py[cod] +*$py.class + +# Environment & credentials +.env +.env.* +*.pem +*.key + +# Backups and logs +*.log +backup_*/ diff --git a/activate.sh b/activate.sh deleted file mode 100755 index a026e62..0000000 --- a/activate.sh +++ /dev/null @@ -1,17 +0,0 @@ -#!/usr/bin/env bash -# Activa el entorno de desarrollo local de la tesis -# Uso: source activate.sh - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" - -source "$SCRIPT_DIR/.venv/bin/activate" - -export AWS_ACCESS_KEY_ID=test -export AWS_SECRET_ACCESS_KEY=test -export AWS_DEFAULT_REGION=us-east-1 -export AWS_ENDPOINT_URL=http://localhost:4566 - -echo "Entorno de tesis activado." -echo " awslocal → $(which awslocal)" -echo " python3 → $(which python3)" -echo " endpoint → $AWS_ENDPOINT_URL" diff --git a/docker-compose.yml b/docker-compose.yml deleted file mode 100644 index dcee7cb..0000000 --- a/docker-compose.yml +++ /dev/null @@ -1,23 +0,0 @@ -version: "3.8" - -services: - localstack: - container_name: "${LOCALSTACK_DOCKER_NAME:-localstack-tesis}" - image: localstack/localstack:3.8 - ports: - - "127.0.0.1:4566:4566" - - "127.0.0.1:4510-4559:4510-4559" - environment: - - DEBUG=${DEBUG:-0} - - SERVICES=s3,sns,sqs,lambda,iam,logs,cloudwatch,events - - DOCKER_HOST=unix:///var/run/docker.sock - - LAMBDA_EXECUTOR=docker - - AWS_DEFAULT_REGION=us-east-1 - volumes: - - "${LOCALSTACK_VOLUME_DIR:-./volume}:/var/lib/localstack" - - "/var/run/docker.sock:/var/run/docker.sock" - healthcheck: - test: ["CMD", "curl", "-f", "http://localhost:4566/_localstack/health"] - interval: 10s - timeout: 5s - retries: 5 diff --git a/infra/lambda-policies/base-policy.json b/infra/lambda-policies/base-policy.json deleted file mode 100644 index d67bb7a..0000000 --- a/infra/lambda-policies/base-policy.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "Version": "2012-10-17", - "Statement": [ - { - "Sid": "S3LogsAccess", - "Effect": "Allow", - "Action": [ - "s3:GetObject", - "s3:PutObject", - "s3:ListBucket" - ], - "Resource": [ - "arn:aws:s3:::tesis-security-logs", - "arn:aws:s3:::tesis-security-logs/*" - ] - }, - { - "Sid": "SNSPublish", - "Effect": "Allow", - "Action": ["sns:Publish"], - "Resource": [ - "arn:aws:sns:us-east-1:000000000000:tesis-security-alerts", - "arn:aws:sns:us-east-1:000000000000:tesis-lambda-triggers" - ] - }, - { - "Sid": "SQSConsume", - "Effect": "Allow", - "Action": [ - "sqs:ReceiveMessage", - "sqs:DeleteMessage", - "sqs:GetQueueAttributes" - ], - "Resource": "arn:aws:sqs:us-east-1:000000000000:tesis-incident-queue" - }, - { - "Sid": "CloudWatchLogs", - "Effect": "Allow", - "Action": [ - "logs:CreateLogStream", - "logs:PutLogEvents", - "logs:DescribeLogStreams" - ], - "Resource": "arn:aws:logs:us-east-1:000000000000:log-group:/tesis/*:*" - } - ] -} diff --git a/infra/setup.sh b/infra/setup.sh deleted file mode 100755 index 4814f0f..0000000 --- a/infra/setup.sh +++ /dev/null @@ -1,99 +0,0 @@ -#!/usr/bin/env bash -# Bootstrap de recursos AWS locales para el Componente C — Automatización de Respuesta -# Requiere: LocalStack corriendo en localhost:4566 y awslocal instalado -set -euo pipefail - -ENDPOINT="http://localhost:4566" -REGION="us-east-1" -ACCOUNT_ID="000000000000" # LocalStack usa este account ID ficticio - -# Colores para output -GREEN='\033[0;32m' -YELLOW='\033[1;33m' -RED='\033[0;31m' -NC='\033[0m' - -log() { echo -e "${GREEN}[OK]${NC} $1"; } -warn() { echo -e "${YELLOW}[--]${NC} $1"; } -fail() { echo -e "${RED}[ERR]${NC} $1"; exit 1; } - -echo "========================================" -echo " Bootstrap Componente C — Tesis" -echo " LocalStack: $ENDPOINT" -echo "========================================" - -# Verificar que LocalStack está corriendo -curl -sf "$ENDPOINT/_localstack/health" > /dev/null || fail "LocalStack no está corriendo. Ejecuta: docker compose up -d" - -# ── S3 ──────────────────────────────────────────────────────────────────────── -warn "Creando bucket S3..." -awslocal s3 mb s3://tesis-security-logs --region $REGION 2>/dev/null || warn "Bucket ya existe" -# Crear prefijos vacíos (objetos vacíos actúan como carpetas) -for prefix in cloudtrail vpc-flow guardduty responses; do - awslocal s3api put-object --bucket tesis-security-logs --key "$prefix/" > /dev/null -done -log "S3: s3://tesis-security-logs [cloudtrail/, vpc-flow/, guardduty/, responses/]" - -# ── SNS ─────────────────────────────────────────────────────────────────────── -warn "Creando tópicos SNS..." -ALERTS_ARN=$(awslocal sns create-topic --name tesis-security-alerts --query 'TopicArn' --output text) -TRIGGERS_ARN=$(awslocal sns create-topic --name tesis-lambda-triggers --query 'TopicArn' --output text) -log "SNS alerts: $ALERTS_ARN" -log "SNS triggers: $TRIGGERS_ARN" - -# ── SQS ─────────────────────────────────────────────────────────────────────── -warn "Creando colas SQS..." -DLQ_URL=$(awslocal sqs create-queue --queue-name tesis-incident-queue-dlq --query 'QueueUrl' --output text) -DLQ_ARN="arn:aws:sqs:$REGION:$ACCOUNT_ID:tesis-incident-queue-dlq" - -# Cola principal con DLQ configurada -QUEUE_URL=$(awslocal sqs create-queue \ - --queue-name tesis-incident-queue \ - --attributes "{\"RedrivePolicy\":\"{\\\"deadLetterTargetArn\\\":\\\"$DLQ_ARN\\\",\\\"maxReceiveCount\\\":\\\"3\\\"}\"}" \ - --query 'QueueUrl' --output text) -log "SQS queue: $QUEUE_URL" -log "SQS DLQ: $DLQ_URL" - -# ── CloudWatch Logs ─────────────────────────────────────────────────────────── -warn "Creando grupos de logs CloudWatch..." -awslocal logs create-log-group --log-group-name /tesis/security-events 2>/dev/null || warn "Log group ya existe" -awslocal logs create-log-group --log-group-name /tesis/lambda-responses 2>/dev/null || warn "Log group ya existe" -log "CloudWatch: /tesis/security-events" -log "CloudWatch: /tesis/lambda-responses" - -# ── IAM ─────────────────────────────────────────────────────────────────────── -warn "Creando rol IAM para Lambdas de respuesta..." -TRUST_POLICY='{ - "Version": "2012-10-17", - "Statement": [{ - "Effect": "Allow", - "Principal": {"Service": "lambda.amazonaws.com"}, - "Action": "sts:AssumeRole" - }] -}' -ROLE_ARN=$(awslocal iam create-role \ - --role-name tesis-lambda-response-role \ - --assume-role-policy-document "$TRUST_POLICY" \ - --query 'Role.Arn' --output text 2>/dev/null) || { - ROLE_ARN=$(awslocal iam get-role --role-name tesis-lambda-response-role --query 'Role.Arn' --output text) - warn "Rol ya existe" -} - -# Adjuntar política de acceso a los recursos del proyecto -awslocal iam put-role-policy \ - --role-name tesis-lambda-response-role \ - --policy-name tesis-lambda-base-policy \ - --policy-document file://$(dirname "$0")/lambda-policies/base-policy.json 2>/dev/null || true -log "IAM Role: $ROLE_ARN" - -# ── Resumen ─────────────────────────────────────────────────────────────────── -echo "" -echo "========================================" -echo " Recursos creados exitosamente" -echo "========================================" -echo "" -awslocal s3 ls -echo "" -awslocal sns list-topics --query 'Topics[].TopicArn' --output table -echo "" -awslocal sqs list-queues --output table diff --git a/lambdas/notify-alert/handler.py b/lambdas/notify-alert/handler.py deleted file mode 100644 index e527a3b..0000000 --- a/lambdas/notify-alert/handler.py +++ /dev/null @@ -1,62 +0,0 @@ -""" -Playbook: notify-alert -Recibe un evento de incidente desde SQS y publica una notificación -estructurada al tópico SNS de alertas. -""" -import json -import os -import boto3 -from datetime import datetime, timezone - -ENDPOINT = os.environ.get("AWS_ENDPOINT_URL", "http://localhost:4566") -REGION = os.environ.get("AWS_DEFAULT_REGION", "us-east-1") -SNS_ARN = os.environ.get("SNS_ALERTS_ARN", "arn:aws:sns:us-east-1:000000000000:tesis-security-alerts") - -sns = boto3.client("sns", endpoint_url=ENDPOINT, region_name=REGION) - - -def lambda_handler(event, context): - results = [] - - for record in event.get("Records", []): - # Parsear mensaje SQS - try: - body = json.loads(record["body"]) - except (KeyError, json.JSONDecodeError) as e: - return {"status": "error", "detail": f"Payload inválido: {e}"} - - incident_type = body.get("incident_type", "UNKNOWN") - severity = body.get("severity", "MEDIUM") - source_ip = body.get("sourceIPAddress", "0.0.0.0") - resource = body.get("affectedResource", "unknown") - timestamp = body.get("timestamp", datetime.now(timezone.utc).isoformat()) - - # Construir mensaje de alerta - alert = { - "alert_type": "SECURITY_INCIDENT", - "incident_type": incident_type, - "severity": severity, - "sourceIPAddress": source_ip, - "affectedResource": resource, - "detectedAt": timestamp, - "respondedAt": datetime.now(timezone.utc).isoformat(), - "playbook": "notify-alert", - "status": "NOTIFIED" - } - - subject = f"[{severity}] Incidente detectado: {incident_type}" - sns.publish( - TopicArn=SNS_ARN, - Subject=subject[:100], # SNS limita el subject a 100 chars - Message=json.dumps(alert, indent=2) - ) - - print(f"[notify-alert] Alerta publicada: {incident_type} desde {source_ip}") - results.append({"status": "success", "action": "sns_published", "details": alert}) - - return { - "status": "success", - "processed": len(results), - "results": results, - "timestamp": datetime.now(timezone.utc).isoformat() - } diff --git a/lambdas/notify-alert/policy.json b/lambdas/notify-alert/policy.json deleted file mode 100644 index e87a50a..0000000 --- a/lambdas/notify-alert/policy.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "Version": "2012-10-17", - "Statement": [ - { - "Sid": "PublishAlertOnly", - "Effect": "Allow", - "Action": ["sns:Publish"], - "Resource": "arn:aws:sns:us-east-1:000000000000:tesis-security-alerts" - }, - { - "Sid": "CloudWatchLogs", - "Effect": "Allow", - "Action": ["logs:CreateLogStream", "logs:PutLogEvents"], - "Resource": "arn:aws:logs:us-east-1:000000000000:log-group:/tesis/lambda-responses:*" - } - ] -} diff --git a/lambdas/notify-alert/test_event.json b/lambdas/notify-alert/test_event.json deleted file mode 100644 index b1bbbdf..0000000 --- a/lambdas/notify-alert/test_event.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "Records": [ - { - "messageId": "test-msg-001", - "receiptHandle": "test-handle", - "body": "{\"incident_type\": \"BRUTE_FORCE\", \"severity\": \"HIGH\", \"sourceIPAddress\": \"203.0.113.42\", \"affectedResource\": \"iam:user/admin\", \"timestamp\": \"2024-01-15T10:30:00Z\"}", - "attributes": {}, - "messageAttributes": {}, - "md5OfBody": "", - "eventSource": "aws:sqs", - "eventSourceARN": "arn:aws:sqs:us-east-1:000000000000:tesis-incident-queue", - "awsRegion": "us-east-1" - } - ] -} diff --git a/lambdas/revoke-credentials/handler.py b/lambdas/revoke-credentials/handler.py deleted file mode 100644 index eb83f8a..0000000 --- a/lambdas/revoke-credentials/handler.py +++ /dev/null @@ -1,73 +0,0 @@ -""" -Playbook: revoke-credentials -Revoca (desactiva) las access keys de un usuario IAM comprometido -y adjunta una política de denegación explícita para bloqueo inmediato. -""" -import json -import os -import boto3 -from datetime import datetime, timezone - -ENDPOINT = os.environ.get("AWS_ENDPOINT_URL", "http://localhost:4566") -REGION = os.environ.get("AWS_DEFAULT_REGION", "us-east-1") - -iam = boto3.client("iam", endpoint_url=ENDPOINT, region_name=REGION) -sns = boto3.client("sns", endpoint_url=ENDPOINT, region_name=REGION) -SNS_ARN = os.environ.get("SNS_ALERTS_ARN", "arn:aws:sns:us-east-1:000000000000:tesis-security-alerts") - -DENY_ALL_POLICY = json.dumps({ - "Version": "2012-10-17", - "Statement": [{ - "Effect": "Deny", - "Action": "*", - "Resource": "*" - }] -}) - - -def lambda_handler(event, context): - for record in event.get("Records", []): - try: - body = json.loads(record["body"]) - except (KeyError, json.JSONDecodeError) as e: - return {"status": "error", "detail": f"Payload inválido: {e}"} - - username = body.get("affectedResource", "").replace("iam:user/", "") - if not username: - return {"status": "error", "detail": "affectedResource no contiene usuario IAM"} - - actions_taken = [] - - # 1. Listar y desactivar todas las access keys del usuario - keys = iam.list_access_keys(UserName=username).get("AccessKeyMetadata", []) - for key in keys: - kid = key["AccessKeyId"] - iam.update_access_key(UserName=username, AccessKeyId=kid, Status="Inactive") - actions_taken.append(f"AccessKey desactivada: {kid}") - print(f"[revoke-credentials] Desactivada key {kid} de usuario {username}") - - # 2. Adjuntar política de Deny-All como medida de contención - iam.put_user_policy( - UserName=username, - PolicyName="EmergencyDenyAll", - PolicyDocument=DENY_ALL_POLICY - ) - actions_taken.append("Política EmergencyDenyAll adjuntada") - print(f"[revoke-credentials] DenyAll aplicado al usuario {username}") - - # 3. Notificar al equipo - result = { - "playbook": "revoke-credentials", - "username": username, - "actions": actions_taken, - "status": "CONTAINED", - "timestamp": datetime.now(timezone.utc).isoformat() - } - sns.publish( - TopicArn=SNS_ARN, - Subject=f"[RESPUESTA] Credenciales revocadas: {username}", - Message=json.dumps(result, indent=2) - ) - - return {"status": "success", "action": "credentials_revoked", "details": result, - "timestamp": datetime.now(timezone.utc).isoformat()} diff --git a/lambdas/revoke-credentials/policy.json b/lambdas/revoke-credentials/policy.json deleted file mode 100644 index 3223958..0000000 --- a/lambdas/revoke-credentials/policy.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "Version": "2012-10-17", - "Statement": [ - { - "Sid": "IAMRevokeOnly", - "Effect": "Allow", - "Action": [ - "iam:ListAccessKeys", - "iam:UpdateAccessKey", - "iam:PutUserPolicy" - ], - "Resource": "arn:aws:iam::000000000000:user/*" - }, - { - "Sid": "SNSNotify", - "Effect": "Allow", - "Action": ["sns:Publish"], - "Resource": "arn:aws:sns:us-east-1:000000000000:tesis-security-alerts" - }, - { - "Sid": "CloudWatchLogs", - "Effect": "Allow", - "Action": ["logs:CreateLogStream", "logs:PutLogEvents"], - "Resource": "arn:aws:logs:us-east-1:000000000000:log-group:/tesis/lambda-responses:*" - } - ] -} diff --git a/lambdas/revoke-credentials/test_event.json b/lambdas/revoke-credentials/test_event.json deleted file mode 100644 index 3d60183..0000000 --- a/lambdas/revoke-credentials/test_event.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "Records": [ - { - "messageId": "test-msg-002", - "receiptHandle": "test-handle", - "body": "{\"incident_type\": \"CREDENTIAL_LEAK\", \"severity\": \"CRITICAL\", \"sourceIPAddress\": \"198.51.100.77\", \"affectedResource\": \"iam:user/dev-operator\", \"timestamp\": \"2024-01-15T11:00:00Z\"}", - "eventSource": "aws:sqs", - "eventSourceARN": "arn:aws:sqs:us-east-1:000000000000:tesis-incident-queue", - "awsRegion": "us-east-1" - } - ] -} diff --git a/logs/sample_cloudtrail.json b/logs/sample_cloudtrail.json deleted file mode 100644 index 473e131..0000000 --- a/logs/sample_cloudtrail.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "Records": [ - { - "eventVersion": "1.08", - "eventTime": "2024-01-15T10:30:00Z", - "eventSource": "signin.amazonaws.com", - "eventName": "ConsoleLogin", - "awsRegion": "us-east-1", - "sourceIPAddress": "203.0.113.42", - "userAgent": "aws-cli/2.x Python/3.11", - "requestID": "a1b2c3d4-0000-0000-0000-000000000001", - "eventID": "e1b2c3d4-0000-0000-0000-000000000001", - "readOnly": false, - "errorCode": "AccessDenied", - "errorMessage": "Failed authentication", - "responseElements": {"ConsoleLogin": "Failure"}, - "userIdentity": { - "type": "IAMUser", - "userName": "admin", - "arn": "arn:aws:iam::123456789012:user/admin", - "accountId": "123456789012" - } - }, - { - "eventVersion": "1.08", - "eventTime": "2024-01-15T10:30:15Z", - "eventSource": "signin.amazonaws.com", - "eventName": "ConsoleLogin", - "awsRegion": "us-east-1", - "sourceIPAddress": "203.0.113.42", - "requestID": "a1b2c3d4-0000-0000-0000-000000000002", - "eventID": "e1b2c3d4-0000-0000-0000-000000000002", - "readOnly": false, - "errorCode": "AccessDenied", - "errorMessage": "Failed authentication", - "responseElements": {"ConsoleLogin": "Failure"}, - "userIdentity": { - "type": "IAMUser", - "userName": "admin", - "arn": "arn:aws:iam::123456789012:user/admin", - "accountId": "123456789012" - } - } - ] -} diff --git a/queries/detect_brute_force.sql b/queries/detect_brute_force.sql deleted file mode 100644 index 8e888fc..0000000 --- a/queries/detect_brute_force.sql +++ /dev/null @@ -1,18 +0,0 @@ --- Detección de Fuerza Bruta --- Busca >5 intentos fallidos de ConsoleLogin desde la misma IP en una ventana de 5 minutos --- Equivalente a una regla Athena sobre la tabla de CloudTrail - -SELECT - sourceIPAddress, - userIdentity.userName AS username, - COUNT(*) AS failed_attempts, - MIN(eventTime) AS first_attempt, - MAX(eventTime) AS last_attempt, - epoch_ms(MAX(epoch_ms(last_attempt)) - MIN(epoch_ms(first_attempt))) AS window_seconds -FROM read_json_auto('$LOG_PATH', format='array') -WHERE eventName = 'ConsoleLogin' - AND errorCode = 'AccessDenied' - AND epoch_ms(eventTime) >= now() - INTERVAL '1 hour' -GROUP BY sourceIPAddress, userIdentity.userName -HAVING COUNT(*) > 5 -ORDER BY failed_attempts DESC; diff --git a/queries/detect_exfiltration.sql b/queries/detect_exfiltration.sql deleted file mode 100644 index 617d88d..0000000 --- a/queries/detect_exfiltration.sql +++ /dev/null @@ -1,16 +0,0 @@ --- Detección de Exfiltración de Datos --- Busca acceso masivo a S3 GetObject (>50 objetos) desde la misma IP en 1 hora - -SELECT - sourceIPAddress, - userIdentity.userName AS username, - COUNT(*) AS total_downloads, - MIN(eventTime) AS first_access, - MAX(eventTime) AS last_access -FROM read_json_auto('$LOG_PATH', format='array') -WHERE eventSource = 's3.amazonaws.com' - AND eventName = 'GetObject' - AND epoch_ms(eventTime) >= now() - INTERVAL '1 hour' -GROUP BY sourceIPAddress, userIdentity.userName -HAVING COUNT(*) > 50 -ORDER BY total_downloads DESC; diff --git a/queries/detect_privilege_esc.sql b/queries/detect_privilege_esc.sql deleted file mode 100644 index 3fc45b4..0000000 --- a/queries/detect_privilege_esc.sql +++ /dev/null @@ -1,22 +0,0 @@ --- Detección de Escalada de Privilegios --- Busca eventos IAM sospechosos: adjuntar políticas admin, crear keys, modificar roles - -SELECT - userIdentity.userName AS username, - sourceIPAddress, - eventName, - eventTime, - requestParameters -FROM read_json_auto('$LOG_PATH', format='array') -WHERE eventSource = 'iam.amazonaws.com' - AND eventName IN ( - 'AttachUserPolicy', - 'AttachRolePolicy', - 'CreateAccessKey', - 'PutUserPolicy', - 'AddUserToGroup', - 'CreateLoginProfile', - 'UpdateLoginProfile' - ) - AND epoch_ms(eventTime) >= now() - INTERVAL '24 hours' -ORDER BY eventTime DESC; diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index d9e1bff..0000000 --- a/requirements.txt +++ /dev/null @@ -1,3 +0,0 @@ -boto3>=1.34 -awscli-local>=0.22 -duckdb>=0.10 diff --git a/simulators/cloudtrail_gen.py b/simulators/cloudtrail_gen.py deleted file mode 100644 index e424e17..0000000 --- a/simulators/cloudtrail_gen.py +++ /dev/null @@ -1,159 +0,0 @@ -""" -Generador de eventos CloudTrail simulados. -Produce logs JSON con la estructura real de CloudTrail para probar -los componentes de Detección (B) y Respuesta (C) sin depender de AWS real. -""" -import json -import random -import uuid -from datetime import datetime, timezone, timedelta - - -USERS = ["admin", "dev-operator", "ci-runner", "readonly-audit", "external-contractor"] -REGIONS = ["us-east-1", "us-west-2"] -IPS_LEGIT = ["10.0.1.15", "10.0.2.30", "192.168.1.100"] -IPS_ATTACK = ["203.0.113.42", "198.51.100.77", "185.220.101.5", "45.33.32.156"] - - -def _base_event(username: str, source_ip: str, event_name: str, event_source: str) -> dict: - return { - "eventVersion": "1.08", - "eventTime": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"), - "eventSource": event_source, - "eventName": event_name, - "awsRegion": random.choice(REGIONS), - "sourceIPAddress": source_ip, - "userAgent": "aws-cli/2.x Python/3.11", - "requestID": str(uuid.uuid4()), - "eventID": str(uuid.uuid4()), - "readOnly": False, - "userIdentity": { - "type": "IAMUser", - "userName": username, - "arn": f"arn:aws:iam::123456789012:user/{username}", - "accountId": "123456789012" - } - } - - -def brute_force(attempts: int = 10, target_user: str = None) -> list[dict]: - """Genera múltiples intentos fallidos de login (simula fuerza bruta).""" - user = target_user or random.choice(USERS) - ip = random.choice(IPS_ATTACK) - events = [] - base_time = datetime.now(timezone.utc) - - for i in range(attempts): - e = _base_event(user, ip, "ConsoleLogin", "signin.amazonaws.com") - e["eventTime"] = (base_time + timedelta(seconds=i * 15)).isoformat().replace("+00:00", "Z") - e["responseElements"] = {"ConsoleLogin": "Failure"} - e["errorCode"] = "AccessDenied" - e["errorMessage"] = "Failed authentication" - events.append(e) - - return events - - -def privilege_escalation(username: str = None) -> list[dict]: - """Genera eventos de escalada de privilegios: un usuario adjunta políticas de admin.""" - user = username or random.choice(USERS) - ip = random.choice(IPS_ATTACK) - events = [] - - # Intento de listar roles (reconocimiento) - e = _base_event(user, ip, "ListRoles", "iam.amazonaws.com") - e["readOnly"] = True - events.append(e) - - # Adjuntar política AdministratorAccess a sí mismo - e = _base_event(user, ip, "AttachUserPolicy", "iam.amazonaws.com") - e["requestParameters"] = { - "userName": user, - "policyArn": "arn:aws:iam::aws:policy/AdministratorAccess" - } - events.append(e) - - # Crear nueva access key para persistencia - e = _base_event(user, ip, "CreateAccessKey", "iam.amazonaws.com") - e["requestParameters"] = {"userName": user} - e["responseElements"] = { - "accessKey": { - "accessKeyId": f"AKIA{''.join(random.choices('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', k=16))}", - "status": "Active", - "userName": user - } - } - events.append(e) - - return events - - -def credential_leak(username: str = None) -> list[dict]: - """Simula uso de credenciales desde IP externa inusual (posible filtración).""" - user = username or random.choice(USERS) - ip = random.choice(IPS_ATTACK) - - e = _base_event(user, ip, "GetCallerIdentity", "sts.amazonaws.com") - e["readOnly"] = True - e["requestParameters"] = None - e["responseElements"] = { - "userId": f"AIDA{''.join(random.choices('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', k=16))}", - "account": "123456789012", - "arn": f"arn:aws:iam::123456789012:user/{user}" - } - return [e] - - -def exfiltration(bucket: str = "prod-data-bucket", files: int = 50) -> list[dict]: - """Genera muchos GetObject consecutivos desde la misma IP (exfiltración de datos).""" - user = random.choice(USERS) - ip = random.choice(IPS_ATTACK) - events = [] - - for i in range(files): - e = _base_event(user, ip, "GetObject", "s3.amazonaws.com") - e["readOnly"] = True - e["resources"] = [{ - "ARN": f"arn:aws:s3:::{bucket}/data/record_{i:04d}.json", - "accountId": "123456789012", - "type": "AWS::S3::Object" - }] - events.append(e) - - return events - - -def port_scan(source_ip: str = None) -> list[dict]: - """Simula un evento de reconocimiento (DescribeSecurityGroups masivo).""" - user = random.choice(USERS) - ip = source_ip or random.choice(IPS_ATTACK) - events = [] - - for action in ["DescribeSecurityGroups", "DescribeInstances", "DescribeSubnets", - "DescribeVpcs", "DescribeNetworkInterfaces"]: - e = _base_event(user, ip, action, "ec2.amazonaws.com") - e["readOnly"] = True - events.append(e) - - return events - - -GENERATORS = { - "brute-force": brute_force, - "privilege-escalation": privilege_escalation, - "credential-leak": credential_leak, - "exfiltration": exfiltration, - "port-scan": port_scan, -} - - -if __name__ == "__main__": - import sys - incident = sys.argv[1] if len(sys.argv) > 1 else "brute-force" - gen = GENERATORS.get(incident) - if not gen: - print(f"Tipos disponibles: {', '.join(GENERATORS)}", file=sys.stderr) - sys.exit(1) - - events = gen() - print(json.dumps(events, indent=2)) diff --git a/simulators/inject_logs.py b/simulators/inject_logs.py deleted file mode 100644 index 7418531..0000000 --- a/simulators/inject_logs.py +++ /dev/null @@ -1,83 +0,0 @@ -""" -Inyector de logs simulados hacia LocalStack. -Genera eventos con cloudtrail_gen.py y los sube a S3 + SQS para -activar el flujo completo del Componente C. -""" -import json -import sys -import os -import uuid -from datetime import datetime, timezone - -import boto3 -from cloudtrail_gen import GENERATORS - -ENDPOINT = os.environ.get("AWS_ENDPOINT_URL", "http://localhost:4566") -REGION = os.environ.get("AWS_DEFAULT_REGION", "us-east-1") -BUCKET = os.environ.get("S3_BUCKET", "tesis-security-logs") -QUEUE = os.environ.get("SQS_QUEUE", "tesis-incident-queue") -QUEUE_URL = f"{ENDPOINT}/000000000000/{QUEUE}" - -s3 = boto3.client("s3", endpoint_url=ENDPOINT, region_name=REGION) -sqs = boto3.client("sqs", endpoint_url=ENDPOINT, region_name=REGION) - -SEVERITY_MAP = { - "brute-force": "HIGH", - "privilege-escalation": "CRITICAL", - "credential-leak": "CRITICAL", - "exfiltration": "HIGH", - "port-scan": "MEDIUM", -} - - -def inject(incident_type: str): - gen = GENERATORS.get(incident_type) - if not gen: - print(f"Tipo desconocido: {incident_type}. Disponibles: {', '.join(GENERATORS)}") - sys.exit(1) - - events = gen() - print(f"[inject] Generados {len(events)} eventos de tipo '{incident_type}'") - - # 1. Subir a S3 como archivo JSON (simula CloudTrail → S3) - timestamp = datetime.now(timezone.utc).strftime("%Y/%m/%d/%H%M%S") - s3_key = f"cloudtrail/{timestamp}/{incident_type}-{uuid.uuid4().hex[:8]}.json" - s3.put_object( - Bucket=BUCKET, - Key=s3_key, - Body=json.dumps({"Records": events}, indent=2).encode(), - ContentType="application/json" - ) - print(f"[inject] Subido a s3://{BUCKET}/{s3_key}") - - # 2. Detectar el evento más relevante para el payload de respuesta - first = events[0] - payload = { - "incident_type": incident_type.replace("-", "_").upper(), - "severity": SEVERITY_MAP.get(incident_type, "MEDIUM"), - "sourceIPAddress": first.get("sourceIPAddress", "0.0.0.0"), - "affectedResource": f"iam:user/{first['userIdentity']['userName']}", - "s3_log_key": s3_key, - "event_count": len(events), - "timestamp": first.get("eventTime", datetime.now(timezone.utc).isoformat()), - } - - # 3. Publicar en SQS para triggear Lambda de respuesta - sqs.send_message( - QueueUrl=QUEUE_URL, - MessageBody=json.dumps(payload), - MessageAttributes={ - "incident_type": { - "StringValue": incident_type, - "DataType": "String" - } - } - ) - print(f"[inject] Mensaje SQS enviado a {QUEUE}") - print(f"[inject] Payload:\n{json.dumps(payload, indent=2)}") - return payload - - -if __name__ == "__main__": - incident = sys.argv[1] if len(sys.argv) > 1 else "brute-force" - inject(incident) diff --git a/terraform-tesis-ir-secure-portal/.gitignore b/terraform-tesis-ir-secure-portal/.gitignore new file mode 100644 index 0000000..f04c579 --- /dev/null +++ b/terraform-tesis-ir-secure-portal/.gitignore @@ -0,0 +1,18 @@ +.terraform/ +*.tfstate +*.tfstate.* +.terraform.lock.hcl +terraform.tfvars +terraform.tfvars.json + +# Lambda build artifacts +*.zip + +# Python cache +__pycache__/ +*.py[cod] +*$py.class + +# Crash logs +crash.log +crash.*.log diff --git a/terraform-tesis-ir-secure-portal/GUIA_PRUEBAS_INCIDENTES.md b/terraform-tesis-ir-secure-portal/GUIA_PRUEBAS_INCIDENTES.md new file mode 100644 index 0000000..c04f900 --- /dev/null +++ b/terraform-tesis-ir-secure-portal/GUIA_PRUEBAS_INCIDENTES.md @@ -0,0 +1,135 @@ +# Guía de pruebas de incidentes + +## Incidente 1: BRUTE_FORCE + +1. Abre `portal_url`. +2. Usa `admin.demo` con contraseña incorrecta 5 veces. +3. Verifica: + - CloudWatch Logs → `/aws/ec2/tesis-ir-portal-app` + - Lambda → `/aws/lambda/lambda-tesis-ir-detector-b` + - DynamoDB → `tesis-ir_incidents` + - S3 Evidence → `incident-01-bruteforce/` + - SQS → `tesis-ir-incident-queue` + +Variables publicadas: + +```json +{ + "incident_type": "BRUTE_FORCE", + "severity": "HIGH", + "sourceIPAddress": "IP origen", + "affectedResource": "iam:user/admin.demo", + "s3_log_key": "incident-01-bruteforce/INC-....json", + "timestamp": "fecha deteccion", + "event_count": 5, + "failed_attempts": 5, + "detection_window": "5 minutes" +} +``` + +## Incidente 2: PORT_SCAN + +Prueba solo contra tu propia EC2. + +```powershell +$ip = terraform output -raw portal_public_ip +81..92 | ForEach-Object { Test-NetConnection $ip -Port $_ -InformationLevel Quiet } +``` + +Verifica: + +- CloudWatch Logs → `/aws/vpc/tesis-ir-flowlogs` +- S3 Evidence → `incident-02-port-scan/` +- SQS → `tesis-ir-incident-queue` + +## Incidente 3: PRIVILEGE_ESCALATION + +Ejemplo controlado: + +```powershell +aws iam create-user --user-name tesis-ir-temp-escalation-test +aws iam attach-user-policy --user-name tesis-ir-temp-escalation-test --policy-arn arn:aws:iam::aws:policy/ReadOnlyAccess +``` + +Limpieza: + +```powershell +aws iam detach-user-policy --user-name tesis-ir-temp-escalation-test --policy-arn arn:aws:iam::aws:policy/ReadOnlyAccess +aws iam delete-user --user-name tesis-ir-temp-escalation-test +``` + +Verifica: + +- CloudTrail Event history → `CreateUser` o `AttachUserPolicy` +- CloudWatch Logs → `/aws/cloudtrail/tesis-ir-management` +- S3 Evidence → `incident-03-privilege-escalation/` +- SQS → `tesis-ir-incident-queue` + +## Incidente 4: CREDENTIAL_LEAK + +Este incidente se detecta cuando una identidad válida ejecuta acciones como `GetCallerIdentity` desde una IP no autorizada. + +Para probarlo de forma controlada, configura `authorized_ip_cidrs` con una IP ficticia y ejecuta: + +```powershell +aws sts get-caller-identity +``` + +Verifica: + +- CloudTrail Event history → `GetCallerIdentity` +- CloudWatch Logs → `/aws/cloudtrail/tesis-ir-management` +- S3 Evidence → `incident-04-credential-leak/` +- SQS → `tesis-ir-incident-queue` + +Luego restaura `authorized_ip_cidrs = []` o tu IP real. + +## Incidente 5: EXFILTRATION + +Activa temporalmente: + +```hcl +enable_s3_data_events = true +``` + +Aplica: + +```powershell +terraform apply +``` + +Luego ejecuta descargas repetidas del objeto ficticio: + +```powershell +$bucket = terraform output -raw sensitive_bucket +1..55 | ForEach-Object { aws s3 cp "s3://$bucket/sensible/clientes_demo.json" ".\clientes_demo_$_.json" } +``` + +Verifica: + +- CloudTrail Event history → `GetObject` +- CloudWatch Logs → `/aws/cloudtrail/tesis-ir-management` +- S3 Evidence → `incident-05-exfiltration/` +- SQS → `tesis-ir-incident-queue` + +Después apaga: + +```hcl +enable_s3_data_events = false +``` + +```powershell +terraform apply +``` + + +## Playbooks de mitigación para Incidente 1 + +Esta versión integra dos playbooks Lambda para `BRUTE_FORCE`: + +- `lambda-tesis-ir-playbook-notify-alert`: recibe el incidente desde una cola SQS dedicada, publica una alerta en SNS y guarda auditoría en `S3 Evidence/responses/notify-alert/`. +- `lambda-tesis-ir-playbook-block-ip`: recibe el mismo incidente desde otra cola SQS dedicada y aplica contención real creando una regla `DENY` de entrada en la Network ACL de la VPC para la IP origen del ataque. También guarda evidencia en `S3 Evidence/responses/block-ip/`. + +El detector sigue publicando el JSON normalizado principal en `tesis-ir-incident-queue`, pero para evitar que dos Lambdas compitan por el mismo mensaje SQS se agregaron dos colas internas de playbooks: `tesis-ir-playbook-notify-alert-queue` y `tesis-ir-playbook-block-ip-queue`. + +Advertencia operacional: cuando `block-ip` bloquee tu IP pública, el portal puede dejar de cargar desde esa IP. Esto es esperado porque representa la mitigación real del incidente. Para recuperar el acceso, elimina la regla DENY creada en la Network ACL o vuelve a desplegar/ajustar la infraestructura con Terraform. diff --git a/terraform-tesis-ir-secure-portal/README_EJECUCION.md b/terraform-tesis-ir-secure-portal/README_EJECUCION.md new file mode 100644 index 0000000..cf2318b --- /dev/null +++ b/terraform-tesis-ir-secure-portal/README_EJECUCION.md @@ -0,0 +1,167 @@ +# Terraform - Laboratorio AWS de detección de incidentes + +Este proyecto crea una infraestructura de laboratorio para detección de incidentes en AWS con enfoque de bajo costo/capa gratuita. La versión actual reemplaza el botón simple de generación de logs por un portal realista de autenticación con login, dashboard, bloqueo temporal e instrucciones de prueba. + +## Qué crea + +- VPC `10.10.0.0/16` +- 2 subredes públicas y 2 subredes privadas reservadas +- Internet Gateway y tabla de rutas pública +- Security Group para portal HTTP restringible por CIDR y SSH limitado a tu IP +- EC2 Amazon Linux 2023 con portal web de autenticación de laboratorio +- Nginx como reverse proxy hacia la app Python local +- CloudWatch Agent para logs de Nginx y aplicación +- CloudWatch Logs `/aws/ec2/tesis-ir-portal-app` +- S3 para logs, evidencia e información sensible ficticia +- CloudTrail hacia S3 y CloudWatch Logs +- VPC Flow Logs sobre la ENI de la EC2 +- DynamoDB para incidentes y estado temporal +- SQS `tesis-ir-incident-queue` para publicar el JSON normalizado requerido por el componente B +- Lambda Detector B +- SNS para alertas +- Metric filters y alarmas CloudWatch +- Athena Workgroup +- Budget opcional si defines `alert_email` +- AWS Config opcional + +## Seguridad aplicada + +- El portal web NO tiene credenciales AWS y NO puede consultar CloudWatch, Lambda, DynamoDB ni S3. +- El portal solo escribe eventos JSON locales en `/var/log/tesis-portal/app.log`. +- CloudWatch Agent, instalado en la EC2, lee ese archivo y lo envía a CloudWatch Logs. +- La EC2 usa IMDSv2 obligatorio. +- El volumen EBS está cifrado. +- Los buckets S3 tienen bloqueo total de acceso público, versionado y cifrado SSE-S3. +- SSH se limita a `ssh_allowed_cidr`. +- HTTP se limita a `http_allowed_cidrs`; si queda vacío, usa automáticamente `ssh_allowed_cidr`. +- Lambda usa un rol IAM separado y solo puede escribir en DynamoDB, S3 Evidence, SNS, SQS y métricas `TesisIR`. + +## Importante sobre costos + +Para reducir costos, este proyecto NO crea: + +- NAT Gateway +- Load Balancer +- RDS +- OpenSearch +- Network Firewall +- Elastic IP + +Por defecto deja apagados: + +```hcl +enable_s3_data_events = false +enable_aws_config = false +cloudtrail_multi_region = false +``` + +Activa `enable_s3_data_events=true` solo cuando vayas a probar EXFILTRATION. Activa `enable_aws_config=true` solo cuando necesites evidencia adicional de cambios de configuración/IAM. + +## Uso + +Copia el ejemplo: + +```powershell +copy terraform.tfvars.example terraform.tfvars +``` + +Edita: + +```hcl +ssh_allowed_cidr = "TU_IP_PUBLICA/32" +http_allowed_cidrs = [] +alert_email = "tu_correo@ejemplo.com" +``` + +Inicializa: + +```powershell +terraform init +``` + +Revisa: + +```powershell +terraform validate +terraform plan -out=tfplan +``` + +Aplica: + +```powershell +terraform apply "tfplan" +``` + +Cuando termine, Terraform mostrará: + +```text +portal_url +portal_public_ip +evidence_bucket +dynamodb_incidents_table +lambda_detector_name +incident_queue_url +``` + +Abre `portal_url` en el navegador. + +## Usuarios del portal + +| Usuario | Contraseña | Rol | +|---|---|---| +| `admin.demo` | `AdminDemo#2026` | Administrador AWS simulado | +| `soc.demo` | `SocDemo#2026` | Analista SOC simulado | +| `usuario.demo` | `UsuarioDemo#2026` | Usuario estándar simulado | + +## Flujo de logs del portal + +```text +Navegador +→ EC2/Nginx +→ App Python /opt/tesis-portal/app.py +→ /var/log/tesis-portal/app.log +→ CloudWatch Agent +→ CloudWatch Logs /aws/ec2/tesis-ir-portal-app +→ Subscription Filter +→ Lambda Detector B +→ DynamoDB + S3 Evidence + SQS + SNS +``` + +## Incidentes normalizados en SQS + +Lambda publica en `tesis-ir-incident-queue` un JSON con las variables obligatorias por incidente: + +- `incident_type` +- `severity` +- `sourceIPAddress` +- `affectedResource` +- `s3_log_key` +- `timestamp` +- `event_count` + +También añade variables opcionales como `failed_attempts`, `scanned_ports_count`, `suspicious_actions`, `service_accessed`, `total_downloads` o `affected_bucket`, según el incidente. + +## Destruir laboratorio + +```powershell +terraform plan -destroy -out=tfdestroy +terraform apply "tfdestroy" +``` + +Por defecto `force_destroy_buckets=true`, así que Terraform puede eliminar buckets con objetos. Para evidencia real usa: + +```hcl +force_destroy_buckets = false +``` + + +## Playbooks de mitigación para Incidente 1 + +Esta versión integra dos playbooks Lambda para `BRUTE_FORCE`: + +- `lambda-tesis-ir-playbook-notify-alert`: recibe el incidente desde una cola SQS dedicada, publica una alerta en SNS y guarda auditoría en `S3 Evidence/responses/notify-alert/`. +- `lambda-tesis-ir-playbook-block-ip`: recibe el mismo incidente desde otra cola SQS dedicada y aplica contención real creando una regla `DENY` de entrada en la Network ACL de la VPC para la IP origen del ataque. También guarda evidencia en `S3 Evidence/responses/block-ip/`. + +El detector sigue publicando el JSON normalizado principal en `tesis-ir-incident-queue`, pero para evitar que dos Lambdas compitan por el mismo mensaje SQS se agregaron dos colas internas de playbooks: `tesis-ir-playbook-notify-alert-queue` y `tesis-ir-playbook-block-ip-queue`. + +Advertencia operacional: cuando `block-ip` bloquee tu IP pública, el portal puede dejar de cargar desde esa IP. Esto es esperado porque representa la mitigación real del incidente. Para recuperar el acceso, elimina la regla DENY creada en la Network ACL o vuelve a desplegar/ajustar la infraestructura con Terraform. diff --git a/terraform-tesis-ir-secure-portal/lambda/lambda_function.py b/terraform-tesis-ir-secure-portal/lambda/lambda_function.py new file mode 100644 index 0000000..eeee5ae --- /dev/null +++ b/terraform-tesis-ir-secure-portal/lambda/lambda_function.py @@ -0,0 +1,626 @@ +import base64 +import gzip +import ipaddress +import json +import os +import time +import uuid +from datetime import datetime, timezone +from zoneinfo import ZoneInfo +from decimal import Decimal + +import boto3 +from boto3.dynamodb.conditions import Key +from botocore.exceptions import ClientError + +dynamodb = boto3.resource("dynamodb") +s3 = boto3.client("s3") +sns = boto3.client("sns") +sqs = boto3.client("sqs") +cloudwatch = boto3.client("cloudwatch") + +INCIDENTS_TABLE = os.environ["INCIDENTS_TABLE"] +STATE_TABLE = os.environ["STATE_TABLE"] +EVIDENCE_BUCKET = os.environ["EVIDENCE_BUCKET"] +SNS_TOPIC_ARN = os.environ["SNS_TOPIC_ARN"] +CONFIG_KEY = os.environ["CONFIG_KEY"] +INCIDENT_QUEUE_URL = os.environ.get("INCIDENT_QUEUE_URL", "") +VPC_ID = os.environ.get("VPC_ID", "unknown-vpc") +PORTAL_INSTANCE_ID = os.environ.get("PORTAL_INSTANCE_ID", "unknown-instance") +PLAYBOOK_NOTIFY_QUEUE_URL = os.environ.get("PLAYBOOK_NOTIFY_QUEUE_URL", "") +PLAYBOOK_BLOCK_IP_QUEUE_URL = os.environ.get("PLAYBOOK_BLOCK_IP_QUEUE_URL", "") +PLAYBOOK_REVOKE_CREDENTIALS_QUEUE_URL = os.environ.get("PLAYBOOK_REVOKE_CREDENTIALS_QUEUE_URL", "") +ECUADOR_TZ = ZoneInfo("America/Guayaquil") + +incidents_table = dynamodb.Table(INCIDENTS_TABLE) +state_table = dynamodb.Table(STATE_TABLE) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def ecuador_now() -> str: + return datetime.now(ECUADOR_TZ).isoformat() + + +def epoch_now() -> int: + return int(time.time()) + + +def current_window(minutes: int) -> int: + return epoch_now() // (minutes * 60) + + +def decimal_default(obj): + if isinstance(obj, Decimal): + return int(obj) + raise TypeError(f"Object of type {type(obj)} is not JSON serializable") + + +def load_config() -> dict: + obj = s3.get_object(Bucket=EVIDENCE_BUCKET, Key=CONFIG_KEY) + return json.loads(obj["Body"].read().decode("utf-8")) + + +def decode_cloudwatch_event(event: dict) -> dict: + if "awslogs" not in event: + return { + "logGroup": "direct-test", + "logStream": "manual", + "logEvents": [ + { + "id": str(uuid.uuid4()), + "timestamp": int(time.time() * 1000), + "message": json.dumps(event), + } + ], + } + + payload = base64.b64decode(event["awslogs"]["data"]) + uncompressed = gzip.decompress(payload) + return json.loads(uncompressed) + + +def safe_json_loads(value: str): + try: + return json.loads(value) + except Exception: + return None + + +def ip_in_cidrs(ip_value: str, cidrs: list[str]) -> bool: + try: + ip = ipaddress.ip_address(ip_value) + except Exception: + return False + + for cidr in cidrs: + try: + if ip in ipaddress.ip_network(cidr, strict=False): + return True + except Exception: + continue + return False + + +def username_from_identity(event_json: dict) -> str: + identity = event_json.get("userIdentity", {}) or {} + username = identity.get("userName") + if username: + return username + + arn = identity.get("arn", "") + if ":user/" in arn: + return arn.split(":user/", 1)[1] + if ":assumed-role/" in arn: + return arn.rsplit("/", 1)[-1] + if identity.get("principalId"): + return str(identity.get("principalId")) + return "unknown" + + +def affected_iam_user(event_json: dict, fallback_username: str | None = None) -> str: + username = fallback_username or username_from_identity(event_json) + if not username: + username = "unknown" + return f"iam:user/{username}" + + +def increment_counter(pk: str, sk: str = "counter", ttl_seconds: int = 900) -> int: + response = state_table.update_item( + Key={"pk": pk, "sk": sk}, + UpdateExpression="SET #ttl = :ttl, updated_at = :updated_at ADD #count :one", + ExpressionAttributeNames={ + "#ttl": "ttl", + "#count": "count", + }, + ExpressionAttributeValues={ + ":ttl": epoch_now() + ttl_seconds, + ":updated_at": utc_now(), + ":one": 1, + }, + ReturnValues="UPDATED_NEW", + ) + return int(response["Attributes"]["count"]) + + +def mark_alert_once(alert_key: str, ttl_seconds: int = 900) -> bool: + try: + state_table.put_item( + Item={ + "pk": f"alert#{alert_key}", + "sk": "sent", + "ttl": epoch_now() + ttl_seconds, + "created_at": utc_now(), + }, + ConditionExpression="attribute_not_exists(pk) AND attribute_not_exists(sk)", + ) + return True + except ClientError as exc: + if exc.response.get("Error", {}).get("Code") == "ConditionalCheckFailedException": + return False + raise + + +def put_distinct_port_and_count(srcaddr: str, dstport: str, ttl_seconds: int = 900) -> int: + pk = f"portscan#{srcaddr}#window#{current_window(5)}" + sk = f"port#{dstport}" + state_table.put_item( + Item={ + "pk": pk, + "sk": sk, + "ttl": epoch_now() + ttl_seconds, + "updated_at": utc_now(), + } + ) + response = state_table.query(KeyConditionExpression=Key("pk").eq(pk), Select="COUNT") + return int(response.get("Count", 0)) + + +def evidence_folder(incident_type: str) -> str: + mapping = { + "BRUTE_FORCE": "incident-01-bruteforce", + "PORT_SCAN": "incident-02-port-scan", + "PRIVILEGE_ESCALATION": "incident-03-privilege-escalation", + "CREDENTIAL_LEAK": "incident-04-credential-leak", + "EXFILTRATION": "incident-05-exfiltration", + } + return mapping.get(incident_type, incident_type.lower()) + + +def build_evidence_key(incident_type: str, incident_id: str) -> str: + return f"{evidence_folder(incident_type)}/{incident_id}.json" + + +def send_sqs_message(queue_url: str, payload: dict) -> None: + if not queue_url: + return + try: + sqs.send_message(QueueUrl=queue_url, MessageBody=json.dumps(payload, default=decimal_default)) + except Exception as e: + print(f"[ERROR] Failed to send message to SQS queue {queue_url}: {e}") + + +def publish_incident_queue(payload: dict) -> None: + # Cola principal exigida por Variables_Incidentes.docx. + send_sqs_message(INCIDENT_QUEUE_URL, payload) + + # Fan-out controlado a playbooks de respuesta automatica. + # Se usan colas dedicadas para que notify-alert y los playbooks de contencion + # reciban ambos el mismo evento sin competir por el mensaje SQS. + # + # Cobertura completa de incidentes: + # 1. BRUTE_FORCE → notify-alert + block-ip + # 2. PORT_SCAN → notify-alert + block-ip + # 3. PRIVILEGE_ESCALATION → notify-alert + revoke-credentials + # 4. CREDENTIAL_LEAK → notify-alert + revoke-credentials + # 5. EXFILTRATION → notify-alert + incident_type = payload.get("incident_type") + + # notify-alert se activa para TODOS los incidentes soportados + NOTIFY_INCIDENTS = {"BRUTE_FORCE", "PORT_SCAN", "PRIVILEGE_ESCALATION", "CREDENTIAL_LEAK", "EXFILTRATION"} + if incident_type in NOTIFY_INCIDENTS: + send_sqs_message(PLAYBOOK_NOTIFY_QUEUE_URL, payload) + + # block-ip se activa para incidentes de red (contención perimetral) + BLOCK_IP_INCIDENTS = {"BRUTE_FORCE", "PORT_SCAN"} + if incident_type in BLOCK_IP_INCIDENTS: + send_sqs_message(PLAYBOOK_BLOCK_IP_QUEUE_URL, payload) + + # revoke-credentials se activa para incidentes de credenciales/IAM (contención de identidad) + REVOKE_INCIDENTS = {"PRIVILEGE_ESCALATION", "CREDENTIAL_LEAK"} + if incident_type in REVOKE_INCIDENTS: + send_sqs_message(PLAYBOOK_REVOKE_CREDENTIALS_QUEUE_URL, payload) + + +def save_incident(payload: dict, source: str, raw_event: dict, summary: str) -> str: + incident_id = f"INC-{datetime.now(timezone.utc).strftime('%Y%m%d%H%M%S')}-{str(uuid.uuid4())[:8]}" + created_at = utc_now() + created_at_ecuador = ecuador_now() + evidence_key = build_evidence_key(payload["incident_type"], incident_id) + + final_payload = dict(payload) + final_payload["incident_id"] = incident_id + final_payload["timestamp"] = final_payload.get("timestamp") or created_at_ecuador + final_payload["timestamp_utc"] = final_payload.get("timestamp_utc") or created_at + final_payload["timestamp_ecuador"] = final_payload.get("timestamp_ecuador") or created_at_ecuador + final_payload["timezone"] = final_payload.get("timezone") or "America/Guayaquil" + final_payload["s3_log_key"] = evidence_key + # Registrar qué playbooks se activan para este incidente + if final_payload.get("incident_type") in {"BRUTE_FORCE", "PORT_SCAN"}: + final_payload["playbooks_requested"] = ["notify-alert", "block-ip"] + elif final_payload.get("incident_type") in {"PRIVILEGE_ESCALATION", "CREDENTIAL_LEAK"}: + final_payload["playbooks_requested"] = ["notify-alert", "revoke-credentials"] + elif final_payload.get("incident_type") == "EXFILTRATION": + final_payload["playbooks_requested"] = ["notify-alert"] + + evidence_doc = { + "incident_id": incident_id, + "incident_payload": final_payload, + "source": source, + "summary": summary, + "created_at": created_at, + "created_at_ecuador": created_at_ecuador, + "timezone": "America/Guayaquil", + "raw_event": raw_event, + } + + s3.put_object( + Bucket=EVIDENCE_BUCKET, + Key=evidence_key, + Body=json.dumps(evidence_doc, indent=2, default=decimal_default).encode("utf-8"), + ContentType="application/json", + ) + + incidents_table.put_item( + Item={ + "incident_id": incident_id, + "type": final_payload["incident_type"], + "severity": final_payload["severity"], + "status": "DETECTED", + "sourceIPAddress": final_payload.get("sourceIPAddress", "unknown"), + "affectedResource": final_payload.get("affectedResource", "unknown"), + "event_count": int(final_payload.get("event_count", 1)), + "source": source, + "summary": summary, + "s3_log_key": evidence_key, + "evidence_s3_uri": f"s3://{EVIDENCE_BUCKET}/{evidence_key}", + "created_at": created_at, + "created_at_ecuador": created_at_ecuador, + "affected_service": final_payload.get("affected_service", final_payload.get("affectedService", "unknown")), + "asset_name": final_payload.get("asset_name", final_payload.get("assetName", "unknown")), + "severity_basis": final_payload.get("severity_basis", "not_specified"), + } + ) + + publish_incident_queue(final_payload) + + cloudwatch.put_metric_data( + Namespace="TesisIR", + MetricData=[ + { + "MetricName": final_payload["incident_type"], + "Value": 1, + "Unit": "Count", + } + ], + ) + return incident_id + + +def analyze_app_event(event_json: dict, config: dict): + if event_json.get("event_type") != "login_failed": + return None + + thresholds = config.get("thresholds", {}) + source_ip = event_json.get("source_ip") or event_json.get("sourceIPAddress") or "unknown" + username = event_json.get("username", "unknown") + threshold = int(thresholds.get("app_login_failures_same_ip_5m", 5)) + window = current_window(5) + count = increment_counter(f"app_bruteforce#{source_ip}#window#{window}", ttl_seconds=900) + + if count >= threshold and mark_alert_once(f"BRUTE_FORCE#APP#{source_ip}#{window}"): + severity_basis = ( + f"HIGH: La IP {source_ip} alcanzó {count} intentos fallidos de autenticación " + f"en 5 minutos (umbral={threshold})." + ) + payload = { + "incident_type": "BRUTE_FORCE", + "severity": "HIGH", + "sourceIPAddress": source_ip, + "affectedResource": event_json.get("affectedResource") or f"iam:user/{username}", + "s3_log_key": "pending", + "timestamp": event_json.get("timestamp") or ecuador_now(), + "timestamp_utc": event_json.get("timestamp_utc") or utc_now(), + "timezone": "America/Guayaquil", + "event_count": count, + "failed_attempts": count, + "detection_window": "5 minutes", + "affected_service": event_json.get("affected_service", "Portal Web Corporativo"), + "asset_name": event_json.get("asset_name", f"EC2 Instance ({PORTAL_INSTANCE_ID})"), + "asset_type": event_json.get("asset_type", "EC2 Web Application"), + "severity_basis": severity_basis, + "mitigation_playbooks": ["notify-alert", "block-ip"], + } + return payload, f"{count} intentos fallidos de login del portal desde {source_ip} en 5 minutos." + return None + + +def analyze_cloudtrail(event_json: dict, config: dict): + event_name = event_json.get("eventName") + event_source = event_json.get("eventSource") + source_ip = event_json.get("sourceIPAddress", "unknown") + aws_region = event_json.get("awsRegion", "unknown") + username = username_from_identity(event_json) + thresholds = config.get("thresholds", {}) + allowed_ips = config.get("authorized_ips", []) + + # Incidente 1: fuerza bruta por ConsoleLogin fallido. + if event_name == "ConsoleLogin": + response = event_json.get("responseElements", {}) or {} + if response.get("ConsoleLogin") == "Failure": + threshold_ip = int(thresholds.get("console_login_failures_same_ip_5m", 10)) + threshold_user = int(thresholds.get("console_login_failures_same_user_5m", 5)) + window = current_window(5) + count_ip = increment_counter(f"console_bruteforce_ip#{source_ip}#window#{window}", ttl_seconds=900) + count_user = increment_counter(f"console_bruteforce_user#{username}#window#{window}", ttl_seconds=900) + if count_user >= threshold_user and mark_alert_once(f"BRUTE_FORCE#USER#{username}#{window}"): + payload = { + "incident_type": "BRUTE_FORCE", + "severity": "HIGH", + "sourceIPAddress": source_ip, + "affectedResource": affected_iam_user(event_json, username), + "s3_log_key": "pending", + "timestamp": event_json.get("eventTime", ecuador_now()), + "timestamp_utc": event_json.get("eventTime", utc_now()), + "timezone": "America/Guayaquil", + "event_count": count_user, + "failed_attempts": count_user, + "detection_window": "5 minutes", + "affected_service": "AWS Sign-In / IAM Console", + "asset_name": f"IAM User ({username})", + "asset_type": "AWS Control Plane", + "severity_basis": f"HIGH: Se alcanzaron {count_user} fallos de ConsoleLogin para {username} en 5 minutos (umbral={threshold_user}).", + "mitigation_playbooks": ["notify-alert", "block-ip"], + } + return payload, f"{count_user} fallos de ConsoleLogin para {username} en 5 minutos." + if count_ip >= threshold_ip and mark_alert_once(f"BRUTE_FORCE#IP#{source_ip}#{window}"): + payload = { + "incident_type": "BRUTE_FORCE", + "severity": "HIGH", + "sourceIPAddress": source_ip, + "affectedResource": affected_iam_user(event_json, username), + "s3_log_key": "pending", + "timestamp": event_json.get("eventTime", ecuador_now()), + "timestamp_utc": event_json.get("eventTime", utc_now()), + "timezone": "America/Guayaquil", + "event_count": count_ip, + "failed_attempts": count_ip, + "detection_window": "5 minutes", + "affected_service": "AWS Sign-In / IAM Console", + "asset_name": f"AWS Console (IP: {source_ip})", + "asset_type": "AWS Control Plane", + "severity_basis": f"HIGH: Se alcanzaron {count_ip} fallos de ConsoleLogin desde {source_ip} en 5 minutos (umbral={threshold_ip}).", + "mitigation_playbooks": ["notify-alert", "block-ip"], + } + return payload, f"{count_ip} fallos de ConsoleLogin desde {source_ip} en 5 minutos." + + # Incidente 3: escalada de privilegios. + iam_critical_events = { + "CreateUser", + "AttachUserPolicy", + "AttachRolePolicy", + "PutUserPolicy", + "PutRolePolicy", + "CreateAccessKey", + "AddUserToGroup", + "CreatePolicyVersion", + "UpdateAssumeRolePolicy", + } + if event_source == "iam.amazonaws.com" and event_name in iam_critical_events: + request_params = event_json.get("requestParameters", {}) or {} + target_policy_arn = request_params.get("policyArn") or request_params.get("policyDocument", "") + window = current_window(5) + count = increment_counter(f"privilege_escalation#{username}#window#{window}", ttl_seconds=900) + severity_basis = ( + f"CRITICAL: Acción IAM crítica '{event_name}' ejecutada por " + f"la identidad '{username}' desde {source_ip}." + ) + payload = { + "incident_type": "PRIVILEGE_ESCALATION", + "severity": "CRITICAL", + "sourceIPAddress": source_ip, + "affectedResource": affected_iam_user(event_json, username), + "affected_service": "AWS Identity and Access Management (IAM)", + "asset_name": f"IAM Principal ({username})", + "asset_type": "IAM Identity", + "severity_basis": severity_basis, + "s3_log_key": "pending", + "timestamp": event_json.get("eventTime", ecuador_now()), + "timestamp_utc": event_json.get("eventTime", utc_now()), + "timezone": "America/Guayaquil", + "event_count": count, + "suspicious_actions": [event_name], + "mitigation_playbooks": ["notify-alert", "revoke-credentials"], + } + if target_policy_arn: + payload["target_policy_arn"] = str(target_policy_arn)[:500] + return payload, f"Accion IAM critica {event_name} ejecutada por {username} desde {source_ip}." + + # Incidente 4: fuga de credenciales por uso desde IP no autorizada. + # Se restringe a eventos de identidad/API claramente representativos para reducir falsos positivos. + credential_leak_events = {"GetCallerIdentity", "GetUser", "ListAccessKeys"} + identity_type = (event_json.get("userIdentity", {}) or {}).get("type", "") + if event_name in credential_leak_events and identity_type in {"IAMUser", "AssumedRole"}: + if source_ip != "unknown" and not ip_in_cidrs(source_ip, allowed_ips): + if mark_alert_once(f"CREDENTIAL_LEAK#{username}#{source_ip}#{current_window(5)}", ttl_seconds=900): + severity_basis = ( + f"CRITICAL: Credenciales de '{username}' utilizadas desde IP no autorizada " + f"{source_ip} (Región: {aws_region}, API: {event_name})." + ) + payload = { + "incident_type": "CREDENTIAL_LEAK", + "severity": "CRITICAL", + "sourceIPAddress": source_ip, + "affectedResource": affected_iam_user(event_json, username), + "affected_service": f"AWS IAM / {event_source}", + "asset_name": f"IAM User ({username})", + "asset_type": "IAM Credentials", + "severity_basis": severity_basis, + "s3_log_key": "pending", + "timestamp": event_json.get("eventTime", ecuador_now()), + "timestamp_utc": event_json.get("eventTime", utc_now()), + "timezone": "America/Guayaquil", + "event_count": 1, + "service_accessed": event_source, + "unusual_region": aws_region, + "mitigation_playbooks": ["notify-alert", "revoke-credentials"], + } + return payload, f"Credenciales de {username} usadas desde IP no autorizada {source_ip}." + + # Incidente 5: exfiltracion por muchas descargas GetObject desde una IP en 1 hora. + if event_source == "s3.amazonaws.com" and event_name == "GetObject": + request_params = event_json.get("requestParameters", {}) or {} + bucket = request_params.get("bucketName") or extract_bucket_from_resources(event_json) + window = current_window(60) + count = increment_counter(f"exfiltration#{source_ip}#{bucket}#window#{window}", ttl_seconds=7200) + threshold = int(thresholds.get("s3_getobject_exfiltration_count_1h", 50)) + if count >= threshold and mark_alert_once(f"EXFILTRATION#{source_ip}#{bucket}#{window}", ttl_seconds=7200): + severity_basis = ( + f"HIGH: Descarga masiva no autorizada detectada ({count} operaciones GetObject en 1 hora, " + f"umbral={threshold}) sobre el bucket '{bucket}' desde {source_ip}." + ) + payload = { + "incident_type": "EXFILTRATION", + "severity": "HIGH", + "sourceIPAddress": source_ip, + "affectedResource": f"s3:::{bucket}" if bucket else f"ec2:instance/{PORTAL_INSTANCE_ID}", + "affected_service": "Amazon Simple Storage Service (S3)", + "asset_name": f"S3 Bucket ({bucket})", + "asset_type": "Cloud Storage Data", + "severity_basis": severity_basis, + "s3_log_key": "pending", + "timestamp": event_json.get("eventTime", ecuador_now()), + "timestamp_utc": event_json.get("eventTime", utc_now()), + "timezone": "America/Guayaquil", + "event_count": count, + "total_downloads": count, + "affected_bucket": bucket or "unknown", + "first_access": "tracked_in_detection_window", + "last_access": event_json.get("eventTime", ecuador_now()), + "mitigation_playbooks": ["notify-alert"], + } + return payload, f"{count} operaciones GetObject desde {source_ip} sobre bucket {bucket} en 1 hora." + + return None + + +def extract_bucket_from_resources(event_json: dict) -> str: + resources = event_json.get("resources", []) or [] + for resource in resources: + arn = resource.get("ARN") or resource.get("arn") or "" + if arn.startswith("arn:aws:s3:::"): + value = arn.replace("arn:aws:s3:::", "", 1) + return value.split("/", 1)[0] + return "unknown" + + +def parse_flow_log(message: str): + parts = message.strip().split() + if len(parts) < 14: + return None + return { + "version": parts[0], + "account_id": parts[1], + "interface_id": parts[2], + "srcaddr": parts[3], + "dstaddr": parts[4], + "srcport": parts[5], + "dstport": parts[6], + "protocol": parts[7], + "packets": parts[8], + "bytes": parts[9], + "start": parts[10], + "end": parts[11], + "action": parts[12], + "log_status": parts[13], + "raw_message": message, + } + + +def analyze_flow_log(message: str, config: dict): + flow = parse_flow_log(message) + if not flow or flow.get("action") != "REJECT": + return None + + thresholds = config.get("thresholds", {}) + threshold = int(thresholds.get("port_scan_distinct_ports_5m", 10)) + srcaddr = flow.get("srcaddr", "unknown") + dstport = flow.get("dstport", "unknown") + window = current_window(5) + distinct_count = put_distinct_port_and_count(srcaddr, dstport) + rejected_count = increment_counter(f"portscan_rejects#{srcaddr}#window#{window}", ttl_seconds=900) + + if distinct_count >= threshold and mark_alert_once(f"PORT_SCAN#{srcaddr}#{window}"): + severity_basis = ( + f"MEDIUM: La IP {srcaddr} sondeó {distinct_count} puertos distintos " + f"con paquetes REJECT en VPC Flow Logs en 5 minutos (umbral={threshold})." + ) + payload = { + "incident_type": "PORT_SCAN", + "severity": "MEDIUM", + "sourceIPAddress": srcaddr, + "affectedResource": f"vpc/{VPC_ID}", + "affected_service": "Amazon VPC / Network Security", + "asset_name": f"VPC-{VPC_ID} (Portal Instance: {PORTAL_INSTANCE_ID})", + "asset_type": "VPC Network Boundary", + "severity_basis": severity_basis, + "s3_log_key": "pending", + "timestamp": ecuador_now(), + "timestamp_utc": utc_now(), + "timezone": "America/Guayaquil", + "event_count": rejected_count, + "rejected_connections": rejected_count, + "scanned_ports_count": distinct_count, + "mitigation_playbooks": ["notify-alert", "block-ip"], + } + return payload, f"Posible escaneo: {distinct_count} puertos distintos rechazados desde {srcaddr} en 5 minutos.", flow + return None + + +def lambda_handler(event, context): + config = load_config() + decoded = decode_cloudwatch_event(event) + log_group = decoded.get("logGroup", "unknown") + results = [] + + for log_event in decoded.get("logEvents", []): + raw_message = log_event.get("message", "") + message_json = safe_json_loads(raw_message) + analysis = None + raw_for_evidence = message_json if isinstance(message_json, dict) else {"raw_message": raw_message} + + if isinstance(message_json, dict): + if "eventSource" in message_json or "eventName" in message_json: + analysis = analyze_cloudtrail(message_json, config) + else: + analysis = analyze_app_event(message_json, config) + else: + flow_analysis = analyze_flow_log(raw_message, config) + if flow_analysis: + payload, summary, flow = flow_analysis + analysis = (payload, summary) + raw_for_evidence = flow + + if analysis: + payload, summary = analysis + incident_id = save_incident( + payload=payload, + source=log_group, + raw_event=raw_for_evidence, + summary=summary, + ) + results.append(incident_id) + + return {"statusCode": 200, "detected_incidents": results} diff --git a/terraform-tesis-ir-secure-portal/main.tf b/terraform-tesis-ir-secure-portal/main.tf new file mode 100644 index 0000000..d8161e3 --- /dev/null +++ b/terraform-tesis-ir-secure-portal/main.tf @@ -0,0 +1,1852 @@ +terraform { + required_version = ">= 1.5.0" + + required_providers { + aws = { + source = "hashicorp/aws" + version = ">= 5.0" + } + archive = { + source = "hashicorp/archive" + version = ">= 2.4" + } + } +} + +provider "aws" { + region = var.aws_region + + default_tags { + tags = { + Project = var.project_name + Environment = "lab" + ManagedBy = "terraform" + Owner = "estudiante-b" + } + } +} + +data "aws_caller_identity" "current" {} + +data "aws_availability_zones" "available" { + state = "available" +} + +data "aws_ami" "al2023" { + most_recent = true + owners = ["amazon"] + + filter { + name = "name" + values = ["al2023-ami-2023.*-x86_64"] + } + + filter { + name = "architecture" + values = ["x86_64"] + } + + filter { + name = "virtualization-type" + values = ["hvm"] + } +} + +locals { + account_id = data.aws_caller_identity.current.account_id + + name_prefix = var.project_name + + az_1 = data.aws_availability_zones.available.names[0] + az_2 = data.aws_availability_zones.available.names[1] + + logs_bucket_name = "${var.project_name}-logs-${local.account_id}-${var.aws_region}" + evidence_bucket_name = "${var.project_name}-evidence-${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] + portal_http_cidrs = length(var.http_allowed_cidrs) > 0 ? var.http_allowed_cidrs : [var.ssh_allowed_cidr] + + common_log_groups = { + cloudtrail = "/aws/cloudtrail/${var.project_name}-management" + flowlogs = "/aws/vpc/${var.project_name}-flowlogs" + config = "/aws/config/${var.project_name}-changes" + app = "/aws/ec2/${var.project_name}-portal-app" + normalized = "/aws/${var.project_name}/incidents-normalized" + lambda = "/aws/lambda/lambda-${var.project_name}-detector-b" + } + + evidence_prefixes = [ + "incident-01-bruteforce/", + "incident-02-port-scan/", + "incident-03-privilege-escalation/", + "incident-04-credential-leak/", + "incident-05-exfiltration/", + "config/" + ] + + logs_prefixes = [ + "cloudtrail/", + "vpc-flow-logs/", + "config/", + "athena-results/" + ] + + sensitive_prefixes = [ + "sensible/", + "public/" + ] +} + +# ----------------------------------------------------------------------------- +# Presupuesto básico. Se crea solo si defines alert_email y create_budget=true. +# ----------------------------------------------------------------------------- + +resource "aws_budgets_budget" "monthly_cost" { + count = var.create_budget && var.alert_email != "" ? 1 : 0 + + name = "${var.project_name}-monthly-budget" + budget_type = "COST" + limit_amount = tostring(var.monthly_budget_limit_usd) + limit_unit = "USD" + time_unit = "MONTHLY" + + notification { + comparison_operator = "GREATER_THAN" + threshold = 50 + threshold_type = "PERCENTAGE" + notification_type = "ACTUAL" + subscriber_email_addresses = [var.alert_email] + } + + notification { + comparison_operator = "GREATER_THAN" + threshold = 80 + threshold_type = "PERCENTAGE" + notification_type = "ACTUAL" + subscriber_email_addresses = [var.alert_email] + } + + notification { + comparison_operator = "GREATER_THAN" + threshold = 100 + threshold_type = "PERCENTAGE" + notification_type = "FORECASTED" + subscriber_email_addresses = [var.alert_email] + } +} + +# ----------------------------------------------------------------------------- +# Red: VPC, subredes públicas/privadas reservadas, IGW y rutas públicas. +# No se crea NAT Gateway, ALB, RDS ni VPC Endpoints para reducir costos. +# ----------------------------------------------------------------------------- + +resource "aws_vpc" "this" { + cidr_block = var.vpc_cidr + enable_dns_hostnames = true + enable_dns_support = true + + tags = { + Name = "${var.project_name}-vpc" + } +} + +resource "aws_internet_gateway" "this" { + vpc_id = aws_vpc.this.id + + tags = { + Name = "${var.project_name}-igw" + } +} + +resource "aws_subnet" "public_a" { + vpc_id = aws_vpc.this.id + cidr_block = var.public_subnet_a_cidr + availability_zone = local.az_1 + map_public_ip_on_launch = true + + tags = { + Name = "${var.project_name}-subnet-public1-${local.az_1}" + Tier = "public" + } +} + +resource "aws_subnet" "public_b" { + vpc_id = aws_vpc.this.id + cidr_block = var.public_subnet_b_cidr + availability_zone = local.az_2 + map_public_ip_on_launch = true + + tags = { + Name = "${var.project_name}-subnet-public2-${local.az_2}" + Tier = "public" + } +} + +resource "aws_subnet" "private_a" { + vpc_id = aws_vpc.this.id + cidr_block = var.private_subnet_a_cidr + availability_zone = local.az_1 + + tags = { + Name = "${var.project_name}-subnet-private1-${local.az_1}" + Tier = "private-reserved" + } +} + +resource "aws_subnet" "private_b" { + vpc_id = aws_vpc.this.id + cidr_block = var.private_subnet_b_cidr + availability_zone = local.az_2 + + tags = { + Name = "${var.project_name}-subnet-private2-${local.az_2}" + Tier = "private-reserved" + } +} + +resource "aws_route_table" "public" { + vpc_id = aws_vpc.this.id + + tags = { + Name = "${var.project_name}-rtb-public" + } +} + +resource "aws_route" "public_default_ipv4" { + route_table_id = aws_route_table.public.id + destination_cidr_block = "0.0.0.0/0" + gateway_id = aws_internet_gateway.this.id +} + +resource "aws_route_table_association" "public_a" { + subnet_id = aws_subnet.public_a.id + route_table_id = aws_route_table.public.id +} + +resource "aws_route_table_association" "public_b" { + subnet_id = aws_subnet.public_b.id + route_table_id = aws_route_table.public.id +} + +resource "aws_route_table" "private" { + vpc_id = aws_vpc.this.id + + tags = { + Name = "${var.project_name}-rtb-private-local-only" + } +} + +resource "aws_route_table_association" "private_a" { + subnet_id = aws_subnet.private_a.id + route_table_id = aws_route_table.private.id +} + +resource "aws_route_table_association" "private_b" { + subnet_id = aws_subnet.private_b.id + route_table_id = aws_route_table.private.id +} + +# ----------------------------------------------------------------------------- +# Security Group del portal. +# SSH queda limitado a tu IP pública /32. +# ----------------------------------------------------------------------------- + +resource "aws_security_group" "portal" { + name = "${var.project_name}-portal-sg" + description = "Security group para portal web de laboratorio IR" + vpc_id = aws_vpc.this.id + + ingress { + description = "HTTP del portal limitado a CIDRs autorizados" + from_port = 80 + to_port = 80 + protocol = "tcp" + cidr_blocks = local.portal_http_cidrs + } + + ingress { + description = "SSH solo desde la IP autorizada" + from_port = 22 + to_port = 22 + protocol = "tcp" + cidr_blocks = [var.ssh_allowed_cidr] + } + + egress { + description = "Salida necesaria para instalar paquetes y enviar logs" + from_port = 0 + to_port = 0 + protocol = "-1" + cidr_blocks = ["0.0.0.0/0"] + } + + tags = { + Name = "${var.project_name}-portal-sg" + } +} + +# ----------------------------------------------------------------------------- +# Buckets S3: logs, evidencia y datos sensibles ficticios. +# ----------------------------------------------------------------------------- + +resource "aws_s3_bucket" "logs" { + bucket = local.logs_bucket_name + force_destroy = var.force_destroy_buckets + + tags = { + Name = local.logs_bucket_name + Role = "logs" + } +} + +resource "aws_s3_bucket" "evidence" { + bucket = local.evidence_bucket_name + force_destroy = var.force_destroy_buckets + + tags = { + Name = local.evidence_bucket_name + Role = "incident-evidence" + } +} + +resource "aws_s3_bucket" "sensitive" { + bucket = local.sensitive_bucket_name + force_destroy = var.force_destroy_buckets + + tags = { + Name = local.sensitive_bucket_name + Role = "sensitive-demo-data" + } +} + +resource "aws_s3_bucket_public_access_block" "all" { + for_each = { + logs = aws_s3_bucket.logs.id + evidence = aws_s3_bucket.evidence.id + sensitive = aws_s3_bucket.sensitive.id + } + + bucket = each.value + block_public_acls = true + block_public_policy = true + ignore_public_acls = true + restrict_public_buckets = true +} + +resource "aws_s3_bucket_ownership_controls" "all" { + for_each = { + logs = aws_s3_bucket.logs.id + evidence = aws_s3_bucket.evidence.id + sensitive = aws_s3_bucket.sensitive.id + } + + bucket = each.value + + rule { + object_ownership = "BucketOwnerEnforced" + } +} + +resource "aws_s3_bucket_versioning" "all" { + for_each = { + logs = aws_s3_bucket.logs.id + evidence = aws_s3_bucket.evidence.id + sensitive = aws_s3_bucket.sensitive.id + } + + bucket = each.value + + versioning_configuration { + status = "Enabled" + } +} + +resource "aws_s3_bucket_server_side_encryption_configuration" "all" { + for_each = { + logs = aws_s3_bucket.logs.id + evidence = aws_s3_bucket.evidence.id + sensitive = aws_s3_bucket.sensitive.id + } + + bucket = each.value + + rule { + apply_server_side_encryption_by_default { + sse_algorithm = "AES256" + } + } +} + +resource "aws_s3_object" "logs_prefixes" { + for_each = toset(local.logs_prefixes) + + bucket = aws_s3_bucket.logs.id + key = each.value + content = "" +} + +resource "aws_s3_object" "evidence_prefixes" { + for_each = toset(local.evidence_prefixes) + + bucket = aws_s3_bucket.evidence.id + key = each.value + content = "" +} + +resource "aws_s3_object" "sensitive_prefixes" { + for_each = toset(local.sensitive_prefixes) + + bucket = aws_s3_bucket.sensitive.id + key = each.value + content = "" +} + +resource "aws_s3_object" "demo_sensitive_clients" { + bucket = aws_s3_bucket.sensitive.id + key = "sensible/clientes_demo.json" + content_type = "application/json" + + content = jsonencode({ + aviso = "Datos ficticios para laboratorio. No usar informacion real." + clientes = [ + { id = 1, nombre = "Cliente Demo 1", nivel = "interno" }, + { id = 2, nombre = "Cliente Demo 2", nivel = "interno" } + ] + }) +} + +resource "aws_s3_object" "demo_public_readme" { + bucket = aws_s3_bucket.sensitive.id + key = "public/readme.txt" + content_type = "text/plain" + content = "Bucket de laboratorio. No contiene datos reales.\n" +} + +resource "aws_s3_object" "detector_config" { + bucket = aws_s3_bucket.evidence.id + key = "config/authorized_ips.json" + content_type = "application/json" + + content = jsonencode({ + authorized_ips = local.authorized_ip_cidrs + sensitive_buckets = [ + aws_s3_bucket.sensitive.bucket + ] + critical_policies = [ + aws_iam_policy.critical_policy.name + ] + authorized_admin_users = var.authorized_admin_users + thresholds = { + console_login_failures_same_user_5m = var.threshold_console_login_failures_same_user_5m + console_login_failures_same_ip_5m = var.threshold_console_login_failures_same_ip_5m + app_login_failures_same_ip_5m = var.threshold_app_login_failures_same_ip_5m + port_scan_distinct_ports_5m = var.threshold_port_scan_distinct_ports_5m + s3_getobject_unusual_count_5m = var.threshold_s3_getobject_unusual_count_5m + s3_getobject_exfiltration_count_1h = var.threshold_s3_getobject_exfiltration_count_1h + } + resource_ids = { + vpc_id = aws_vpc.this.id + portal_instance_id = aws_instance.portal.id + } + }) +} + +# Bucket policy necesaria para CloudTrail. +resource "aws_s3_bucket_policy" "logs" { + bucket = aws_s3_bucket.logs.id + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Sid = "AWSCloudTrailAclCheck" + Effect = "Allow" + Principal = { Service = "cloudtrail.amazonaws.com" } + Action = "s3:GetBucketAcl" + Resource = aws_s3_bucket.logs.arn + }, + { + Sid = "AWSCloudTrailWrite" + Effect = "Allow" + Principal = { Service = "cloudtrail.amazonaws.com" } + Action = "s3:PutObject" + Resource = "${aws_s3_bucket.logs.arn}/cloudtrail/AWSLogs/${local.account_id}/*" + Condition = { + StringEquals = { + "s3:x-amz-acl" = "bucket-owner-full-control" + } + } + } + ] + }) +} + +# ----------------------------------------------------------------------------- +# CloudWatch Log Groups. +# ----------------------------------------------------------------------------- + +resource "aws_cloudwatch_log_group" "cloudtrail" { + name = local.common_log_groups.cloudtrail + retention_in_days = var.cloudwatch_retention_days +} + +resource "aws_cloudwatch_log_group" "flowlogs" { + name = local.common_log_groups.flowlogs + retention_in_days = var.cloudwatch_retention_days +} + +resource "aws_cloudwatch_log_group" "config" { + name = local.common_log_groups.config + retention_in_days = var.cloudwatch_retention_days +} + +resource "aws_cloudwatch_log_group" "ec2_app" { + name = local.common_log_groups.app + retention_in_days = var.cloudwatch_retention_days +} + +resource "aws_cloudwatch_log_group" "normalized" { + name = local.common_log_groups.normalized + retention_in_days = var.normalized_log_retention_days +} + +resource "aws_cloudwatch_log_group" "lambda" { + name = local.common_log_groups.lambda + retention_in_days = var.cloudwatch_retention_days +} + +resource "aws_cloudwatch_log_group" "playbook_notify" { + name = "/aws/lambda/lambda-${var.project_name}-playbook-notify-alert" + retention_in_days = var.cloudwatch_retention_days +} + +resource "aws_cloudwatch_log_group" "playbook_block_ip" { + name = "/aws/lambda/lambda-${var.project_name}-playbook-block-ip" + retention_in_days = var.cloudwatch_retention_days +} + +# ----------------------------------------------------------------------------- +# IAM para EC2: SSM + CloudWatch Agent. +# ----------------------------------------------------------------------------- + +resource "aws_iam_role" "ec2" { + name = "role-ec2-${var.project_name}-portal" + + assume_role_policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Principal = { Service = "ec2.amazonaws.com" } + Action = "sts:AssumeRole" + } + ] + }) +} + +resource "aws_iam_role_policy_attachment" "ec2_ssm" { + role = aws_iam_role.ec2.name + policy_arn = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore" +} + +resource "aws_iam_role_policy" "ec2_cloudwatch_agent_limited" { + name = "policy-ec2-${var.project_name}-cloudwatch-agent-limited" + role = aws_iam_role.ec2.id + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Sid = "WriteOnlyPortalLogs" + Effect = "Allow" + Action = [ + "logs:CreateLogStream", + "logs:PutLogEvents", + "logs:DescribeLogGroups", + "logs:DescribeLogStreams" + ] + Resource = [ + aws_cloudwatch_log_group.ec2_app.arn, + "${aws_cloudwatch_log_group.ec2_app.arn}:*" + ] + } + ] + }) +} + +resource "aws_iam_instance_profile" "ec2" { + name = "profile-ec2-${var.project_name}-portal" + role = aws_iam_role.ec2.name +} + +# ----------------------------------------------------------------------------- +# EC2 portal web de laboratorio. +# ----------------------------------------------------------------------------- + +resource "aws_instance" "portal" { + ami = data.aws_ami.al2023.id + instance_type = var.ec2_instance_type + subnet_id = aws_subnet.public_a.id + private_ip = var.portal_private_ip + vpc_security_group_ids = [aws_security_group.portal.id] + associate_public_ip_address = true + iam_instance_profile = aws_iam_instance_profile.ec2.name + key_name = var.key_name != "" ? var.key_name : null + + user_data_base64 = base64gzip(templatefile("${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 + + root_block_device { + volume_size = var.ec2_volume_size_gb + volume_type = "gp3" + delete_on_termination = true + encrypted = true + } + + metadata_options { + http_tokens = "required" + } + + tags = { + Name = "${var.project_name}-portal-ec2" + Role = "portal-web-laboratorio" + } + + depends_on = [ + aws_cloudwatch_log_group.ec2_app, + aws_iam_role_policy.ec2_cloudwatch_agent_limited, + aws_iam_role_policy_attachment.ec2_ssm + ] +} + +# ----------------------------------------------------------------------------- +# VPC Flow Logs sobre la ENI de la EC2, no sobre toda la VPC. +# ----------------------------------------------------------------------------- + +resource "aws_iam_role" "vpc_flowlogs" { + name = "role-${var.project_name}-vpc-flowlogs" + + assume_role_policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Principal = { Service = "vpc-flow-logs.amazonaws.com" } + Action = "sts:AssumeRole" + } + ] + }) +} + +resource "aws_iam_role_policy" "vpc_flowlogs" { + name = "policy-${var.project_name}-vpc-flowlogs" + role = aws_iam_role.vpc_flowlogs.id + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Action = [ + "logs:CreateLogStream", + "logs:PutLogEvents", + "logs:DescribeLogGroups", + "logs:DescribeLogStreams" + ] + Resource = "${aws_cloudwatch_log_group.flowlogs.arn}:*" + } + ] + }) +} + +resource "aws_flow_log" "portal_eni" { + count = var.enable_vpc_flow_logs ? 1 : 0 + + iam_role_arn = aws_iam_role.vpc_flowlogs.arn + log_destination = aws_cloudwatch_log_group.flowlogs.arn + traffic_type = "ALL" + eni_id = aws_instance.portal.primary_network_interface_id + + max_aggregation_interval = 60 + + log_format = "$${version} $${account-id} $${interface-id} $${srcaddr} $${dstaddr} $${srcport} $${dstport} $${protocol} $${packets} $${bytes} $${start} $${end} $${action} $${log-status}" + + tags = { + Name = "${var.project_name}-vpc-flowlogs-ec2" + } + + depends_on = [ + aws_iam_role_policy.vpc_flowlogs + ] +} + +# ----------------------------------------------------------------------------- +# CloudTrail: management events por defecto. +# S3 data events quedan apagados por defecto para reducir costos. +# ----------------------------------------------------------------------------- + +resource "aws_iam_role" "cloudtrail_cloudwatch" { + name = "role-${var.project_name}-cloudtrail-cloudwatch" + + assume_role_policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Principal = { Service = "cloudtrail.amazonaws.com" } + Action = "sts:AssumeRole" + } + ] + }) +} + +resource "aws_iam_role_policy" "cloudtrail_cloudwatch" { + name = "policy-${var.project_name}-cloudtrail-cloudwatch" + role = aws_iam_role.cloudtrail_cloudwatch.id + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Action = [ + "logs:CreateLogStream", + "logs:PutLogEvents" + ] + Resource = "${aws_cloudwatch_log_group.cloudtrail.arn}:*" + } + ] + }) +} + +resource "aws_cloudtrail" "management" { + name = "${var.project_name}-cloudtrail-management" + s3_bucket_name = aws_s3_bucket.logs.id + s3_key_prefix = "cloudtrail" + include_global_service_events = true + is_multi_region_trail = var.cloudtrail_multi_region + enable_log_file_validation = true + + cloud_watch_logs_group_arn = "${aws_cloudwatch_log_group.cloudtrail.arn}:*" + cloud_watch_logs_role_arn = aws_iam_role.cloudtrail_cloudwatch.arn + + event_selector { + read_write_type = "All" + include_management_events = true + + dynamic "data_resource" { + for_each = var.enable_s3_data_events ? [1] : [] + + content { + type = "AWS::S3::Object" + values = ["${aws_s3_bucket.sensitive.arn}/sensible/"] + } + } + } + + depends_on = [ + aws_s3_bucket_policy.logs, + aws_iam_role_policy.cloudtrail_cloudwatch + ] + + tags = { + Name = "${var.project_name}-cloudtrail-management" + } +} + +# ----------------------------------------------------------------------------- +# AWS Config opcional: puede generar cargos por configuration items y reglas. +# Por defecto está desactivado. Actívalo solo para pruebas de cambios IAM. +# ----------------------------------------------------------------------------- + +resource "aws_iam_role" "config" { + count = var.enable_aws_config ? 1 : 0 + + name = "role-${var.project_name}-aws-config" + + assume_role_policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Principal = { Service = "config.amazonaws.com" } + Action = "sts:AssumeRole" + } + ] + }) +} + +resource "aws_iam_role_policy_attachment" "config_managed" { + count = var.enable_aws_config ? 1 : 0 + + role = aws_iam_role.config[0].name + policy_arn = "arn:aws:iam::aws:policy/service-role/AWS_ConfigRole" +} + +resource "aws_iam_role_policy" "config_s3_delivery" { + count = var.enable_aws_config ? 1 : 0 + + name = "policy-${var.project_name}-aws-config-s3-delivery" + role = aws_iam_role.config[0].id + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Action = "s3:GetBucketAcl" + Resource = aws_s3_bucket.logs.arn + }, + { + Effect = "Allow" + Action = "s3:PutObject" + Resource = "${aws_s3_bucket.logs.arn}/config/AWSLogs/${local.account_id}/*" + Condition = { + StringEquals = { + "s3:x-amz-acl" = "bucket-owner-full-control" + } + } + } + ] + }) +} + +resource "aws_config_configuration_recorder" "this" { + count = var.enable_aws_config ? 1 : 0 + + name = "${var.project_name}-config-recorder" + role_arn = aws_iam_role.config[0].arn + + recording_group { + all_supported = false + include_global_resource_types = true + resource_types = var.config_resource_types + } + + depends_on = [ + aws_iam_role_policy_attachment.config_managed, + aws_iam_role_policy.config_s3_delivery + ] +} + +resource "aws_config_delivery_channel" "this" { + count = var.enable_aws_config ? 1 : 0 + + name = "${var.project_name}-config-delivery" + s3_bucket_name = aws_s3_bucket.logs.bucket + s3_key_prefix = "config" + + depends_on = [ + aws_config_configuration_recorder.this + ] +} + +resource "aws_config_configuration_recorder_status" "this" { + count = var.enable_aws_config ? 1 : 0 + + name = aws_config_configuration_recorder.this[0].name + is_enabled = true + + depends_on = [ + aws_config_delivery_channel.this + ] +} + +resource "aws_config_config_rule" "iam_no_admin_access" { + count = var.enable_aws_config ? 1 : 0 + + name = "${var.project_name}-iam-policy-no-admin-access" + + source { + owner = "AWS" + source_identifier = "IAM_POLICY_NO_STATEMENTS_WITH_ADMIN_ACCESS" + } + + depends_on = [ + aws_config_configuration_recorder_status.this + ] +} + +# ----------------------------------------------------------------------------- +# DynamoDB: incidentes y estado temporal de detección. +# ----------------------------------------------------------------------------- + +resource "aws_dynamodb_table" "incidents" { + name = "${var.project_name}_incidents" + billing_mode = "PAY_PER_REQUEST" + hash_key = "incident_id" + + attribute { + name = "incident_id" + type = "S" + } + + tags = { + Name = "${var.project_name}_incidents" + Role = "incident-registry" + } +} + +resource "aws_dynamodb_table" "state" { + name = "${var.project_name}_detection_state" + billing_mode = "PAY_PER_REQUEST" + hash_key = "pk" + range_key = "sk" + + attribute { + name = "pk" + type = "S" + } + + attribute { + name = "sk" + type = "S" + } + + ttl { + attribute_name = "ttl" + enabled = true + } + + tags = { + Name = "${var.project_name}_detection_state" + Role = "detector-state" + } +} + +# ----------------------------------------------------------------------------- +# SNS para alertas. +# ----------------------------------------------------------------------------- + +resource "aws_sns_topic" "alerts" { + name = "${var.project_name}-incident-alerts" +} + +# Suscripcion de correo gestionada directamente via SES HTML Card (evita correos duplicados en texto plano) +# Si deseas reactivar el correo de texto plano de SNS, descomenta este bloque: +# resource "aws_sns_topic_subscription" "email" { +# count = var.alert_email != "" ? 1 : 0 +# topic_arn = aws_sns_topic.alerts.arn +# protocol = "email" +# endpoint = var.alert_email +# } + +resource "aws_ses_email_identity" "alert" { + count = var.alert_email != "" ? 1 : 0 + email = var.alert_email +} + +# ----------------------------------------------------------------------------- +# Amazon SES: Identidad de Dominio y Firma Digital DKIM (soc.bryan-bano.com) +# ----------------------------------------------------------------------------- + +resource "aws_ses_domain_identity" "soc" { + count = var.ses_domain != "" ? 1 : 0 + domain = var.ses_domain +} + +resource "aws_ses_domain_dkim" "soc" { + count = var.ses_domain != "" ? 1 : 0 + domain = aws_ses_domain_identity.soc[0].domain +} + +# ----------------------------------------------------------------------------- +# SQS: cola de incidentes para entregar el JSON normalizado exigido por el +# componente B. Lambda publica aqui las variables obligatorias por incidente. +# ----------------------------------------------------------------------------- + +resource "aws_sqs_queue" "incident_queue" { + name = "${var.project_name}-incident-queue" + message_retention_seconds = 345600 + visibility_timeout_seconds = 30 + sqs_managed_sse_enabled = true + + tags = { + Name = "${var.project_name}-incident-queue" + Role = "normalized-incident-queue" + } +} + +resource "aws_sqs_queue" "playbook_notify_queue" { + name = "${var.project_name}-playbook-notify-alert-queue" + message_retention_seconds = 345600 + visibility_timeout_seconds = 60 + sqs_managed_sse_enabled = true + + tags = { + Name = "${var.project_name}-playbook-notify-alert-queue" + Role = "playbook-dispatch-notify-alert" + } +} + +resource "aws_sqs_queue" "playbook_block_ip_queue" { + name = "${var.project_name}-playbook-block-ip-queue" + message_retention_seconds = 345600 + visibility_timeout_seconds = 60 + sqs_managed_sse_enabled = true + + tags = { + Name = "${var.project_name}-playbook-block-ip-queue" + Role = "playbook-dispatch-block-ip" + } +} + +resource "aws_sqs_queue" "playbook_revoke_credentials_queue" { + name = "${var.project_name}-playbook-revoke-credentials-queue" + message_retention_seconds = 345600 + visibility_timeout_seconds = 60 + sqs_managed_sse_enabled = true + + tags = { + Name = "${var.project_name}-playbook-revoke-credentials-queue" + Role = "playbook-dispatch-revoke-credentials" + } +} + + +# ----------------------------------------------------------------------------- +# IAM policy crítica de prueba e IAM user de laboratorio. +# No se crean access keys ni password de consola. +# ----------------------------------------------------------------------------- + +resource "aws_iam_policy" "critical_policy" { + name = "${var.project_name}-critical-policy" + description = "Politica critica de laboratorio para detectar cambios controlados" + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Sid = "AllowReadOnlySensitiveDemoBucket" + Effect = "Allow" + Action = [ + "s3:GetObject", + "s3:ListBucket" + ] + Resource = [ + aws_s3_bucket.sensitive.arn, + "${aws_s3_bucket.sensitive.arn}/sensible/*" + ] + } + ] + }) +} + +resource "aws_iam_user" "test_user" { + count = var.create_test_iam_user ? 1 : 0 + + name = "${var.project_name}-user-test" + force_destroy = true + + tags = { + Role = "lab-test-user" + } +} + +# ----------------------------------------------------------------------------- +# Lambda Detector B. +# ----------------------------------------------------------------------------- + +data "archive_file" "lambda_zip" { + type = "zip" + source_file = "${path.module}/lambda/lambda_function.py" + output_path = "${path.module}/lambda_tesis_detector.zip" +} + +resource "aws_iam_role" "lambda_detector" { + name = "role-lambda-${var.project_name}-detector" + + assume_role_policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Principal = { Service = "lambda.amazonaws.com" } + Action = "sts:AssumeRole" + } + ] + }) +} + +resource "aws_iam_role_policy_attachment" "lambda_basic" { + role = aws_iam_role.lambda_detector.name + policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" +} + +resource "aws_iam_role_policy" "lambda_detector" { + name = "policy-lambda-${var.project_name}-detector" + role = aws_iam_role.lambda_detector.id + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Sid = "DynamoDBIncidentAccess" + Effect = "Allow" + Action = [ + "dynamodb:PutItem", + "dynamodb:GetItem", + "dynamodb:UpdateItem", + "dynamodb:Query" + ] + Resource = [ + aws_dynamodb_table.incidents.arn, + aws_dynamodb_table.state.arn + ] + }, + { + Sid = "EvidenceS3Access" + Effect = "Allow" + Action = [ + "s3:PutObject", + "s3:GetObject" + ] + Resource = [ + "${aws_s3_bucket.evidence.arn}/*" + ] + }, + { + Sid = "SnsPublishAlerts" + Effect = "Allow" + Action = "sns:Publish" + Resource = aws_sns_topic.alerts.arn + }, + { + Sid = "SqsPublishNormalizedIncidentAndPlaybooks" + Effect = "Allow" + Action = "sqs:SendMessage" + Resource = [ + aws_sqs_queue.incident_queue.arn, + aws_sqs_queue.playbook_notify_queue.arn, + aws_sqs_queue.playbook_block_ip_queue.arn, + aws_sqs_queue.playbook_revoke_credentials_queue.arn + ] + }, + { + Sid = "CloudWatchCustomMetrics" + Effect = "Allow" + Action = "cloudwatch:PutMetricData" + Resource = "*" + Condition = { + StringEquals = { + "cloudwatch:namespace" = "TesisIR" + } + } + } + ] + }) +} + +resource "aws_lambda_function" "detector" { + function_name = "lambda-${var.project_name}-detector-b" + role = aws_iam_role.lambda_detector.arn + handler = "lambda_function.lambda_handler" + runtime = "python3.12" + architectures = ["x86_64"] + memory_size = 256 + timeout = 30 + + filename = data.archive_file.lambda_zip.output_path + source_code_hash = data.archive_file.lambda_zip.output_base64sha256 + + environment { + variables = { + INCIDENTS_TABLE = aws_dynamodb_table.incidents.name + STATE_TABLE = aws_dynamodb_table.state.name + EVIDENCE_BUCKET = aws_s3_bucket.evidence.bucket + SNS_TOPIC_ARN = aws_sns_topic.alerts.arn + CONFIG_KEY = aws_s3_object.detector_config.key + INCIDENT_QUEUE_URL = aws_sqs_queue.incident_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_REVOKE_CREDENTIALS_QUEUE_URL = aws_sqs_queue.playbook_revoke_credentials_queue.url + VPC_ID = aws_vpc.this.id + PORTAL_INSTANCE_ID = aws_instance.portal.id + } + } + + depends_on = [ + aws_iam_role_policy_attachment.lambda_basic, + aws_iam_role_policy.lambda_detector, + aws_cloudwatch_log_group.lambda + ] + + tags = { + Name = "lambda-${var.project_name}-detector-b" + Role = "incident-detector" + } +} + +# Permisos para que CloudWatch Logs invoque Lambda. +resource "aws_lambda_permission" "from_cloudtrail_logs" { + statement_id = "AllowCloudWatchCloudTrail" + action = "lambda:InvokeFunction" + function_name = aws_lambda_function.detector.function_name + principal = "logs.${var.aws_region}.amazonaws.com" + source_arn = "${aws_cloudwatch_log_group.cloudtrail.arn}:*" +} + +resource "aws_lambda_permission" "from_app_logs" { + statement_id = "AllowCloudWatchAppLogs" + action = "lambda:InvokeFunction" + function_name = aws_lambda_function.detector.function_name + principal = "logs.${var.aws_region}.amazonaws.com" + source_arn = "${aws_cloudwatch_log_group.ec2_app.arn}:*" +} + +resource "aws_lambda_permission" "from_flow_logs" { + count = var.enable_vpc_flow_logs ? 1 : 0 + + statement_id = "AllowCloudWatchFlowLogs" + action = "lambda:InvokeFunction" + function_name = aws_lambda_function.detector.function_name + principal = "logs.${var.aws_region}.amazonaws.com" + source_arn = "${aws_cloudwatch_log_group.flowlogs.arn}:*" +} + +# Subscription filters. +resource "aws_cloudwatch_log_subscription_filter" "cloudtrail_to_lambda" { + name = "sf-cloudtrail-to-detector" + log_group_name = aws_cloudwatch_log_group.cloudtrail.name + filter_pattern = "{ ($.eventSource = \"signin.amazonaws.com\") || ($.eventSource = \"iam.amazonaws.com\") || ($.eventSource = \"s3.amazonaws.com\") || ($.eventSource = \"sts.amazonaws.com\") }" + destination_arn = aws_lambda_function.detector.arn + + depends_on = [ + aws_lambda_permission.from_cloudtrail_logs + ] +} + +resource "aws_cloudwatch_log_subscription_filter" "app_to_lambda" { + name = "sf-app-to-detector" + log_group_name = aws_cloudwatch_log_group.ec2_app.name + filter_pattern = "{ $.event_type = \"login_failed\" }" + destination_arn = aws_lambda_function.detector.arn + + depends_on = [ + aws_lambda_permission.from_app_logs + ] +} + +resource "aws_cloudwatch_log_subscription_filter" "flowlogs_to_lambda" { + count = var.enable_vpc_flow_logs ? 1 : 0 + + name = "sf-flowlogs-to-detector" + log_group_name = aws_cloudwatch_log_group.flowlogs.name + filter_pattern = "[version, account_id, interface_id, srcaddr, dstaddr, srcport, dstport, protocol, packets, bytes, start, end, action = \"REJECT\", log_status]" + destination_arn = aws_lambda_function.detector.arn + + depends_on = [ + aws_lambda_permission.from_flow_logs + ] +} + + +# ----------------------------------------------------------------------------- +# Playbooks de respuesta para Incidente 1: BRUTE_FORCE. +# notify-alert notifica por SNS y deja auditoria en S3. +# block-ip aplica contencion real en la NACL con una regla DENY para la IP origen. +# ----------------------------------------------------------------------------- + +data "archive_file" "notify_alert_zip" { + type = "zip" + source_file = "${path.module}/playbooks/notify_alert/handler.py" + output_path = "${path.module}/lambda_playbook_notify_alert.zip" +} + +data "archive_file" "block_ip_zip" { + type = "zip" + source_file = "${path.module}/playbooks/block_ip/handler.py" + output_path = "${path.module}/lambda_playbook_block_ip.zip" +} + +resource "aws_iam_role" "playbook_notify" { + name = "role-lambda-${var.project_name}-playbook-notify-alert" + + assume_role_policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Principal = { Service = "lambda.amazonaws.com" } + Action = "sts:AssumeRole" + } + ] + }) +} + +resource "aws_iam_role" "playbook_block_ip" { + name = "role-lambda-${var.project_name}-playbook-block-ip" + + assume_role_policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Principal = { Service = "lambda.amazonaws.com" } + Action = "sts:AssumeRole" + } + ] + }) +} + +resource "aws_iam_role_policy_attachment" "playbook_notify_basic" { + role = aws_iam_role.playbook_notify.name + policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" +} + +resource "aws_iam_role_policy_attachment" "playbook_block_ip_basic" { + role = aws_iam_role.playbook_block_ip.name + policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" +} + +resource "aws_iam_role_policy" "playbook_notify" { + name = "policy-lambda-${var.project_name}-playbook-notify-alert" + role = aws_iam_role.playbook_notify.id + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Sid = "ReadDedicatedQueue" + Effect = "Allow" + Action = [ + "sqs:ReceiveMessage", + "sqs:DeleteMessage", + "sqs:GetQueueAttributes" + ] + Resource = aws_sqs_queue.playbook_notify_queue.arn + }, + { + Sid = "PublishAlert" + Effect = "Allow" + Action = "sns:Publish" + Resource = aws_sns_topic.alerts.arn + }, + { + Sid = "SendSESEmail" + Effect = "Allow" + Action = [ + "ses:SendEmail", + "ses:SendRawEmail" + ] + Resource = "*" + }, + { + Sid = "WritePlaybookAudit" + Effect = "Allow" + Action = [ + "s3:PutObject" + ] + Resource = "${aws_s3_bucket.evidence.arn}/responses/notify-alert/*" + } + ] + }) +} + +resource "aws_iam_role_policy" "playbook_block_ip" { + name = "policy-lambda-${var.project_name}-playbook-block-ip" + role = aws_iam_role.playbook_block_ip.id + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Sid = "ReadDedicatedQueue" + Effect = "Allow" + Action = [ + "sqs:ReceiveMessage", + "sqs:DeleteMessage", + "sqs:GetQueueAttributes" + ] + Resource = aws_sqs_queue.playbook_block_ip_queue.arn + }, + { + Sid = "ManageNaclDenyRule" + Effect = "Allow" + Action = [ + "ec2:DescribeNetworkAcls", + "ec2:CreateNetworkAclEntry" + ] + Resource = "*" + }, + { + Sid = "WriteBlockAudit" + Effect = "Allow" + Action = [ + "s3:GetObject", + "s3:PutObject" + ] + Resource = "${aws_s3_bucket.evidence.arn}/responses/block-ip/*" + }, + { + Sid = "PublishAlert" + Effect = "Allow" + Action = "sns:Publish" + Resource = aws_sns_topic.alerts.arn + }, + { + Sid = "SendSESEmail" + Effect = "Allow" + Action = [ + "ses:SendEmail", + "ses:SendRawEmail" + ] + Resource = "*" + } + ] + }) +} + +resource "aws_lambda_function" "playbook_notify" { + function_name = "lambda-${var.project_name}-playbook-notify-alert" + role = aws_iam_role.playbook_notify.arn + handler = "handler.lambda_handler" + runtime = "python3.12" + architectures = ["x86_64"] + memory_size = 128 + timeout = 20 + + filename = data.archive_file.notify_alert_zip.output_path + source_code_hash = data.archive_file.notify_alert_zip.output_base64sha256 + + environment { + variables = { + SNS_ALERTS_ARN = aws_sns_topic.alerts.arn + EVIDENCE_BUCKET = aws_s3_bucket.evidence.bucket + RESPONSE_PREFIX = "responses/notify-alert" + ALERT_EMAIL = var.alert_email + SES_SENDER_EMAIL = var.ses_sender_email + } + } + + depends_on = [ + aws_iam_role_policy_attachment.playbook_notify_basic, + aws_iam_role_policy.playbook_notify, + aws_cloudwatch_log_group.playbook_notify + ] + + tags = { + Name = "lambda-${var.project_name}-playbook-notify-alert" + Role = "playbook-notify-alert" + } +} + +resource "aws_lambda_function" "playbook_block_ip" { + function_name = "lambda-${var.project_name}-playbook-block-ip" + role = aws_iam_role.playbook_block_ip.arn + handler = "handler.lambda_handler" + runtime = "python3.12" + architectures = ["x86_64"] + memory_size = 128 + timeout = 30 + + filename = data.archive_file.block_ip_zip.output_path + source_code_hash = data.archive_file.block_ip_zip.output_base64sha256 + + environment { + variables = { + SNS_ALERTS_ARN = aws_sns_topic.alerts.arn + EVIDENCE_BUCKET = aws_s3_bucket.evidence.bucket + TARGET_NACL_ID = aws_vpc.this.default_network_acl_id + RESPONSE_PREFIX = "responses/block-ip" + RULE_MIN = "1" + RULE_MAX = "99" + ALERT_EMAIL = var.alert_email + SES_SENDER_EMAIL = var.ses_sender_email + } + } + + depends_on = [ + aws_iam_role_policy_attachment.playbook_block_ip_basic, + aws_iam_role_policy.playbook_block_ip, + aws_cloudwatch_log_group.playbook_block_ip + ] + + tags = { + Name = "lambda-${var.project_name}-playbook-block-ip" + Role = "playbook-block-ip" + } +} + +resource "aws_lambda_event_source_mapping" "playbook_notify_from_queue" { + event_source_arn = aws_sqs_queue.playbook_notify_queue.arn + function_name = aws_lambda_function.playbook_notify.arn + batch_size = 5 + enabled = true +} + +resource "aws_lambda_event_source_mapping" "playbook_block_ip_from_queue" { + event_source_arn = aws_sqs_queue.playbook_block_ip_queue.arn + function_name = aws_lambda_function.playbook_block_ip.arn + batch_size = 1 + enabled = true +} + +# ----------------------------------------------------------------------------- +# Playbook de respuesta para Incidente 3 y 4: PRIVILEGE_ESCALATION y CREDENTIAL_LEAK. +# revoke-credentials desactiva las access keys del usuario y le aplica Deny-All. +# ----------------------------------------------------------------------------- + +data "archive_file" "revoke_credentials_zip" { + type = "zip" + source_file = "${path.module}/playbooks/revoke_credentials/handler.py" + output_path = "${path.module}/lambda_playbook_revoke_credentials.zip" +} + +resource "aws_cloudwatch_log_group" "playbook_revoke_credentials" { + name = "/aws/lambda/lambda-${var.project_name}-playbook-revoke-credentials" + retention_in_days = var.cloudwatch_retention_days +} + +resource "aws_iam_role" "playbook_revoke_credentials" { + name = "role-lambda-${var.project_name}-playbook-revoke-credentials" + + assume_role_policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Principal = { Service = "lambda.amazonaws.com" } + Action = "sts:AssumeRole" + } + ] + }) +} + +resource "aws_iam_role_policy_attachment" "playbook_revoke_credentials_basic" { + role = aws_iam_role.playbook_revoke_credentials.name + policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" +} + +resource "aws_iam_role_policy" "playbook_revoke_credentials" { + name = "policy-lambda-${var.project_name}-playbook-revoke-credentials" + role = aws_iam_role.playbook_revoke_credentials.id + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Sid = "ReadDedicatedQueue" + Effect = "Allow" + Action = [ + "sqs:ReceiveMessage", + "sqs:DeleteMessage", + "sqs:GetQueueAttributes" + ] + Resource = aws_sqs_queue.playbook_revoke_credentials_queue.arn + }, + { + Sid = "ManageUserCredentialsAndPolicies" + Effect = "Allow" + Action = [ + "iam:ListAccessKeys", + "iam:UpdateAccessKey", + "iam:PutUserPolicy" + ] + Resource = "*" + }, + { + Sid = "WriteRevokeAudit" + Effect = "Allow" + Action = [ + "s3:GetObject", + "s3:PutObject" + ] + Resource = "${aws_s3_bucket.evidence.arn}/responses/revoke-credentials/*" + }, + { + Sid = "PublishAlert" + Effect = "Allow" + Action = "sns:Publish" + Resource = aws_sns_topic.alerts.arn + }, + { + Sid = "SendSESEmail" + Effect = "Allow" + Action = [ + "ses:SendEmail", + "ses:SendRawEmail" + ] + Resource = "*" + } + ] + }) +} + +resource "aws_lambda_function" "playbook_revoke_credentials" { + function_name = "lambda-${var.project_name}-playbook-revoke-credentials" + role = aws_iam_role.playbook_revoke_credentials.arn + handler = "handler.lambda_handler" + runtime = "python3.12" + architectures = ["x86_64"] + memory_size = 128 + timeout = 30 + + filename = data.archive_file.revoke_credentials_zip.output_path + source_code_hash = data.archive_file.revoke_credentials_zip.output_base64sha256 + + environment { + variables = { + SNS_ALERTS_ARN = aws_sns_topic.alerts.arn + EVIDENCE_BUCKET = aws_s3_bucket.evidence.bucket + RESPONSE_PREFIX = "responses/revoke-credentials" + ALERT_EMAIL = var.alert_email + SES_SENDER_EMAIL = var.ses_sender_email + } + } + + depends_on = [ + aws_iam_role_policy_attachment.playbook_revoke_credentials_basic, + aws_iam_role_policy.playbook_revoke_credentials, + aws_cloudwatch_log_group.playbook_revoke_credentials + ] + + tags = { + Name = "lambda-${var.project_name}-playbook-revoke-credentials" + Role = "playbook-revoke-credentials" + } +} + +resource "aws_lambda_event_source_mapping" "playbook_revoke_credentials_from_queue" { + event_source_arn = aws_sqs_queue.playbook_revoke_credentials_queue.arn + function_name = aws_lambda_function.playbook_revoke_credentials.arn + batch_size = 1 + enabled = true +} + +# ----------------------------------------------------------------------------- +# Integracion de notificaciones a Telegram via SNS +# ----------------------------------------------------------------------------- + +data "archive_file" "telegram_notifier_zip" { + count = var.telegram_bot_token != "" && var.telegram_chat_id != "" ? 1 : 0 + type = "zip" + source_dir = "${path.module}/playbooks/telegram_notifier" + output_path = "${path.module}/lambda_playbook_telegram_notifier.zip" +} + +resource "aws_cloudwatch_log_group" "telegram_notifier" { + count = var.telegram_bot_token != "" && var.telegram_chat_id != "" ? 1 : 0 + name = "/aws/lambda/lambda-${var.project_name}-telegram-notifier" + retention_in_days = var.cloudwatch_retention_days +} + +resource "aws_iam_role" "telegram_notifier" { + count = var.telegram_bot_token != "" && var.telegram_chat_id != "" ? 1 : 0 + name = "role-lambda-${var.project_name}-telegram-notifier" + + assume_role_policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Principal = { Service = "lambda.amazonaws.com" } + Action = "sts:AssumeRole" + } + ] + }) +} + +resource "aws_iam_role_policy_attachment" "telegram_notifier_basic" { + count = var.telegram_bot_token != "" && var.telegram_chat_id != "" ? 1 : 0 + role = aws_iam_role.telegram_notifier[0].name + policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" +} + +resource "aws_lambda_function" "telegram_notifier" { + count = var.telegram_bot_token != "" && var.telegram_chat_id != "" ? 1 : 0 + function_name = "lambda-${var.project_name}-telegram-notifier" + role = aws_iam_role.telegram_notifier[0].arn + handler = "handler.lambda_handler" + runtime = "python3.12" + architectures = ["x86_64"] + memory_size = 256 + timeout = 30 + + filename = data.archive_file.telegram_notifier_zip[0].output_path + source_code_hash = data.archive_file.telegram_notifier_zip[0].output_base64sha256 + + environment { + variables = { + TELEGRAM_BOT_TOKEN = var.telegram_bot_token + TELEGRAM_CHAT_ID = var.telegram_chat_id + } + } + + depends_on = [ + aws_iam_role_policy_attachment.telegram_notifier_basic, + aws_cloudwatch_log_group.telegram_notifier + ] + + tags = { + Name = "lambda-${var.project_name}-telegram-notifier" + Role = "telegram-alert-notifier" + } +} + +resource "aws_lambda_permission" "from_sns_telegram" { + count = var.telegram_bot_token != "" && var.telegram_chat_id != "" ? 1 : 0 + statement_id = "AllowExecutionFromSNS" + action = "lambda:InvokeFunction" + function_name = aws_lambda_function.telegram_notifier[0].function_name + principal = "sns.amazonaws.com" + source_arn = aws_sns_topic.alerts.arn +} + +resource "aws_sns_topic_subscription" "telegram" { + count = var.telegram_bot_token != "" && var.telegram_chat_id != "" ? 1 : 0 + topic_arn = aws_sns_topic.alerts.arn + protocol = "lambda" + endpoint = aws_lambda_function.telegram_notifier[0].arn + + depends_on = [ + aws_lambda_permission.from_sns_telegram + ] +} + + +# ----------------------------------------------------------------------------- +# Metric filters y alarmas simples de respaldo. +# ----------------------------------------------------------------------------- + +resource "aws_cloudwatch_log_metric_filter" "console_login_failure" { + name = "mf-console-login-failure" + log_group_name = aws_cloudwatch_log_group.cloudtrail.name + pattern = "{ ($.eventName = \"ConsoleLogin\") && ($.responseElements.ConsoleLogin = \"Failure\") }" + + metric_transformation { + name = "ConsoleLoginFailure" + namespace = "TesisIR" + value = "1" + default_value = "0" + } +} + +resource "aws_cloudwatch_log_metric_filter" "iam_critical_action" { + name = "mf-iam-critical-action" + log_group_name = aws_cloudwatch_log_group.cloudtrail.name + pattern = "{ ($.eventSource = \"iam.amazonaws.com\") && (($.eventName = \"CreateUser\") || ($.eventName = \"AttachUserPolicy\") || ($.eventName = \"AttachRolePolicy\") || ($.eventName = \"PutUserPolicy\") || ($.eventName = \"PutRolePolicy\") || ($.eventName = \"CreateAccessKey\") || ($.eventName = \"AddUserToGroup\")) }" + + metric_transformation { + name = "IAMCriticalAction" + namespace = "TesisIR" + value = "1" + default_value = "0" + } +} + +resource "aws_cloudwatch_log_metric_filter" "iam_policy_change" { + name = "mf-iam-policy-change" + log_group_name = aws_cloudwatch_log_group.cloudtrail.name + pattern = "{ ($.eventSource = \"iam.amazonaws.com\") && (($.eventName = \"CreatePolicyVersion\") || ($.eventName = \"DeletePolicyVersion\") || ($.eventName = \"PutUserPolicy\") || ($.eventName = \"PutRolePolicy\") || ($.eventName = \"UpdateAssumeRolePolicy\")) }" + + metric_transformation { + name = "IAMPolicyChange" + namespace = "TesisIR" + value = "1" + default_value = "0" + } +} + +resource "aws_cloudwatch_log_metric_filter" "vpc_rejected_traffic" { + count = var.enable_vpc_flow_logs ? 1 : 0 + + name = "mf-vpc-rejected-traffic" + log_group_name = aws_cloudwatch_log_group.flowlogs.name + pattern = "[version, account_id, interface_id, srcaddr, dstaddr, srcport, dstport, protocol, packets, bytes, start, end, action = \"REJECT\", log_status]" + + metric_transformation { + name = "VPCRejectedTraffic" + namespace = "TesisIR" + value = "1" + default_value = "0" + } +} + +resource "aws_cloudwatch_metric_alarm" "console_login_failure" { + alarm_name = "alarm-console-login-failure" + comparison_operator = "GreaterThanOrEqualToThreshold" + evaluation_periods = 1 + metric_name = "ConsoleLoginFailure" + namespace = "TesisIR" + period = 300 + statistic = "Sum" + threshold = var.threshold_console_login_failures_same_user_5m + alarm_description = "Alarma por multiples fallos de inicio de sesion" + treat_missing_data = "notBreaching" + + depends_on = [aws_cloudwatch_log_metric_filter.console_login_failure] +} + +resource "aws_cloudwatch_metric_alarm" "iam_critical_action" { + alarm_name = "alarm-iam-critical-action" + comparison_operator = "GreaterThanOrEqualToThreshold" + evaluation_periods = 1 + metric_name = "IAMCriticalAction" + namespace = "TesisIR" + period = 300 + statistic = "Sum" + threshold = 1 + alarm_description = "Alarma por accion critica IAM" + treat_missing_data = "notBreaching" + + depends_on = [aws_cloudwatch_log_metric_filter.iam_critical_action] +} + +resource "aws_cloudwatch_metric_alarm" "iam_policy_change" { + alarm_name = "alarm-iam-policy-change" + comparison_operator = "GreaterThanOrEqualToThreshold" + evaluation_periods = 1 + metric_name = "IAMPolicyChange" + namespace = "TesisIR" + period = 300 + statistic = "Sum" + threshold = 1 + alarm_description = "Alarma por cambio de politica IAM" + treat_missing_data = "notBreaching" + + depends_on = [aws_cloudwatch_log_metric_filter.iam_policy_change] +} + +resource "aws_cloudwatch_metric_alarm" "vpc_rejected_traffic" { + count = var.enable_vpc_flow_logs ? 1 : 0 + + alarm_name = "alarm-vpc-rejected-traffic" + comparison_operator = "GreaterThanOrEqualToThreshold" + evaluation_periods = 1 + metric_name = "VPCRejectedTraffic" + namespace = "TesisIR" + period = 300 + statistic = "Sum" + threshold = var.threshold_port_scan_distinct_ports_5m + alarm_description = "Alarma por trafico rechazado repetido hacia la EC2" + treat_missing_data = "notBreaching" + + depends_on = [aws_cloudwatch_log_metric_filter.vpc_rejected_traffic] +} + +# ----------------------------------------------------------------------------- +# Athena workgroup para consultas históricas sobre S3. +# No crea tablas Glue/CloudTrail automáticamente para evitar complejidad/costos. +# ----------------------------------------------------------------------------- + +resource "aws_athena_workgroup" "ir" { + name = "${var.project_name}-athena-workgroup" + + configuration { + enforce_workgroup_configuration = true + + result_configuration { + output_location = "s3://${aws_s3_bucket.logs.bucket}/athena-results/" + } + } + + tags = { + Name = "${var.project_name}-athena-workgroup" + } +} diff --git a/terraform-tesis-ir-secure-portal/outputs.tf b/terraform-tesis-ir-secure-portal/outputs.tf new file mode 100644 index 0000000..ba286dc --- /dev/null +++ b/terraform-tesis-ir-secure-portal/outputs.tf @@ -0,0 +1,159 @@ +output "region" { + value = var.aws_region +} + +output "vpc_id" { + value = aws_vpc.this.id +} + +output "public_subnet_a_id" { + value = aws_subnet.public_a.id +} + +output "public_subnet_b_id" { + value = aws_subnet.public_b.id +} + +output "portal_instance_id" { + value = aws_instance.portal.id +} + +output "portal_public_ip" { + value = aws_instance.portal.public_ip +} + +output "portal_url" { + value = "http://${aws_instance.portal.public_ip}" +} + +output "logs_bucket" { + value = aws_s3_bucket.logs.bucket +} + +output "evidence_bucket" { + value = aws_s3_bucket.evidence.bucket +} + +output "sensitive_bucket" { + value = aws_s3_bucket.sensitive.bucket +} + +output "cloudtrail_log_group" { + value = aws_cloudwatch_log_group.cloudtrail.name +} + +output "ec2_app_log_group" { + value = aws_cloudwatch_log_group.ec2_app.name +} + +output "vpc_flow_log_group" { + value = aws_cloudwatch_log_group.flowlogs.name +} + +output "lambda_detector_name" { + value = aws_lambda_function.detector.function_name +} + +output "sns_topic_arn" { + value = aws_sns_topic.alerts.arn +} + +output "dynamodb_incidents_table" { + value = aws_dynamodb_table.incidents.name +} + +output "dynamodb_state_table" { + value = aws_dynamodb_table.state.name +} + +output "athena_workgroup" { + value = aws_athena_workgroup.ir.name +} + +output "warning_optional_cost_resources" { + value = "AWS Config=${var.enable_aws_config}, S3 Data Events=${var.enable_s3_data_events}, CloudTrail multi-region=${var.cloudtrail_multi_region}. Mantenerlos apagados reduce riesgo de costos." +} + +output "incident_queue_url" { + value = aws_sqs_queue.incident_queue.url +} + +output "incident_queue_arn" { + value = aws_sqs_queue.incident_queue.arn +} + +output "playbook_notify_lambda_name" { + value = aws_lambda_function.playbook_notify.function_name +} + +output "playbook_block_ip_lambda_name" { + value = aws_lambda_function.playbook_block_ip.function_name +} + +output "playbook_revoke_credentials_lambda_name" { + value = aws_lambda_function.playbook_revoke_credentials.function_name +} + +output "playbook_notify_queue_url" { + value = aws_sqs_queue.playbook_notify_queue.url +} + +output "playbook_block_ip_queue_url" { + value = aws_sqs_queue.playbook_block_ip_queue.url +} + +output "playbook_revoke_credentials_queue_url" { + value = aws_sqs_queue.playbook_revoke_credentials_queue.url +} + +output "mitigation_network_acl_id" { + value = aws_vpc.this.default_network_acl_id +} + +output "telegram_notifier_lambda_name" { + value = try(aws_lambda_function.telegram_notifier[0].function_name, "disabled") + description = "Nombre de la Lambda de Telegram (si esta habilitada)." +} + +output "ses_subdomain" { + value = try(aws_ses_domain_identity.soc[0].domain, "") + description = "Subdominio registrado para Amazon SES." +} + +output "ses_sender_email" { + value = var.ses_sender_email + description = "Direccion del remitente firmada con DKIM para reportes de incidentes." +} + +output "cloudflare_dkim_records" { + value = var.ses_domain != "" ? [ + for token in try(aws_ses_domain_dkim.soc[0].dkim_tokens, []) : { + tipo = "CNAME" + nombre = "${token}._domainkey.soc" + contenido = "${token}.dkim.amazonses.com" + proxy_status = "DNS only (Proxy deshabilitado / Nube Gris)" + } + ] : [] + description = "Registros CNAME exactos para copiar en Cloudflare DNS para activar la Firma Digital DKIM." +} + +output "cloudflare_spf_record" { + value = var.ses_domain != "" ? { + tipo = "TXT" + nombre = "soc" + contenido = "v=spf1 include:amazonses.com ~all" + proxy_status = "DNS only" + } : null + description = "Registro SPF para autorizar el envio de correos desde Amazon SES en Cloudflare." +} + +output "cloudflare_dmarc_record" { + value = var.ses_domain != "" ? { + tipo = "TXT" + nombre = "_dmarc.soc" + contenido = "v=DMARC1; p=none;" + proxy_status = "DNS only" + } : null + description = "Registro DMARC para validar la autenticacion de correos en Cloudflare." +} + diff --git a/terraform-tesis-ir-secure-portal/playbooks/block_ip/handler.py b/terraform-tesis-ir-secure-portal/playbooks/block_ip/handler.py new file mode 100644 index 0000000..bc8a34c --- /dev/null +++ b/terraform-tesis-ir-secure-portal/playbooks/block_ip/handler.py @@ -0,0 +1,382 @@ +""" +Playbook: block-ip +Mitigacion de contención real para incidentes de red. +Bloquea la IP origen creando una regla DENY inbound en la Network ACL +objetivo, registra evidencia de respuesta en S3 y notifica via HTML Card (SES) y SNS (Telegram). +""" +import html +import ipaddress +import json +import os +import uuid +from datetime import datetime +from zoneinfo import ZoneInfo + +import boto3 + +s3 = boto3.client("s3") +sns = boto3.client("sns") +ec2 = boto3.client("ec2") +ses = boto3.client("ses") + +EVIDENCE_BUCKET = os.environ["EVIDENCE_BUCKET"] +SNS_ARN = os.environ["SNS_ALERTS_ARN"] +TARGET_NACL_ID = os.environ["TARGET_NACL_ID"] +RESPONSE_PREFIX = os.environ.get("RESPONSE_PREFIX", "responses/block-ip") +RULE_MIN = int(os.environ.get("RULE_MIN", "1")) +RULE_MAX = int(os.environ.get("RULE_MAX", "99")) +ALERT_EMAIL = os.environ.get("ALERT_EMAIL", "") +SES_SENDER_EMAIL = os.environ.get("SES_SENDER_EMAIL") or ALERT_EMAIL +EC_TZ = ZoneInfo("America/Guayaquil") + +BLOCK_INCIDENT_TYPES = {"BRUTE_FORCE", "PORT_SCAN"} + + +def now_ecuador() -> str: + return datetime.now(EC_TZ).isoformat() + + +def format_dt(dt_str: str) -> str: + if not dt_str or dt_str == "N/A": + return "N/A" + try: + dt = datetime.fromisoformat(dt_str) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=EC_TZ) + else: + dt = dt.astimezone(EC_TZ) + return dt.strftime("%Y-%m-%d %H:%M:%S (America/Guayaquil)") + except Exception: + return dt_str + + +def generate_html_card(title: str, subtitle: str, badge_text: str, badge_type: str, sections: dict, callout_label: str, callout_text: str, footer_text: str) -> str: + color_map = { + "CRITICAL": {"header": "#B71C1C", "badge_bg": "#FFEBEE", "badge_text": "#B71C1C", "border": "#EF5350"}, + "HIGH": {"header": "#E65100", "badge_bg": "#FFF3E0", "badge_text": "#E65100", "border": "#FF9800"}, + "MEDIUM": {"header": "#F57F17", "badge_bg": "#FFFDE7", "badge_text": "#F57F17", "border": "#FFEE58"}, + "LOW": {"header": "#0277BD", "badge_bg": "#E1F5FE", "badge_text": "#0277BD", "border": "#29B6F6"}, + "BLOCKED": {"header": "#B71C1C", "badge_bg": "#FFEBEE", "badge_text": "#B71C1C", "border": "#EF5350"}, + "CONTAINED": {"header": "#0D47A1", "badge_bg": "#E3F2FD", "badge_text": "#0D47A1", "border": "#42A5F5"}, + } + c = color_map.get(badge_type.upper(), {"header": "#1E293B", "badge_bg": "#F1F5F9", "badge_text": "#1E293B", "border": "#94A3B8"}) + + sections_html = "" + for sec_title, kvs in sections.items(): + rows = "" + for k, v in kvs: + rows += f""" + + {html.escape(str(k))} + {html.escape(str(v))} + """ + sections_html += f""" +
+
{html.escape(sec_title)}
+ + {rows} +
+
""" + + callout_html = "" + if callout_text: + callout_html = f""" +
+
{html.escape(callout_label)}
+
+ {html.escape(callout_text)} +
+
""" + + return f""" + + + +
+
+
{html.escape(subtitle)}
+
{html.escape(title)}
+
+
+
+ {html.escape(badge_text)} +
+ {sections_html} + {callout_html} +
+
+ {html.escape(footer_text)} +
+
+ +""" + + +def format_mitigation_html(entry: dict, enforcement: dict, key: str) -> str: + status = entry.get("status", "BLOCKED") + incident_type = entry.get("incident_type", "INCIDENT") + ip_value = entry.get("sourceIPAddress", "N/A") + timestamp = format_dt(entry.get("timestamp", "")) + nacl_id = enforcement.get("network_acl_id", "N/A") + rule_num = enforcement.get("rule_number", "N/A") + + return generate_html_card( + title="[MITIGACION DE SEGURIDAD AWS]", + subtitle="Network ACL Automated Containment", + badge_text=f"ACCION: {status}", + badge_type="BLOCKED" if status == "BLOCKED" else "HIGH", + sections={ + "INFORMACION GENERAL": [ + ("Estado", status), + ("Playbook", "block-ip"), + ("Tipo de Incidente", incident_type), + ("ID de Incidente", entry.get("incident_id", "N/A")), + ], + "CONTENCION APLICADA": [ + ("IP Bloqueada", f"{ip_value}/32"), + ("Network ACL", nacl_id), + ("Regla Inbound", f"#{rule_num} (DENY All Traffic)"), + ("Enforcement", "Bloqueo perimetral a nivel de subred en VPC"), + ], + "TRAZABILIDAD": [ + ("Hora Mitigacion", timestamp), + ("Evidencia S3", key), + ] + }, + callout_label="DETALLES DE MITIGACION", + callout_text=f"Trafico de entrada proveniente de la IP atacante {ip_value} bloqueado permanentemente mediante regla DENY #{rule_num} en la Network ACL {nacl_id}.", + footer_text="AWS Automated Incident Response System | Tesis IR" + ) + + +def send_ses_email(subject: str, html_body: str, plain_body: str) -> None: + if not ALERT_EMAIL: + return + sender = SES_SENDER_EMAIL or ALERT_EMAIL + try: + ses.send_email( + Source=f"AWS Security SOC <{sender}>", + Destination={"ToAddresses": [ALERT_EMAIL]}, + Message={ + "Subject": {"Data": subject, "Charset": "UTF-8"}, + "Body": { + "Html": {"Data": html_body, "Charset": "UTF-8"}, + "Text": {"Data": plain_body, "Charset": "UTF-8"}, + } + } + ) + print(f"[SES] Correo HTML de mitigacion enviado a {ALERT_EMAIL} desde {sender}") + except Exception as exc: + print(f"[SES] Envio SES no disponible ({exc}). Se mantiene envio via SNS.") + + +def valid_public_ip(ip_value: str) -> bool: + try: + ip = ipaddress.ip_address(ip_value) + except ValueError: + return False + return not ( + ip.is_private or ip.is_loopback or ip.is_multicast + or ip.is_unspecified or ip.is_reserved + ) + + +def next_rule_number(nacl_id: str) -> int: + response = ec2.describe_network_acls(NetworkAclIds=[nacl_id]) + used = set() + for entry in response.get("NetworkAcls", [{}])[0].get("Entries", []): + if not entry.get("Egress", False): + used.add(entry.get("RuleNumber")) + for number in range(RULE_MIN, RULE_MAX + 1): + if number not in used: + return number + raise RuntimeError("No quedan numeros de regla libres para reglas DENY de mitigacion.") + + +def block_ip(ip_value: str) -> dict: + cidr = f"{ip_value}/32" + response = ec2.describe_network_acls(NetworkAclIds=[TARGET_NACL_ID]) + entries = response.get("NetworkAcls", [{}])[0].get("Entries", []) + + for entry in entries: + if (not entry.get("Egress", False) + and entry.get("CidrBlock") == cidr + and entry.get("RuleAction") == "deny"): + return { + "enforced": True, + "already_present": True, + "network_acl_id": TARGET_NACL_ID, + "rule_number": entry.get("RuleNumber"), + "cidr": cidr, + } + + rule_number = next_rule_number(TARGET_NACL_ID) + ec2.create_network_acl_entry( + NetworkAclId=TARGET_NACL_ID, + RuleNumber=rule_number, + Protocol="-1", + RuleAction="deny", + Egress=False, + CidrBlock=cidr, + ) + print(f"[block-ip] NACL {TARGET_NACL_ID}: regla DENY #{rule_number} creada para {cidr}") + return { + "enforced": True, + "already_present": False, + "network_acl_id": TARGET_NACL_ID, + "rule_number": rule_number, + "cidr": cidr, + } + + +def load_blocklist() -> list: + try: + obj = s3.get_object(Bucket=EVIDENCE_BUCKET, Key=f"{RESPONSE_PREFIX}/blocked-ips.json") + return json.loads(obj["Body"].read()) + except Exception: + return [] + + +def save_blocklist(blocklist: list) -> None: + s3.put_object( + Bucket=EVIDENCE_BUCKET, + Key=f"{RESPONSE_PREFIX}/blocked-ips.json", + Body=json.dumps(blocklist, indent=2, ensure_ascii=False).encode("utf-8"), + ContentType="application/json", + ) + + +def lambda_handler(event, context): + results = [] + + for record in event.get("Records", []): + try: + body = json.loads(record.get("body", "{}")) + except json.JSONDecodeError as exc: + results.append({"status": "skipped", "reason": f"invalid_json: {exc}"}) + continue + + incident_type = body.get("incident_type", "UNKNOWN") + + if incident_type not in BLOCK_INCIDENT_TYPES: + print(f"[block-ip] Tipo {incident_type} no requiere bloqueo de IP. Omitiendo.") + results.append({"status": "skipped", "reason": f"not_in_block_list:{incident_type}"}) + continue + + ip_value = body.get("sourceIPAddress", "") + timestamp = now_ecuador() + + # ── Aplicar bloqueo real en NACL ────────────────────────────────── + if not valid_public_ip(ip_value): + enforcement = { + "enforced": False, + "reason": "invalid_or_non_public_ip", + "ip": ip_value, + } + status = "SKIPPED" + print(f"[block-ip] IP invalida o privada: {ip_value}. Omitiendo bloqueo.") + else: + try: + enforcement = block_ip(ip_value) + status = "BLOCKED" if enforcement.get("enforced") else "BLOCK_FAILED" + except Exception as exc: + enforcement = {"enforced": False, "error": str(exc), "ip": ip_value} + status = "BLOCK_FAILED" + print(f"[block-ip] ERROR aplicando bloqueo para {ip_value}: {exc}") + + # ── Construir registro de evidencia ──────────────────────────────── + entry = { + "playbook": "block-ip", + "incident_type": incident_type, + "severity": body.get("severity", "MEDIUM"), + "sourceIPAddress": ip_value, + "affectedResource": body.get("affectedResource", "unknown"), + "affected_service": body.get("affected_service", + body.get("affectedService", "unknown")), + "asset_name": body.get("asset_name", body.get("assetName", "unknown")), + "severity_basis": body.get("severity_basis", + f"Umbral de {incident_type} alcanzado."), + "status": status, + "enforcement": enforcement, + "timestamp": timestamp, + "timezone": "America/Guayaquil", + "incident_id": body.get("incident_id", ""), + } + + if incident_type == "PORT_SCAN": + entry["scanned_ports_count"] = body.get("scanned_ports_count", + body.get("event_count", 0)) + entry["rejected_connections"] = body.get("rejected_connections", 0) + elif incident_type == "BRUTE_FORCE": + entry["failed_attempts"] = body.get("failed_attempts", + body.get("event_count", 0)) + + # ── Actualizar lista de IPs bloqueadas ──────────────────────────── + blocklist = load_blocklist() + if not any(item.get("sourceIPAddress") == ip_value for item in blocklist): + blocklist.append(entry) + save_blocklist(blocklist) + + # ── Guardar evidencia individual por incidente ───────────────────── + key = f"{RESPONSE_PREFIX}/{body.get('incident_id') or uuid.uuid4().hex}.json" + s3.put_object( + Bucket=EVIDENCE_BUCKET, + Key=key, + Body=json.dumps(entry, indent=2, ensure_ascii=False).encode("utf-8"), + ContentType="application/json", + ) + + # ── Generar reportes ─────────────────────────────────────────────── + subject = f"[{entry['severity']}] Mitigacion: IP {ip_value} {status} en NACL" + formatted_time = format_dt(timestamp) + nacl_id = enforcement.get('network_acl_id', 'N/A') + rule_num = enforcement.get('rule_number', 'N/A') + + mitigation_plain = "\n".join([ + "=" * 60, + f"[MITIGACION DE SEGURIDAD AWS] - ACCION: {status}", + "=" * 60, + "INFORMACION GENERAL:", + f" Estado : {status}", + f" Playbook : block-ip", + f" Tipo de Incidente : {incident_type}", + f" ID de Incidente : {entry['incident_id']}", + "", + "CONTENCION APLICADA:", + f" IP Bloqueada : {ip_value}/32", + f" Network ACL : {nacl_id}", + f" Regla Inbound : #{rule_num} (DENY All Traffic)", + " Enforcement : Bloqueo perimetral a nivel de subred en VPC", + "", + "TRAZABILIDAD:", + f" Hora Mitigacion : {formatted_time}", + f" Evidencia S3 : {key}", + "=" * 60, + ]) + mitigation_html = format_mitigation_html(entry, enforcement, key) + + # ── Envio directo de correo HTML via SES ─────────────────────────── + send_ses_email(subject, mitigation_html, mitigation_plain) + + # ── Publicar reporte en SNS ──────────────────────────────────────── + sns.publish( + TopicArn=SNS_ARN, + Subject=subject[:100], + Message=mitigation_plain, + ) + + print(f"[block-ip] {incident_type} → {status} para {ip_value}. " + f"NACL rule={enforcement.get('rule_number')}. evidence={key}") + results.append({ + "status": "success", + "action": status, + "evidence_key": key, + "details": enforcement, + }) + + return { + "status": "success", + "processed": len(results), + "results": results, + "timestamp": now_ecuador(), + } diff --git a/terraform-tesis-ir-secure-portal/playbooks/notify_alert/handler.py b/terraform-tesis-ir-secure-portal/playbooks/notify_alert/handler.py new file mode 100644 index 0000000..e19b496 --- /dev/null +++ b/terraform-tesis-ir-secure-portal/playbooks/notify_alert/handler.py @@ -0,0 +1,293 @@ +""" +Playbook: notify-alert +Recibe incidentes desde una cola SQS dedicada, genera un reporte profesional +de seguridad para el SOC (formato tarjeta HTML con colores diferenciados y texto plano normalizado) +y lo entrega via SES a Gmail y via SNS a Telegram. Tambien registra evidencia en S3. +""" +import html +import json +import os +import uuid +from datetime import datetime +from zoneinfo import ZoneInfo + +import boto3 + +sns = boto3.client("sns") +s3 = boto3.client("s3") +ses = boto3.client("ses") + +SNS_ARN = os.environ["SNS_ALERTS_ARN"] +EVIDENCE_BUCKET = os.environ["EVIDENCE_BUCKET"] +RESPONSE_PREFIX = os.environ.get("RESPONSE_PREFIX", "responses/notify-alert") +ALERT_EMAIL = os.environ.get("ALERT_EMAIL", "") +SES_SENDER_EMAIL = os.environ.get("SES_SENDER_EMAIL") or ALERT_EMAIL +EC_TZ = ZoneInfo("America/Guayaquil") + +SUPPORTED_INCIDENT_TYPES = { + "BRUTE_FORCE", + "PORT_SCAN", + "PRIVILEGE_ESCALATION", + "CREDENTIAL_LEAK", + "EXFILTRATION", +} + + +def now_ecuador() -> str: + return datetime.now(EC_TZ).isoformat() + + +def format_dt(dt_str: str) -> str: + if not dt_str or dt_str == "N/A": + return "N/A" + try: + dt = datetime.fromisoformat(dt_str) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=EC_TZ) + else: + dt = dt.astimezone(EC_TZ) + return dt.strftime("%Y-%m-%d %H:%M:%S (America/Guayaquil)") + except Exception: + return dt_str + + +def generate_html_card(title: str, subtitle: str, badge_text: str, badge_type: str, sections: dict, callout_label: str, callout_text: str, footer_text: str) -> str: + color_map = { + "CRITICAL": {"header": "#B71C1C", "badge_bg": "#FFEBEE", "badge_text": "#B71C1C", "border": "#EF5350"}, + "HIGH": {"header": "#E65100", "badge_bg": "#FFF3E0", "badge_text": "#E65100", "border": "#FF9800"}, + "MEDIUM": {"header": "#F57F17", "badge_bg": "#FFFDE7", "badge_text": "#F57F17", "border": "#FFEE58"}, + "LOW": {"header": "#0277BD", "badge_bg": "#E1F5FE", "badge_text": "#0277BD", "border": "#29B6F6"}, + "BLOCKED": {"header": "#B71C1C", "badge_bg": "#FFEBEE", "badge_text": "#B71C1C", "border": "#EF5350"}, + "CONTAINED": {"header": "#0D47A1", "badge_bg": "#E3F2FD", "badge_text": "#0D47A1", "border": "#42A5F5"}, + } + c = color_map.get(badge_type.upper(), {"header": "#1E293B", "badge_bg": "#F1F5F9", "badge_text": "#1E293B", "border": "#94A3B8"}) + + sections_html = "" + for sec_title, kvs in sections.items(): + rows = "" + for k, v in kvs: + rows += f""" + + {html.escape(str(k))} + {html.escape(str(v))} + """ + sections_html += f""" +
+
{html.escape(sec_title)}
+ + {rows} +
+
""" + + callout_html = "" + if callout_text: + callout_html = f""" +
+
{html.escape(callout_label)}
+
+ {html.escape(callout_text)} +
+
""" + + return f""" + + + +
+
+
{html.escape(subtitle)}
+
{html.escape(title)}
+
+
+
+ {html.escape(badge_text)} +
+ {sections_html} + {callout_html} +
+
+ {html.escape(footer_text)} +
+
+ +""" + + +def format_incident_report(alert: dict) -> str: + """Genera un reporte profesional de seguridad (SOC) estructurado y normalizado en texto plano.""" + incident_type = alert.get("incident_type", "NO_ESPECIFICADO") + severity = alert.get("severity", "MEDIUM") + status = alert.get("status", "NOTIFICADO") + incident_id = alert.get("incident_id", "N/A") + source_ip = alert.get("sourceIPAddress", "N/A") + resource = alert.get("affectedResource", "N/A") + service = alert.get("affected_service", "N/A") + asset = alert.get("asset_name", "N/A") + basis = alert.get("severity_basis", "N/A") + detected_at = format_dt(alert.get("detectedAt", "N/A")) + responded_at = format_dt(alert.get("respondedAt", "N/A")) + s3_key = alert.get("s3_log_key", "N/A") + + lines = [ + "=" * 60, + "[ALERTA DE SEGURIDAD AWS] - SOC INCIDENT RESPONSE", + "=" * 60, + "INFORMACION GENERAL:", + f" Severidad : {severity}", + f" Tipo de Incidente : {incident_type}", + f" ID de Incidente : {incident_id}", + f" Estado : {status}", + f" Playbook : notify-alert", + "", + "RECURSO Y ORIGEN:", + f" IP Origen : {source_ip}", + f" Recurso Afectado : {resource}", + f" Servicio Afectado : {service}", + f" Activo Objetivo : {asset}", + "", + "CRITERIO Y DIAGNOSTICO:", + f" Criterio / Motivo : {basis}", + f" Hora Deteccion : {detected_at}", + f" Hora Respuesta : {responded_at}", + f" Evidencia S3 : {s3_key}", + "=" * 60, + ] + return "\n".join(lines) + + +def format_incident_html(alert: dict) -> str: + """Genera la tarjeta visual HTML con colores diferenciados según la severidad.""" + incident_type = alert.get("incident_type", "NO_ESPECIFICADO") + severity = alert.get("severity", "MEDIUM") + status = alert.get("status", "NOTIFICADO") + incident_id = alert.get("incident_id", "N/A") + source_ip = alert.get("sourceIPAddress", "N/A") + resource = alert.get("affectedResource", "N/A") + service = alert.get("affected_service", "N/A") + asset = alert.get("asset_name", "N/A") + basis = alert.get("severity_basis", "N/A") + detected_at = format_dt(alert.get("detectedAt", "N/A")) + responded_at = format_dt(alert.get("respondedAt", "N/A")) + s3_key = alert.get("s3_log_key", "N/A") + + return generate_html_card( + title="[ALERTA DE SEGURIDAD AWS]", + subtitle="SOC Automated Incident Response", + badge_text=f"SEVERIDAD: {severity}", + badge_type=severity, + sections={ + "INFORMACION GENERAL": [ + ("Tipo de Incidente", incident_type), + ("ID de Incidente", incident_id), + ("Estado", status), + ("Playbook", "notify-alert"), + ], + "RECURSO Y ORIGEN": [ + ("IP Origen", source_ip), + ("Recurso Afectado", resource), + ("Servicio Afectado", service), + ("Activo Objetivo", asset), + ], + "TRAZABILIDAD": [ + ("Hora Deteccion", detected_at), + ("Hora Respuesta", responded_at), + ("Evidencia S3", s3_key), + ] + }, + callout_label="CRITERIO Y DIAGNOSTICO", + callout_text=basis, + footer_text="AWS Automated Incident Response System | Tesis IR" + ) + + +def send_ses_email(subject: str, html_body: str, plain_body: str) -> None: + if not ALERT_EMAIL: + return + sender = SES_SENDER_EMAIL or ALERT_EMAIL + try: + ses.send_email( + Source=f"AWS Security SOC <{sender}>", + Destination={"ToAddresses": [ALERT_EMAIL]}, + Message={ + "Subject": {"Data": subject, "Charset": "UTF-8"}, + "Body": { + "Html": {"Data": html_body, "Charset": "UTF-8"}, + "Text": {"Data": plain_body, "Charset": "UTF-8"}, + } + } + ) + print(f"[SES] Correo HTML enviado a {ALERT_EMAIL} desde {sender}") + except Exception as exc: + print(f"[SES] Envio SES no disponible ({exc}). Se mantiene envio via SNS.") + + +def lambda_handler(event, context): + results = [] + + for record in event.get("Records", []): + try: + body = json.loads(record.get("body", "{}")) + except json.JSONDecodeError as exc: + results.append({"status": "skipped", "reason": f"invalid_json: {exc}"}) + continue + + incident_type = body.get("incident_type", "UNKNOWN") + if incident_type not in SUPPORTED_INCIDENT_TYPES: + results.append({"status": "skipped", "reason": f"unsupported_type:{incident_type}"}) + continue + + # ── Construir alerta estructurada ────────────────────────────────── + alert = { + "alert_type": "SECURITY_INCIDENT", + "incident_type": incident_type, + "severity": body.get("severity", "MEDIUM"), + "sourceIPAddress": body.get("sourceIPAddress", "unknown"), + "affectedResource": body.get("affectedResource", "unknown"), + "affected_service": body.get("affected_service", + body.get("affectedService", "unknown")), + "asset_name": body.get("asset_name", + body.get("assetName", "unknown")), + "severity_basis": body.get("severity_basis", + f"Umbral de {incident_type} alcanzado."), + "detectedAt": body.get("timestamp", now_ecuador()), + "respondedAt": now_ecuador(), + "timezone": "America/Guayaquil", + "playbook": "notify-alert", + "status": "NOTIFIED", + "s3_log_key": body.get("s3_log_key", ""), + "incident_id": body.get("incident_id", ""), + } + + # ── Guardar evidencia JSON en S3 ─────────────────────────────────── + key = f"{RESPONSE_PREFIX}/{body.get('incident_id') or uuid.uuid4().hex}.json" + s3.put_object( + Bucket=EVIDENCE_BUCKET, + Key=key, + Body=json.dumps(alert, indent=2, ensure_ascii=False).encode("utf-8"), + ContentType="application/json", + ) + + # ── Generar reportes ─────────────────────────────────────────────── + subject = f"[{alert['severity']}] Incidente: {incident_type} ({alert['affectedResource']})" + report_text = format_incident_report(alert) + report_html = format_incident_html(alert) + + # ── Envio directo de correo HTML via SES (si esta disponible) ────── + send_ses_email(subject, report_html, report_text) + + # ── Publicar reporte en SNS (para Telegram y subscriptores SNS) ──── + sns.publish( + TopicArn=SNS_ARN, + Subject=subject[:100], + Message=report_text, + ) + + print(f"[notify-alert] {incident_type} notificado profesionalmente. evidence_key={key}") + results.append({"status": "success", "action": "sns_published", "evidence_key": key}) + + return { + "status": "success", + "processed": len(results), + "results": results, + "timestamp": now_ecuador(), + } diff --git a/terraform-tesis-ir-secure-portal/playbooks/revoke_credentials/handler.py b/terraform-tesis-ir-secure-portal/playbooks/revoke_credentials/handler.py new file mode 100644 index 0000000..f02bf14 --- /dev/null +++ b/terraform-tesis-ir-secure-portal/playbooks/revoke_credentials/handler.py @@ -0,0 +1,354 @@ +""" +Playbook: revoke-credentials +Revoca (desactiva) las access keys de un usuario IAM comprometido, +adjunta una politica de denegacion explicita (DenyAll) para bloqueo inmediato, +registra evidencia en S3 y notifica via HTML Card (SES) y SNS (Telegram). +""" +import html +import json +import os +import uuid +from datetime import datetime +from zoneinfo import ZoneInfo + +import boto3 + +s3 = boto3.client("s3") +sns = boto3.client("sns") +iam = boto3.client("iam") +ses = boto3.client("ses") + +EVIDENCE_BUCKET = os.environ["EVIDENCE_BUCKET"] +SNS_ARN = os.environ["SNS_ALERTS_ARN"] +RESPONSE_PREFIX = os.environ.get("RESPONSE_PREFIX", "responses/revoke-credentials") +ALERT_EMAIL = os.environ.get("ALERT_EMAIL", "") +SES_SENDER_EMAIL = os.environ.get("SES_SENDER_EMAIL") or ALERT_EMAIL +EC_TZ = ZoneInfo("America/Guayaquil") + +DENY_ALL_POLICY = json.dumps({ + "Version": "2012-10-17", + "Statement": [{ + "Effect": "Deny", + "Action": "*", + "Resource": "*" + }] +}) + + +def now_ecuador() -> str: + return datetime.now(EC_TZ).isoformat() + + +def format_dt(dt_str: str) -> str: + if not dt_str or dt_str == "N/A": + return "N/A" + try: + dt = datetime.fromisoformat(dt_str) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=EC_TZ) + else: + dt = dt.astimezone(EC_TZ) + return dt.strftime("%Y-%m-%d %H:%M:%S (America/Guayaquil)") + except Exception: + return dt_str + + +def generate_html_card(title: str, subtitle: str, badge_text: str, badge_type: str, sections: dict, callout_label: str, callout_text: str, footer_text: str) -> str: + color_map = { + "CRITICAL": {"header": "#B71C1C", "badge_bg": "#FFEBEE", "badge_text": "#B71C1C", "border": "#EF5350"}, + "HIGH": {"header": "#E65100", "badge_bg": "#FFF3E0", "badge_text": "#E65100", "border": "#FF9800"}, + "MEDIUM": {"header": "#F57F17", "badge_bg": "#FFFDE7", "badge_text": "#F57F17", "border": "#FFEE58"}, + "LOW": {"header": "#0277BD", "badge_bg": "#E1F5FE", "badge_text": "#0277BD", "border": "#29B6F6"}, + "BLOCKED": {"header": "#B71C1C", "badge_bg": "#FFEBEE", "badge_text": "#B71C1C", "border": "#EF5350"}, + "CONTAINED": {"header": "#0D47A1", "badge_bg": "#E3F2FD", "badge_text": "#0D47A1", "border": "#42A5F5"}, + } + c = color_map.get(badge_type.upper(), {"header": "#1E293B", "badge_bg": "#F1F5F9", "badge_text": "#1E293B", "border": "#94A3B8"}) + + sections_html = "" + for sec_title, kvs in sections.items(): + rows = "" + for k, v in kvs: + rows += f""" + + {html.escape(str(k))} + {html.escape(str(v))} + """ + sections_html += f""" +
+
{html.escape(sec_title)}
+ + {rows} +
+
""" + + callout_html = "" + if callout_text: + callout_html = f""" +
+
{html.escape(callout_label)}
+
+ {html.escape(callout_text)} +
+
""" + + return f""" + + + +
+
+
{html.escape(subtitle)}
+
{html.escape(title)}
+
+
+
+ {html.escape(badge_text)} +
+ {sections_html} + {callout_html} +
+
+ {html.escape(footer_text)} +
+
+ +""" + + +def format_mitigation_html(entry: dict, username: str, actions_taken: list, enforcement: dict, key: str) -> str: + status = entry.get("status", "CONTAINED") + incident_type = entry.get("incident_type", "INCIDENT") + timestamp = format_dt(entry.get("timestamp", "")) + actions_str = ", ".join(actions_taken) if actions_taken else "Ninguna acción registrada" + deny_status = "EmergencyDenyAll adjuntada (Bloqueo Total)" if enforcement.get("deny_all_applied") else "No aplicada" + + return generate_html_card( + title="[MITIGACION DE SEGURIDAD AWS]", + subtitle="IAM Automated Credential Revocation", + badge_text=f"ACCION: {status}", + badge_type="CONTAINED" if status == "CONTAINED" else "CRITICAL", + sections={ + "INFORMACION GENERAL": [ + ("Estado", status), + ("Playbook", "revoke-credentials"), + ("Tipo de Incidente", incident_type), + ("ID de Incidente", entry.get("incident_id", "N/A")), + ], + "CONTENCION APLICADA": [ + ("Usuario IAM", username), + ("Acciones Tomadas", actions_str), + ("Politica DenyAll", deny_status), + ("Enforcement", "Desactivacion inmediata de credenciales y revocacion de permisos"), + ], + "TRAZABILIDAD": [ + ("Hora Mitigacion", timestamp), + ("Evidencia S3", key), + ] + }, + callout_label="DETALLES DE MITIGACION", + callout_text=f"Credenciales de acceso para el usuario IAM '{username}' revocadas. Llaves desactivadas ({enforcement.get('keys_deactivated', 0)}) y politica inline EmergencyDenyAll adjuntada.", + footer_text="AWS Automated Incident Response System | Tesis IR" + ) + + +def send_ses_email(subject: str, html_body: str, plain_body: str) -> None: + if not ALERT_EMAIL: + return + sender = SES_SENDER_EMAIL or ALERT_EMAIL + try: + ses.send_email( + Source=f"AWS Security SOC <{sender}>", + Destination={"ToAddresses": [ALERT_EMAIL]}, + Message={ + "Subject": {"Data": subject, "Charset": "UTF-8"}, + "Body": { + "Html": {"Data": html_body, "Charset": "UTF-8"}, + "Text": {"Data": plain_body, "Charset": "UTF-8"}, + } + } + ) + print(f"[SES] Correo HTML de mitigacion enviado a {ALERT_EMAIL} desde {sender}") + except Exception as exc: + print(f"[SES] Envio SES no disponible ({exc}). Se mantiene envio via SNS.") + + +def load_revoke_log() -> list: + try: + obj = s3.get_object(Bucket=EVIDENCE_BUCKET, Key=f"{RESPONSE_PREFIX}/revoked-credentials.json") + return json.loads(obj["Body"].read()) + except Exception: + return [] + + +def save_revoke_log(revoke_log: list) -> None: + s3.put_object( + Bucket=EVIDENCE_BUCKET, + Key=f"{RESPONSE_PREFIX}/revoked-credentials.json", + Body=json.dumps(revoke_log, indent=2, ensure_ascii=False).encode("utf-8"), + ContentType="application/json", + ) + + +def lambda_handler(event, context): + results = [] + + for record in event.get("Records", []): + try: + body = json.loads(record.get("body", "{}")) + except json.JSONDecodeError as exc: + results.append({"status": "skipped", "reason": f"invalid_json: {exc}"}) + continue + + incident_type = body.get("incident_type", "UNKNOWN") + if incident_type not in {"PRIVILEGE_ESCALATION", "CREDENTIAL_LEAK"}: + print(f"[revoke-credentials] Tipo {incident_type} no requiere revocacion. Omitiendo.") + results.append({"status": "skipped", "reason": f"not_in_revoke_list:{incident_type}"}) + continue + + affected_resource = body.get("affectedResource", "") + username = affected_resource.replace("iam:user/", "") if affected_resource.startswith("iam:user/") else affected_resource + source_ip = body.get("sourceIPAddress", "0.0.0.0") + timestamp = now_ecuador() + incident_id = body.get("incident_id", "") + + if not username or username == "unknown": + print(f"[revoke-credentials] affectedResource invalido: {affected_resource}. Omitiendo.") + results.append({"status": "skipped", "reason": f"invalid_affected_resource:{affected_resource}"}) + continue + + actions_taken = [] + keys_revoked = [] + enforcement = {} + + # ── 1. CUMPLIMIENTO REAL: desactivar todas las access keys ─────────── + try: + keys = iam.list_access_keys(UserName=username).get("AccessKeyMetadata", []) + for key in keys: + kid = key["AccessKeyId"] + if key.get("Status") == "Active": + iam.update_access_key( + UserName=username, + AccessKeyId=kid, + Status="Inactive" + ) + keys_revoked.append(kid) + actions_taken.append(f"AccessKey desactivada: {kid}") + print(f"[revoke-credentials] Desactivada key {kid} de {username}") + else: + actions_taken.append(f"AccessKey ya inactiva: {kid}") + enforcement["keys_found"] = len(keys) + enforcement["keys_deactivated"] = len(keys_revoked) + enforcement["key_ids"] = keys_revoked + except Exception as e: + enforcement["keys_error"] = str(e) + print(f"[revoke-credentials] Error desactivando keys de {username}: {e}") + + # ── 2. CUMPLIMIENTO ADICIONAL: política DenyAll (bloqueo total) ────── + try: + iam.put_user_policy( + UserName=username, + PolicyName="EmergencyDenyAll", + PolicyDocument=DENY_ALL_POLICY + ) + actions_taken.append("Politica EmergencyDenyAll adjuntada") + enforcement["deny_all_applied"] = True + print(f"[revoke-credentials] EmergencyDenyAll aplicado a {username}") + except Exception as e: + enforcement["deny_all_error"] = str(e) + enforcement["deny_all_applied"] = False + print(f"[revoke-credentials] Error aplicando DenyAll a {username}: {e}") + + # Status final + status = "CONTAINED" if (len(keys_revoked) > 0 or enforcement.get("deny_all_applied")) else "NO_ACTION_TAKEN" + + # ── 3. Construir registro de evidencia ─────────────────────────────── + entry = { + "playbook": "revoke-credentials", + "incident_type": incident_type, + "severity": body.get("severity", "CRITICAL"), + "sourceIPAddress": source_ip, + "affectedResource": affected_resource, + "status": status, + "enforcement": enforcement, + "actions_taken": actions_taken, + "timestamp": timestamp, + "timezone": "America/Guayaquil", + "incident_id": incident_id, + } + + # ── 4. Actualizar lista acumulativa ─────────────────────────────────── + revoke_log = load_revoke_log() + if not any(item.get("username") == username for item in revoke_log): + revoke_log.append({ + "username": username, + "revoked_at": timestamp, + "reason": incident_type, + "severity": body.get("severity", "CRITICAL"), + "sourceIPAddress": source_ip, + "enforcement": enforcement, + "actions_taken": actions_taken, + }) + save_revoke_log(revoke_log) + + # ── 5. Guardar evidencia individual por incidente ───────────────────── + key = f"{RESPONSE_PREFIX}/{incident_id or uuid.uuid4().hex}.json" + s3.put_object( + Bucket=EVIDENCE_BUCKET, + Key=key, + Body=json.dumps(entry, indent=2, ensure_ascii=False).encode("utf-8"), + ContentType="application/json", + ) + + # ── 6. Generar reportes ────────────────────────────────────────────── + subject = f"[{entry['severity']}] Mitigacion: Credenciales {username} {status}" + formatted_time = format_dt(timestamp) + actions_str = ", ".join(actions_taken) if actions_taken else "Ninguna acción registrada" + deny_status = "EmergencyDenyAll adjuntada (Bloqueo Total)" if enforcement.get('deny_all_applied') else "No aplicada" + + mitigation_plain = "\n".join([ + "=" * 60, + f"[MITIGACION DE SEGURIDAD AWS] - ACCION: {status}", + "=" * 60, + "INFORMACION GENERAL:", + f" Estado : {status}", + f" Playbook : revoke-credentials", + f" Tipo de Incidente : {incident_type}", + f" ID de Incidente : {incident_id}", + "", + "CONTENCION APLICADA:", + f" Usuario IAM : {username}", + f" Acciones Tomadas : {actions_str}", + f" Politica DenyAll : {deny_status}", + " Enforcement : Desactivacion inmediata de credenciales y revocacion de permisos", + "", + "TRAZABILIDAD:", + f" Hora Mitigacion : {formatted_time}", + f" Evidencia S3 : {key}", + "=" * 60, + ]) + mitigation_html = format_mitigation_html(entry, username, actions_taken, enforcement, key) + + # ── Envio directo de correo HTML via SES ─────────────────────────── + send_ses_email(subject, mitigation_html, mitigation_plain) + + # ── Publicar reporte en SNS ──────────────────────────────────────── + sns.publish( + TopicArn=SNS_ARN, + Subject=subject[:100], + Message=mitigation_plain, + ) + + print(f"[revoke-credentials] {incident_type} → {status} para {username}. evidence={key}") + results.append({ + "status": "success", + "action": status, + "evidence_key": key, + "details": enforcement, + }) + + return { + "status": "success", + "processed": len(results), + "results": results, + "timestamp": now_ecuador(), + } diff --git a/terraform-tesis-ir-secure-portal/playbooks/telegram_notifier/card_image.py b/terraform-tesis-ir-secure-portal/playbooks/telegram_notifier/card_image.py new file mode 100644 index 0000000..41f0eaa --- /dev/null +++ b/terraform-tesis-ir-secure-portal/playbooks/telegram_notifier/card_image.py @@ -0,0 +1,318 @@ +""" +Generador gráfico nativo de tarjetas de seguridad en formato PNG (Pure Python). +Dibuja tarjetas visuales con cabeceras de color según severidad/acción, +insignias (badges), tablas estructuradas de información, bloques de diagnóstico y pie de página. +No requiere dependencias externas ni bibliotecas C, funciona 100% en AWS Lambda. +""" +import io +import struct +import zlib + +# Fuente de mapa de bits 5x7 estándar para caracteres ASCII imprimibles (32 a 126) +FONT_5x7 = { + ' ': [0x00, 0x00, 0x00, 0x00, 0x00], + '!': [0x00, 0x00, 0x5F, 0x00, 0x00], + '"': [0x00, 0x07, 0x00, 0x07, 0x00], + '#': [0x14, 0x7F, 0x14, 0x7F, 0x14], + '$': [0x24, 0x2A, 0x7F, 0x2A, 0x12], + '%': [0x23, 0x13, 0x08, 0x64, 0x62], + '&': [0x36, 0x49, 0x55, 0x22, 0x50], + "'": [0x00, 0x05, 0x03, 0x00, 0x00], + '(': [0x00, 0x1C, 0x22, 0x41, 0x00], + ')': [0x00, 0x41, 0x22, 0x1C, 0x00], + '*': [0x14, 0x08, 0x3E, 0x08, 0x14], + '+': [0x08, 0x08, 0x3E, 0x08, 0x08], + ',': [0x00, 0x50, 0x30, 0x00, 0x00], + '-': [0x08, 0x08, 0x08, 0x08, 0x08], + '.': [0x00, 0x60, 0x60, 0x00, 0x00], + '/': [0x20, 0x10, 0x08, 0x04, 0x02], + '0': [0x3E, 0x51, 0x49, 0x45, 0x3E], + '1': [0x00, 0x42, 0x7F, 0x40, 0x00], + '2': [0x42, 0x61, 0x51, 0x49, 0x46], + '3': [0x21, 0x41, 0x45, 0x4B, 0x31], + '4': [0x18, 0x14, 0x12, 0x7F, 0x10], + '5': [0x27, 0x45, 0x45, 0x45, 0x39], + '6': [0x3C, 0x4A, 0x49, 0x49, 0x30], + '7': [0x01, 0x71, 0x09, 0x05, 0x03], + '8': [0x36, 0x49, 0x49, 0x49, 0x36], + '9': [0x06, 0x49, 0x49, 0x29, 0x1E], + ':': [0x00, 0x36, 0x36, 0x00, 0x00], + ';': [0x00, 0x56, 0x36, 0x00, 0x00], + '<': [0x08, 0x14, 0x22, 0x41, 0x00], + '=': [0x14, 0x14, 0x14, 0x14, 0x14], + '>': [0x00, 0x41, 0x22, 0x14, 0x08], + '?': [0x02, 0x01, 0x51, 0x09, 0x06], + '@': [0x32, 0x49, 0x79, 0x41, 0x3E], + 'A': [0x7E, 0x11, 0x11, 0x11, 0x7E], + 'B': [0x7F, 0x49, 0x49, 0x49, 0x36], + 'C': [0x3E, 0x41, 0x41, 0x41, 0x22], + 'D': [0x7F, 0x41, 0x41, 0x22, 0x1C], + 'E': [0x7F, 0x49, 0x49, 0x49, 0x41], + 'F': [0x7F, 0x09, 0x09, 0x09, 0x01], + 'G': [0x3E, 0x41, 0x49, 0x49, 0x7A], + 'H': [0x7F, 0x08, 0x08, 0x08, 0x7F], + 'I': [0x00, 0x41, 0x7F, 0x41, 0x00], + 'J': [0x20, 0x40, 0x41, 0x3F, 0x01], + 'K': [0x7F, 0x08, 0x14, 0x22, 0x41], + 'L': [0x7F, 0x40, 0x40, 0x40, 0x40], + 'M': [0x7F, 0x02, 0x0C, 0x02, 0x7F], + 'N': [0x7F, 0x04, 0x08, 0x10, 0x7F], + 'O': [0x3E, 0x41, 0x41, 0x41, 0x3E], + 'P': [0x7F, 0x09, 0x09, 0x09, 0x06], + 'Q': [0x3E, 0x41, 0x51, 0x21, 0x5E], + 'R': [0x7F, 0x09, 0x19, 0x29, 0x46], + 'S': [0x46, 0x49, 0x49, 0x49, 0x31], + 'T': [0x01, 0x01, 0x7F, 0x01, 0x01], + 'U': [0x3F, 0x40, 0x40, 0x40, 0x3F], + 'V': [0x1F, 0x20, 0x40, 0x20, 0x1F], + 'W': [0x3F, 0x40, 0x38, 0x40, 0x3F], + 'X': [0x63, 0x14, 0x08, 0x14, 0x63], + 'Y': [0x07, 0x08, 0x70, 0x08, 0x07], + 'Z': [0x61, 0x51, 0x49, 0x45, 0x43], + '[': [0x00, 0x7F, 0x41, 0x41, 0x00], + '\\': [0x02, 0x04, 0x08, 0x10, 0x20], + ']': [0x00, 0x41, 0x41, 0x7F, 0x00], + '^': [0x04, 0x02, 0x01, 0x02, 0x04], + '_': [0x40, 0x40, 0x40, 0x40, 0x40], + '`': [0x00, 0x01, 0x02, 0x04, 0x00], + 'a': [0x20, 0x54, 0x54, 0x54, 0x78], + 'b': [0x7F, 0x48, 0x44, 0x44, 0x38], + 'c': [0x38, 0x44, 0x44, 0x44, 0x20], + 'd': [0x38, 0x44, 0x44, 0x48, 0x7F], + 'e': [0x38, 0x54, 0x54, 0x54, 0x18], + 'f': [0x08, 0x7E, 0x09, 0x01, 0x02], + 'g': [0x0C, 0x52, 0x52, 0x52, 0x3E], + 'h': [0x7F, 0x08, 0x04, 0x04, 0x78], + 'i': [0x00, 0x44, 0x7D, 0x40, 0x00], + 'j': [0x20, 0x40, 0x44, 0x3D, 0x00], + 'k': [0x7F, 0x10, 0x28, 0x44, 0x00], + 'l': [0x00, 0x41, 0x7F, 0x40, 0x00], + 'm': [0x7C, 0x04, 0x18, 0x04, 0x78], + 'n': [0x7C, 0x08, 0x04, 0x04, 0x78], + 'o': [0x38, 0x44, 0x44, 0x44, 0x38], + 'p': [0x7C, 0x14, 0x14, 0x14, 0x08], + 'q': [0x08, 0x14, 0x14, 0x18, 0x7C], + 'r': [0x7C, 0x08, 0x04, 0x04, 0x08], + 's': [0x48, 0x54, 0x54, 0x54, 0x20], + 't': [0x04, 0x3F, 0x44, 0x40, 0x20], + 'u': [0x3C, 0x40, 0x40, 0x20, 0x7C], + 'v': [0x1C, 0x20, 0x40, 0x20, 0x1C], + 'w': [0x3C, 0x40, 0x30, 0x40, 0x3C], + 'x': [0x44, 0x28, 0x10, 0x28, 0x44], + 'y': [0x0C, 0x50, 0x50, 0x50, 0x3C], + 'z': [0x44, 0x64, 0x54, 0x4C, 0x44], + '{': [0x00, 0x08, 0x36, 0x41, 0x00], + '|': [0x00, 0x00, 0x7F, 0x00, 0x00], + '}': [0x00, 0x41, 0x36, 0x08, 0x00], + '~': [0x08, 0x04, 0x08, 0x10, 0x08], +} + + +class Canvas: + def __init__(self, width: int, height: int, bg_color=(244, 246, 248)): + self.width = width + self.height = height + self.bg_color = bg_color + # Buffer de píxeles: lista plana de tuplas (R, G, B) + self.pixels = [bg_color] * (width * height) + + def set_pixel(self, x: int, y: int, color: tuple): + if 0 <= x < self.width and 0 <= y < self.height: + self.pixels[y * self.width + x] = color + + def fill_rect(self, x: int, y: int, w: int, h: int, color: tuple): + x1 = max(0, x) + y1 = max(0, y) + x2 = min(self.width, x + w) + y2 = min(self.height, y + h) + for cy in range(y1, y2): + row_start = cy * self.width + for cx in range(x1, x2): + self.pixels[row_start + cx] = color + + def draw_rect(self, x: int, y: int, w: int, h: int, border_color: tuple, border_width: int = 1): + # Top and bottom + self.fill_rect(x, y, w, border_width, border_color) + self.fill_rect(x, y + h - border_width, w, border_width, border_color) + # Left and right + self.fill_rect(x, y, border_width, h, border_color) + self.fill_rect(x + w - border_width, y, border_width, h, border_color) + + def draw_char(self, x: int, y: int, char: str, color: tuple, scale: int = 2): + glyph = FONT_5x7.get(char, FONT_5x7.get('?')) + for col_idx, col_byte in enumerate(glyph): + for row_idx in range(7): + if (col_byte >> row_idx) & 1: + px = x + col_idx * scale + py = y + row_idx * scale + self.fill_rect(px, py, scale, scale, color) + + def draw_text(self, x: int, y: int, text: str, color: tuple, scale: int = 2) -> int: + cur_x = x + char_width = 6 * scale + for char in str(text): + if char == '\n': + y += 9 * scale + cur_x = x + continue + self.draw_char(cur_x, y, char, color, scale) + cur_x += char_width + return cur_x + + def draw_text_wrapped(self, x: int, y: int, text: str, max_w: int, color: tuple, scale: int = 2) -> int: + words = str(text).split(' ') + cur_x = x + cur_y = y + char_w = 6 * scale + line_h = 9 * scale + + for word in words: + word_w = len(word) * char_w + if cur_x + word_w > x + max_w and cur_x > x: + cur_y += line_h + cur_x = x + for char in word: + self.draw_char(cur_x, cur_y, char, color, scale) + cur_x += char_w + cur_x += char_w # Space + + return cur_y + line_h + + def to_png_bytes(self) -> bytes: + raw_data = bytearray() + for y in range(self.height): + raw_data.append(0) # Filter byte 0 (None) + row_start = y * self.width + for x in range(self.width): + r, g, b = self.pixels[row_start + x] + raw_data.extend((r, g, b, 255)) # RGBA + + compressed = zlib.compress(bytes(raw_data), 1) + + out = bytearray(b'\x89PNG\r\n\x1a\n') + + # IHDR + ihdr_data = struct.pack('>IIBBBBB', self.width, self.height, 8, 6, 0, 0, 0) + out.extend(struct.pack('>I', len(ihdr_data))) + out.extend(b'IHDR') + out.extend(ihdr_data) + out.extend(struct.pack('>I', zlib.crc32(b'IHDR' + ihdr_data) & 0xffffffff)) + + # IDAT + out.extend(struct.pack('>I', len(compressed))) + out.extend(b'IDAT') + out.extend(compressed) + out.extend(struct.pack('>I', zlib.crc32(b'IDAT' + compressed) & 0xffffffff)) + + # IEND + out.extend(struct.pack('>I', 0)) + out.extend(b'IEND') + out.extend(struct.pack('>I', zlib.crc32(b'IEND') & 0xffffffff)) + + return bytes(out) + + +def hex_to_rgb(hex_str: str) -> tuple: + hex_str = hex_str.lstrip('#') + return tuple(int(hex_str[i:i+2], 16) for i in (0, 2, 4)) + + +def generate_security_card_png( + title: str, + subtitle: str, + badge_text: str, + badge_type: str, + sections: dict, + callout_label: str, + callout_text: str, + footer_text: str +) -> bytes: + """Genera la imagen PNG de la tarjeta de seguridad completa con estilo profesional.""" + color_map = { + 'CRITICAL': {'header': (183, 28, 28), 'badge_bg': (255, 235, 238), 'badge_text': (183, 28, 28), 'border': (239, 83, 80)}, + 'HIGH': {'header': (230, 81, 0), 'badge_bg': (255, 243, 224), 'badge_text': (230, 81, 0), 'border': (255, 152, 0)}, + 'MEDIUM': {'header': (245, 127, 23), 'badge_bg': (255, 253, 231), 'badge_text': (245, 127, 23), 'border': (255, 238, 88)}, + 'LOW': {'header': (2, 119, 189), 'badge_bg': (225, 245, 254), 'badge_text': (2, 119, 189), 'border': (41, 182, 246)}, + 'BLOCKED': {'header': (183, 28, 28), 'badge_bg': (255, 235, 238), 'badge_text': (183, 28, 28), 'border': (239, 83, 80)}, + 'CONTAINED': {'header': (13, 71, 161), 'badge_bg': (227, 242, 253), 'badge_text': (13, 71, 161), 'border': (66, 165, 245)}, + } + theme = color_map.get(badge_type.upper(), {'header': (30, 41, 59), 'badge_bg': (241, 245, 249), 'badge_text': (30, 41, 59), 'border': (148, 163, 184)}) + + width = 760 + # Calcular altura dinámica + num_rows = sum(len(kvs) for kvs in sections.values()) + num_secs = len(sections) + height = 140 + (num_secs * 30) + (num_rows * 24) + 120 + 50 + + canvas = Canvas(width, height, bg_color=(240, 243, 246)) + + card_x = 20 + card_y = 20 + card_w = width - 40 + card_h = height - 40 + + # Fondo de la tarjeta (Blanco) + canvas.fill_rect(card_x, card_y, card_w, card_h, (255, 255, 255)) + canvas.draw_rect(card_x, card_y, card_w, card_h, (226, 232, 240), border_width=2) + + # Cabecera de color + header_h = 64 + canvas.fill_rect(card_x, card_y, card_w, header_h, theme['header']) + canvas.draw_text(card_x + 20, card_y + 12, subtitle.upper(), (255, 255, 255), scale=1) + canvas.draw_text(card_x + 20, card_y + 28, title, (255, 255, 255), scale=2) + + cur_y = card_y + header_h + 16 + + # Badge de severidad / acción + badge_str = f" {badge_text} " + badge_w = len(badge_str) * 12 + 10 + badge_h = 22 + canvas.fill_rect(card_x + 20, cur_y, badge_w, badge_h, theme['badge_bg']) + canvas.draw_rect(card_x + 20, cur_y, badge_w, badge_h, theme['border'], border_width=1) + canvas.draw_text(card_x + 26, cur_y + 4, badge_str, theme['badge_text'], scale=2) + + cur_y += badge_h + 16 + + # Secciones + for sec_title, kvs in sections.items(): + # Título de sección + canvas.draw_text(card_x + 20, cur_y, sec_title, (51, 65, 85), scale=2) + cur_y += 18 + canvas.fill_rect(card_x + 20, cur_y, card_w - 40, 2, (226, 232, 240)) + cur_y += 8 + + # Filas clave-valor + for k, v in kvs: + # Clave + canvas.draw_text(card_x + 24, cur_y, str(k), (100, 116, 139), scale=2) + # Valor (monoespaciado oscuro) + val_str = str(v) + if len(val_str) > 40: + val_str = val_str[:37] + "..." + canvas.draw_text(card_x + 240, cur_y, val_str, (15, 23, 42), scale=2) + cur_y += 22 + cur_y += 10 + + # Bloque de Diagnóstico / Detalle + if callout_text: + canvas.draw_text(card_x + 20, cur_y, callout_label, (51, 65, 85), scale=2) + cur_y += 18 + canvas.fill_rect(card_x + 20, cur_y, card_w - 40, 2, (226, 232, 240)) + cur_y += 8 + + callout_box_h = 52 + canvas.fill_rect(card_x + 20, cur_y, card_w - 40, callout_box_h, (248, 250, 252)) + canvas.fill_rect(card_x + 20, cur_y, 6, callout_box_h, theme['border']) + canvas.draw_rect(card_x + 20, cur_y, card_w - 40, callout_box_h, (226, 232, 240), border_width=1) + + canvas.draw_text_wrapped(card_x + 36, cur_y + 10, callout_text, card_w - 70, (30, 41, 59), scale=1) + cur_y += callout_box_h + 16 + + # Pie de página + footer_h = 32 + footer_y = card_y + card_h - footer_h + canvas.fill_rect(card_x, footer_y, card_w, footer_h, (241, 245, 249)) + canvas.draw_rect(card_x, footer_y, card_w, footer_h, (226, 232, 240), border_width=1) + canvas.draw_text(card_x + 140, footer_y + 10, footer_text, (100, 116, 139), scale=1) + + return canvas.to_png_bytes() diff --git a/terraform-tesis-ir-secure-portal/playbooks/telegram_notifier/handler.py b/terraform-tesis-ir-secure-portal/playbooks/telegram_notifier/handler.py new file mode 100644 index 0000000..ce54410 --- /dev/null +++ b/terraform-tesis-ir-secure-portal/playbooks/telegram_notifier/handler.py @@ -0,0 +1,258 @@ +""" +Lambda: telegram-notifier +Suscrito a Amazon SNS (Topic de alertas de seguridad). +Recibe las notificaciones de incidentes y mitigaciones de seguridad publicadas +en el tópico SNS, genera una tarjeta visual en formato de imagen PNG de alta resolución +(con cabeceras de color según severidad/acción, tablas e insignias) y la entrega +directamente al chat de Telegram mediante la API sendPhoto. +""" +import html +import json +import os +import urllib.parse +import urllib.request +import uuid + +try: + import card_image +except ImportError: + from . import card_image + +TELEGRAM_BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN", "") +TELEGRAM_CHAT_ID = os.environ.get("TELEGRAM_CHAT_ID", "") + + +def parse_key_values(raw_text: str) -> dict: + """Extrae pares clave-valor de reportes en texto estructurado.""" + data = {} + for line in raw_text.splitlines(): + line = line.strip() + if not line or line.startswith("=") or line.startswith("-") or line.startswith("━"): + continue + if ":" in line: + parts = line.split(":", 1) + k = parts[0].strip().lstrip("•").strip() + v = parts[1].strip() + data[k] = v + return data + + +def create_incident_card_image(data: dict) -> bytes: + sev = str(data.get("severity") or data.get("Severidad") or "HIGH") + inc_type = str(data.get("incident_type") or data.get("Tipo de Incidente") or data.get("Tipo Incidente") or "INCIDENT") + inc_id = str(data.get("incident_id") or data.get("ID de Incidente") or data.get("ID Incidente") or "N/A") + status = str(data.get("status") or data.get("Estado") or "NOTIFICADO") + playbook = str(data.get("playbook") or data.get("Playbook") or "notify-alert") + ip = str(data.get("sourceIPAddress") or data.get("IP Origen") or "N/A") + resource = str(data.get("affectedResource") or data.get("Recurso Afectado") or data.get("Recurso") or "N/A") + service = str(data.get("affected_service") or data.get("Servicio Afectado") or data.get("Servicio") or "N/A") + asset = str(data.get("asset_name") or data.get("Activo Objetivo") or data.get("Activo") or "N/A") + basis = str(data.get("severity_basis") or data.get("Criterio / Motivo") or data.get("Motivo") or "N/A") + det_time = str(data.get("detectedAt") or data.get("Hora Deteccion") or data.get("Hora Detección") or data.get("timestamp_ecuador") or data.get("timestamp") or "N/A") + s3_key = str(data.get("s3_log_key") or data.get("Evidencia S3") or "N/A") + + sections = { + "INFORMACION GENERAL": [ + ("Tipo de Incidente", inc_type), + ("ID de Incidente", inc_id), + ("Estado", status), + ("Playbook", playbook), + ], + "RECURSO Y ORIGEN": [ + ("IP Origen", ip), + ("Recurso Afectado", resource), + ("Servicio Afectado", service), + ("Activo Objetivo", asset), + ], + "TRAZABILIDAD": [ + ("Hora Deteccion", det_time), + ("Evidencia S3", s3_key), + ] + } + + return card_image.generate_security_card_png( + title="[ALERTA DE SEGURIDAD AWS]", + subtitle="SOC Automated Incident Response", + badge_text=f"SEVERIDAD: {sev}", + badge_type=sev, + sections=sections, + callout_label="CRITERIO Y DIAGNOSTICO", + callout_text=basis, + footer_text="AWS Automated Incident Response System | Tesis IR" + ) + + +def create_mitigation_card_image(raw_text: str, kv: dict) -> bytes: + is_block = "block-ip" in raw_text or "IP Bloqueada" in kv or "Network ACL" in kv + status = str(kv.get("Estado", "CONTAINED")) + playbook = str(kv.get("Playbook", "mitigation-playbook")) + inc_type = str(kv.get("Tipo de Incidente") or kv.get("Tipo Incidente") or "INCIDENT") + inc_id = str(kv.get("ID de Incidente") or kv.get("ID Incidente") or "N/A") + exec_time = str(kv.get("Hora Mitigacion") or kv.get("Hora Ejecución") or "N/A") + s3_key = str(kv.get("Evidencia S3", "N/A")) + + if is_block: + ip = str(kv.get("IP Bloqueada") or kv.get("IP Objetivo") or "N/A") + nacl = str(kv.get("Network ACL", "N/A")) + regla = str(kv.get("Regla Inbound") or kv.get("Regla Creada") or "N/A") + enforce = str(kv.get("Enforcement", "Bloqueo perimetral a nivel de subred en VPC")) + + sections = { + "INFORMACION GENERAL": [ + ("Estado", status), + ("Playbook", playbook), + ("Tipo de Incidente", inc_type), + ("ID de Incidente", inc_id), + ], + "CONTENCION APLICADA": [ + ("IP Bloqueada", ip), + ("Network ACL", nacl), + ("Regla Inbound", regla), + ("Enforcement", enforce), + ], + "TRAZABILIDAD": [ + ("Hora Mitigacion", exec_time), + ("Evidencia S3", s3_key), + ] + } + return card_image.generate_security_card_png( + title="[MITIGACION DE SEGURIDAD AWS]", + subtitle="Network ACL Automated Containment", + badge_text=f"ACCION: {status}", + badge_type="BLOCKED" if status == "BLOCKED" else "HIGH", + sections=sections, + callout_label="DETALLES DE MITIGACION", + callout_text=f"Trafico de entrada desde {ip} bloqueado permanentemente mediante regla DENY en {nacl}.", + footer_text="AWS Automated Incident Response System | Tesis IR" + ) + else: + user = str(kv.get("Usuario IAM", "N/A")) + actions = str(kv.get("Acciones Tomadas") or kv.get("Acciones") or "N/A") + deny = str(kv.get("Politica DenyAll") or kv.get("DenyAll Policy") or "N/A") + enforce = str(kv.get("Enforcement", "Desactivacion inmediata de credenciales y revocacion de permisos")) + + sections = { + "INFORMACION GENERAL": [ + ("Estado", status), + ("Playbook", playbook), + ("Tipo de Incidente", inc_type), + ("ID de Incidente", inc_id), + ], + "CONTENCION APLICADA": [ + ("Usuario IAM", user), + ("Acciones Tomadas", actions), + ("Politica DenyAll", deny), + ("Enforcement", enforce), + ], + "TRAZABILIDAD": [ + ("Hora Mitigacion", exec_time), + ("Evidencia S3", s3_key), + ] + } + return card_image.generate_security_card_png( + title="[MITIGACION DE SEGURIDAD AWS]", + subtitle="IAM Automated Credential Revocation", + badge_text=f"ACCION: {status}", + badge_type="CONTAINED" if status == "CONTAINED" else "CRITICAL", + sections=sections, + callout_label="DETALLES DE MITIGACION", + callout_text=f"Credenciales de {user} revocadas y politica inline EmergencyDenyAll adjuntada.", + footer_text="AWS Automated Incident Response System | Tesis IR" + ) + + +def send_telegram_photo(png_bytes: bytes, caption: str = "") -> dict: + """Envía la tarjeta de imagen PNG a Telegram usando multipart/form-data.""" + if not TELEGRAM_BOT_TOKEN or not TELEGRAM_CHAT_ID: + print("[telegram-notifier] Variables TELEGRAM_BOT_TOKEN o TELEGRAM_CHAT_ID no configuradas.") + return {"status": "skipped", "reason": "missing_credentials"} + + boundary = f"----WebKitFormBoundary{uuid.uuid4().hex[:16]}" + body = bytearray() + + # Campo: chat_id + body.extend(f"--{boundary}\r\n".encode("utf-8")) + body.extend(b'Content-Disposition: form-data; name="chat_id"\r\n\r\n') + body.extend(f"{TELEGRAM_CHAT_ID}\r\n".encode("utf-8")) + + # Campo opcional: caption + if caption: + body.extend(f"--{boundary}\r\n".encode("utf-8")) + body.extend(b'Content-Disposition: form-data; name="caption"\r\n\r\n') + body.extend(caption.encode("utf-8")) + body.extend(b"\r\n") + + # Campo: photo (archivo PNG en memoria) + body.extend(f"--{boundary}\r\n".encode("utf-8")) + body.extend(b'Content-Disposition: form-data; name="photo"; filename="security_card.png"\r\n') + body.extend(b"Content-Type: image/png\r\n\r\n") + body.extend(png_bytes) + body.extend(b"\r\n") + + body.extend(f"--{boundary}--\r\n".encode("utf-8")) + + api_url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendPhoto" + req = urllib.request.Request( + api_url, + data=bytes(body), + headers={"Content-Type": f"multipart/form-data; boundary={boundary}"}, + method="POST" + ) + + try: + with urllib.request.urlopen(req, timeout=12) as response: + resp_body = response.read().decode("utf-8") + print(f"[telegram-notifier] Tarjeta de imagen enviada a Telegram. HTTP {response.status}") + return {"status": "success", "response": json.loads(resp_body)} + except Exception as exc: + print(f"[telegram-notifier] Error enviando imagen a Telegram: {exc}") + return {"status": "error", "error": str(exc)} + + +def lambda_handler(event, context): + results = [] + + for record in event.get("Records", []): + sns_record = record.get("Sns", {}) + raw_message = sns_record.get("Message", "").strip() + + if not raw_message: + continue + + png_bytes = None + caption = "" + + try: + if raw_message.startswith("{"): + data = json.loads(raw_message) + if "incident_payload" in data: + data = data["incident_payload"] + png_bytes = create_incident_card_image(data) + caption = f"Incidente: {data.get('incident_type', 'INCIDENT')} ({data.get('severity', 'HIGH')})" + elif "ALERTA DE SEGURIDAD AWS" in raw_message: + kv = parse_key_values(raw_message) + png_bytes = create_incident_card_image(kv) + caption = f"Alerta: {kv.get('Tipo de Incidente', 'INCIDENT')} [{kv.get('Severidad', 'HIGH')}]" + elif "MITIGACION DE SEGURIDAD AWS" in raw_message or "MITIGACIÓN DE SEGURIDAD AWS" in raw_message: + kv = parse_key_values(raw_message) + png_bytes = create_mitigation_card_image(raw_message, kv) + caption = f"Mitigacion: {kv.get('Playbook', 'block-ip')} [{kv.get('Estado', 'BLOCKED')}]" + else: + # Si es un mensaje generico, crear tarjeta generica + kv = parse_key_values(raw_message) + png_bytes = create_incident_card_image(kv) + caption = "Notificacion de Seguridad AWS" + except Exception as exc: + print(f"[telegram-notifier] Error construyendo tarjeta grafica: {exc}") + + if png_bytes: + send_res = send_telegram_photo(png_bytes, caption) + results.append(send_res) + else: + print("[telegram-notifier] No se pudo generar la tarjeta grafica PNG.") + + return { + "status": "success", + "processed": len(results), + "results": results + } diff --git a/terraform-tesis-ir-secure-portal/scripts/user_data.sh.tpl b/terraform-tesis-ir-secure-portal/scripts/user_data.sh.tpl new file mode 100644 index 0000000..8a81aea --- /dev/null +++ b/terraform-tesis-ir-secure-portal/scripts/user_data.sh.tpl @@ -0,0 +1,502 @@ +#!/bin/bash +set -euo pipefail + +# Portal corporativo de laboratorio. +# La aplicacion NO usa credenciales AWS ni llama servicios AWS. +# Solo escribe eventos JSON locales en /var/log/tesis-portal/app.log. +# 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"{html_escape(username)}Salir" + return f""" + + + + + {html_escape(title)} + + + +
{COMPANY_NAME}
{session_area}
+ {content} + +""" + + +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"
{html_escape(message)}
" + content = f""" +
+
+

Iniciar sesion

+

Acceda con sus credenciales corporativas.

+ {alert} +
+ + + + + +
+
+
+ """ + self.respond(200, page("Inicio de sesion", content)) + + def render_dashboard(self, username): + role = USERS.get(username, {}).get("display", "Usuario") + content = f""" +
+
+
+

Panel principal

+

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

+
+

Solicitudes

12

En revision

+

Operaciones

98%

Disponibilidad

+

Cuenta

Activa

Sesion protegida

+
+
+ """ + self.respond(200, page("Panel principal", content, authenticated=True, username=username)) + + def render_access_denied(self, remaining): + content = f""" +
+
+

Acceso temporalmente restringido

+

Se detectaron demasiados intentos incorrectos. Intente nuevamente en unos minutos.

+
Tiempo restante aproximado: {remaining} segundos
+ Volver +
+
+ """ + 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", "

404

Pagina no encontrada.

")) + + 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 diff --git a/terraform-tesis-ir-secure-portal/terraform.tfvars.example b/terraform-tesis-ir-secure-portal/terraform.tfvars.example new file mode 100644 index 0000000..0b8e363 --- /dev/null +++ b/terraform-tesis-ir-secure-portal/terraform.tfvars.example @@ -0,0 +1,55 @@ +# Copia este archivo como terraform.tfvars y edita los valores. + +aws_region = "ca-central-1" +project_name = "tesis-ir" + +# Obligatorio: coloca TU IP publica con /32. +# Puedes verla buscando "what is my ip". +ssh_allowed_cidr = "181.000.000.000/32" + +# Recomendado: restringir HTTP tambien a tu IP /32. +# Si dejas [] Terraform usara automaticamente ssh_allowed_cidr. +# Solo para exposiciones publicas temporales usa ["0.0.0.0/0"]. +http_allowed_cidrs = [] + +# IPs consideradas normales/autorizadas por Lambda Detector B. +# Si queda vacio, se usa ssh_allowed_cidr. +authorized_ip_cidrs = [] + +# Opcional: correo para SNS y Budget. Debes confirmar la suscripcion SNS por email. +alert_email = "tu_correo@ejemplo.com" + +# Subdominio para firma digital DKIM en Amazon SES (opcional) +ses_domain = "soc.tudominio.com" +ses_sender_email = "alertas@soc.tudominio.com" + +# Opcional: Notificaciones a Telegram +# Obtén el token con @BotFather y el chat_id con @userinfobot o @RawDataBot +telegram_bot_token = "" +telegram_chat_id = "" + +# Si ya tienes una key pair EC2 creada en esa region: +# key_name = "tesis-ir-key" +key_name = "" + +# Mantener bajo costo: +enable_vpc_flow_logs = true +enable_s3_data_events = false +enable_aws_config = false +cloudtrail_multi_region = false + +# Activa estos SOLO cuando vayas a probar esos incidentes: +# enable_s3_data_events = true # para EXFILTRATION con S3 GetObject +# enable_aws_config = true # para evidencia adicional de cambios IAM/configuracion + +ec2_instance_type = "t3.micro" +ec2_volume_size_gb = 8 +cloudwatch_retention_days = 14 +monthly_budget_limit_usd = 5 + +# Umbrales alineados con Variables_Incidentes.docx +threshold_app_login_failures_same_ip_5m = 5 +threshold_console_login_failures_same_user_5m = 5 +threshold_console_login_failures_same_ip_5m = 10 +threshold_port_scan_distinct_ports_5m = 10 +threshold_s3_getobject_exfiltration_count_1h = 50 diff --git a/terraform-tesis-ir-secure-portal/variables.tf b/terraform-tesis-ir-secure-portal/variables.tf new file mode 100644 index 0000000..a9fa3a7 --- /dev/null +++ b/terraform-tesis-ir-secure-portal/variables.tf @@ -0,0 +1,240 @@ +variable "aws_region" { + description = "Region AWS. Use ca-central-1 si quieres mantener la region que venias usando, o us-east-1 si seguiras exactamente el documento base." + type = string + default = "ca-central-1" +} + +variable "project_name" { + description = "Prefijo de nombres para todos los recursos. Usa solo minusculas, numeros y guiones." + type = string + default = "tesis-ir" + + validation { + condition = can(regex("^[a-z0-9-]+$", var.project_name)) + error_message = "project_name solo puede tener minusculas, numeros y guiones." + } +} + +variable "ssh_allowed_cidr" { + description = "Tu IP publica en formato CIDR para SSH. Ejemplo: 181.39.10.20/32. No uses 0.0.0.0/0." + type = string + + validation { + condition = can(cidrhost(var.ssh_allowed_cidr, 0)) && var.ssh_allowed_cidr != "0.0.0.0/0" + error_message = "ssh_allowed_cidr debe ser un CIDR valido y no debe ser 0.0.0.0/0." + } +} + +variable "http_allowed_cidrs" { + description = "CIDRs permitidos para HTTP del portal. Si queda vacio, se usa ssh_allowed_cidr. Para demo publica podrias usar 0.0.0.0/0, pero no es lo recomendado." + type = list(string) + default = [] +} + +variable "authorized_ip_cidrs" { + description = "IPs autorizadas para la logica del detector. Si queda vacio, se usa ssh_allowed_cidr." + type = list(string) + default = [] +} + +variable "authorized_admin_users" { + description = "Usuarios autorizados usados en config/authorized_ips.json." + type = list(string) + default = ["tesis-admin", "estudiante-b"] +} + +variable "alert_email" { + description = "Correo para SNS y presupuesto. Si lo dejas vacio, no se crea suscripcion email ni budget." + type = string + default = "" +} + +variable "ses_domain" { + description = "Subdominio o dominio registrado para firma digital DKIM en Amazon SES (ej: soc.tudominio.com)." + type = string + default = "" +} + +variable "ses_sender_email" { + description = "Direccion de remitente firmada con DKIM para el envio de reportes SOC (ej: alertas@soc.tudominio.com)." + type = string + default = "" +} + +variable "create_budget" { + description = "Crear un presupuesto mensual con alertas si alert_email no esta vacio." + type = bool + default = true +} + +variable "monthly_budget_limit_usd" { + description = "Monto del budget mensual." + type = number + default = 5 +} + +variable "vpc_cidr" { + description = "CIDR de la VPC." + type = string + default = "10.10.0.0/16" +} + +variable "public_subnet_a_cidr" { + description = "CIDR subred publica A." + type = string + default = "10.10.1.0/24" +} + +variable "public_subnet_b_cidr" { + description = "CIDR subred publica B." + type = string + default = "10.10.2.0/24" +} + +variable "private_subnet_a_cidr" { + description = "CIDR subred privada A reservada." + type = string + default = "10.10.11.0/24" +} + +variable "private_subnet_b_cidr" { + description = "CIDR subred privada B reservada." + type = string + default = "10.10.12.0/24" +} + +variable "portal_private_ip" { + description = "IP privada fija para la EC2 dentro de la subred publica A." + type = string + default = "10.10.1.10" +} + +variable "ec2_instance_type" { + description = "Tipo de instancia. En ca-central-1 muchas cuentas usan t3.micro como elegible Free Tier; valida con aws ec2 describe-instance-types." + type = string + default = "t3.micro" +} + +variable "ec2_volume_size_gb" { + description = "Tamaño EBS gp3 de la EC2." + type = number + default = 8 +} + +variable "key_name" { + description = "Nombre de una key pair existente para SSH. Si queda vacio, usa Session Manager en lugar de SSH tradicional." + type = string + default = "" +} + +variable "cloudwatch_retention_days" { + description = "Retencion de logs en CloudWatch para reducir costos." + type = number + default = 14 +} + +variable "normalized_log_retention_days" { + description = "Retencion del log group normalizado de incidentes." + type = number + default = 30 +} + +variable "force_destroy_buckets" { + description = "Permite destruir buckets con objetos al ejecutar terraform destroy. Para laboratorio es practico; para evidencia real usa false." + type = bool + default = true +} + +variable "enable_vpc_flow_logs" { + description = "Activa VPC Flow Logs sobre la ENI de la EC2." + type = bool + default = true +} + +variable "cloudtrail_multi_region" { + description = "Trail multi-region. Para bajo costo/logs reducidos se deja false." + type = bool + default = false +} + +variable "enable_s3_data_events" { + description = "Activa CloudTrail Data Events sobre el prefijo sensible del bucket demo. Puede generar cargos; activalo solo para la prueba del incidente 5." + type = bool + default = false +} + +variable "enable_aws_config" { + description = "Activa AWS Config y una regla administrada. Puede generar cargos; activalo solo cuando pruebes cambios de configuracion." + type = bool + default = false +} + +variable "config_resource_types" { + description = "Tipos de recursos monitoreados por AWS Config cuando enable_aws_config=true." + type = list(string) + default = [ + "AWS::IAM::User", + "AWS::IAM::Role", + "AWS::IAM::Policy", + "AWS::EC2::SecurityGroup", + "AWS::EC2::NetworkAcl", + "AWS::EC2::Instance", + "AWS::S3::Bucket" + ] +} + +variable "create_test_iam_user" { + description = "Crea un usuario IAM de laboratorio sin claves ni password de consola." + type = bool + default = true +} + +variable "threshold_console_login_failures_same_user_5m" { + description = "Umbral de fallos ConsoleLogin por usuario en 5 minutos." + type = number + default = 5 +} + +variable "threshold_console_login_failures_same_ip_5m" { + description = "Umbral de fallos ConsoleLogin por IP en 5 minutos." + type = number + default = 10 +} + +variable "threshold_app_login_failures_same_ip_5m" { + description = "Umbral de login_failed del portal por IP en 5 minutos." + type = number + default = 5 +} + +variable "threshold_port_scan_distinct_ports_5m" { + description = "Puertos distintos rechazados desde una misma IP en 5 minutos." + type = number + default = 10 +} + +variable "threshold_s3_getobject_unusual_count_5m" { + description = "Umbral de accesos S3 GetObject/ListBucket inusuales en 5 minutos." + type = number + default = 10 +} + +variable "threshold_s3_getobject_exfiltration_count_1h" { + description = "Umbral de GetObject desde la misma IP en 1 hora para EXFILTRATION, segun Variables_Incidentes.docx." + type = number + default = 50 +} + +variable "telegram_bot_token" { + description = "Token del Bot de Telegram para envio de alertas. Opcional; si queda vacio no se despliega la integracion." + type = string + default = "" + sensitive = true +} + +variable "telegram_chat_id" { + description = "Chat ID o ID de grupo/canal de Telegram donde se enviaran las alertas." + type = string + default = "" +} +