fix: respetar administracion autorizada y evitar bucles de respuesta
This commit is contained in:
parent
a789257551
commit
b3652a83fc
|
|
@ -102,3 +102,9 @@ Cuando un incidente supera los umbrales de detección, la función `save_inciden
|
|||
- Si el incidente es de red (`BRUTE_FORCE`, `PORT_SCAN`), publica a `tesis-ir-playbook-block-ip-queue`.
|
||||
- Si el incidente es de credenciales (`PRIVILEGE_ESCALATION`, `CREDENTIAL_LEAK`), publica a `tesis-ir-playbook-revoke-credentials-queue`.
|
||||
5. **Métricas en CloudWatch:** Emite un punto métrico con Namespace `TesisIR`, nombre `IncidentDetected` y dimensiones por tipo de incidente y severidad.
|
||||
|
||||
## Administracion autorizada y acciones de respuesta
|
||||
|
||||
Una accion IAM critica no genera escalada si el actor esta en `authorized_admin_users` **y** su IP pertenece a `authorized_ips`. Configura el usuario real del despliegue en tu `terraform.tfvars` privado (por ejemplo `authorized_admin_users = ["admin-tesis"]`) y conserva tu IP actual autorizada. El mismo usuario desde otra IP sigue sujeto a deteccion de escalada/fuga de credenciales.
|
||||
|
||||
Terraform publica el ARN del rol del playbook de revocacion en `automated_response_role_arns`. El detector excluye unicamente sus llamadas IAM esperadas (`ListAccessKeys`, `UpdateAccessKey`, `PutUserPolicy`), verificando la identidad `AssumedRole` y el ARN del emisor. Esto evita que la contencion genere incidentes recursivos; las acciones del playbook conservan su auditoria en S3/CloudTrail. Otras operaciones y otros roles siguen siendo evaluados.
|
||||
|
|
|
|||
|
|
@ -356,6 +356,17 @@ def analyze_cloudtrail(event_json: dict, config: dict):
|
|||
thresholds = config.get("thresholds", {})
|
||||
allowed_ips = config.get("authorized_ips", [])
|
||||
|
||||
# La contencion escribe su propia evidencia; no realimentar sus llamadas IAM.
|
||||
identity = event_json.get("userIdentity", {}) or {}
|
||||
issuer = ((identity.get("sessionContext") or {}).get("sessionIssuer") or {}).get("arn")
|
||||
if (
|
||||
event_source == "iam.amazonaws.com"
|
||||
and identity.get("type") == "AssumedRole"
|
||||
and event_name in {"ListAccessKeys", "UpdateAccessKey", "PutUserPolicy"}
|
||||
and issuer in config.get("automated_response_role_arns", [])
|
||||
):
|
||||
return None
|
||||
|
||||
# Incidente 1: fuerza bruta por ConsoleLogin fallido.
|
||||
if event_name == "ConsoleLogin":
|
||||
response = event_json.get("responseElements", {}) or {}
|
||||
|
|
@ -419,6 +430,8 @@ def analyze_cloudtrail(event_json: dict, config: dict):
|
|||
"UpdateAssumeRolePolicy",
|
||||
}
|
||||
if event_source == "iam.amazonaws.com" and event_name in iam_critical_events:
|
||||
if username in config.get("authorized_admin_users", []) and ip_in_cidrs(source_ip, allowed_ips):
|
||||
return None
|
||||
request_params = event_json.get("requestParameters", {}) or {}
|
||||
target_policy_arn = request_params.get("policyArn") or request_params.get("policyDocument", "")
|
||||
window = current_window(5)
|
||||
|
|
|
|||
|
|
@ -436,7 +436,8 @@ resource "aws_s3_object" "detector_config" {
|
|||
critical_policies = [
|
||||
aws_iam_policy.critical_policy.name
|
||||
]
|
||||
authorized_admin_users = var.authorized_admin_users
|
||||
authorized_admin_users = var.authorized_admin_users
|
||||
automated_response_role_arns = [aws_iam_role.playbook_revoke_credentials.arn]
|
||||
thresholds = {
|
||||
console_login_failures_same_user_5m = var.threshold_console_login_failures_same_user_5m
|
||||
console_login_failures_same_ip_5m = var.threshold_console_login_failures_same_ip_5m
|
||||
|
|
|
|||
|
|
@ -0,0 +1,68 @@
|
|||
import copy
|
||||
import importlib.util
|
||||
import os
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
|
||||
class DetectorAuthorizationTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
env = {name: "test-value" for name in [
|
||||
"INCIDENTS_TABLE", "STATE_TABLE", "EVIDENCE_BUCKET", "SNS_TOPIC_ARN", "CONFIG_KEY"
|
||||
]}
|
||||
path = Path(__file__).resolve().parents[1] / "terraform-tesis-ir-secure-portal/lambda/lambda_function.py"
|
||||
with patch.dict(os.environ, env), patch("boto3.resource"), patch("boto3.client"):
|
||||
spec = importlib.util.spec_from_file_location("detector_authorization", path)
|
||||
self.detector = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(self.detector)
|
||||
counter = patch.object(self.detector, "increment_counter", return_value=1)
|
||||
once = patch.object(self.detector, "mark_alert_once", return_value=True)
|
||||
counter.start()
|
||||
once.start()
|
||||
self.addCleanup(counter.stop)
|
||||
self.addCleanup(once.stop)
|
||||
self.role = "arn:aws:iam::123456789012:role/response-worker"
|
||||
self.config = {
|
||||
"authorized_admin_users": ["admin-tesis"],
|
||||
"authorized_ips": ["192.0.2.10/32"],
|
||||
"automated_response_role_arns": [self.role],
|
||||
}
|
||||
self.event = {
|
||||
"eventName": "AttachRolePolicy", "eventSource": "iam.amazonaws.com",
|
||||
"sourceIPAddress": "192.0.2.10",
|
||||
"userIdentity": {"type": "IAMUser", "userName": "admin-tesis"},
|
||||
}
|
||||
|
||||
def test_admin_exemption_requires_both_identity_and_allowed_ip(self):
|
||||
self.assertIsNone(self.detector.analyze_cloudtrail(self.event, self.config))
|
||||
for name, ip in [("other-user", "192.0.2.10"), ("admin-tesis", "198.51.100.20")]:
|
||||
event = copy.deepcopy(self.event)
|
||||
event["userIdentity"]["userName"] = name
|
||||
event["sourceIPAddress"] = ip
|
||||
payload, _ = self.detector.analyze_cloudtrail(event, self.config)
|
||||
self.assertEqual(payload["incident_type"], "PRIVILEGE_ESCALATION")
|
||||
|
||||
def test_response_role_exemption_is_limited_to_expected_iam_actions(self):
|
||||
event = copy.deepcopy(self.event)
|
||||
event["sourceIPAddress"] = "198.51.100.20"
|
||||
event["userIdentity"] = {
|
||||
"type": "AssumedRole", "arn": "arn:aws:sts::123456789012:assumed-role/response-worker/session",
|
||||
"sessionContext": {"sessionIssuer": {"arn": self.role}},
|
||||
}
|
||||
for action in ["ListAccessKeys", "UpdateAccessKey", "PutUserPolicy"]:
|
||||
event["eventName"] = action
|
||||
self.assertIsNone(self.detector.analyze_cloudtrail(event, self.config))
|
||||
event["eventName"] = "CreateAccessKey"
|
||||
payload, _ = self.detector.analyze_cloudtrail(event, self.config)
|
||||
self.assertEqual(payload["incident_type"], "PRIVILEGE_ESCALATION")
|
||||
event["eventName"] = "PutUserPolicy"
|
||||
event["userIdentity"]["sessionContext"]["sessionIssuer"]["arn"] = self.role + "-other"
|
||||
payload, _ = self.detector.analyze_cloudtrail(event, self.config)
|
||||
self.assertEqual(payload["incident_type"], "PRIVILEGE_ESCALATION")
|
||||
|
||||
def test_authorized_admin_from_foreign_ip_still_triggers_credential_leak(self):
|
||||
event = copy.deepcopy(self.event)
|
||||
event.update(eventName="GetCallerIdentity", eventSource="sts.amazonaws.com", sourceIPAddress="198.51.100.20")
|
||||
payload, _ = self.detector.analyze_cloudtrail(event, self.config)
|
||||
self.assertEqual(payload["incident_type"], "CREDENTIAL_LEAK")
|
||||
Loading…
Reference in New Issue