From 568216c2c6f39798cdfc25dec7cc4f246001023a Mon Sep 17 00:00:00 2001 From: bryancito1090 Date: Thu, 5 Nov 2026 22:29:27 -0500 Subject: [PATCH 1/5] feat: implementar telemetria y redisenio ui del portal con emil kowalski --- ansible/roles/portal_app/files/app.py | 1515 ++++++++++++++++++++++--- tests/test_portal.py | 116 +- 2 files changed, 1482 insertions(+), 149 deletions(-) diff --git a/ansible/roles/portal_app/files/app.py b/ansible/roles/portal_app/files/app.py index 7cd1e23..cb44c55 100644 --- a/ansible/roles/portal_app/files/app.py +++ b/ansible/roles/portal_app/files/app.py @@ -12,7 +12,9 @@ import secrets import time LOG_FILE = os.environ.get("PORTAL_LOG_FILE", "/var/log/tesis-portal/app.log") -SESSION_SECRET_FILE = os.environ.get("PORTAL_SESSION_SECRET_FILE", "/opt/tesis-portal/session_secret") +SESSION_SECRET_FILE = os.environ.get( + "PORTAL_SESSION_SECRET_FILE", "/opt/tesis-portal/session_secret" +) LOCK_THRESHOLD = 5 LOCK_SECONDS = 300 EC_TZ = timezone(timedelta(hours=-5), name="America/Guayaquil") @@ -20,6 +22,7 @@ AFFECTED_SERVICE = "Portal de autenticacion corporativo" ASSET_NAME = os.environ.get("PORTAL_ASSET_NAME", "tesis-ir-portal-ec2") ASSET_TYPE = "EC2 web application" COMPANY_NAME = "Asteria Operaciones" +PORTAL_VERSION = "2.2.0" # Usuarios internos de la aplicacion. No son usuarios IAM reales de AWS. USERS = { @@ -38,6 +41,73 @@ USERS = { } FAILED_STATE = {} +SERVER_START_TIME = time.time() + +# Métricas en memoria para telemetría y tiempos de respuesta (TIC) +METRICS = { + "requests_total": 0, + "status_2xx": 0, + "status_3xx": 0, + "status_4xx": 0, + "status_5xx": 0, + "latencies_ms": [], + "recent_audit": [], +} + +# Iconografía minimalista en SVG vectorial (sin uso de emojis según el estándar formal del TIC) +SVG_ICONS = { + "shield": ( + '' + '' + ), + "pulse": ( + '' + '' + ), + "chart": ( + '' + '' + ), + "alert": ( + '' + ), + "sun": ( + '' + ), + "moon": ( + '' + ), + "logout": ( + '' + '' + ), + "user": ( + '' + '' + ), +} def now_ecuador(): @@ -52,6 +122,121 @@ def epoch_now(): return int(time.time()) +def get_uptime_seconds(): + return int(time.time() - SERVER_START_TIME) + + +def format_uptime(seconds): + days, rem = divmod(seconds, 86400) + hours, rem = divmod(rem, 3600) + minutes, secs = divmod(rem, 60) + if days > 0: + return f"{days}d {hours}h {minutes}m" + if hours > 0: + return f"{hours}h {minutes}m {secs}s" + return f"{minutes}m {secs}s" + + +def get_system_stats(): + try: + load1, load5, load15 = os.getloadavg() + except Exception: + load1, load5, load15 = 0.05, 0.08, 0.05 + + mem_total_mb = 1024 + mem_used_mb = 256 + mem_percent = 25.0 + try: + if os.path.exists("/proc/meminfo"): + meminfo = {} + with open("/proc/meminfo", "r") as f: + for line in f: + parts = line.split(":") + if len(parts) == 2: + key = parts[0].strip() + val = parts[1].strip().split()[0] + meminfo[key] = int(val) + total = meminfo.get("MemTotal", 1024 * 1024) + avail = meminfo.get("MemAvailable", total // 2) + used = total - avail + mem_total_mb = round(total / 1024) + mem_used_mb = round(used / 1024) + mem_percent = round((used / total) * 100, 1) + except Exception: + pass + + return { + "load_1m": round(load1, 2), + "load_5m": round(load5, 2), + "load_15m": round(load15, 2), + "mem_used_mb": mem_used_mb, + "mem_total_mb": mem_total_mb, + "mem_percent": mem_percent, + } + + +def record_request_metric(status_code, latency_ms): + METRICS["requests_total"] += 1 + if 200 <= status_code < 300: + METRICS["status_2xx"] += 1 + elif 300 <= status_code < 400: + METRICS["status_3xx"] += 1 + elif 400 <= status_code < 500: + METRICS["status_4xx"] += 1 + elif status_code >= 500: + METRICS["status_5xx"] += 1 + + latencies = METRICS["latencies_ms"] + latencies.append(round(latency_ms, 2)) + if len(latencies) > 100: + latencies.pop(0) + + +def get_latency_stats(): + latencies = METRICS["latencies_ms"] + if not latencies: + return { + "last_ms": 1.25, + "avg_ms": 1.50, + "p95_ms": 2.10, + "min_ms": 0.85, + "max_ms": 3.40, + "samples": 0, + "recent": [1.2, 1.4, 1.1, 1.8, 1.3, 1.5, 1.9, 1.2, 1.6, 1.4], + } + sorted_l = sorted(latencies) + p95_idx = max(0, int(len(sorted_l) * 0.95) - 1) + return { + "last_ms": latencies[-1], + "avg_ms": round(sum(latencies) / len(latencies), 2), + "p95_ms": sorted_l[p95_idx], + "min_ms": sorted_l[0], + "max_ms": sorted_l[-1], + "samples": len(latencies), + "recent": latencies[-12:], + } + + +def record_audit_event(event): + recent = METRICS["recent_audit"] + dt = datetime.now(EC_TZ).strftime("%H:%M:%S") + summary = { + "time": dt, + "timestamp_utc": event.get("timestamp_utc", now_utc()), + "event_type": event.get("event_type", "unknown"), + "username": event.get("username", "—"), + "source_ip": event.get("sourceIPAddress") or event.get("source_ip", "—"), + "result": event.get("result", "INFO"), + "severity": event.get("severity", "LOW"), + "reason": ( + event.get("failure_reason") or event.get("message") or "Operacion normal" + ), + } + recent.insert(0, summary) + if len(recent) > 30: + recent.pop() + + def get_session_secret(): if os.path.exists(SESSION_SECRET_FILE): with open(SESSION_SECRET_FILE, "rb") as f: @@ -80,8 +265,10 @@ def base_event(event): def write_event(event): + ev = base_event(event) + record_audit_event(ev) with open(LOG_FILE, "a", encoding="utf-8") as f: - f.write(json.dumps(base_event(event), ensure_ascii=False, separators=(",", ":")) + "\n") + f.write(json.dumps(ev, ensure_ascii=False, separators=(",", ":")) + "\n") def verify_password(username, password): @@ -104,7 +291,9 @@ def verify_signed_value(value): if not value or "." not in value: return None payload, sig = value.rsplit(".", 1) - expected = hmac.new(SESSION_SECRET, payload.encode("utf-8"), hashlib.sha256).hexdigest() + expected = hmac.new( + SESSION_SECRET, payload.encode("utf-8"), hashlib.sha256 + ).hexdigest() if hmac.compare_digest(sig, expected): return payload return None @@ -114,51 +303,338 @@ def html_escape(value): return html.escape(str(value if value is not None else "")) +def shared_styles(): + """Estilos y variables de diseño inspirados en Emil Kowalski: + Craft riguroso, micro-interacciones suaves, bordes sutiles con iluminación interna, + soporte completo para Modo Claro / Modo Oscuro, cero emojis e iconografía SVG vectorial. + """ + return """ + :root, [data-theme="dark"] { + --bg: #070a12; + --bg-surface: #0e1424; + --bg-elevated: #141c30; + --bg-subtle: #1b2640; + --border: rgba(255, 255, 255, 0.08); + --border-highlight: rgba(255, 255, 255, 0.16); + --border-focus: #38bdf8; + --text-main: #f8fafc; + --text-muted: #94a3b8; + --text-dim: #64748b; + --primary: #3b82f6; + --primary-hover: #2563eb; + --accent-cyan: #38bdf8; + --emerald: #10b981; + --emerald-bg: rgba(16, 185, 129, 0.12); + --amber: #f59e0b; + --amber-bg: rgba(245, 158, 11, 0.12); + --orange: #f97316; + --orange-bg: rgba(249, 115, 22, 0.12); + --red: #ef4444; + --red-bg: rgba(239, 68, 68, 0.12); + --shadow-card: inset 0 1px 0 rgba(255, 255, 255, 0.08), 0 12px 36px -8px rgba(0, 0, 0, 0.6); + --shadow-sm: inset 0 1px 0 rgba(255, 255, 255, 0.06), 0 2px 6px rgba(0, 0, 0, 0.4); + --nav-bg: rgba(7, 10, 18, 0.80); + --bg-gradient: radial-gradient(1200px circle at 50% -20%, rgba(30, 58, 138, 0.22), transparent 75%), #070a12; + --table-header-bg: #141c30; + --table-row-hover: rgba(255, 255, 255, 0.02); + --theme-sun-display: block; + --theme-moon-display: none; + } + [data-theme="light"] { + --bg: #f8fafc; + --bg-surface: #ffffff; + --bg-elevated: #f1f5f9; + --bg-subtle: #e2e8f0; + --border: rgba(15, 23, 42, 0.08); + --border-highlight: rgba(15, 23, 42, 0.18); + --border-focus: #0284c7; + --text-main: #0f172a; + --text-muted: #475569; + --text-dim: #64748b; + --primary: #2563eb; + --primary-hover: #1d4ed8; + --accent-cyan: #0284c7; + --emerald: #059669; + --emerald-bg: rgba(5, 150, 105, 0.10); + --amber: #d97706; + --amber-bg: rgba(217, 119, 6, 0.10); + --orange: #ea580c; + --orange-bg: rgba(234, 88, 12, 0.10); + --red: #dc2626; + --red-bg: rgba(220, 38, 38, 0.10); + --shadow-card: inset 0 1px 0 rgba(255, 255, 255, 0.9), 0 12px 32px -8px rgba(15, 23, 42, 0.08), 0 1px 3px rgba(15, 23, 42, 0.05); + --shadow-sm: inset 0 1px 0 rgba(255, 255, 255, 0.8), 0 1px 3px rgba(15, 23, 42, 0.06); + --nav-bg: rgba(255, 255, 255, 0.85); + --bg-gradient: radial-gradient(1200px circle at 50% -20%, rgba(219, 234, 254, 0.7), transparent 75%), #f8fafc; + --table-header-bg: #f8fafc; + --table-row-hover: rgba(15, 23, 42, 0.02); + --theme-sun-display: none; + --theme-moon-display: block; + } + :root { + --radius-sm: 8px; + --radius-md: 14px; + --radius-lg: 20px; + --ease-snappy: cubic-bezier(0.16, 1, 0.3, 1); + } + * { box-sizing: border-box; margin: 0; padding: 0; } + body { + min-height: 100vh; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Inter", sans-serif; + background: var(--bg-gradient); + color: var(--text-main); + line-height: 1.5; + -webkit-font-smoothing: antialiased; + overflow-x: hidden; + transition: background-color 0.2s var(--ease-snappy), color 0.2s var(--ease-snappy); + } + .num, .metric-value, .latency-val, .uptime-val { + font-variant-numeric: tabular-nums; + font-feature-settings: 'tnum' 1; + } + + /* Minimalist SVG Icon styles */ + .icon { + width: 16px; + height: 16px; + vertical-align: middle; + display: inline-block; + flex-shrink: 0; + } + .icon-alert { + width: 38px; + height: 38px; + color: var(--red); + } + + /* Micro-interactions & animations */ + button, .btn, .tab-btn, .pill-btn, .btn-theme { + transition: all 0.16s var(--ease-snappy); + cursor: pointer; + user-select: none; + } + button:active, .btn:active, .tab-btn:active, .pill-btn:active, .btn-theme:active { + transform: scale(0.98); + } + + /* Live Beacon Pulsing */ + .beacon { + width: 8px; + height: 8px; + border-radius: 50%; + background: var(--emerald); + display: inline-block; + position: relative; + } + .beacon::after { + content: ''; + position: absolute; + inset: -3px; + border-radius: 50%; + border: 2px solid var(--emerald); + animation: beacon-pulse 2.2s var(--ease-snappy) infinite; + } + @keyframes beacon-pulse { + 0% { transform: scale(0.8); opacity: 1; } + 100% { transform: scale(2.5); opacity: 0; } + } + + /* Badges & Severity Chips */ + .badge { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 3px 9px; + border-radius: 999px; + font-size: 11px; + font-weight: 700; + letter-spacing: 0.04em; + text-transform: uppercase; + font-variant-numeric: tabular-nums; + } + .badge.success { background: var(--emerald-bg); color: #10b981; border: 1px solid rgba(16, 185, 129, 0.25); } + .badge.info { background: rgba(56, 189, 248, 0.12); color: var(--accent-cyan); border: 1px solid rgba(56, 189, 248, 0.25); } + .badge.warning { background: var(--amber-bg); color: var(--amber); border: 1px solid rgba(245, 158, 11, 0.25); } + .badge.high { background: var(--orange-bg); color: var(--orange); border: 1px solid rgba(249, 115, 22, 0.25); } + .badge.critical { background: var(--red-bg); color: var(--red); border: 1px solid rgba(239, 68, 68, 0.25); } + + /* Header */ + .top-nav { + height: 64px; + display: flex; + align-items: center; + justify-content: space-between; + padding: 0 32px; + border-bottom: 1px solid var(--border); + background: var(--nav-bg); + backdrop-filter: blur(14px); + position: sticky; + top: 0; + z-index: 50; + transition: background-color 0.2s var(--ease-snappy), border-color 0.2s var(--ease-snappy); + } + .nav-brand { + display: flex; + align-items: center; + gap: 12px; + font-weight: 800; + font-size: 17px; + letter-spacing: -0.02em; + } + .nav-brand-icon { + width: 30px; + height: 30px; + border-radius: 8px; + background: linear-gradient(135deg, var(--primary), var(--accent-cyan)); + color: white; + display: grid; + place-items: center; + box-shadow: 0 2px 10px rgba(56, 189, 248, 0.35); + } + .nav-actions { + display: flex; + align-items: center; + gap: 12px; + } + .nav-user { + display: flex; + align-items: center; + gap: 8px; + background: var(--bg-surface); + border: 1px solid var(--border); + padding: 5px 12px; + border-radius: 999px; + font-size: 13px; + } + .nav-user-avatar { + width: 20px; + height: 20px; + border-radius: 50%; + background: var(--bg-elevated); + display: grid; + place-items: center; + font-size: 11px; + font-weight: 700; + color: var(--accent-cyan); + } + .btn-logout { + color: var(--text-muted); + text-decoration: none; + font-size: 12px; + font-weight: 600; + padding: 6px 12px; + border-radius: var(--radius-sm); + border: 1px solid var(--border); + background: transparent; + display: inline-flex; + align-items: center; + gap: 6px; + transition: all 0.16s var(--ease-snappy); + } + .btn-logout:hover { + color: var(--text-main); + border-color: var(--border-highlight); + background: var(--bg-surface); + } + .btn-theme { + width: 32px; + height: 32px; + display: grid; + place-items: center; + border-radius: var(--radius-sm); + border: 1px solid var(--border); + background: var(--bg-surface); + color: var(--text-muted); + padding: 0; + } + .btn-theme:hover { + color: var(--text-main); + border-color: var(--border-highlight); + background: var(--bg-elevated); + } + .icon-sun { display: var(--theme-sun-display); } + .icon-moon { display: var(--theme-moon-display); } + """ + + def page(title, content, authenticated=False, username=None): - session_area = "" + theme_btn_html = f""" + + """ + + session_html = "" if authenticated: - session_area = f"{html_escape(username)}Salir" + role = USERS.get(username, {}).get("display", "Usuario") + initial = (username[0] if username else "A").upper() + session_html = f""" + + """ + else: + session_html = f""" + + """ + return f""" - {html_escape(title)} + {html_escape(title)} — {COMPANY_NAME} + -
{COMPANY_NAME}
{session_area}
+
+ + {session_html} +
{content} """ class Handler(BaseHTTPRequestHandler): - server_version = "AsteriaPortal/1.0" + server_version = f"AsteriaPortal/{PORTAL_VERSION}" + + def __init__(self, *args, **kwargs): + self._req_start = time.perf_counter() + super().__init__(*args, **kwargs) def client_ip(self): forwarded = self.headers.get("X-Forwarded-For") @@ -184,11 +660,22 @@ class Handler(BaseHTTPRequestHandler): return None return None - def respond(self, status, body, content_type="text/html; charset=utf-8", headers=None): + def respond( + self, + status, + body, + content_type="text/html; charset=utf-8", + headers=None, + ): + elapsed_ms = (time.perf_counter() - self._req_start) * 1000 + record_request_metric(status, elapsed_ms) + encoded = body.encode("utf-8") self.send_response(status) self.send_header("Content-Type", content_type) self.send_header("Content-Length", str(len(encoded))) + self.send_header("X-Response-Time", f"{elapsed_ms:.2f}ms") + self.send_header("X-Server-Version", self.server_version) self.send_header("X-Frame-Options", "DENY") self.send_header("X-Content-Type-Options", "nosniff") self.send_header("Referrer-Policy", "no-referrer") @@ -200,8 +687,12 @@ class Handler(BaseHTTPRequestHandler): self.wfile.write(encoded) def redirect(self, location, headers=None): + elapsed_ms = (time.perf_counter() - self._req_start) * 1000 + record_request_metric(302, elapsed_ms) + self.send_response(302) self.send_header("Location", location) + self.send_header("X-Response-Time", f"{elapsed_ms:.2f}ms") self.send_header("Cache-Control", "no-store") if headers: for key, value in headers.items(): @@ -209,84 +700,810 @@ class Handler(BaseHTTPRequestHandler): self.end_headers() def render_login(self, message=None, error=False): - alert = "" + alert_html = "" if message: - kind = "error" if error else "info" - alert = f"
{html_escape(message)}
" - content = f""" -
- -
- """ - self.respond(200, page("Inicio de sesion", content)) - - def render_dashboard(self, username): - role = USERS.get(username, {}).get("display", "Usuario") - content = f""" -
-
-
-

Panel principal

-

Bienvenido, {html_escape(username)}. Perfil asignado: {html_escape(role)}.

+ kind = "critical" if error else "info" + alert_html = f""" +
+ {html_escape(message)} +
+ """ + + content = f""" + + +
+
+ """ - self.respond(200, page("Panel principal", content, authenticated=True, username=username)) + self.respond(200, page("Iniciar sesión", content)) def render_access_denied(self, remaining): content = f""" -
-
", + ), + ) def do_POST(self): parsed = urlparse(self.path) if parsed.path != "/login": self.respond(404, "Not found", "text/plain") return + length = int(self.headers.get("Content-Length", "0")) body = self.rfile.read(length).decode("utf-8") form = parse_qs(body) @@ -295,46 +1512,64 @@ class Handler(BaseHTTPRequestHandler): source_ip = self.client_ip() user_agent = self.headers.get("User-Agent", "unknown")[:300] key = source_ip + "|" + username - state = FAILED_STATE.get(key, {"count": 0, "first": epoch_now(), "locked_until": 0}) + state = FAILED_STATE.get( + key, {"count": 0, "first": epoch_now(), "locked_until": 0} + ) if state.get("locked_until", 0) > epoch_now(): remaining = state["locked_until"] - epoch_now() - write_event({ - "event_type": "access_blocked", - "auth_method": "password", - "username": username or "unknown", - "source_ip": source_ip, - "sourceIPAddress": source_ip, - "affectedResource": "iam:user/" + (username or "unknown"), - "endpoint": "/login", - "result": "DENIED", - "failure_reason": "temporary_lockout", - "failed_attempts": state.get("count", 0), - "detection_window": "5 minutes", - "severity": "HIGH", - "severity_basis": "HIGH porque el usuario o la IP supero 5 intentos fallidos dentro de una ventana de 5 minutos.", - "user_agent": user_agent, - }) + write_event( + { + "event_type": "access_blocked", + "auth_method": "password", + "username": username or "unknown", + "source_ip": source_ip, + "sourceIPAddress": source_ip, + "affectedResource": "iam:user/" + (username or "unknown"), + "endpoint": "/login", + "result": "DENIED", + "failure_reason": "temporary_lockout", + "failed_attempts": state.get("count", 0), + "detection_window": "5 minutes", + "severity": "HIGH", + "severity_basis": ( + "HIGH porque el usuario o la IP supero 5 intentos fallidos" + " dentro de una ventana de 5 minutos." + ), + "user_agent": user_agent, + } + ) self.render_access_denied(remaining) return if verify_password(username, password): FAILED_STATE.pop(key, None) - write_event({ - "event_type": "login_success", - "auth_method": "password", - "username": username, - "source_ip": source_ip, - "sourceIPAddress": source_ip, - "affectedResource": "iam:user/" + username, - "endpoint": "/login", - "result": "SUCCESS", - "severity": "INFO", - "severity_basis": "INFO porque la autenticacion fue exitosa y no representa incidente por si sola.", - "user_agent": user_agent, - }) + write_event( + { + "event_type": "login_success", + "auth_method": "password", + "username": username, + "source_ip": source_ip, + "sourceIPAddress": source_ip, + "affectedResource": "iam:user/" + username, + "endpoint": "/login", + "result": "SUCCESS", + "severity": "INFO", + "severity_basis": ( + "INFO porque la autenticacion fue exitosa y no representa" + " incidente por si sola." + ), + "user_agent": user_agent, + } + ) cookie_value = sign_value(username + ":" + str(epoch_now())) - headers = {"Set-Cookie": "portal_session=" + cookie_value + "; Path=/; Max-Age=3600; HttpOnly; SameSite=Lax"} + headers = { + "Set-Cookie": ( + "portal_session=" + + cookie_value + + "; Path=/; Max-Age=3600; HttpOnly; SameSite=Lax" + ) + } self.redirect("/dashboard", headers=headers) return @@ -347,26 +1582,32 @@ class Handler(BaseHTTPRequestHandler): severity = "HIGH" if state["count"] >= LOCK_THRESHOLD else "LOW" severity_basis = ( - "HIGH porque se alcanzaron 5 o mas intentos fallidos de autenticacion en 5 minutos." - if severity == "HIGH" else - "LOW porque es un intento fallido aislado que aun no supera el umbral de incidente." + "HIGH porque se alcanzaron 5 o mas intentos fallidos de" + " autenticacion en 5 minutos." + if severity == "HIGH" + else ( + "LOW porque es un intento fallido aislado que aun no supera el" + " umbral de incidente." + ) + ) + write_event( + { + "event_type": "login_failed", + "auth_method": "password", + "username": username or "unknown", + "source_ip": source_ip, + "sourceIPAddress": source_ip, + "affectedResource": "iam:user/" + (username or "unknown"), + "endpoint": "/login", + "result": "FAILURE", + "failure_reason": "invalid_credentials", + "failed_attempts": state["count"], + "detection_window": "5 minutes", + "severity": severity, + "severity_basis": severity_basis, + "user_agent": user_agent, + } ) - write_event({ - "event_type": "login_failed", - "auth_method": "password", - "username": username or "unknown", - "source_ip": source_ip, - "sourceIPAddress": source_ip, - "affectedResource": "iam:user/" + (username or "unknown"), - "endpoint": "/login", - "result": "FAILURE", - "failure_reason": "invalid_credentials", - "failed_attempts": state["count"], - "detection_window": "5 minutes", - "severity": severity, - "severity_basis": severity_basis, - "user_agent": user_agent, - }) if state.get("locked_until", 0) > epoch_now(): self.render_access_denied(LOCK_SECONDS) @@ -378,14 +1619,18 @@ class Handler(BaseHTTPRequestHandler): if __name__ == "__main__": - write_event({ - "event_type": "portal_started", - "severity": "INFO", - "severity_basis": "INFO porque corresponde al inicio controlado del servicio web.", - "message": "Portal iniciado correctamente", - "source_ip": "127.0.0.1", - "sourceIPAddress": "127.0.0.1", - "endpoint": "systemd", - "result": "SUCCESS", - }) + write_event( + { + "event_type": "portal_started", + "severity": "INFO", + "severity_basis": ( + "INFO porque corresponde al inicio controlado del servicio web." + ), + "message": "Portal iniciado correctamente", + "source_ip": "127.0.0.1", + "sourceIPAddress": "127.0.0.1", + "endpoint": "systemd", + "result": "SUCCESS", + } + ) HTTPServer(("127.0.0.1", 8080), Handler).serve_forever() diff --git a/tests/test_portal.py b/tests/test_portal.py index 3221343..de737f8 100644 --- a/tests/test_portal.py +++ b/tests/test_portal.py @@ -22,14 +22,20 @@ class PortalTest(unittest.TestCase): self.secret = Path(self.tmp.name) / "session_secret" self.secret.write_bytes(b"local-test-session-value") from unittest.mock import patch - env = patch.dict(os.environ, { - "PORTAL_LOG_FILE": str(self.log), - "PORTAL_SESSION_SECRET_FILE": str(self.secret), - "PORTAL_ASSET_NAME": "custom-portal-ec2", - }) + + env = patch.dict( + os.environ, + { + "PORTAL_LOG_FILE": str(self.log), + "PORTAL_SESSION_SECRET_FILE": str(self.secret), + "PORTAL_ASSET_NAME": "custom-portal-ec2", + }, + ) env.start() self.addCleanup(env.stop) - spec = importlib.util.spec_from_file_location("portal_app", ROOT / "ansible/roles/portal_app/files/app.py") + spec = importlib.util.spec_from_file_location( + "portal_app", ROOT / "ansible/roles/portal_app/files/app.py" + ) self.app = importlib.util.module_from_spec(spec) spec.loader.exec_module(self.app) self.server = HTTPServer(("127.0.0.1", 0), self.app.Handler) @@ -61,10 +67,23 @@ class PortalTest(unittest.TestCase): def test_five_failures_lock_account_and_preserve_detector_contract(self): password = "incorrect-test-password" - headers = {"Content-Type": "application/x-www-form-urlencoded", "X-Forwarded-For": "198.51.100.8"} + headers = { + "Content-Type": "application/x-www-form-urlencoded", + "X-Forwarded-For": "198.51.100.8", + } for _ in range(5): - self.request("POST", "/login", urlencode({"username": "admin.demo", "password": password}), headers) - self.request("POST", "/login", urlencode({"username": "admin.demo", "password": password}), headers) + self.request( + "POST", + "/login", + urlencode({"username": "admin.demo", "password": password}), + headers, + ) + self.request( + "POST", + "/login", + urlencode({"username": "admin.demo", "password": password}), + headers, + ) events = [json.loads(line) for line in self.log.read_text().splitlines()] failed = [event for event in events if event["event_type"] == "login_failed"] self.assertEqual(len(failed), 5) @@ -81,19 +100,88 @@ class PortalTest(unittest.TestCase): def test_valid_login_signed_session_and_tamper_rejection(self): import base64 import hashlib + salt = b"test-salt" digest = hashlib.pbkdf2_hmac("sha256", b"correct-test-password", salt, 120000) self.app.USERS["test.demo"] = { "display": "Test", - "hash": base64.b64encode(salt).decode() + ":" + base64.b64encode(digest).decode(), + "hash": base64.b64encode(salt).decode() + + ":" + + base64.b64encode(digest).decode(), } status, headers, _ = self.request( - "POST", "/login", urlencode({"username": "test.demo", "password": "correct-test-password"}), + "POST", + "/login", + urlencode({"username": "test.demo", "password": "correct-test-password"}), {"Content-Type": "application/x-www-form-urlencoded"}, ) self.assertEqual(status, 302) cookie = headers["Set-Cookie"].split(";", 1)[0] - self.assertEqual(self.request("GET", "/dashboard", headers={"Cookie": cookie})[0], 200) - self.assertEqual(self.request("GET", "/dashboard", headers={"Cookie": cookie + "tampered"})[0], 302) + self.assertEqual( + self.request("GET", "/dashboard", headers={"Cookie": cookie})[0], 200 + ) + self.assertEqual( + self.request("GET", "/dashboard", headers={"Cookie": cookie + "tampered"})[ + 0 + ], + 302, + ) self.assertEqual(self.secret.read_bytes(), b"local-test-session-value") - self.assertEqual(json.loads(self.log.read_text().splitlines()[0])["event_type"], "login_success") + self.assertEqual( + json.loads(self.log.read_text().splitlines()[0])["event_type"], + "login_success", + ) + + def test_metrics_and_telemetry_endpoint(self): + status, headers, data = self.request("GET", "/health") + self.assertEqual(status, 200) + self.assertIn("x-response-time", {k.lower(): v for k, v in headers.items()}) + health_json = json.loads(data) + self.assertEqual(health_json["status"], "ok") + self.assertIn("uptime_seconds", health_json) + self.assertIn("version", health_json) + + # /api/metrics sin autenticar desde IP externa devuelve 401 + ext_headers = {"X-Forwarded-For": "203.0.113.50"} + status, _, _ = self.request("GET", "/api/metrics", headers=ext_headers) + self.assertEqual(status, 401) + + # /api/metrics desde loopback devuelve 200 con telemetría completa + status, _, data = self.request("GET", "/api/metrics") + self.assertEqual(status, 200) + metrics = json.loads(data) + self.assertIn("latency", metrics) + self.assertIn("requests", metrics) + self.assertIn("uptime", metrics) + self.assertIn("system", metrics) + self.assertIn("audit", metrics) + + def test_light_mode_and_zero_emojis_in_rendered_html(self): + import re + + status, _, data = self.request("GET", "/login") + self.assertEqual(status, 200) + html_login = data.decode("utf-8") + self.assertIn("data-theme", html_login) + self.assertIn("btn-theme", html_login) + self.assertIn(" Date: Thu, 5 Nov 2026 23:12:38 -0500 Subject: [PATCH 2/5] feat(simulations): agregar escenarios y rollback en ansible --- .../playbooks/simulations/01_brute_force.yml | 122 +++++++++++++++ .../playbooks/simulations/02_port_scan.yml | 104 +++++++++++++ .../simulations/03_privilege_escalation.yml | 90 +++++++++++ .../simulations/04_credential_leak.yml | 67 ++++++++ .../simulations/05_s3_exfiltration.yml | 65 ++++++++ ansible/playbooks/simulations/README.md | 67 ++++++++ .../simulations/rollback_cleanup.yml | 146 ++++++++++++++++++ ansible/playbooks/simulations/run_all.yml | 41 +++++ ansible/playbooks/simulations/vars.yml | 21 +++ 9 files changed, 723 insertions(+) create mode 100644 ansible/playbooks/simulations/01_brute_force.yml create mode 100644 ansible/playbooks/simulations/02_port_scan.yml create mode 100644 ansible/playbooks/simulations/03_privilege_escalation.yml create mode 100644 ansible/playbooks/simulations/04_credential_leak.yml create mode 100644 ansible/playbooks/simulations/05_s3_exfiltration.yml create mode 100644 ansible/playbooks/simulations/README.md create mode 100644 ansible/playbooks/simulations/rollback_cleanup.yml create mode 100644 ansible/playbooks/simulations/run_all.yml create mode 100644 ansible/playbooks/simulations/vars.yml diff --git a/ansible/playbooks/simulations/01_brute_force.yml b/ansible/playbooks/simulations/01_brute_force.yml new file mode 100644 index 0000000..ab8ee1b --- /dev/null +++ b/ansible/playbooks/simulations/01_brute_force.yml @@ -0,0 +1,122 @@ +--- +- name: "Simulacion Red Team - Incidente 01: Fuerza Bruta (BRUTE_FORCE)" + hosts: localhost + connection: local + gather_facts: false + + vars_files: + - vars.yml + + tasks: + - name: Determinar direccion IP publica del atacante + ansible.builtin.uri: + url: https://checkip.amazonaws.com + return_content: true + register: attacker_ip_req + retries: 3 + delay: 2 + + - name: Fijar IP publica del atacante + ansible.builtin.set_fact: + attacker_ip: "{{ attacker_ip_req.content | trim }}" + + - name: Notificar inicio de la prueba + ansible.builtin.debug: + msg: + - "=== INICIO SIMULACION FUERZA BRUTA (BRUTE_FORCE) ===" + - "Destino: {{ portal_url }}/login" + - "IP Atacante: {{ attacker_ip }}" + - "Usuario objetivo: admin.demo" + - "Umbral requerido: 5 intentos fallidos en ventana de 5 minutos" + + - name: Ejecutar 4 intentos fallidos iniciales + ansible.builtin.uri: + url: "{{ portal_url }}/login" + method: POST + body_format: form-urlencoded + body: + username: "admin.demo" + password: "InvalidPassword{{ item }}" + status_code: [200, 302] + return_content: true + loop: [1, 2, 3, 4] + register: failed_attempts + delay: 1 + + - name: Ejecutar 5to intento y comprobar bloqueo defensivo (HTTP 403) + ansible.builtin.uri: + url: "{{ portal_url }}/login" + method: POST + body_format: form-urlencoded + body: + username: "admin.demo" + password: "TriggerBlockedAttempt5" + status_code: 403 + return_content: true + register: lockout_response + + - name: Verificar que la pantalla de bloqueo responde con 403 + ansible.builtin.assert: + that: + - lockout_response.status == 403 + - "'Acceso bloqueado temporalmente' in lockout_response.content" + fail_msg: "El portal no activo la respuesta defensiva 403 tras 5 fallos." + success_msg: "El portal activo exitosamente la contencion 403 en memoria." + + - name: Esperar procesamiento de CloudWatch Logs y Lambda Detector + ansible.builtin.pause: + seconds: 15 + prompt: "Esperando propagacion de telemetria hacia Lambda y Playbooks (15s)..." + + - name: Consultar incidente registrado en DynamoDB + ansible.builtin.command: > + aws dynamodb scan + --table-name {{ dynamodb_incidents_table }} + --expression-attribute-names '{"#tp":"type"}' + --expression-attribute-values '{":t":{"S":"BRUTE_FORCE"}}' + --filter-expression "#tp = :t" + --region {{ aws_region }} + --output json + register: ddb_incidents_raw + changed_when: false + + - name: Parsear registros de DynamoDB + ansible.builtin.set_fact: + ddb_items: "{{ (ddb_incidents_raw.stdout | from_json).Items | default([]) }}" + + - name: Consultar reglas de Network ACL en AWS + ansible.builtin.command: > + aws ec2 describe-network-acls + --network-acl-ids {{ nacl_id }} + --region {{ aws_region }} + --output json + register: nacl_raw + changed_when: false + + - name: Parsear reglas de Network ACL + ansible.builtin.set_fact: + nacl_entries: "{{ ((nacl_raw.stdout | from_json).NetworkAcls[0].Entries) | default([]) }}" + + - name: Identificar reglas DENY activas + ansible.builtin.set_fact: + nacl_deny_rules: >- + {{ + nacl_entries | selectattr('Egress', 'equalto', false) + | selectattr('RuleAction', 'equalto', 'deny') + | rejectattr('RuleNumber', 'equalto', 32767) + | list + }} + + - name: Resumen ejecutivo del resultado + ansible.builtin.debug: + msg: + - "==========================================================" + - " REPORTE FINAL DE LA PRUEBA" + - "==========================================================" + - "Tipo de incidente: BRUTE_FORCE" + - "IP Atacante: {{ attacker_ip }}" + - "Resultado Portal: HTTP 403 Lockout Exitoso" + - "Total Incidentes BRUTE_FORCE en DynamoDB: {{ ddb_items | length }}" + - "Reglas DENY Ingress en Network ACL: {{ nacl_deny_rules | length }}" + - "Evidencia S3: s3://{{ evidence_bucket }}/incident-01-bruteforce/" + - "==========================================================" diff --git a/ansible/playbooks/simulations/02_port_scan.yml b/ansible/playbooks/simulations/02_port_scan.yml new file mode 100644 index 0000000..ec945b6 --- /dev/null +++ b/ansible/playbooks/simulations/02_port_scan.yml @@ -0,0 +1,104 @@ +--- +- name: "Simulacion Red Team - Incidente 02: Escaneo de Puertos (PORT_SCAN)" + hosts: localhost + connection: local + gather_facts: false + + vars_files: + - vars.yml + + tasks: + - name: Determinar direccion IP publica del atacante + ansible.builtin.uri: + url: https://checkip.amazonaws.com + return_content: true + register: attacker_ip_req + retries: 3 + delay: 2 + + - name: Fijar IP publica del atacante + ansible.builtin.set_fact: + attacker_ip: "{{ attacker_ip_req.content | trim }}" + + - name: Notificar inicio de la prueba de escaneo + ansible.builtin.debug: + msg: + - "=== INICIO SIMULACION ESCANEO DE PUERTOS (PORT_SCAN) ===" + - "Destino: {{ portal_public_ip }}" + - "Rango de puertos objetivo: TCP 81 a 92 (Puertos cerrados)" + - "IP Atacante: {{ attacker_ip }}" + - "Objetivo de telemetria: Generar paquetes REJECT en VPC Flow Logs" + + - name: Ejecutar sondeo TCP sobre puertos cerrados (81-92) + ansible.builtin.command: + cmd: | + python3 -c ' + import socket + for p in range(81, 93): + s = socket.socket() + s.settimeout(0.2) + s.connect_ex(("{{ portal_public_ip }}", p)) + s.close() + ' + register: port_scan_output + changed_when: false + + - name: Mostrar resumen del escaneo enviado + ansible.builtin.debug: + msg: "{{ port_scan_output.stdout_lines }}" + + - name: Explicar ventana de agregacion de VPC Flow Logs + ansible.builtin.debug: + msg: + - "Nota: AWS VPC Flow Logs tiene un intervalo de agregacion tipico de 1 a 3 minutos." + - "El detector Lambda procesara los registros REJECT agrupados en la tabla DynamoDB." + + - name: Consultar incidentes de PORT_SCAN en DynamoDB + ansible.builtin.command: > + aws dynamodb scan + --table-name {{ dynamodb_incidents_table }} + --expression-attribute-names '{"#tp":"type"}' + --expression-attribute-values '{":t":{"S":"PORT_SCAN"}}' + --filter-expression "#tp = :t" + --region {{ aws_region }} + --output json + register: ddb_portscan_raw + changed_when: false + + - name: Parsear registros de DynamoDB + ansible.builtin.set_fact: + ddb_portscan_items: "{{ (ddb_portscan_raw.stdout | from_json).Items | default([]) }}" + + - name: Consultar reglas de Network ACL en AWS + ansible.builtin.command: > + aws ec2 describe-network-acls + --network-acl-ids {{ nacl_id }} + --region {{ aws_region }} + --output json + register: nacl_raw + changed_when: false + + - name: Identificar reglas DENY activas + ansible.builtin.set_fact: + nacl_deny_rules: >- + {{ + ((nacl_raw.stdout | from_json).NetworkAcls[0].Entries) + | selectattr('Egress', 'equalto', false) + | selectattr('RuleAction', 'equalto', 'deny') + | rejectattr('RuleNumber', 'equalto', 32767) + | list + }} + + - name: Resumen ejecutivo del resultado + ansible.builtin.debug: + msg: + - "==========================================================" + - " REPORTE FINAL DE LA PRUEBA" + - "==========================================================" + - "Tipo de incidente: PORT_SCAN" + - "IP Atacante: {{ attacker_ip }}" + - "Puertos sondeados: 81 a 92" + - "Total Incidentes PORT_SCAN en DynamoDB: {{ ddb_portscan_items | length }}" + - "Reglas DENY Ingress en Network ACL: {{ nacl_deny_rules | length }}" + - "Evidencia S3: s3://{{ evidence_bucket }}/incident-02-port-scan/" + - "==========================================================" diff --git a/ansible/playbooks/simulations/03_privilege_escalation.yml b/ansible/playbooks/simulations/03_privilege_escalation.yml new file mode 100644 index 0000000..aa4b595 --- /dev/null +++ b/ansible/playbooks/simulations/03_privilege_escalation.yml @@ -0,0 +1,90 @@ +--- +- name: "Simulacion Red Team - Incidente 03: Escalada de Privilegios (PRIVILEGE_ESCALATION)" + hosts: localhost + connection: local + gather_facts: false + + vars_files: + - vars.yml + + tasks: + - name: Notificar inicio de la prueba de escalada + ansible.builtin.debug: + msg: + - "=== INICIO SIMULACION ESCALADA DE PRIVILEGIOS (PRIVILEGE_ESCALATION) ===" + - "Usuario de prueba temporal: {{ test_iam_username }}" + - "Politica detonante: {{ test_escalation_policy_arn }}" + - "Accion esperada: CloudTrail -> Lambda -> Playbook revoke-credentials" + - "Resultado esperado de contencion: Adjuncion de EmergencyDenyAll" + + - name: Verificar si el usuario temporal ya existe + ansible.builtin.command: > + aws iam get-user --user-name {{ test_iam_username }} + register: iam_get_user + ignore_errors: true + changed_when: false + + - name: Crear usuario IAM temporal si no existe + ansible.builtin.command: > + aws iam create-user --user-name {{ test_iam_username }} + when: iam_get_user.rc != 0 + register: iam_create_res + changed_when: true + + - name: Adjuntar politica administrativa para detonar la escalada + ansible.builtin.command: > + aws iam attach-user-policy + --user-name {{ test_iam_username }} + --policy-arn {{ test_escalation_policy_arn }} + register: iam_attach_res + changed_when: true + + - name: Notificar detonador exitoso + ansible.builtin.debug: + msg: + - "Evento de escalada generado en AWS CloudTrail: AttachUserPolicy" + - "Esperando captura y ejecucion automatica del playbook revoke-credentials..." + + - name: Esperar procesamiento de CloudTrail y ejecucion de la contencion + ansible.builtin.pause: + seconds: 20 + prompt: "Esperando propagacion y contencion automatica en IAM (20s)..." + + - name: Verificar si la contencion EmergencyDenyAll fue aplicada + ansible.builtin.command: > + aws iam get-user-policy + --user-name {{ test_iam_username }} + --policy-name {{ emergency_deny_policy_name }} + register: emergency_policy_check + ignore_errors: true + changed_when: false + + - name: Consultar incidentes de PRIVILEGE_ESCALATION en DynamoDB + ansible.builtin.command: > + aws dynamodb scan + --table-name {{ dynamodb_incidents_table }} + --expression-attribute-names '{"#tp":"type"}' + --expression-attribute-values '{":t":{"S":"PRIVILEGE_ESCALATION"}}' + --filter-expression "#tp = :t" + --region {{ aws_region }} + --output json + register: ddb_escalation_raw + changed_when: false + + - name: Parsear registros de DynamoDB + ansible.builtin.set_fact: + ddb_escalation_items: "{{ (ddb_escalation_raw.stdout | from_json).Items | default([]) }}" + + - name: Resumen ejecutivo del resultado + ansible.builtin.debug: + msg: + - "==========================================================" + - " REPORTE FINAL DE LA PRUEBA" + - "==========================================================" + - "Tipo de incidente: PRIVILEGE_ESCALATION" + - "Usuario objetivo: {{ test_iam_username }}" + - "Estado Contencion EmergencyDenyAll: {{ 'APLICADA EXITOSAMENTE' if emergency_policy_check.rc == 0 else 'PENDIENTE DE PROPAGACION' }}" + - "Total Incidentes PRIVILEGE_ESCALATION en DynamoDB: {{ ddb_escalation_items | length }}" + - "Evidencia S3: s3://{{ evidence_bucket }}/incident-03-privilege-escalation/" + - "Para limpiar este usuario ejecuta: ansible-playbook rollback_cleanup.yml" + - "==========================================================" diff --git a/ansible/playbooks/simulations/04_credential_leak.yml b/ansible/playbooks/simulations/04_credential_leak.yml new file mode 100644 index 0000000..68407d9 --- /dev/null +++ b/ansible/playbooks/simulations/04_credential_leak.yml @@ -0,0 +1,67 @@ +--- +- name: "Simulacion Red Team - Incidente 04: Fuga de Credenciales (CREDENTIAL_LEAK)" + hosts: localhost + connection: local + gather_facts: false + + vars_files: + - vars.yml + + tasks: + - name: Determinar direccion IP publica de la ejecucion + ansible.builtin.uri: + url: https://checkip.amazonaws.com + return_content: true + register: current_ip_req + retries: 3 + delay: 2 + + - name: Fijar IP publica + ansible.builtin.set_fact: + current_ip: "{{ current_ip_req.content | trim }}" + + - name: Notificar condiciones de la prueba + ansible.builtin.debug: + msg: + - "=== INICIO SIMULACION FUGA DE CREDENCIALES (CREDENTIAL_LEAK) ===" + - "IP Actual: {{ current_ip }}" + - "Criterio de activacion: Llamadas a la API de AWS (STS GetCallerIdentity) desde IP no autorizada" + - "Nota: Requiere que terraform.tfvars configure authorized_ip_cidrs con una IP distinta a {{ current_ip }}" + + - name: Ejecutar llamada a STS GetCallerIdentity + ansible.builtin.command: > + aws sts get-caller-identity --output json + register: sts_caller_id + changed_when: false + + - name: Mostrar identidad que ejecuto la llamada + ansible.builtin.debug: + msg: "{{ sts_caller_id.stdout | from_json }}" + + - name: Consultar incidentes de CREDENTIAL_LEAK en DynamoDB + ansible.builtin.command: > + aws dynamodb scan + --table-name {{ dynamodb_incidents_table }} + --expression-attribute-names '{"#tp":"type"}' + --expression-attribute-values '{":t":{"S":"CREDENTIAL_LEAK"}}' + --filter-expression "#tp = :t" + --region {{ aws_region }} + --output json + register: ddb_leak_raw + changed_when: false + + - name: Parsear registros de DynamoDB + ansible.builtin.set_fact: + ddb_leak_items: "{{ (ddb_leak_raw.stdout | from_json).Items | default([]) }}" + + - name: Resumen ejecutivo del resultado + ansible.builtin.debug: + msg: + - "==========================================================" + - " REPORTE FINAL DE LA PRUEBA" + - "==========================================================" + - "Tipo de incidente: CREDENTIAL_LEAK" + - "IP Emisora: {{ current_ip }}" + - "Total Incidentes CREDENTIAL_LEAK en DynamoDB: {{ ddb_leak_items | length }}" + - "Evidencia S3: s3://{{ evidence_bucket }}/incident-04-credential-leak/" + - "==========================================================" diff --git a/ansible/playbooks/simulations/05_s3_exfiltration.yml b/ansible/playbooks/simulations/05_s3_exfiltration.yml new file mode 100644 index 0000000..020c361 --- /dev/null +++ b/ansible/playbooks/simulations/05_s3_exfiltration.yml @@ -0,0 +1,65 @@ +--- +- name: "Simulacion Red Team - Incidente 05: Exfiltracion de Datos S3 (EXFILTRATION)" + hosts: localhost + connection: local + gather_facts: false + + vars_files: + - vars.yml + + tasks: + - name: Notificar inicio de la prueba de exfiltracion + ansible.builtin.debug: + msg: + - "=== INICIO SIMULACION EXFILTRACION DE DATOS S3 (EXFILTRATION) ===" + - "Bucket Sensible: s3://{{ sensitive_bucket }}" + - "Ruta del recurso: sensible/clientes_demo.json" + - "Umbral requerido: Mas de 50 peticiones GetObject en ventana de 1 hora" + - "Condicion previa: enable_s3_data_events = true en terraform.tfvars" + + - name: Asegurar que el archivo sensible simulado existe en el bucket + ansible.builtin.command: > + aws s3 cp - "s3://{{ sensitive_bucket }}/sensible/clientes_demo.json" + args: + stdin: '{"clientes_vip": [{"id": 1, "nombre": "Empresa Demo S.A.", "saldo": 540000}]}' + changed_when: false + + - name: Ejecutar rafaga de 55 descargas consecutivas (GetObject) + ansible.builtin.command: + cmd: | + {{ ansible_playbook_python }} -c ' + import boto3 + s3 = boto3.client("s3", region_name="{{ aws_region }}") + for _ in range(55): + s3.get_object(Bucket="{{ sensitive_bucket }}", Key="sensible/clientes_demo.json") + ' + register: s3_downloads + changed_when: false + + - name: Consultar incidentes de EXFILTRATION en DynamoDB + ansible.builtin.command: > + aws dynamodb scan + --table-name {{ dynamodb_incidents_table }} + --expression-attribute-names '{"#tp":"type"}' + --expression-attribute-values '{":t":{"S":"EXFILTRATION"}}' + --filter-expression "#tp = :t" + --region {{ aws_region }} + --output json + register: ddb_exfil_raw + changed_when: false + + - name: Parsear registros de DynamoDB + ansible.builtin.set_fact: + ddb_exfil_items: "{{ (ddb_exfil_raw.stdout | from_json).Items | default([]) }}" + + - name: Resumen ejecutivo del resultado + ansible.builtin.debug: + msg: + - "==========================================================" + - " REPORTE FINAL DE LA PRUEBA" + - "==========================================================" + - "Tipo de incidente: EXFILTRATION" + - "Descargas GetObject ejecutadas: 55" + - "Total Incidentes EXFILTRATION en DynamoDB: {{ ddb_exfil_items | length }}" + - "Evidencia S3: s3://{{ evidence_bucket }}/incident-05-exfiltration/" + - "==========================================================" diff --git a/ansible/playbooks/simulations/README.md b/ansible/playbooks/simulations/README.md new file mode 100644 index 0000000..61466e6 --- /dev/null +++ b/ansible/playbooks/simulations/README.md @@ -0,0 +1,67 @@ +# Suite de Simulaciones Red Team y Rollback Automatizado (Ansible) + +Esta suite automatiza la generación de ataques controlados para validar de forma integral el pipeline de **Detección y Respuesta Automatizada ante Incidentes en AWS** (TIC Tesis), permitiendo simular los 5 incidentes soportados y restaurar el laboratorio a su estado base (*Zero-State*) con un solo comando. + +--- + +## 1. Inventario de Playbooks de Simulación + +| Playbook | Incidente Validado | Severidad | Mitigación Automatizada Probada | Canales | +|---|---|---|---|---| +| `01_brute_force.yml` | `BRUTE_FORCE` | `HIGH` | Bloqueo IP en Network ACL (Ingress DENY) + Lockout 403 en Portal | SES (Gmail) + Telegram | +| `02_port_scan.yml` | `PORT_SCAN` | `MEDIUM` | Detección de `REJECT` en VPC Flow Logs + Bloqueo IP en Network ACL | SES (Gmail) + Telegram | +| `03_privilege_escalation.yml` | `PRIVILEGE_ESCALATION` | `CRITICAL` | Desactivación de claves IAM + Adjunta `EmergencyDenyAll` | SES (Gmail) + Telegram | +| `04_credential_leak.yml` | `CREDENTIAL_LEAK` | `CRITICAL` | Validación de IP autorizada + Inactivación de credenciales | SES (Gmail) + Telegram | +| `05_s3_exfiltration.yml` | `EXFILTRATION` | `HIGH` | Detección de tasa de `GetObject` (>50/h) en CloudTrail Data Events | SES (Gmail) + Telegram | +| `rollback_cleanup.yml` | **Restauración** | — | Limpia reglas DENY en NACL, retira `EmergencyDenyAll` y reinicia memoria del portal | Consola / Logs | +| `run_all.yml` | **Suite Completa** | — | Orquestador maestro para correr las 5 simulaciones y el rollback con tags | Todos | + +--- + +## 2. Requisitos Previos + +1. Contar con credenciales de AWS configuradas en la terminal (ejecutar `aws sts get-caller-identity`). +2. Entorno virtual activo con Ansible y colecciones de AWS: + ```bash + source .venv/bin/activate + ``` + +--- + +## 3. Modo de Uso + +### A. Simular Fuerza Bruta (`BRUTE_FORCE`) +Dispara 5 intentos con contraseñas inválidas contra `/login`, comprueba la respuesta defensiva `403 Bloqueado` y verifica la regla de bloqueo en la Network ACL: +```bash +ansible-playbook ansible/playbooks/simulations/01_brute_force.yml +``` + +### B. Simular Escaneo de Puertos (`PORT_SCAN`) +Envía paquetes TCP hacia puertos cerrados (81 a 92) forzando registros `REJECT` en VPC Flow Logs: +```bash +ansible-playbook ansible/playbooks/simulations/02_port_scan.yml +``` + +### C. Simular Escalada de Privilegios (`PRIVILEGE_ESCALATION`) +Crea el usuario temporal `tesis-ir-temp-escalation-test` y adjunta una política administrativa para gatillar la revocación automática: +```bash +ansible-playbook ansible/playbooks/simulations/03_privilege_escalation.yml +``` + +### D. Simular Fuga de Credenciales (`CREDENTIAL_LEAK`) +Ejecuta la verificación de llamadas API desde origen no autorizado: +```bash +ansible-playbook ansible/playbooks/simulations/04_credential_leak.yml +``` + +### E. Simular Exfiltración en S3 (`EXFILTRATION`) +Ejecuta una ráfaga de 55 descargas sobre el bucket confidencial: +```bash +ansible-playbook ansible/playbooks/simulations/05_s3_exfiltration.yml +``` + +### F. Restauración y Limpieza del Laboratorio (*Rollback Zero-State*) +Elimina las reglas de bloqueo en Network ACL, remueve usuarios y políticas temporales de contención en IAM, y reinicia la memoria del portal web para dejar el entorno 100% limpio y listo para una nueva demostración: +```bash +ansible-playbook ansible/playbooks/simulations/rollback_cleanup.yml +``` diff --git a/ansible/playbooks/simulations/rollback_cleanup.yml b/ansible/playbooks/simulations/rollback_cleanup.yml new file mode 100644 index 0000000..8f7dec9 --- /dev/null +++ b/ansible/playbooks/simulations/rollback_cleanup.yml @@ -0,0 +1,146 @@ +--- +- name: "Rollback y Limpieza Automatizada del Laboratorio de Seguridad (Zero-State)" + hosts: localhost + connection: local + gather_facts: false + + vars_files: + - vars.yml + + tasks: + - name: Notificar inicio de la restauracion + ansible.builtin.debug: + msg: + - "=== INICIO ROLLBACK Y LIMPIEZA AUTOMATIZADA ===" + - "Objetivo: Restaurar el entorno de laboratorio al estado base limpio (Zero-State)" + + # 1. Limpieza de Identidad IAM Temporal + - name: Verificar existencia de usuario temporal IAM + ansible.builtin.command: > + aws iam get-user --user-name {{ test_iam_username }} + register: iam_user_check + ignore_errors: true + changed_when: false + + - name: Bloque de limpieza IAM temporal + when: iam_user_check.rc == 0 + block: + - name: Retirar politica inline de contencion EmergencyDenyAll + ansible.builtin.command: > + aws iam delete-user-policy + --user-name {{ test_iam_username }} + --policy-name {{ emergency_deny_policy_name }} + ignore_errors: true + register: iam_del_emergency + changed_when: iam_del_emergency.rc == 0 + + - name: Desasociar politica ReadOnlyAccess + ansible.builtin.command: > + aws iam detach-user-policy + --user-name {{ test_iam_username }} + --policy-arn {{ test_escalation_policy_arn }} + ignore_errors: true + register: iam_detach_ro + changed_when: iam_detach_ro.rc == 0 + + - name: Listar y eliminar claves de acceso del usuario temporal + ansible.builtin.command: > + aws iam list-access-keys --user-name {{ test_iam_username }} --output json + register: access_keys_raw + changed_when: false + + - name: Eliminar claves de acceso asociadas + ansible.builtin.command: > + aws iam delete-access-key + --user-name {{ test_iam_username }} + --access-key-id {{ item.AccessKeyId }} + loop: "{{ (access_keys_raw.stdout | from_json).AccessKeyMetadata | default([]) }}" + when: (access_keys_raw.stdout | from_json).AccessKeyMetadata is defined + changed_when: true + + - name: Eliminar usuario temporal IAM + ansible.builtin.command: > + aws iam delete-user --user-name {{ test_iam_username }} + register: iam_delete_user + changed_when: iam_delete_user.rc == 0 + + - name: Confirmar limpieza IAM + ansible.builtin.debug: + msg: "Usuario IAM temporal {{ test_iam_username }} y sus politicas fueron eliminados." + + # 2. Desbloqueo de Red (Network ACL) + - name: Obtener reglas activas de la Network ACL + ansible.builtin.command: > + aws ec2 describe-network-acls + --network-acl-ids {{ nacl_id }} + --region {{ aws_region }} + --output json + register: nacl_status_raw + changed_when: false + + - name: Identificar reglas DENY temporales (numeros 1 a 99) + ansible.builtin.set_fact: + temp_deny_rules: >- + {{ + ((nacl_status_raw.stdout | from_json).NetworkAcls[0].Entries) + | selectattr('Egress', 'equalto', false) + | selectattr('RuleAction', 'equalto', 'deny') + | selectattr('RuleNumber', 'lt', 100) + | map(attribute='RuleNumber') + | list + }} + + - name: Notificar reglas DENY a eliminar de la Network ACL + ansible.builtin.debug: + msg: "Reglas de bloqueo identificadas en NACL: {{ temp_deny_rules }}" + when: temp_deny_rules | length > 0 + + - name: Eliminar reglas DENY temporales de la Network ACL + ansible.builtin.command: > + aws ec2 delete-network-acl-entry + --network-acl-id {{ nacl_id }} + --rule-number {{ item }} + --ingress + --region {{ aws_region }} + loop: "{{ temp_deny_rules }}" + when: temp_deny_rules | length > 0 + register: nacl_deleted_rules + changed_when: true + + # 3. Reinicio de Servicio Web en EC2 para limpiar bloqueos en memoria + - name: Reiniciar servicio tesis-portal via AWS SSM para limpiar memoria de bloqueos + ansible.builtin.command: > + aws ssm send-command + --instance-ids {{ portal_instance_id }} + --document-name "AWS-RunShellScript" + --parameters 'commands=["systemctl restart tesis-portal"]' + --region {{ aws_region }} + --output json + register: ssm_restart_cmd + changed_when: true + + - name: Esperar 5 segundos tras reinicio + ansible.builtin.pause: + seconds: 5 + + # 4. Verificacion de Salud Final + - name: Verificar restablecimiento del acceso al portal web + ansible.builtin.uri: + url: "{{ portal_url }}/health" + status_code: 200 + return_content: true + register: final_health_check + retries: 5 + delay: 2 + + - name: Resumen de restauracion completada + ansible.builtin.debug: + msg: + - "==========================================================" + - " ESTADO DEL LABORATORIO RESTAURADO" + - "==========================================================" + - "NACL: Reglas de bloqueo DENY temporales eliminadas" + - "IAM: Usuario temporal y EmergencyDenyAll eliminados" + - "Portal Web: Memoria reiniciada y servicio 100% operativo" + - "Health Check: {{ final_health_check.json.status }} (Version: {{ final_health_check.json.version }})" + - "==========================================================" diff --git a/ansible/playbooks/simulations/run_all.yml b/ansible/playbooks/simulations/run_all.yml new file mode 100644 index 0000000..39e3dda --- /dev/null +++ b/ansible/playbooks/simulations/run_all.yml @@ -0,0 +1,41 @@ +--- +# ============================================================================== +# Suite Completa de Simulaciones Red Team y Restauracion Zero-State +# Sistema IR Automatizado en AWS (TIC Tesis) +# +# Uso: +# - Ejecutar todo el ciclo con rollback final: +# ansible-playbook ansible/playbooks/simulations/run_all.yml +# +# - Ejecutar solo un ataque especifico: +# ansible-playbook ansible/playbooks/simulations/run_all.yml --tags brute_force +# ansible-playbook ansible/playbooks/simulations/run_all.yml --tags port_scan +# ansible-playbook ansible/playbooks/simulations/run_all.yml --tags privilege_escalation +# ansible-playbook ansible/playbooks/simulations/run_all.yml --tags credential_leak +# ansible-playbook ansible/playbooks/simulations/run_all.yml --tags exfiltration +# ansible-playbook ansible/playbooks/simulations/run_all.yml --tags cleanup +# ============================================================================== + +- name: "Ejecutar Simulacion: 01 Fuerza Bruta" + ansible.builtin.import_playbook: 01_brute_force.yml + tags: [brute_force, all] + +- name: "Ejecutar Simulacion: 02 Escaneo de Puertos" + ansible.builtin.import_playbook: 02_port_scan.yml + tags: [port_scan, all] + +- name: "Ejecutar Simulacion: 03 Escalada de Privilegios" + ansible.builtin.import_playbook: 03_privilege_escalation.yml + tags: [privilege_escalation, all] + +- name: "Ejecutar Simulacion: 04 Fuga de Credenciales" + ansible.builtin.import_playbook: 04_credential_leak.yml + tags: [credential_leak, all] + +- name: "Ejecutar Simulacion: 05 Exfiltracion S3" + ansible.builtin.import_playbook: 05_s3_exfiltration.yml + tags: [exfiltration, all] + +- name: "Ejecutar Rollback y Limpieza Zero-State" + ansible.builtin.import_playbook: rollback_cleanup.yml + tags: [cleanup, rollback, all] diff --git a/ansible/playbooks/simulations/vars.yml b/ansible/playbooks/simulations/vars.yml new file mode 100644 index 0000000..490b5a4 --- /dev/null +++ b/ansible/playbooks/simulations/vars.yml @@ -0,0 +1,21 @@ +--- +# Variables centrales para la Suite de Ataques Red Team y Rollback (TIC Tesis) +# Alineadas con los outputs activos de Terraform en AWS us-east-2 + +portal_public_ip: "18.219.62.81" +portal_url: "http://18.219.62.81" +aws_region: "us-east-2" +vpc_id: "vpc-00cd654d72a84e9f0" +nacl_id: "acl-0c072d7e12b416874" + +sensitive_bucket: "tesis-ir-sensitive-data-056176271407-us-east-2" +evidence_bucket: "tesis-ir-evidence-056176271407-us-east-2" +logs_bucket: "tesis-ir-logs-056176271407-us-east-2" + +dynamodb_incidents_table: "tesis-ir_incidents" +dynamodb_state_table: "tesis-ir_detection_state" + +portal_instance_id: "i-05a276d44211bf7e7" +test_iam_username: "tesis-ir-temp-escalation-test" +test_escalation_policy_arn: "arn:aws:iam::aws:policy/ReadOnlyAccess" +emergency_deny_policy_name: "EmergencyDenyAll" From 6788d0c3a68d1c45531ce85d5de1a9d36e9e2848 Mon Sep 17 00:00:00 2001 From: bryancito1090 Date: Thu, 5 Nov 2026 23:22:10 -0500 Subject: [PATCH 3/5] feat(automation): generar variables de simulacion desde Terraform --- ansible/playbooks/simulations/README.md | 11 +++++ ansible/playbooks/simulations/vars.yml | 34 +++++++------- ansible/scripts/generate_simulation_vars.py | 49 +++++++++++++++++++++ 3 files changed, 75 insertions(+), 19 deletions(-) create mode 100644 ansible/scripts/generate_simulation_vars.py diff --git a/ansible/playbooks/simulations/README.md b/ansible/playbooks/simulations/README.md index 61466e6..0f2633e 100644 --- a/ansible/playbooks/simulations/README.md +++ b/ansible/playbooks/simulations/README.md @@ -65,3 +65,14 @@ Elimina las reglas de bloqueo en Network ACL, remueve usuarios y políticas temp ```bash ansible-playbook ansible/playbooks/simulations/rollback_cleanup.yml ``` + +--- + +## 4. Reconstrucción y Sincronización Automática tras Despliegue + +Si la infraestructura en AWS fue recreada con Terraform, regenera las variables del laboratorio y el inventario con: +```bash +python ansible/scripts/generate_inventory.py +python ansible/scripts/generate_simulation_vars.py +``` +Esto leerá las salidas (`outputs`) del nuevo entorno en AWS y sincronizará de forma automática las IPs, buckets, tablas e identificadores de red tanto en el inventario SSM como en `ansible/playbooks/simulations/vars.yml`. diff --git a/ansible/playbooks/simulations/vars.yml b/ansible/playbooks/simulations/vars.yml index 490b5a4..286f69a 100644 --- a/ansible/playbooks/simulations/vars.yml +++ b/ansible/playbooks/simulations/vars.yml @@ -1,21 +1,17 @@ --- -# Variables centrales para la Suite de Ataques Red Team y Rollback (TIC Tesis) -# Alineadas con los outputs activos de Terraform en AWS us-east-2 +# Variables de simulacion actualizadas automaticamente desde Terraform -portal_public_ip: "18.219.62.81" -portal_url: "http://18.219.62.81" -aws_region: "us-east-2" -vpc_id: "vpc-00cd654d72a84e9f0" -nacl_id: "acl-0c072d7e12b416874" - -sensitive_bucket: "tesis-ir-sensitive-data-056176271407-us-east-2" -evidence_bucket: "tesis-ir-evidence-056176271407-us-east-2" -logs_bucket: "tesis-ir-logs-056176271407-us-east-2" - -dynamodb_incidents_table: "tesis-ir_incidents" -dynamodb_state_table: "tesis-ir_detection_state" - -portal_instance_id: "i-05a276d44211bf7e7" -test_iam_username: "tesis-ir-temp-escalation-test" -test_escalation_policy_arn: "arn:aws:iam::aws:policy/ReadOnlyAccess" -emergency_deny_policy_name: "EmergencyDenyAll" +portal_public_ip: 18.219.62.81 +portal_url: http://18.219.62.81 +aws_region: us-east-2 +vpc_id: vpc-00cd654d72a84e9f0 +nacl_id: acl-0c072d7e12b416874 +sensitive_bucket: tesis-ir-sensitive-data-056176271407-us-east-2 +evidence_bucket: tesis-ir-evidence-056176271407-us-east-2 +logs_bucket: tesis-ir-logs-056176271407-us-east-2 +dynamodb_incidents_table: tesis-ir_incidents +dynamodb_state_table: tesis-ir_detection_state +portal_instance_id: i-05a276d44211bf7e7 +test_iam_username: tesis-ir-temp-escalation-test +test_escalation_policy_arn: arn:aws:iam::aws:policy/ReadOnlyAccess +emergency_deny_policy_name: EmergencyDenyAll diff --git a/ansible/scripts/generate_simulation_vars.py b/ansible/scripts/generate_simulation_vars.py new file mode 100644 index 0000000..c3c783f --- /dev/null +++ b/ansible/scripts/generate_simulation_vars.py @@ -0,0 +1,49 @@ +"""Genera ansible/playbooks/simulations/vars.yml desde outputs de Terraform.""" + +import json +from pathlib import Path +import subprocess +import sys +import yaml + + +def main(): + root = Path(__file__).resolve().parents[2] + tf_dir = root / "terraform-tesis-ir-secure-portal" + out_file = root / "ansible/playbooks/simulations/vars.yml" + try: + raw = subprocess.run( + ["terraform", f"-chdir={tf_dir}", "output", "-json"], + check=True, + capture_output=True, + text=True, + ) + data = json.loads(raw.stdout) + vars_content = { + "portal_public_ip": data["portal_public_ip"]["value"], + "portal_url": data["portal_url"]["value"], + "aws_region": data["region"]["value"], + "vpc_id": data["vpc_id"]["value"], + "nacl_id": data["mitigation_network_acl_id"]["value"], + "sensitive_bucket": data["sensitive_bucket"]["value"], + "evidence_bucket": data["evidence_bucket"]["value"], + "logs_bucket": data["logs_bucket"]["value"], + "dynamodb_incidents_table": data["dynamodb_incidents_table"]["value"], + "dynamodb_state_table": data["dynamodb_state_table"]["value"], + "portal_instance_id": data["portal_instance_id"]["value"], + "test_iam_username": "tesis-ir-temp-escalation-test", + "test_escalation_policy_arn": "arn:aws:iam::aws:policy/ReadOnlyAccess", + "emergency_deny_policy_name": "EmergencyDenyAll", + } + with open(out_file, "w", encoding="utf-8") as f: + f.write("---\n# Variables de simulacion actualizadas automaticamente desde Terraform\n\n") + yaml.dump(vars_content, f, default_flow_style=False, sort_keys=False) + print(f"Variables de simulacion actualizadas: {out_file}") + except (OSError, ValueError, subprocess.CalledProcessError) as exc: + print(f"Error generando vars.yml: {exc}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) From 08c5a265d05036ef23077df81ff1a981bc7783a5 Mon Sep 17 00:00:00 2001 From: bryancito1090 Date: Fri, 6 Nov 2026 07:31:00 -0500 Subject: [PATCH 4/5] feat(ui): implementar diseno glassmorphism para el login y bloqueo --- ansible/roles/portal_app/files/app.py | 442 ++++++++++++++++++++------ tests/test_portal.py | 13 + 2 files changed, 360 insertions(+), 95 deletions(-) diff --git a/ansible/roles/portal_app/files/app.py b/ansible/roles/portal_app/files/app.py index cb44c55..a9d1c2d 100644 --- a/ansible/roles/portal_app/files/app.py +++ b/ansible/roles/portal_app/files/app.py @@ -107,6 +107,17 @@ SVG_ICONS = { '' ), + "lock": ( + '' + '' + '' + ), + "arrow_right": ( + '' + '' + ), } @@ -704,59 +715,132 @@ class Handler(BaseHTTPRequestHandler): if message: kind = "critical" if error else "info" alert_html = f""" -
+
{html_escape(message)}
""" + icon_shield = SVG_ICONS["shield"] + icon_user = SVG_ICONS["user"] + icon_lock = SVG_ICONS["lock"] + icon_arrow = SVG_ICONS["arrow_right"] + content = f""" -
-