Add Telegram notifier for SNS alerts

- Implemented a new Lambda function `telegram-notifier` that subscribes to an Amazon SNS topic for security alerts.
- The function receives structured notifications from the SNS topic and sends them directly to a specified Telegram chat in a monospaced format.
- Added error handling for missing Telegram bot token and chat ID.
- Formatted messages for better readability in Telegram, including incident severity, type, ID, status, source IP, and affected resource.
- Created a new Python handler file for the Telegram notifier functionality.
This commit is contained in:
bryancito1090 2026-08-31 16:21:11 -05:00
parent ec632afcab
commit 3ad13d8336
18 changed files with 287 additions and 40 deletions

View File

@ -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=[

View File

@ -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]
}

View File

@ -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)."
}

View File

@ -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}. "

View File

@ -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 {

View File

@ -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}")

View File

@ -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 (<pre>) 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"<pre>{text}</pre>",
"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
}

View File

@ -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 = ""

View File

@ -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 = ""
}