Iniciar sesión
Portal seguro de operaciones y telemetría
from http.server import BaseHTTPRequestHandler, HTTPServer from urllib.parse import parse_qs, urlparse from http import cookies from datetime import datetime, timezone, timedelta import base64 import hashlib import hmac import html import json import os 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" ) LOCK_THRESHOLD = 5 LOCK_SECONDS = 300 EC_TZ = timezone(timedelta(hours=-5), name="America/Guayaquil") 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 = { "admin.demo": { "display": "Administrador", "hash": "VpqSvQMFATBEs7T3ZU/BSA==:xioUwz95jf3bZ1gsUHqTc3H6cTcU6upr0fZiFuoU9ZY=", }, "soc.demo": { "display": "Analista SOC", "hash": "9lkouWYrd54ObTxyAsNSUw==:UPSlJBYvlF2uIdpzV9LVmqMUuMNsLwXFDX+f5dedX04=", }, "usuario.demo": { "display": "Usuario operativo", "hash": "n33eTr4zUj6AkGU1EfAx8A==:C3Bu/CHMnuT3SPOvBTvp0H0qpmCFJvpOjtnv7YKD9yQ=", }, } 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(): return datetime.now(EC_TZ).isoformat() def now_utc(): return datetime.now(timezone.utc).isoformat() 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: return f.read().strip() secret = base64.urlsafe_b64encode(secrets.token_bytes(48)) with open(SESSION_SECRET_FILE, "wb") as f: f.write(secret) os.chmod(SESSION_SECRET_FILE, 0o600) return secret SESSION_SECRET = get_session_secret() def base_event(event): clean = dict(event) clean.pop("password", None) clean.setdefault("timestamp", now_ecuador()) clean.setdefault("timestamp_utc", now_utc()) clean.setdefault("timezone", "America/Guayaquil") clean.setdefault("affected_service", AFFECTED_SERVICE) clean.setdefault("asset_name", ASSET_NAME) clean.setdefault("asset_type", ASSET_TYPE) clean.setdefault("service_owner", COMPANY_NAME) return clean 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(ev, ensure_ascii=False, separators=(",", ":")) + "\n") def verify_password(username, password): user = USERS.get(username) if not user: return False salt_b64, hash_b64 = user["hash"].split(":", 1) salt = base64.b64decode(salt_b64) expected = base64.b64decode(hash_b64) candidate = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, 120000) return hmac.compare_digest(candidate, expected) def sign_value(value): sig = hmac.new(SESSION_SECRET, value.encode("utf-8"), hashlib.sha256).hexdigest() return value + "." + sig 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() if hmac.compare_digest(sig, expected): return payload return None 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): theme_btn_html = f""" """ session_html = "" if authenticated: role = USERS.get(username, {}).get("display", "Usuario") initial = (username[0] if username else "A").upper() session_html = f"""
""" else: session_html = f""" """ return f"""Portal seguro de operaciones y telemetría
Se detectó un exceso de intentos fallidos. El sistema IR activó la ventana de contención defensiva.
{html_escape(ev['event_type'])}{html_escape(ev['source_ip'])}Módulo corporativo simulado para el seguimiento de solicitudes bancarias y auditoría forense.
| Ref Operación | Tipo de Registro | Usuario Asignado | Estado | Hora Local | Bóveda Segura |
|---|---|---|---|---|---|
AST-2026-9041 |
Transferencia Corporativa Swift | {html_escape(username)} |
Completado | 10:14:22 | S3 /sensible/clientes_demo.json |
AST-2026-9042 |
Auditoría de Acceso IAM | soc.demo |
En Revisión | 11:02:18 | CloudTrail Forensic Store |
AST-2026-9043 |
Exportación de Cuentas VIP | admin.demo |
Custodiado | 11:45:09 | S3 Sensitive Encrypted Bucket |
Mediciones exactas en milisegundos tomadas con reloj monotónico de precisión.
| Última petición (Latency) | {lat["last_ms"]} ms |
| Percentil 95 (p95) | {lat["p95_ms"]} ms |
| Promedio ponderado | {lat["avg_ms"]} ms |
| Latencia mínima registrada | {lat["min_ms"]} ms |
| Latencia máxima registrada | {lat["max_ms"]} ms |
Telemetría directa del sistema operativo de la máquina virtual ({ASSET_NAME}).
| IP Pública de tu cliente | {html_escape(client_ip)} |
| Servidor web Nginx | Activo (Reverse Proxy) |
| Proceso Python Systemd | Activo (8080) |
| Agente CloudWatch | Recolectando logs |
Eventos estructurados capturados por app.py y enviados a CloudWatch para la correlación Lambda.
| Hora | Evento | Usuario | IP Origen | Severidad | Resultado | Detalle |
|---|
Página no" " encontrada.