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/terraform-tesis-ir-secure-portal/.gitignore b/terraform-tesis-ir-secure-portal/.gitignore index 2fb93ba..f04c579 100644 --- a/terraform-tesis-ir-secure-portal/.gitignore +++ b/terraform-tesis-ir-secure-portal/.gitignore @@ -3,6 +3,16 @@ *.tfstate.* .terraform.lock.hcl terraform.tfvars -lambda_tesis_detector.zip +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/lambda/__pycache__/lambda_function.cpython-314.pyc b/terraform-tesis-ir-secure-portal/lambda/__pycache__/lambda_function.cpython-314.pyc deleted file mode 100644 index 7c34dac..0000000 Binary files a/terraform-tesis-ir-secure-portal/lambda/__pycache__/lambda_function.cpython-314.pyc and /dev/null differ diff --git a/terraform-tesis-ir-secure-portal/lambda/lambda_function.py b/terraform-tesis-ir-secure-portal/lambda/lambda_function.py index 50c32fe..eeee5ae 100644 --- a/terraform-tesis-ir-secure-portal/lambda/lambda_function.py +++ b/terraform-tesis-ir-secure-portal/lambda/lambda_function.py @@ -207,22 +207,30 @@ def publish_incident_queue(payload: dict) -> None: send_sqs_message(INCIDENT_QUEUE_URL, payload) # Fan-out controlado a playbooks de respuesta automatica. - # Se usan colas dedicadas para que notify-alert y block-ip reciban ambos - # el mismo evento sin competir por el mensaje SQS. + # Se usan colas dedicadas para que notify-alert y los playbooks de contencion + # reciban ambos el mismo evento sin competir por el mensaje SQS. # - # Incidentes con respuesta automatica activa: - # BRUTE_FORCE → notify-alert + block-ip (Incidente 1) - # PORT_SCAN → notify-alert + block-ip (Incidente 2) - # PRIVILEGE_ESCALATION → notify-alert + revoke-credentials (Incidente 3) - # CREDENTIAL_LEAK → notify-alert + revoke-credentials (Incidente 4) - PLAYBOOK_INCIDENTS = {"BRUTE_FORCE", "PORT_SCAN"} - if payload.get("incident_type") in PLAYBOOK_INCIDENTS: + # 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 payload.get("incident_type") in REVOKE_INCIDENTS: - send_sqs_message(PLAYBOOK_NOTIFY_QUEUE_URL, payload) + if incident_type in REVOKE_INCIDENTS: send_sqs_message(PLAYBOOK_REVOKE_CREDENTIALS_QUEUE_URL, payload) @@ -244,6 +252,8 @@ def save_incident(payload: dict, source: str, raw_event: dict, summary: str) -> 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, @@ -312,8 +322,8 @@ def analyze_app_event(event_json: dict, config: dict): if count >= threshold and mark_alert_once(f"BRUTE_FORCE#APP#{source_ip}#{window}"): severity_basis = ( - f"HIGH porque la IP {source_ip} alcanzo {count} intentos fallidos " - f"en 5 minutos; el umbral configurado para BRUTE_FORCE es {threshold}." + f"HIGH: La IP {source_ip} alcanzó {count} intentos fallidos de autenticación " + f"en 5 minutos (umbral={threshold})." ) payload = { "incident_type": "BRUTE_FORCE", @@ -327,9 +337,9 @@ def analyze_app_event(event_json: dict, config: dict): "event_count": count, "failed_attempts": count, "detection_window": "5 minutes", - "affected_service": event_json.get("affected_service", "Portal de autenticacion corporativo"), - "asset_name": event_json.get("asset_name", f"{PORTAL_INSTANCE_ID}"), - "asset_type": event_json.get("asset_type", "EC2 web application"), + "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"], } @@ -362,14 +372,16 @@ def analyze_cloudtrail(event_json: dict, config: dict): "sourceIPAddress": source_ip, "affectedResource": affected_iam_user(event_json, username), "s3_log_key": "pending", - "timestamp": event_json.get("eventTime", utc_now()), + "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", - "asset_name": "AWS Console", - "asset_type": "AWS control plane", - "severity_basis": f"HIGH porque se alcanzaron {count_user} fallos de ConsoleLogin para el mismo usuario en 5 minutos.", + "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." @@ -380,14 +392,16 @@ def analyze_cloudtrail(event_json: dict, config: dict): "sourceIPAddress": source_ip, "affectedResource": affected_iam_user(event_json, username), "s3_log_key": "pending", - "timestamp": event_json.get("eventTime", utc_now()), + "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", - "asset_name": "AWS Console", - "asset_type": "AWS control plane", - "severity_basis": f"HIGH porque se alcanzaron {count_ip} fallos de ConsoleLogin desde la misma IP en 5 minutos.", + "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." @@ -409,15 +423,26 @@ def analyze_cloudtrail(event_json: dict, config: dict): 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", utc_now()), + "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] @@ -430,16 +455,27 @@ def analyze_cloudtrail(event_json: dict, config: dict): 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", utc_now()), + "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}." @@ -451,18 +487,29 @@ def analyze_cloudtrail(event_json: dict, config: dict): 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", utc_now()), + "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", utc_now()), + "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." @@ -516,16 +563,27 @@ def analyze_flow_log(message: str, config: dict): 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": utc_now(), + "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 diff --git a/terraform-tesis-ir-secure-portal/lambda_playbook_block_ip.zip b/terraform-tesis-ir-secure-portal/lambda_playbook_block_ip.zip deleted file mode 100644 index 82e837b..0000000 Binary files a/terraform-tesis-ir-secure-portal/lambda_playbook_block_ip.zip and /dev/null differ diff --git a/terraform-tesis-ir-secure-portal/lambda_playbook_notify_alert.zip b/terraform-tesis-ir-secure-portal/lambda_playbook_notify_alert.zip deleted file mode 100644 index 018b52b..0000000 Binary files a/terraform-tesis-ir-secure-portal/lambda_playbook_notify_alert.zip and /dev/null differ diff --git a/terraform-tesis-ir-secure-portal/lambda_playbook_revoke_credentials.zip b/terraform-tesis-ir-secure-portal/lambda_playbook_revoke_credentials.zip deleted file mode 100644 index 27a91b3..0000000 Binary files a/terraform-tesis-ir-secure-portal/lambda_playbook_revoke_credentials.zip and /dev/null differ diff --git a/terraform-tesis-ir-secure-portal/lambda_playbook_telegram_notifier.zip b/terraform-tesis-ir-secure-portal/lambda_playbook_telegram_notifier.zip deleted file mode 100644 index 45cae32..0000000 Binary files a/terraform-tesis-ir-secure-portal/lambda_playbook_telegram_notifier.zip and /dev/null differ diff --git a/terraform-tesis-ir-secure-portal/main.tf b/terraform-tesis-ir-secure-portal/main.tf index 60da5e0..d8161e3 100644 --- a/terraform-tesis-ir-secure-portal/main.tf +++ b/terraform-tesis-ir-secure-portal/main.tf @@ -927,12 +927,32 @@ resource "aws_sns_topic" "alerts" { name = "${var.project_name}-incident-alerts" } -resource "aws_sns_topic_subscription" "email" { - count = var.alert_email != "" ? 1 : 0 +# 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 +# } - 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 } # ----------------------------------------------------------------------------- @@ -1307,6 +1327,15 @@ resource "aws_iam_role_policy" "playbook_notify" { Action = "sns:Publish" Resource = aws_sns_topic.alerts.arn }, + { + Sid = "SendSESEmail" + Effect = "Allow" + Action = [ + "ses:SendEmail", + "ses:SendRawEmail" + ] + Resource = "*" + }, { Sid = "WritePlaybookAudit" Effect = "Allow" @@ -1359,6 +1388,15 @@ resource "aws_iam_role_policy" "playbook_block_ip" { Effect = "Allow" Action = "sns:Publish" Resource = aws_sns_topic.alerts.arn + }, + { + Sid = "SendSESEmail" + Effect = "Allow" + Action = [ + "ses:SendEmail", + "ses:SendRawEmail" + ] + Resource = "*" } ] }) @@ -1378,9 +1416,11 @@ resource "aws_lambda_function" "playbook_notify" { environment { variables = { - SNS_ALERTS_ARN = aws_sns_topic.alerts.arn - EVIDENCE_BUCKET = aws_s3_bucket.evidence.bucket - RESPONSE_PREFIX = "responses/notify-alert" + 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 } } @@ -1410,12 +1450,14 @@ resource "aws_lambda_function" "playbook_block_ip" { 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" + 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 } } @@ -1522,6 +1564,15 @@ resource "aws_iam_role_policy" "playbook_revoke_credentials" { Effect = "Allow" Action = "sns:Publish" Resource = aws_sns_topic.alerts.arn + }, + { + Sid = "SendSESEmail" + Effect = "Allow" + Action = [ + "ses:SendEmail", + "ses:SendRawEmail" + ] + Resource = "*" } ] }) @@ -1541,9 +1592,11 @@ resource "aws_lambda_function" "playbook_revoke_credentials" { environment { variables = { - SNS_ALERTS_ARN = aws_sns_topic.alerts.arn - EVIDENCE_BUCKET = aws_s3_bucket.evidence.bucket - RESPONSE_PREFIX = "responses/revoke-credentials" + 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 } } @@ -1573,7 +1626,7 @@ resource "aws_lambda_event_source_mapping" "playbook_revoke_credentials_from_que data "archive_file" "telegram_notifier_zip" { count = var.telegram_bot_token != "" && var.telegram_chat_id != "" ? 1 : 0 type = "zip" - source_file = "${path.module}/playbooks/telegram_notifier/handler.py" + source_dir = "${path.module}/playbooks/telegram_notifier" output_path = "${path.module}/lambda_playbook_telegram_notifier.zip" } @@ -1612,8 +1665,8 @@ resource "aws_lambda_function" "telegram_notifier" { handler = "handler.lambda_handler" runtime = "python3.12" architectures = ["x86_64"] - memory_size = 128 - timeout = 15 + 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 diff --git a/terraform-tesis-ir-secure-portal/outputs.tf b/terraform-tesis-ir-secure-portal/outputs.tf index 8128211..ba286dc 100644 --- a/terraform-tesis-ir-secure-portal/outputs.tf +++ b/terraform-tesis-ir-secure-portal/outputs.tf @@ -115,3 +115,45 @@ output "telegram_notifier_lambda_name" { 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/__pycache__/handler.cpython-314.pyc b/terraform-tesis-ir-secure-portal/playbooks/block_ip/__pycache__/handler.cpython-314.pyc deleted file mode 100644 index 5af74f2..0000000 Binary files a/terraform-tesis-ir-secure-portal/playbooks/block_ip/__pycache__/handler.cpython-314.pyc and /dev/null differ diff --git a/terraform-tesis-ir-secure-portal/playbooks/block_ip/handler.py b/terraform-tesis-ir-secure-portal/playbooks/block_ip/handler.py index 8e236db..bc8a34c 100644 --- a/terraform-tesis-ir-secure-portal/playbooks/block_ip/handler.py +++ b/terraform-tesis-ir-secure-portal/playbooks/block_ip/handler.py @@ -2,21 +2,9 @@ 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 y registra evidencia de respuesta en S3. - -Incidentes soportados: - - BRUTE_FORCE (severity HIGH) → Incidente 1 - - PORT_SCAN (severity MEDIUM) → Incidente 2 - -Punto de cumplimiento (enforcement point): - ec2.create_network_acl_entry(RuleAction="deny", Egress=False, CidrBlock=IP/32) - Esa es la linea exacta donde el trafico de la IP atacante queda bloqueado - a nivel de red en la VPC. - - Las NACLs evaluan reglas de menor a mayor numero; el DENY se inserta con - numero < 100, por debajo del ALLOW por defecto (nro 100), por eso el bloqueo - es efectivo y no cosmetico. +objetivo, registra evidencia de respuesta en S3 y notifica via HTML Card (SES) y SNS (Telegram). """ +import html import ipaddress import json import os @@ -29,6 +17,7 @@ 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"] @@ -36,9 +25,10 @@ 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") -# Incidentes que activan el bloqueo de IP en NACL. BLOCK_INCIDENT_TYPES = {"BRUTE_FORCE", "PORT_SCAN"} @@ -46,8 +36,141 @@ 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""" +
) usando la biblioteca estandar de Python.
+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 send_telegram_message(text: str) -> dict:
+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"}
- api_url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
- payload = {
- "chat_id": TELEGRAM_CHAT_ID,
- "text": f"{text}",
- "parse_mode": "HTML"
- }
+ boundary = f"----WebKitFormBoundary{uuid.uuid4().hex[:16]}"
+ body = bytearray()
- data_bytes = json.dumps(payload).encode("utf-8")
+ # 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=data_bytes,
- headers={"Content-Type": "application/json"},
+ data=bytes(body),
+ headers={"Content-Type": f"multipart/form-data; boundary={boundary}"},
method="POST"
)
try:
- with urllib.request.urlopen(req, timeout=10) as response:
+ with urllib.request.urlopen(req, timeout=12) as response:
resp_body = response.read().decode("utf-8")
- print(f"[telegram-notifier] Mensaje entregado a Telegram. HTTP {response.status}")
+ 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 mensaje a Telegram: {exc}")
+ print(f"[telegram-notifier] Error enviando imagen a Telegram: {exc}")
return {"status": "error", "error": str(exc)}
@@ -48,38 +214,42 @@ def lambda_handler(event, context):
for record in event.get("Records", []):
sns_record = record.get("Sns", {})
- raw_message = sns_record.get("Message", "")
-
- # Si el mensaje ya es texto plano formateado por notify-alert, enviarlo directo
- if not raw_message.strip().startswith("{"):
- send_result = send_telegram_message(raw_message.strip())
- results.append(send_result)
+ raw_message = sns_record.get("Message", "").strip()
+
+ if not raw_message:
continue
- # Si por alguna razon llega un JSON crudo, parsearlo y formatearlo
+ png_bytes = None
+ caption = ""
+
try:
- message_data = json.loads(raw_message)
- if "incident_payload" in message_data:
- message_data = message_data["incident_payload"]
-
- lines = [
- f"[ALERTA DE SEGURIDAD AWS] - SEVERIDAD: {message_data.get('severity', 'HIGH')}",
- "=" * 50,
- f"Tipo de Incidente : {message_data.get('incident_type', 'NO_ESPECIFICADO')}",
- f"ID de Incidente : {message_data.get('incident_id', 'N/A')}",
- f"Estado : {message_data.get('status', 'NOTIFICADO')}",
- "-" * 50,
- f"IP Origen : {message_data.get('sourceIPAddress', 'N/A')}",
- f"Recurso Afectado : {message_data.get('affectedResource', 'N/A')}",
- f"Criterio / Motivo : {message_data.get('severity_basis', 'N/A')}",
- "=" * 50,
- ]
- formatted_text = "\n".join(lines)
- send_result = send_telegram_message(formatted_text)
- results.append(send_result)
- except Exception:
- send_result = send_telegram_message(str(raw_message))
- results.append(send_result)
+ 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",
diff --git a/terraform-tesis-ir-secure-portal/terraform.tfvars.example b/terraform-tesis-ir-secure-portal/terraform.tfvars.example
index 8da05ed..0b8e363 100644
--- a/terraform-tesis-ir-secure-portal/terraform.tfvars.example
+++ b/terraform-tesis-ir-secure-portal/terraform.tfvars.example
@@ -19,6 +19,10 @@ 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 = ""
diff --git a/terraform-tesis-ir-secure-portal/variables.tf b/terraform-tesis-ir-secure-portal/variables.tf
index 940f8b8..a9fa3a7 100644
--- a/terraform-tesis-ir-secure-portal/variables.tf
+++ b/terraform-tesis-ir-secure-portal/variables.tf
@@ -49,6 +49,18 @@ variable "alert_email" {
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