feat: Implement security card image generation for Telegram notifications

- Added `card_image.py` to generate PNG images for security incident alerts.
- Updated `handler.py` to create and send visual cards for incidents and mitigations via Telegram.
- Enhanced message parsing to support structured incident data and mitigation details.
- Removed old text message sending method and replaced it with image sending functionality.
- Updated Terraform variables and example configuration for SES DKIM settings.
This commit is contained in:
bryancito1090 2026-09-01 15:56:17 -05:00
parent 3ad13d8336
commit 80fd31a299
21 changed files with 1319 additions and 190 deletions

25
.gitignore vendored Normal file
View File

@ -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_*/

View File

@ -3,6 +3,16 @@
*.tfstate.* *.tfstate.*
.terraform.lock.hcl .terraform.lock.hcl
terraform.tfvars 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
crash.*.log crash.*.log

View File

@ -207,22 +207,30 @@ def publish_incident_queue(payload: dict) -> None:
send_sqs_message(INCIDENT_QUEUE_URL, payload) send_sqs_message(INCIDENT_QUEUE_URL, payload)
# Fan-out controlado a playbooks de respuesta automatica. # Fan-out controlado a playbooks de respuesta automatica.
# Se usan colas dedicadas para que notify-alert y block-ip reciban ambos # Se usan colas dedicadas para que notify-alert y los playbooks de contencion
# el mismo evento sin competir por el mensaje SQS. # reciban ambos el mismo evento sin competir por el mensaje SQS.
# #
# Incidentes con respuesta automatica activa: # Cobertura completa de incidentes:
# BRUTE_FORCE → notify-alert + block-ip (Incidente 1) # 1. BRUTE_FORCE → notify-alert + block-ip
# PORT_SCAN → notify-alert + block-ip (Incidente 2) # 2. PORT_SCAN → notify-alert + block-ip
# PRIVILEGE_ESCALATION → notify-alert + revoke-credentials (Incidente 3) # 3. PRIVILEGE_ESCALATION → notify-alert + revoke-credentials
# CREDENTIAL_LEAK → notify-alert + revoke-credentials (Incidente 4) # 4. CREDENTIAL_LEAK → notify-alert + revoke-credentials
PLAYBOOK_INCIDENTS = {"BRUTE_FORCE", "PORT_SCAN"} # 5. EXFILTRATION → notify-alert
if payload.get("incident_type") in PLAYBOOK_INCIDENTS: 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) 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) 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"} REVOKE_INCIDENTS = {"PRIVILEGE_ESCALATION", "CREDENTIAL_LEAK"}
if payload.get("incident_type") in REVOKE_INCIDENTS: if incident_type in REVOKE_INCIDENTS:
send_sqs_message(PLAYBOOK_NOTIFY_QUEUE_URL, payload)
send_sqs_message(PLAYBOOK_REVOKE_CREDENTIALS_QUEUE_URL, payload) 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"] final_payload["playbooks_requested"] = ["notify-alert", "block-ip"]
elif final_payload.get("incident_type") in {"PRIVILEGE_ESCALATION", "CREDENTIAL_LEAK"}: elif final_payload.get("incident_type") in {"PRIVILEGE_ESCALATION", "CREDENTIAL_LEAK"}:
final_payload["playbooks_requested"] = ["notify-alert", "revoke-credentials"] final_payload["playbooks_requested"] = ["notify-alert", "revoke-credentials"]
elif final_payload.get("incident_type") == "EXFILTRATION":
final_payload["playbooks_requested"] = ["notify-alert"]
evidence_doc = { evidence_doc = {
"incident_id": incident_id, "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}"): if count >= threshold and mark_alert_once(f"BRUTE_FORCE#APP#{source_ip}#{window}"):
severity_basis = ( severity_basis = (
f"HIGH porque la IP {source_ip} alcanzo {count} intentos fallidos " f"HIGH: La IP {source_ip} alcanzó {count} intentos fallidos de autenticación "
f"en 5 minutos; el umbral configurado para BRUTE_FORCE es {threshold}." f"en 5 minutos (umbral={threshold})."
) )
payload = { payload = {
"incident_type": "BRUTE_FORCE", "incident_type": "BRUTE_FORCE",
@ -327,9 +337,9 @@ def analyze_app_event(event_json: dict, config: dict):
"event_count": count, "event_count": count,
"failed_attempts": count, "failed_attempts": count,
"detection_window": "5 minutes", "detection_window": "5 minutes",
"affected_service": event_json.get("affected_service", "Portal de autenticacion corporativo"), "affected_service": event_json.get("affected_service", "Portal Web Corporativo"),
"asset_name": event_json.get("asset_name", f"{PORTAL_INSTANCE_ID}"), "asset_name": event_json.get("asset_name", f"EC2 Instance ({PORTAL_INSTANCE_ID})"),
"asset_type": event_json.get("asset_type", "EC2 web application"), "asset_type": event_json.get("asset_type", "EC2 Web Application"),
"severity_basis": severity_basis, "severity_basis": severity_basis,
"mitigation_playbooks": ["notify-alert", "block-ip"], "mitigation_playbooks": ["notify-alert", "block-ip"],
} }
@ -362,14 +372,16 @@ def analyze_cloudtrail(event_json: dict, config: dict):
"sourceIPAddress": source_ip, "sourceIPAddress": source_ip,
"affectedResource": affected_iam_user(event_json, username), "affectedResource": affected_iam_user(event_json, username),
"s3_log_key": "pending", "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, "event_count": count_user,
"failed_attempts": count_user, "failed_attempts": count_user,
"detection_window": "5 minutes", "detection_window": "5 minutes",
"affected_service": "AWS Sign-In / IAM", "affected_service": "AWS Sign-In / IAM Console",
"asset_name": "AWS Console", "asset_name": f"IAM User ({username})",
"asset_type": "AWS control plane", "asset_type": "AWS Control Plane",
"severity_basis": f"HIGH porque se alcanzaron {count_user} fallos de ConsoleLogin para el mismo usuario en 5 minutos.", "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"], "mitigation_playbooks": ["notify-alert", "block-ip"],
} }
return payload, f"{count_user} fallos de ConsoleLogin para {username} en 5 minutos." 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, "sourceIPAddress": source_ip,
"affectedResource": affected_iam_user(event_json, username), "affectedResource": affected_iam_user(event_json, username),
"s3_log_key": "pending", "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, "event_count": count_ip,
"failed_attempts": count_ip, "failed_attempts": count_ip,
"detection_window": "5 minutes", "detection_window": "5 minutes",
"affected_service": "AWS Sign-In / IAM", "affected_service": "AWS Sign-In / IAM Console",
"asset_name": "AWS Console", "asset_name": f"AWS Console (IP: {source_ip})",
"asset_type": "AWS control plane", "asset_type": "AWS Control Plane",
"severity_basis": f"HIGH porque se alcanzaron {count_ip} fallos de ConsoleLogin desde la misma IP en 5 minutos.", "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"], "mitigation_playbooks": ["notify-alert", "block-ip"],
} }
return payload, f"{count_ip} fallos de ConsoleLogin desde {source_ip} en 5 minutos." 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", "") target_policy_arn = request_params.get("policyArn") or request_params.get("policyDocument", "")
window = current_window(5) window = current_window(5)
count = increment_counter(f"privilege_escalation#{username}#window#{window}", ttl_seconds=900) 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 = { payload = {
"incident_type": "PRIVILEGE_ESCALATION", "incident_type": "PRIVILEGE_ESCALATION",
"severity": "CRITICAL", "severity": "CRITICAL",
"sourceIPAddress": source_ip, "sourceIPAddress": source_ip,
"affectedResource": affected_iam_user(event_json, username), "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", "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, "event_count": count,
"suspicious_actions": [event_name], "suspicious_actions": [event_name],
"mitigation_playbooks": ["notify-alert", "revoke-credentials"],
} }
if target_policy_arn: if target_policy_arn:
payload["target_policy_arn"] = str(target_policy_arn)[:500] 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 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 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): 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 = { payload = {
"incident_type": "CREDENTIAL_LEAK", "incident_type": "CREDENTIAL_LEAK",
"severity": "CRITICAL", "severity": "CRITICAL",
"sourceIPAddress": source_ip, "sourceIPAddress": source_ip,
"affectedResource": affected_iam_user(event_json, username), "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", "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, "event_count": 1,
"service_accessed": event_source, "service_accessed": event_source,
"unusual_region": aws_region, "unusual_region": aws_region,
"mitigation_playbooks": ["notify-alert", "revoke-credentials"],
} }
return payload, f"Credenciales de {username} usadas desde IP no autorizada {source_ip}." 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) count = increment_counter(f"exfiltration#{source_ip}#{bucket}#window#{window}", ttl_seconds=7200)
threshold = int(thresholds.get("s3_getobject_exfiltration_count_1h", 50)) 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): 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 = { payload = {
"incident_type": "EXFILTRATION", "incident_type": "EXFILTRATION",
"severity": "HIGH", "severity": "HIGH",
"sourceIPAddress": source_ip, "sourceIPAddress": source_ip,
"affectedResource": f"s3:::{bucket}" if bucket else f"ec2:instance/{PORTAL_INSTANCE_ID}", "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", "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, "event_count": count,
"total_downloads": count, "total_downloads": count,
"affected_bucket": bucket or "unknown", "affected_bucket": bucket or "unknown",
"first_access": "tracked_in_detection_window", "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." 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) 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}"): 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 = { payload = {
"incident_type": "PORT_SCAN", "incident_type": "PORT_SCAN",
"severity": "MEDIUM", "severity": "MEDIUM",
"sourceIPAddress": srcaddr, "sourceIPAddress": srcaddr,
"affectedResource": f"vpc/{VPC_ID}", "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", "s3_log_key": "pending",
"timestamp": utc_now(), "timestamp": ecuador_now(),
"timestamp_utc": utc_now(),
"timezone": "America/Guayaquil",
"event_count": rejected_count, "event_count": rejected_count,
"rejected_connections": rejected_count, "rejected_connections": rejected_count,
"scanned_ports_count": distinct_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 payload, f"Posible escaneo: {distinct_count} puertos distintos rechazados desde {srcaddr} en 5 minutos.", flow
return None return None

View File

@ -927,12 +927,32 @@ resource "aws_sns_topic" "alerts" {
name = "${var.project_name}-incident-alerts" name = "${var.project_name}-incident-alerts"
} }
resource "aws_sns_topic_subscription" "email" { # Suscripcion de correo gestionada directamente via SES HTML Card (evita correos duplicados en texto plano)
count = var.alert_email != "" ? 1 : 0 # 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 resource "aws_ses_email_identity" "alert" {
protocol = "email" count = var.alert_email != "" ? 1 : 0
endpoint = var.alert_email 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" Action = "sns:Publish"
Resource = aws_sns_topic.alerts.arn Resource = aws_sns_topic.alerts.arn
}, },
{
Sid = "SendSESEmail"
Effect = "Allow"
Action = [
"ses:SendEmail",
"ses:SendRawEmail"
]
Resource = "*"
},
{ {
Sid = "WritePlaybookAudit" Sid = "WritePlaybookAudit"
Effect = "Allow" Effect = "Allow"
@ -1359,6 +1388,15 @@ resource "aws_iam_role_policy" "playbook_block_ip" {
Effect = "Allow" Effect = "Allow"
Action = "sns:Publish" Action = "sns:Publish"
Resource = aws_sns_topic.alerts.arn 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 { environment {
variables = { variables = {
SNS_ALERTS_ARN = aws_sns_topic.alerts.arn SNS_ALERTS_ARN = aws_sns_topic.alerts.arn
EVIDENCE_BUCKET = aws_s3_bucket.evidence.bucket EVIDENCE_BUCKET = aws_s3_bucket.evidence.bucket
RESPONSE_PREFIX = "responses/notify-alert" 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 { environment {
variables = { variables = {
SNS_ALERTS_ARN = aws_sns_topic.alerts.arn SNS_ALERTS_ARN = aws_sns_topic.alerts.arn
EVIDENCE_BUCKET = aws_s3_bucket.evidence.bucket EVIDENCE_BUCKET = aws_s3_bucket.evidence.bucket
TARGET_NACL_ID = aws_vpc.this.default_network_acl_id TARGET_NACL_ID = aws_vpc.this.default_network_acl_id
RESPONSE_PREFIX = "responses/block-ip" RESPONSE_PREFIX = "responses/block-ip"
RULE_MIN = "1" RULE_MIN = "1"
RULE_MAX = "99" 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" Effect = "Allow"
Action = "sns:Publish" Action = "sns:Publish"
Resource = aws_sns_topic.alerts.arn 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 { environment {
variables = { variables = {
SNS_ALERTS_ARN = aws_sns_topic.alerts.arn SNS_ALERTS_ARN = aws_sns_topic.alerts.arn
EVIDENCE_BUCKET = aws_s3_bucket.evidence.bucket EVIDENCE_BUCKET = aws_s3_bucket.evidence.bucket
RESPONSE_PREFIX = "responses/revoke-credentials" 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" { data "archive_file" "telegram_notifier_zip" {
count = var.telegram_bot_token != "" && var.telegram_chat_id != "" ? 1 : 0 count = var.telegram_bot_token != "" && var.telegram_chat_id != "" ? 1 : 0
type = "zip" 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" output_path = "${path.module}/lambda_playbook_telegram_notifier.zip"
} }
@ -1612,8 +1665,8 @@ resource "aws_lambda_function" "telegram_notifier" {
handler = "handler.lambda_handler" handler = "handler.lambda_handler"
runtime = "python3.12" runtime = "python3.12"
architectures = ["x86_64"] architectures = ["x86_64"]
memory_size = 128 memory_size = 256
timeout = 15 timeout = 30
filename = data.archive_file.telegram_notifier_zip[0].output_path filename = data.archive_file.telegram_notifier_zip[0].output_path
source_code_hash = data.archive_file.telegram_notifier_zip[0].output_base64sha256 source_code_hash = data.archive_file.telegram_notifier_zip[0].output_base64sha256

View File

@ -115,3 +115,45 @@ output "telegram_notifier_lambda_name" {
description = "Nombre de la Lambda de Telegram (si esta habilitada)." 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."
}

View File

@ -2,21 +2,9 @@
Playbook: block-ip Playbook: block-ip
Mitigacion de contención real para incidentes de red. Mitigacion de contención real para incidentes de red.
Bloquea la IP origen creando una regla DENY inbound en la Network ACL Bloquea la IP origen creando una regla DENY inbound en la Network ACL
objetivo y registra evidencia de respuesta en S3. objetivo, registra evidencia de respuesta en S3 y notifica via HTML Card (SES) y SNS (Telegram).
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.
""" """
import html
import ipaddress import ipaddress
import json import json
import os import os
@ -29,6 +17,7 @@ import boto3
s3 = boto3.client("s3") s3 = boto3.client("s3")
sns = boto3.client("sns") sns = boto3.client("sns")
ec2 = boto3.client("ec2") ec2 = boto3.client("ec2")
ses = boto3.client("ses")
EVIDENCE_BUCKET = os.environ["EVIDENCE_BUCKET"] EVIDENCE_BUCKET = os.environ["EVIDENCE_BUCKET"]
SNS_ARN = os.environ["SNS_ALERTS_ARN"] 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") RESPONSE_PREFIX = os.environ.get("RESPONSE_PREFIX", "responses/block-ip")
RULE_MIN = int(os.environ.get("RULE_MIN", "1")) RULE_MIN = int(os.environ.get("RULE_MIN", "1"))
RULE_MAX = int(os.environ.get("RULE_MAX", "99")) 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") EC_TZ = ZoneInfo("America/Guayaquil")
# Incidentes que activan el bloqueo de IP en NACL.
BLOCK_INCIDENT_TYPES = {"BRUTE_FORCE", "PORT_SCAN"} BLOCK_INCIDENT_TYPES = {"BRUTE_FORCE", "PORT_SCAN"}
@ -46,8 +36,141 @@ def now_ecuador() -> str:
return datetime.now(EC_TZ).isoformat() 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"""
<tr>
<td style="padding: 7px 12px; color: #64748B; font-size: 13px; font-weight: 600; border-bottom: 1px solid #F1F5F9; width: 36%;">{html.escape(str(k))}</td>
<td style="padding: 7px 12px; color: #0F172A; font-size: 13px; font-family: SFMono-Regular, Consolas, monospace; border-bottom: 1px solid #F1F5F9; word-break: break-all;">{html.escape(str(v))}</td>
</tr>"""
sections_html += f"""
<div style="margin-top: 16px;">
<div style="color: #334155; font-size: 12px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; border-bottom: 2px solid #E2E8F0; padding-bottom: 4px; margin-bottom: 8px;">{html.escape(sec_title)}</div>
<table style="width: 100%; border-collapse: collapse;">
{rows}
</table>
</div>"""
callout_html = ""
if callout_text:
callout_html = f"""
<div style="margin-top: 16px;">
<div style="color: #334155; font-size: 12px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; border-bottom: 2px solid #E2E8F0; padding-bottom: 4px; margin-bottom: 8px;">{html.escape(callout_label)}</div>
<div style="background-color: #F8FAFC; border-left: 4px solid {c['border']}; padding: 12px 16px; border-radius: 0 4px 4px 0; color: #1E293B; font-size: 13px; line-height: 1.5;">
{html.escape(callout_text)}
</div>
</div>"""
return f"""<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"></head>
<body style="margin: 0; padding: 20px; background-color: #F4F6F8; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;">
<div style="max-width: 620px; margin: 0 auto; background-color: #FFFFFF; border-radius: 8px; overflow: hidden; border: 1px solid #E2E8F0; box-shadow: 0 2px 8px rgba(0,0,0,0.06);">
<div style="background-color: {c['header']}; padding: 18px 24px; color: #FFFFFF;">
<div style="font-size: 11px; text-transform: uppercase; letter-spacing: 1px; opacity: 0.85; margin-bottom: 4px;">{html.escape(subtitle)}</div>
<div style="font-size: 18px; font-weight: 700; letter-spacing: 0.2px;">{html.escape(title)}</div>
</div>
<div style="padding: 20px 24px;">
<div style="display: inline-block; padding: 4px 12px; border-radius: 4px; background-color: {c['badge_bg']}; color: {c['badge_text']}; font-weight: 700; font-size: 12px; border: 1px solid {c['border']}; text-transform: uppercase; margin-bottom: 8px;">
{html.escape(badge_text)}
</div>
{sections_html}
{callout_html}
</div>
<div style="background-color: #F1F5F9; padding: 12px 24px; border-top: 1px solid #E2E8F0; color: #64748B; font-size: 11px; text-align: center;">
{html.escape(footer_text)}
</div>
</div>
</body>
</html>"""
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: def valid_public_ip(ip_value: str) -> bool:
"""Verifica que la IP sea publica y valida antes de aplicar el bloqueo."""
try: try:
ip = ipaddress.ip_address(ip_value) ip = ipaddress.ip_address(ip_value)
except ValueError: except ValueError:
@ -59,7 +182,6 @@ def valid_public_ip(ip_value: str) -> bool:
def next_rule_number(nacl_id: str) -> int: def next_rule_number(nacl_id: str) -> int:
"""Calcula el siguiente numero de regla libre en el rango DENY (1-99)."""
response = ec2.describe_network_acls(NetworkAclIds=[nacl_id]) response = ec2.describe_network_acls(NetworkAclIds=[nacl_id])
used = set() used = set()
for entry in response.get("NetworkAcls", [{}])[0].get("Entries", []): for entry in response.get("NetworkAcls", [{}])[0].get("Entries", []):
@ -72,10 +194,6 @@ def next_rule_number(nacl_id: str) -> int:
def block_ip(ip_value: str) -> dict: def block_ip(ip_value: str) -> dict:
"""
ENFORCEMENT POINT: crea la regla DENY en la NACL.
Es idempotente: si el DENY ya existe devuelve already_present=True.
"""
cidr = f"{ip_value}/32" cidr = f"{ip_value}/32"
response = ec2.describe_network_acls(NetworkAclIds=[TARGET_NACL_ID]) response = ec2.describe_network_acls(NetworkAclIds=[TARGET_NACL_ID])
entries = response.get("NetworkAcls", [{}])[0].get("Entries", []) entries = response.get("NetworkAcls", [{}])[0].get("Entries", [])
@ -93,13 +211,12 @@ def block_ip(ip_value: str) -> dict:
} }
rule_number = next_rule_number(TARGET_NACL_ID) rule_number = next_rule_number(TARGET_NACL_ID)
# ← línea exacta del bloqueo real a nivel de red
ec2.create_network_acl_entry( ec2.create_network_acl_entry(
NetworkAclId=TARGET_NACL_ID, NetworkAclId=TARGET_NACL_ID,
RuleNumber=rule_number, RuleNumber=rule_number,
Protocol="-1", # todos los protocolos Protocol="-1",
RuleAction="deny", RuleAction="deny",
Egress=False, # tráfico de entrada (desde el atacante) Egress=False,
CidrBlock=cidr, CidrBlock=cidr,
) )
print(f"[block-ip] NACL {TARGET_NACL_ID}: regla DENY #{rule_number} creada para {cidr}") print(f"[block-ip] NACL {TARGET_NACL_ID}: regla DENY #{rule_number} creada para {cidr}")
@ -141,7 +258,6 @@ def lambda_handler(event, context):
incident_type = body.get("incident_type", "UNKNOWN") incident_type = body.get("incident_type", "UNKNOWN")
# Solo procesar incidentes de red que requieren bloqueo de IP
if incident_type not in BLOCK_INCIDENT_TYPES: if incident_type not in BLOCK_INCIDENT_TYPES:
print(f"[block-ip] Tipo {incident_type} no requiere bloqueo de IP. Omitiendo.") 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}"}) results.append({"status": "skipped", "reason": f"not_in_block_list:{incident_type}"})
@ -187,7 +303,6 @@ def lambda_handler(event, context):
"incident_id": body.get("incident_id", ""), "incident_id": body.get("incident_id", ""),
} }
# Campos extra según el tipo de incidente
if incident_type == "PORT_SCAN": if incident_type == "PORT_SCAN":
entry["scanned_ports_count"] = body.get("scanned_ports_count", entry["scanned_ports_count"] = body.get("scanned_ports_count",
body.get("event_count", 0)) body.get("event_count", 0))
@ -196,7 +311,7 @@ def lambda_handler(event, context):
entry["failed_attempts"] = body.get("failed_attempts", entry["failed_attempts"] = body.get("failed_attempts",
body.get("event_count", 0)) body.get("event_count", 0))
# ── Actualizar lista de IPs bloqueadas (blocklist acumulativo) ───── # ── Actualizar lista de IPs bloqueadas ────────────────────────────
blocklist = load_blocklist() blocklist = load_blocklist()
if not any(item.get("sourceIPAddress") == ip_value for item in blocklist): if not any(item.get("sourceIPAddress") == ip_value for item in blocklist):
blocklist.append(entry) blocklist.append(entry)
@ -211,28 +326,43 @@ def lambda_handler(event, context):
ContentType="application/json", ContentType="application/json",
) )
# ── Notificar al equipo via SNS ──────────────────────────────────── # ── Generar reportes ───────────────────────────────────────────────
subject = f"[{entry['severity']}] Mitigacion: IP {ip_value} {status} en NACL" subject = f"[{entry['severity']}] Mitigacion: IP {ip_value} {status} en NACL"
mitigation_report = f""" formatted_time = format_dt(timestamp)
[MITIGACION DE SEGURIDAD AWS] - ACCION: {status} nacl_id = enforcement.get('network_acl_id', 'N/A')
================================================== rule_num = enforcement.get('rule_number', 'N/A')
Playbook : block-ip
Tipo de Incidente : {incident_type} mitigation_plain = "\n".join([
ID de Incidente : {entry['incident_id']} "=" * 60,
Estado : {status} f"[MITIGACION DE SEGURIDAD AWS] - ACCION: {status}",
-------------------------------------------------- "=" * 60,
IP Objetivo : {ip_value} "INFORMACION GENERAL:",
Network ACL : {enforcement.get('network_acl_id', 'N/A')} f" Estado : {status}",
Regla Creada : #{enforcement.get('rule_number', 'N/A')} f" Playbook : block-ip",
-------------------------------------------------- f" Tipo de Incidente : {incident_type}",
Hora Mitigacion : {timestamp} f" ID de Incidente : {entry['incident_id']}",
Evidencia S3 : {key} "",
================================================== "CONTENCION APLICADA:",
""".strip() 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( sns.publish(
TopicArn=SNS_ARN, TopicArn=SNS_ARN,
Subject=subject[:100], Subject=subject[:100],
Message=mitigation_report, Message=mitigation_plain,
) )
print(f"[block-ip] {incident_type} → {status} para {ip_value}. " print(f"[block-ip] {incident_type} → {status} para {ip_value}. "

View File

@ -1,9 +1,10 @@
""" """
Playbook: notify-alert Playbook: notify-alert
Recibe incidentes desde una cola SQS dedicada, genera un reporte profesional 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 de seguridad para el SOC (formato tarjeta HTML con colores diferenciados y texto plano normalizado)
y formateada en Gmail y Telegram). Tambien registra evidencia en S3. y lo entrega via SES a Gmail y via SNS a Telegram. Tambien registra evidencia en S3.
""" """
import html
import json import json
import os import os
import uuid import uuid
@ -14,10 +15,13 @@ import boto3
sns = boto3.client("sns") sns = boto3.client("sns")
s3 = boto3.client("s3") s3 = boto3.client("s3")
ses = boto3.client("ses")
SNS_ARN = os.environ["SNS_ALERTS_ARN"] SNS_ARN = os.environ["SNS_ALERTS_ARN"]
EVIDENCE_BUCKET = os.environ["EVIDENCE_BUCKET"] EVIDENCE_BUCKET = os.environ["EVIDENCE_BUCKET"]
RESPONSE_PREFIX = os.environ.get("RESPONSE_PREFIX", "responses/notify-alert") 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") EC_TZ = ZoneInfo("America/Guayaquil")
SUPPORTED_INCIDENT_TYPES = { SUPPORTED_INCIDENT_TYPES = {
@ -33,8 +37,84 @@ def now_ecuador() -> str:
return datetime.now(EC_TZ).isoformat() 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"""
<tr>
<td style="padding: 7px 12px; color: #64748B; font-size: 13px; font-weight: 600; border-bottom: 1px solid #F1F5F9; width: 36%;">{html.escape(str(k))}</td>
<td style="padding: 7px 12px; color: #0F172A; font-size: 13px; font-family: SFMono-Regular, Consolas, monospace; border-bottom: 1px solid #F1F5F9; word-break: break-all;">{html.escape(str(v))}</td>
</tr>"""
sections_html += f"""
<div style="margin-top: 16px;">
<div style="color: #334155; font-size: 12px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; border-bottom: 2px solid #E2E8F0; padding-bottom: 4px; margin-bottom: 8px;">{html.escape(sec_title)}</div>
<table style="width: 100%; border-collapse: collapse;">
{rows}
</table>
</div>"""
callout_html = ""
if callout_text:
callout_html = f"""
<div style="margin-top: 16px;">
<div style="color: #334155; font-size: 12px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; border-bottom: 2px solid #E2E8F0; padding-bottom: 4px; margin-bottom: 8px;">{html.escape(callout_label)}</div>
<div style="background-color: #F8FAFC; border-left: 4px solid {c['border']}; padding: 12px 16px; border-radius: 0 4px 4px 0; color: #1E293B; font-size: 13px; line-height: 1.5;">
{html.escape(callout_text)}
</div>
</div>"""
return f"""<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"></head>
<body style="margin: 0; padding: 20px; background-color: #F4F6F8; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;">
<div style="max-width: 620px; margin: 0 auto; background-color: #FFFFFF; border-radius: 8px; overflow: hidden; border: 1px solid #E2E8F0; box-shadow: 0 2px 8px rgba(0,0,0,0.06);">
<div style="background-color: {c['header']}; padding: 18px 24px; color: #FFFFFF;">
<div style="font-size: 11px; text-transform: uppercase; letter-spacing: 1px; opacity: 0.85; margin-bottom: 4px;">{html.escape(subtitle)}</div>
<div style="font-size: 18px; font-weight: 700; letter-spacing: 0.2px;">{html.escape(title)}</div>
</div>
<div style="padding: 20px 24px;">
<div style="display: inline-block; padding: 4px 12px; border-radius: 4px; background-color: {c['badge_bg']}; color: {c['badge_text']}; font-weight: 700; font-size: 12px; border: 1px solid {c['border']}; text-transform: uppercase; margin-bottom: 8px;">
{html.escape(badge_text)}
</div>
{sections_html}
{callout_html}
</div>
<div style="background-color: #F1F5F9; padding: 12px 24px; border-top: 1px solid #E2E8F0; color: #64748B; font-size: 11px; text-align: center;">
{html.escape(footer_text)}
</div>
</div>
</body>
</html>"""
def format_incident_report(alert: dict) -> str: def format_incident_report(alert: dict) -> str:
"""Genera un reporte profesional de seguridad (SOC) en texto plano para correo y Telegram.""" """Genera un reporte profesional de seguridad (SOC) estructurado y normalizado en texto plano."""
incident_type = alert.get("incident_type", "NO_ESPECIFICADO") incident_type = alert.get("incident_type", "NO_ESPECIFICADO")
severity = alert.get("severity", "MEDIUM") severity = alert.get("severity", "MEDIUM")
status = alert.get("status", "NOTIFICADO") status = alert.get("status", "NOTIFICADO")
@ -44,32 +124,103 @@ def format_incident_report(alert: dict) -> str:
service = alert.get("affected_service", "N/A") service = alert.get("affected_service", "N/A")
asset = alert.get("asset_name", "N/A") asset = alert.get("asset_name", "N/A")
basis = alert.get("severity_basis", "N/A") basis = alert.get("severity_basis", "N/A")
detected_at = alert.get("detectedAt", "N/A") detected_at = format_dt(alert.get("detectedAt", "N/A"))
responded_at = alert.get("respondedAt", "N/A") responded_at = format_dt(alert.get("respondedAt", "N/A"))
s3_key = alert.get("s3_log_key", "N/A") s3_key = alert.get("s3_log_key", "N/A")
lines = [ lines = [
f"[ALERTA DE SEGURIDAD AWS] - SEVERIDAD: {severity}", "=" * 60,
"=" * 50, "[ALERTA DE SEGURIDAD AWS] - SOC INCIDENT RESPONSE",
f"Tipo de Incidente : {incident_type}", "=" * 60,
f"ID de Incidente : {incident_id}", "INFORMACION GENERAL:",
f"Estado : {status}", f" Severidad : {severity}",
f"Playbook : notify-alert", f" Tipo de Incidente : {incident_type}",
"-" * 50, f" ID de Incidente : {incident_id}",
f"IP Origen : {source_ip}", f" Estado : {status}",
f"Recurso Afectado : {resource}", f" Playbook : notify-alert",
f"Servicio Afectado : {service}", "",
f"Activo Objetivo : {asset}", "RECURSO Y ORIGEN:",
"-" * 50, f" IP Origen : {source_ip}",
f"Criterio / Motivo : {basis}", f" Recurso Afectado : {resource}",
f"Hora Deteccion : {detected_at}", f" Servicio Afectado : {service}",
f"Hora Respuesta : {responded_at}", f" Activo Objetivo : {asset}",
f"Evidencia S3 : {s3_key}", "",
"=" * 50, "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) 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): def lambda_handler(event, context):
results = [] results = []
@ -116,10 +267,15 @@ def lambda_handler(event, context):
ContentType="application/json", ContentType="application/json",
) )
# ── Publicar reporte legible en SNS (llega formateado a Gmail y Telegram) # ── Generar reportes ───────────────────────────────────────────────
subject = f"[{alert['severity']}] Incidente: {incident_type} ({alert['affectedResource']})" subject = f"[{alert['severity']}] Incidente: {incident_type} ({alert['affectedResource']})"
report_text = format_incident_report(alert) 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( sns.publish(
TopicArn=SNS_ARN, TopicArn=SNS_ARN,
Subject=subject[:100], Subject=subject[:100],

View File

@ -1,12 +1,10 @@
""" """
Playbook: revoke-credentials Playbook: revoke-credentials
Revoca (desactiva) las access keys de un usuario IAM comprometido Revoca (desactiva) las access keys de un usuario IAM comprometido,
y adjunta una política de denegación explícita para bloqueo inmediato. adjunta una politica de denegacion explicita (DenyAll) para bloqueo inmediato,
registra evidencia en S3 y notifica via HTML Card (SES) y SNS (Telegram).
Punto de cumplimiento (enforcement point):
1. iam.update_access_key(Status="Inactive") ← key del atacante revocada
2. iam.put_user_policy("EmergencyDenyAll") ← bloqueo total DenyAll
""" """
import html
import json import json
import os import os
import uuid import uuid
@ -18,10 +16,13 @@ import boto3
s3 = boto3.client("s3") s3 = boto3.client("s3")
sns = boto3.client("sns") sns = boto3.client("sns")
iam = boto3.client("iam") iam = boto3.client("iam")
ses = boto3.client("ses")
EVIDENCE_BUCKET = os.environ["EVIDENCE_BUCKET"] EVIDENCE_BUCKET = os.environ["EVIDENCE_BUCKET"]
SNS_ARN = os.environ["SNS_ALERTS_ARN"] SNS_ARN = os.environ["SNS_ALERTS_ARN"]
RESPONSE_PREFIX = os.environ.get("RESPONSE_PREFIX", "responses/revoke-credentials") 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") EC_TZ = ZoneInfo("America/Guayaquil")
DENY_ALL_POLICY = json.dumps({ DENY_ALL_POLICY = json.dumps({
@ -33,9 +34,144 @@ DENY_ALL_POLICY = json.dumps({
}] }]
}) })
def now_ecuador() -> str: def now_ecuador() -> str:
return datetime.now(EC_TZ).isoformat() 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"""
<tr>
<td style="padding: 7px 12px; color: #64748B; font-size: 13px; font-weight: 600; border-bottom: 1px solid #F1F5F9; width: 36%;">{html.escape(str(k))}</td>
<td style="padding: 7px 12px; color: #0F172A; font-size: 13px; font-family: SFMono-Regular, Consolas, monospace; border-bottom: 1px solid #F1F5F9; word-break: break-all;">{html.escape(str(v))}</td>
</tr>"""
sections_html += f"""
<div style="margin-top: 16px;">
<div style="color: #334155; font-size: 12px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; border-bottom: 2px solid #E2E8F0; padding-bottom: 4px; margin-bottom: 8px;">{html.escape(sec_title)}</div>
<table style="width: 100%; border-collapse: collapse;">
{rows}
</table>
</div>"""
callout_html = ""
if callout_text:
callout_html = f"""
<div style="margin-top: 16px;">
<div style="color: #334155; font-size: 12px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; border-bottom: 2px solid #E2E8F0; padding-bottom: 4px; margin-bottom: 8px;">{html.escape(callout_label)}</div>
<div style="background-color: #F8FAFC; border-left: 4px solid {c['border']}; padding: 12px 16px; border-radius: 0 4px 4px 0; color: #1E293B; font-size: 13px; line-height: 1.5;">
{html.escape(callout_text)}
</div>
</div>"""
return f"""<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"></head>
<body style="margin: 0; padding: 20px; background-color: #F4F6F8; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;">
<div style="max-width: 620px; margin: 0 auto; background-color: #FFFFFF; border-radius: 8px; overflow: hidden; border: 1px solid #E2E8F0; box-shadow: 0 2px 8px rgba(0,0,0,0.06);">
<div style="background-color: {c['header']}; padding: 18px 24px; color: #FFFFFF;">
<div style="font-size: 11px; text-transform: uppercase; letter-spacing: 1px; opacity: 0.85; margin-bottom: 4px;">{html.escape(subtitle)}</div>
<div style="font-size: 18px; font-weight: 700; letter-spacing: 0.2px;">{html.escape(title)}</div>
</div>
<div style="padding: 20px 24px;">
<div style="display: inline-block; padding: 4px 12px; border-radius: 4px; background-color: {c['badge_bg']}; color: {c['badge_text']}; font-weight: 700; font-size: 12px; border: 1px solid {c['border']}; text-transform: uppercase; margin-bottom: 8px;">
{html.escape(badge_text)}
</div>
{sections_html}
{callout_html}
</div>
<div style="background-color: #F1F5F9; padding: 12px 24px; border-top: 1px solid #E2E8F0; color: #64748B; font-size: 11px; text-align: center;">
{html.escape(footer_text)}
</div>
</div>
</body>
</html>"""
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: def load_revoke_log() -> list:
try: try:
obj = s3.get_object(Bucket=EVIDENCE_BUCKET, Key=f"{RESPONSE_PREFIX}/revoked-credentials.json") obj = s3.get_object(Bucket=EVIDENCE_BUCKET, Key=f"{RESPONSE_PREFIX}/revoked-credentials.json")
@ -43,6 +179,7 @@ def load_revoke_log() -> list:
except Exception: except Exception:
return [] return []
def save_revoke_log(revoke_log: list) -> None: def save_revoke_log(revoke_log: list) -> None:
s3.put_object( s3.put_object(
Bucket=EVIDENCE_BUCKET, Bucket=EVIDENCE_BUCKET,
@ -51,6 +188,7 @@ def save_revoke_log(revoke_log: list) -> None:
ContentType="application/json", ContentType="application/json",
) )
def lambda_handler(event, context): def lambda_handler(event, context):
results = [] results = []
@ -62,14 +200,12 @@ def lambda_handler(event, context):
continue continue
incident_type = body.get("incident_type", "UNKNOWN") incident_type = body.get("incident_type", "UNKNOWN")
# Procesar incidentes de escalada o leak de credenciales
if incident_type not in {"PRIVILEGE_ESCALATION", "CREDENTIAL_LEAK"}: if incident_type not in {"PRIVILEGE_ESCALATION", "CREDENTIAL_LEAK"}:
print(f"[revoke-credentials] Tipo {incident_type} no requiere revocacion. Omitiendo.") print(f"[revoke-credentials] Tipo {incident_type} no requiere revocacion. Omitiendo.")
results.append({"status": "skipped", "reason": f"not_in_revoke_list:{incident_type}"}) results.append({"status": "skipped", "reason": f"not_in_revoke_list:{incident_type}"})
continue continue
affected_resource = body.get("affectedResource", "") affected_resource = body.get("affectedResource", "")
# Extraer el usuario del formato "iam:user/nombre"
username = affected_resource.replace("iam:user/", "") if affected_resource.startswith("iam:user/") else affected_resource username = affected_resource.replace("iam:user/", "") if affected_resource.startswith("iam:user/") else affected_resource
source_ip = body.get("sourceIPAddress", "0.0.0.0") source_ip = body.get("sourceIPAddress", "0.0.0.0")
timestamp = now_ecuador() timestamp = now_ecuador()
@ -163,28 +299,43 @@ def lambda_handler(event, context):
ContentType="application/json", ContentType="application/json",
) )
# ── 6. Notificar al equipo vía SNS ─────────────────────────────────── # ── 6. Generar reportes ──────────────────────────────────────────────
subject = f"[{entry['severity']}] Mitigacion: Credenciales {username} {status}" subject = f"[{entry['severity']}] Mitigacion: Credenciales {username} {status}"
mitigation_report = f""" formatted_time = format_dt(timestamp)
[MITIGACION DE SEGURIDAD AWS] - ACCION: {status} 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"
Playbook : revoke-credentials
Tipo de Incidente : {incident_type} mitigation_plain = "\n".join([
ID de Incidente : {incident_id} "=" * 60,
Estado : {status} f"[MITIGACION DE SEGURIDAD AWS] - ACCION: {status}",
-------------------------------------------------- "=" * 60,
Usuario IAM : {username} "INFORMACION GENERAL:",
Acciones Tomadas : {', '.join(actions_taken)} f" Estado : {status}",
DenyAll Aplicado : {'SI' if enforcement.get('deny_all_applied') else 'NO'} f" Playbook : revoke-credentials",
-------------------------------------------------- f" Tipo de Incidente : {incident_type}",
Hora Mitigacion : {timestamp} f" ID de Incidente : {incident_id}",
Evidencia S3 : {key} "",
================================================== "CONTENCION APLICADA:",
""".strip() 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( sns.publish(
TopicArn=SNS_ARN, TopicArn=SNS_ARN,
Subject=subject[:100], Subject=subject[:100],
Message=mitigation_report, Message=mitigation_plain,
) )
print(f"[revoke-credentials] {incident_type} → {status} para {username}. evidence={key}") print(f"[revoke-credentials] {incident_type} → {status} para {username}. evidence={key}")

View File

@ -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()

View File

@ -1,45 +1,211 @@
""" """
Lambda: telegram-notifier Lambda: telegram-notifier
Suscrito a Amazon SNS (Topic de alertas de seguridad). Suscrito a Amazon SNS (Topic de alertas de seguridad).
Recibe la notificacion estructurada del topico SNS y la envia directamente Recibe las notificaciones de incidentes y mitigaciones de seguridad publicadas
a Telegram en formato monoespaciado (<pre>) usando la biblioteca estandar de Python. 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 json
import os import os
import urllib.parse import urllib.parse
import urllib.request 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_BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN", "")
TELEGRAM_CHAT_ID = os.environ.get("TELEGRAM_CHAT_ID", "") 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: if not TELEGRAM_BOT_TOKEN or not TELEGRAM_CHAT_ID:
print("[telegram-notifier] Variables TELEGRAM_BOT_TOKEN o TELEGRAM_CHAT_ID no configuradas.") print("[telegram-notifier] Variables TELEGRAM_BOT_TOKEN o TELEGRAM_CHAT_ID no configuradas.")
return {"status": "skipped", "reason": "missing_credentials"} return {"status": "skipped", "reason": "missing_credentials"}
api_url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage" boundary = f"----WebKitFormBoundary{uuid.uuid4().hex[:16]}"
payload = { body = bytearray()
"chat_id": TELEGRAM_CHAT_ID,
"text": f"<pre>{text}</pre>",
"parse_mode": "HTML"
}
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( req = urllib.request.Request(
api_url, api_url,
data=data_bytes, data=bytes(body),
headers={"Content-Type": "application/json"}, headers={"Content-Type": f"multipart/form-data; boundary={boundary}"},
method="POST" method="POST"
) )
try: 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") 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)} return {"status": "success", "response": json.loads(resp_body)}
except Exception as exc: 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)} return {"status": "error", "error": str(exc)}
@ -48,38 +214,42 @@ def lambda_handler(event, context):
for record in event.get("Records", []): for record in event.get("Records", []):
sns_record = record.get("Sns", {}) sns_record = record.get("Sns", {})
raw_message = sns_record.get("Message", "") raw_message = sns_record.get("Message", "").strip()
# Si el mensaje ya es texto plano formateado por notify-alert, enviarlo directo if not raw_message:
if not raw_message.strip().startswith("{"):
send_result = send_telegram_message(raw_message.strip())
results.append(send_result)
continue continue
# Si por alguna razon llega un JSON crudo, parsearlo y formatearlo png_bytes = None
caption = ""
try: try:
message_data = json.loads(raw_message) if raw_message.startswith("{"):
if "incident_payload" in message_data: data = json.loads(raw_message)
message_data = message_data["incident_payload"] if "incident_payload" in data:
data = data["incident_payload"]
lines = [ png_bytes = create_incident_card_image(data)
f"[ALERTA DE SEGURIDAD AWS] - SEVERIDAD: {message_data.get('severity', 'HIGH')}", caption = f"Incidente: {data.get('incident_type', 'INCIDENT')} ({data.get('severity', 'HIGH')})"
"=" * 50, elif "ALERTA DE SEGURIDAD AWS" in raw_message:
f"Tipo de Incidente : {message_data.get('incident_type', 'NO_ESPECIFICADO')}", kv = parse_key_values(raw_message)
f"ID de Incidente : {message_data.get('incident_id', 'N/A')}", png_bytes = create_incident_card_image(kv)
f"Estado : {message_data.get('status', 'NOTIFICADO')}", caption = f"Alerta: {kv.get('Tipo de Incidente', 'INCIDENT')} [{kv.get('Severidad', 'HIGH')}]"
"-" * 50, elif "MITIGACION DE SEGURIDAD AWS" in raw_message or "MITIGACIÓN DE SEGURIDAD AWS" in raw_message:
f"IP Origen : {message_data.get('sourceIPAddress', 'N/A')}", kv = parse_key_values(raw_message)
f"Recurso Afectado : {message_data.get('affectedResource', 'N/A')}", png_bytes = create_mitigation_card_image(raw_message, kv)
f"Criterio / Motivo : {message_data.get('severity_basis', 'N/A')}", caption = f"Mitigacion: {kv.get('Playbook', 'block-ip')} [{kv.get('Estado', 'BLOCKED')}]"
"=" * 50, else:
] # Si es un mensaje generico, crear tarjeta generica
formatted_text = "\n".join(lines) kv = parse_key_values(raw_message)
send_result = send_telegram_message(formatted_text) png_bytes = create_incident_card_image(kv)
results.append(send_result) caption = "Notificacion de Seguridad AWS"
except Exception: except Exception as exc:
send_result = send_telegram_message(str(raw_message)) print(f"[telegram-notifier] Error construyendo tarjeta grafica: {exc}")
results.append(send_result)
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 { return {
"status": "success", "status": "success",

View File

@ -19,6 +19,10 @@ authorized_ip_cidrs = []
# Opcional: correo para SNS y Budget. Debes confirmar la suscripcion SNS por email. # Opcional: correo para SNS y Budget. Debes confirmar la suscripcion SNS por email.
alert_email = "tu_correo@ejemplo.com" 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 # Opcional: Notificaciones a Telegram
# Obtén el token con @BotFather y el chat_id con @userinfobot o @RawDataBot # Obtén el token con @BotFather y el chat_id con @userinfobot o @RawDataBot
telegram_bot_token = "" telegram_bot_token = ""

View File

@ -49,6 +49,18 @@ variable "alert_email" {
default = "" 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" { variable "create_budget" {
description = "Crear un presupuesto mensual con alertas si alert_email no esta vacio." description = "Crear un presupuesto mensual con alertas si alert_email no esta vacio."
type = bool type = bool