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 new file mode 100644 index 0000000..7c34dac Binary files /dev/null and b/terraform-tesis-ir-secure-portal/lambda/__pycache__/lambda_function.cpython-314.pyc differ diff --git a/terraform-tesis-ir-secure-portal/lambda/lambda_function.py b/terraform-tesis-ir-secure-portal/lambda/lambda_function.py index 7aa619b..50c32fe 100644 --- a/terraform-tesis-ir-secure-portal/lambda/lambda_function.py +++ b/terraform-tesis-ir-secure-portal/lambda/lambda_function.py @@ -286,12 +286,6 @@ def save_incident(payload: dict, source: str, raw_event: dict, summary: str) -> publish_incident_queue(final_payload) - sns.publish( - TopicArn=SNS_TOPIC_ARN, - Subject=f"[{final_payload['severity']}] Incidente detectado: {final_payload['incident_type']}", - Message=json.dumps(evidence_doc, indent=2, default=decimal_default), - ) - cloudwatch.put_metric_data( Namespace="TesisIR", MetricData=[ diff --git a/terraform-tesis-ir-secure-portal/lambda_playbook_block_ip.zip b/terraform-tesis-ir-secure-portal/lambda_playbook_block_ip.zip index 16d1ca3..82e837b 100644 Binary files a/terraform-tesis-ir-secure-portal/lambda_playbook_block_ip.zip and b/terraform-tesis-ir-secure-portal/lambda_playbook_block_ip.zip 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 index 72530de..018b52b 100644 Binary files a/terraform-tesis-ir-secure-portal/lambda_playbook_notify_alert.zip and b/terraform-tesis-ir-secure-portal/lambda_playbook_notify_alert.zip 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 index a82f731..27a91b3 100644 Binary files a/terraform-tesis-ir-secure-portal/lambda_playbook_revoke_credentials.zip and b/terraform-tesis-ir-secure-portal/lambda_playbook_revoke_credentials.zip 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 new file mode 100644 index 0000000..45cae32 Binary files /dev/null and b/terraform-tesis-ir-secure-portal/lambda_playbook_telegram_notifier.zip differ diff --git a/terraform-tesis-ir-secure-portal/main.tf b/terraform-tesis-ir-secure-portal/main.tf index 06db3fc..60da5e0 100644 --- a/terraform-tesis-ir-secure-portal/main.tf +++ b/terraform-tesis-ir-secure-portal/main.tf @@ -1566,6 +1566,97 @@ resource "aws_lambda_event_source_mapping" "playbook_revoke_credentials_from_que 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_file = "${path.module}/playbooks/telegram_notifier/handler.py" + 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 = 128 + timeout = 15 + + 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. # ----------------------------------------------------------------------------- @@ -1635,7 +1726,6 @@ resource "aws_cloudwatch_metric_alarm" "console_login_failure" { threshold = var.threshold_console_login_failures_same_user_5m alarm_description = "Alarma por multiples fallos de inicio de sesion" treat_missing_data = "notBreaching" - alarm_actions = [aws_sns_topic.alerts.arn] depends_on = [aws_cloudwatch_log_metric_filter.console_login_failure] } @@ -1651,7 +1741,6 @@ resource "aws_cloudwatch_metric_alarm" "iam_critical_action" { threshold = 1 alarm_description = "Alarma por accion critica IAM" treat_missing_data = "notBreaching" - alarm_actions = [aws_sns_topic.alerts.arn] depends_on = [aws_cloudwatch_log_metric_filter.iam_critical_action] } @@ -1667,7 +1756,6 @@ resource "aws_cloudwatch_metric_alarm" "iam_policy_change" { threshold = 1 alarm_description = "Alarma por cambio de politica IAM" treat_missing_data = "notBreaching" - alarm_actions = [aws_sns_topic.alerts.arn] depends_on = [aws_cloudwatch_log_metric_filter.iam_policy_change] } @@ -1685,7 +1773,6 @@ resource "aws_cloudwatch_metric_alarm" "vpc_rejected_traffic" { threshold = var.threshold_port_scan_distinct_ports_5m alarm_description = "Alarma por trafico rechazado repetido hacia la EC2" treat_missing_data = "notBreaching" - alarm_actions = [aws_sns_topic.alerts.arn] depends_on = [aws_cloudwatch_log_metric_filter.vpc_rejected_traffic] } diff --git a/terraform-tesis-ir-secure-portal/outputs.tf b/terraform-tesis-ir-secure-portal/outputs.tf index 88fc304..8128211 100644 --- a/terraform-tesis-ir-secure-portal/outputs.tf +++ b/terraform-tesis-ir-secure-portal/outputs.tf @@ -109,3 +109,9 @@ output "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)." +} + 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 new file mode 100644 index 0000000..5af74f2 Binary files /dev/null and b/terraform-tesis-ir-secure-portal/playbooks/block_ip/__pycache__/handler.cpython-314.pyc 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 071be22..8e236db 100644 --- a/terraform-tesis-ir-secure-portal/playbooks/block_ip/handler.py +++ b/terraform-tesis-ir-secure-portal/playbooks/block_ip/handler.py @@ -212,11 +212,27 @@ def lambda_handler(event, context): ) # ── Notificar al equipo via SNS ──────────────────────────────────── - subject = f"[{entry['severity']}] Playbook block-ip: {status} {ip_value} ({incident_type})" + subject = f"[{entry['severity']}] Mitigacion: IP {ip_value} {status} en NACL" + mitigation_report = f""" +[MITIGACION DE SEGURIDAD AWS] - ACCION: {status} +================================================== +Playbook : block-ip +Tipo de Incidente : {incident_type} +ID de Incidente : {entry['incident_id']} +Estado : {status} +-------------------------------------------------- +IP Objetivo : {ip_value} +Network ACL : {enforcement.get('network_acl_id', 'N/A')} +Regla Creada : #{enforcement.get('rule_number', 'N/A')} +-------------------------------------------------- +Hora Mitigacion : {timestamp} +Evidencia S3 : {key} +================================================== +""".strip() sns.publish( TopicArn=SNS_ARN, Subject=subject[:100], - Message=json.dumps(entry, indent=2, ensure_ascii=False), + Message=mitigation_report, ) print(f"[block-ip] {incident_type} → {status} para {ip_value}. " diff --git a/terraform-tesis-ir-secure-portal/playbooks/notify_alert/__pycache__/handler.cpython-314.pyc b/terraform-tesis-ir-secure-portal/playbooks/notify_alert/__pycache__/handler.cpython-314.pyc new file mode 100644 index 0000000..54292b3 Binary files /dev/null and b/terraform-tesis-ir-secure-portal/playbooks/notify_alert/__pycache__/handler.cpython-314.pyc differ diff --git a/terraform-tesis-ir-secure-portal/playbooks/notify_alert/handler.py b/terraform-tesis-ir-secure-portal/playbooks/notify_alert/handler.py index cbd33e1..0abad88 100644 --- a/terraform-tesis-ir-secure-portal/playbooks/notify_alert/handler.py +++ b/terraform-tesis-ir-secure-portal/playbooks/notify_alert/handler.py @@ -1,14 +1,8 @@ """ Playbook: notify-alert -Recibe incidentes desde una cola SQS dedicada y publica una notificacion -estructurada en SNS. Tambien deja evidencia operativa en S3. - -Incidentes soportados: - - BRUTE_FORCE (severity HIGH) → Componente C, Incidente 1 - - PORT_SCAN (severity MEDIUM) → Componente C, Incidente 2 - - PRIVILEGE_ESCALATION (severity CRITICAL) - - CREDENTIAL_LEAK (severity CRITICAL) - - EXFILTRATION (severity HIGH) +Recibe incidentes desde una cola SQS dedicada, genera un reporte profesional +de seguridad para el SOC y lo publica al topico SNS (para entrega simultanea +y formateada en Gmail y Telegram). Tambien registra evidencia en S3. """ import json import os @@ -26,8 +20,6 @@ EVIDENCE_BUCKET = os.environ["EVIDENCE_BUCKET"] RESPONSE_PREFIX = os.environ.get("RESPONSE_PREFIX", "responses/notify-alert") EC_TZ = ZoneInfo("America/Guayaquil") -# Tipos de incidente que este playbook debe procesar. -# Cualquier otro tipo se omite (skip) para evitar procesamiento no intencionado. SUPPORTED_INCIDENT_TYPES = { "BRUTE_FORCE", "PORT_SCAN", @@ -41,6 +33,43 @@ def now_ecuador() -> str: return datetime.now(EC_TZ).isoformat() +def format_incident_report(alert: dict) -> str: + """Genera un reporte profesional de seguridad (SOC) en texto plano para correo y Telegram.""" + 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 = alert.get("detectedAt", "N/A") + responded_at = alert.get("respondedAt", "N/A") + s3_key = alert.get("s3_log_key", "N/A") + + lines = [ + f"[ALERTA DE SEGURIDAD AWS] - SEVERIDAD: {severity}", + "=" * 50, + f"Tipo de Incidente : {incident_type}", + f"ID de Incidente : {incident_id}", + f"Estado : {status}", + f"Playbook : notify-alert", + "-" * 50, + f"IP Origen : {source_ip}", + f"Recurso Afectado : {resource}", + f"Servicio Afectado : {service}", + f"Activo Objetivo : {asset}", + "-" * 50, + f"Criterio / Motivo : {basis}", + f"Hora Deteccion : {detected_at}", + f"Hora Respuesta : {responded_at}", + f"Evidencia S3 : {s3_key}", + "=" * 50, + ] + return "\n".join(lines) + + def lambda_handler(event, context): results = [] @@ -78,17 +107,7 @@ def lambda_handler(event, context): "incident_id": body.get("incident_id", ""), } - # Campos extra según el tipo de incidente - if incident_type == "PORT_SCAN": - alert["scanned_ports_count"] = body.get("scanned_ports_count", - body.get("event_count", 0)) - alert["rejected_connections"] = body.get("rejected_connections", 0) - elif incident_type == "BRUTE_FORCE": - alert["failed_attempts"] = body.get("failed_attempts", - body.get("event_count", 0)) - alert["detection_window"] = body.get("detection_window", "5 minutes") - - # ── Guardar evidencia en S3 ──────────────────────────────────────── + # ── Guardar evidencia JSON en S3 ─────────────────────────────────── key = f"{RESPONSE_PREFIX}/{body.get('incident_id') or uuid.uuid4().hex}.json" s3.put_object( Bucket=EVIDENCE_BUCKET, @@ -97,15 +116,17 @@ def lambda_handler(event, context): ContentType="application/json", ) - # ── Publicar en SNS ──────────────────────────────────────────────── - subject = f"[{alert['severity']}] Playbook notify-alert: {incident_type}" + # ── Publicar reporte legible en SNS (llega formateado a Gmail y Telegram) + subject = f"[{alert['severity']}] Incidente: {incident_type} ({alert['affectedResource']})" + report_text = format_incident_report(alert) + sns.publish( TopicArn=SNS_ARN, Subject=subject[:100], - Message=json.dumps(alert, indent=2, ensure_ascii=False), + Message=report_text, ) - print(f"[notify-alert] {incident_type} notificado. evidence_key={key}") + print(f"[notify-alert] {incident_type} notificado profesionalmente. evidence_key={key}") results.append({"status": "success", "action": "sns_published", "evidence_key": key}) return { diff --git a/terraform-tesis-ir-secure-portal/playbooks/revoke_credentials/__pycache__/handler.cpython-314.pyc b/terraform-tesis-ir-secure-portal/playbooks/revoke_credentials/__pycache__/handler.cpython-314.pyc new file mode 100644 index 0000000..995b1a5 Binary files /dev/null and b/terraform-tesis-ir-secure-portal/playbooks/revoke_credentials/__pycache__/handler.cpython-314.pyc differ diff --git a/terraform-tesis-ir-secure-portal/playbooks/revoke_credentials/handler.py b/terraform-tesis-ir-secure-portal/playbooks/revoke_credentials/handler.py index 14c0e2a..6f02b57 100644 --- a/terraform-tesis-ir-secure-portal/playbooks/revoke_credentials/handler.py +++ b/terraform-tesis-ir-secure-portal/playbooks/revoke_credentials/handler.py @@ -164,11 +164,27 @@ def lambda_handler(event, context): ) # ── 6. Notificar al equipo vía SNS ─────────────────────────────────── - subject = f"[{entry['severity']}] Playbook revoke-credentials: {status} {username}" + subject = f"[{entry['severity']}] Mitigacion: Credenciales {username} {status}" + mitigation_report = f""" +[MITIGACION DE SEGURIDAD AWS] - ACCION: {status} +================================================== +Playbook : revoke-credentials +Tipo de Incidente : {incident_type} +ID de Incidente : {incident_id} +Estado : {status} +-------------------------------------------------- +Usuario IAM : {username} +Acciones Tomadas : {', '.join(actions_taken)} +DenyAll Aplicado : {'SI' if enforcement.get('deny_all_applied') else 'NO'} +-------------------------------------------------- +Hora Mitigacion : {timestamp} +Evidencia S3 : {key} +================================================== +""".strip() sns.publish( TopicArn=SNS_ARN, Subject=subject[:100], - Message=json.dumps(entry, indent=2, ensure_ascii=False), + Message=mitigation_report, ) print(f"[revoke-credentials] {incident_type} → {status} para {username}. evidence={key}") diff --git a/terraform-tesis-ir-secure-portal/playbooks/telegram_notifier/__pycache__/handler.cpython-314.pyc b/terraform-tesis-ir-secure-portal/playbooks/telegram_notifier/__pycache__/handler.cpython-314.pyc new file mode 100644 index 0000000..d2ec698 Binary files /dev/null and b/terraform-tesis-ir-secure-portal/playbooks/telegram_notifier/__pycache__/handler.cpython-314.pyc differ 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..707706f --- /dev/null +++ b/terraform-tesis-ir-secure-portal/playbooks/telegram_notifier/handler.py @@ -0,0 +1,88 @@ +""" +Lambda: telegram-notifier +Suscrito a Amazon SNS (Topic de alertas de seguridad). +Recibe la notificacion estructurada del topico SNS y la envia directamente +a Telegram en formato monoespaciado (
) usando la biblioteca estandar de Python.
+"""
+import json
+import os
+import urllib.parse
+import urllib.request
+
+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:
+    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" + } + + data_bytes = json.dumps(payload).encode("utf-8") + req = urllib.request.Request( + api_url, + data=data_bytes, + headers={"Content-Type": "application/json"}, + method="POST" + ) + + try: + with urllib.request.urlopen(req, timeout=10) as response: + resp_body = response.read().decode("utf-8") + print(f"[telegram-notifier] Mensaje entregado 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}") + 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", "") + + # 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) + continue + + # Si por alguna razon llega un JSON crudo, parsearlo y formatearlo + 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) + + return { + "status": "success", + "processed": len(results), + "results": results + } diff --git a/terraform-tesis-ir-secure-portal/terraform.tfvars.example b/terraform-tesis-ir-secure-portal/terraform.tfvars.example index f038e0f..8da05ed 100644 --- a/terraform-tesis-ir-secure-portal/terraform.tfvars.example +++ b/terraform-tesis-ir-secure-portal/terraform.tfvars.example @@ -19,6 +19,11 @@ authorized_ip_cidrs = [] # Opcional: correo para SNS y Budget. Debes confirmar la suscripcion SNS por email. alert_email = "tu_correo@ejemplo.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 = "" diff --git a/terraform-tesis-ir-secure-portal/variables.tf b/terraform-tesis-ir-secure-portal/variables.tf index 80116a0..940f8b8 100644 --- a/terraform-tesis-ir-secure-portal/variables.tf +++ b/terraform-tesis-ir-secure-portal/variables.tf @@ -212,3 +212,17 @@ variable "threshold_s3_getobject_exfiltration_count_1h" { 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 = "" +} +