From 21c41eedf3eb03a7a67ef60b58572688ad563a14 Mon Sep 17 00:00:00 2001 From: Tobias Jurnet <114355588+binaryTob@users.noreply.github.com> Date: Wed, 14 Oct 2026 20:25:52 -0300 Subject: [PATCH] Translate workflows, diagnostics and report output into English --- .gitignore | 4 +- AGENTS.md | 7 +- README.md | 6 + REPORTING.md | 5 + config/target.example.json | 4 +- lib/diagnosis.yaml | 408 ++++++++++---------- scripts/gen_report.py | 204 +++++----- skills/_index.yaml | 12 +- skills/_schema.yaml | 54 +-- skills/_template.md | 78 ++-- skills/analysis/configuration-analysis.md | 4 +- skills/common/helpers.md | 50 +-- skills/discovery/system-inventory.md | 2 +- skills/discovery/systemd-analysis.md | 10 +- skills/platform/etcd-analysis.md | 58 +-- skills/platform/kubernetes-analysis.md | 4 +- skills/platform/patroni-analysis.md | 74 ++-- skills/platform/teleport-analysis.md | 48 +-- skills/platform/tls-certificate-analysis.md | 2 +- skills/resources/cpu-analysis.md | 4 +- skills/resources/disk-analysis.md | 2 +- skills/resources/io-analysis.md | 2 +- skills/resources/memory-analysis.md | 6 +- skills/resources/network-analysis.md | 10 +- templates/executive-summary.md | 20 +- templates/findings-template.md | 27 +- templates/optimization-comparison.md | 32 +- templates/optimization-report.md | 40 +- templates/server-report.md | 10 +- tests/test_safety.py | 7 +- workflows/advanced-credential-theft-v2.md | 80 ++-- workflows/credential-theft-investigation.md | 78 ++-- workflows/incident-triage.md | 102 ++--- workflows/infrastructure-audit.md | 88 ++--- workflows/server-resource-analysis.md | 20 +- 35 files changed, 788 insertions(+), 774 deletions(-) diff --git a/.gitignore b/.gitignore index b01cbbf..13da981 100644 --- a/.gitignore +++ b/.gitignore @@ -3,7 +3,7 @@ # SSH target config (contains host/user/port — no credentials, but host-specific) config/target.json -# Reportes: escaneos, evidencia y reportes generados +# Generated scan data, evidence and reports reportes/ # Current run id marker (temporary state) @@ -26,7 +26,7 @@ __pycache__/ *.tmp *.bak -# ── Secrets / credentials (defensivo) ───────────────────────────────────── +# ── Secrets / credentials (defensive exclusions) ───────────────────────── *.key *.pem diff --git a/AGENTS.md b/AGENTS.md index 6459466..4efe806 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -26,6 +26,7 @@ See `SAFETY.md`. 6. **Migration rule.** A migration objective does NOT start with the migration plan. It starts with fully understanding the current state. 7. **Skill economy.** Discovering a technology is never, by itself, a reason to create a skill. Reuse existing capabilities and bounded ad-hoc checks first. Persist only capabilities that are necessary, non-overlapping, host-agnostic, and expected to be reused across targets or runs. 8. **Single execution path.** Every remote command is executed through `scripts/ssh_exec.sh`. Command blocks in skills describe remote payloads; never run their literal `ssh` examples directly or write raw output to evidence. +9. **English narrative output.** Write analysis, findings, recommendations and executive summaries in English. Preserve captured target output verbatim after redaction; do not translate evidence or rename existing storage paths. ## How to run an audit (operator) @@ -36,8 +37,8 @@ See `SAFETY.md`. ## How to run a diagnosis (operator) -If you are reporting a **symptom** (not asking for a full audit) — e.g. "el sitio da 502", -"el disco se llenó", "un contenedor se reinicia solo" — the agent follows +If you are reporting a **symptom** (not asking for a full audit) — e.g. "the site returns 502", +"the disk is full", "a container keeps restarting" — the agent follows `workflows/incident-triage.md` and reads `lib/diagnosis.yaml` (symptom -> hypotheses -> evidence -> skills). It runs only the skills needed to find the root cause and the remediation, and it never fixes anything without Level 3 approval. @@ -91,7 +92,7 @@ infrastructure-expert/ │ ├── observability/ <- monitoring stack health │ ├── backup/ <- backup mechanisms detection │ └── migration/ <- A->B migration assessment -├── workflows/ <- entry points: audit (por modo) + incident triage +├── workflows/ <- entry points: audit (by mode) + incident triage ├── templates/ <- report templates └── reportes/ <- scan data + reports (gitignored) ``` diff --git a/README.md b/README.md index 26a6c3f..c9453ce 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,12 @@ All scan data and reports are stored in `reportes//`: - `reportes//informe-.html` — self-contained offline HTML report - Executive summary printed to the console. +Documentation, agent-authored findings and generated report labels use English. +The existing `reportes/`, `evidencia/` and `informe-*.html` storage names are retained +for compatibility with existing runs; they are path identifiers, not a report +language setting. Captured target output is preserved as evidence in its original +language rather than translated. + ## Safety | Level | Description | Default | diff --git a/REPORTING.md b/REPORTING.md index 683aa45..5da2b6c 100644 --- a/REPORTING.md +++ b/REPORTING.md @@ -4,6 +4,11 @@ `reportes//informe-.html` — single, offline, self-contained HTML (no external CDN; all CSS/JS inline). +Use English for report headings, analysis, findings, remediation and summaries. +The renderer declares `lang="en"`. Keep captured evidence in its original language +after redaction; translating it would alter the source record. Retain existing +storage path names for compatibility with earlier runs. + ## Sections (in order) 1. **Executive Summary** — overall state, top risks, top recommendations. diff --git a/config/target.example.json b/config/target.example.json index 4ec6dac..490d036 100644 --- a/config/target.example.json +++ b/config/target.example.json @@ -7,7 +7,7 @@ "connect_timeout": 15, "command_timeout": 60 }, - "objective": "Analizar completamente la infraestructura.", - "context": "Nivel de seguridad: L1+L2 solamente (no corras ningun comando que pueda modificar algo en el servidor, solo verificar).", + "objective": "Analyze the infrastructure comprehensively.", + "context": "Safety level: L1+L2 only. Do not run commands that could modify the server; observe and verify only.", "mode": "FULL" } diff --git a/lib/diagnosis.yaml b/lib/diagnosis.yaml index 7bd9cbc..a8627a9 100644 --- a/lib/diagnosis.yaml +++ b/lib/diagnosis.yaml @@ -2,8 +2,8 @@ version: "1.0" # --------------------------------------------------------------------------- # Symptom-driven diagnosis map. # -# The agent reads this file when the operator reports a *symptom* ("el sitio -# da 502", "el disco se llenó", "un contenedor se reinicia solo") and needs to +# The agent reads this file when the operator reports a *symptom* ("the site +# returns 502", "the disk is full", "a container keeps restarting") and needs to # go from symptom -> ranked hypotheses -> evidence -> root cause -> remediation. # # This file is DATA, not code. Adding a new symptom is a YAML edit, no Python @@ -14,7 +14,7 @@ version: "1.0" symptoms: - id: "http_5xx" - label: "Sitio responde 500 / 502 / 503 / 504" + label: "Site returns 500 / 502 / 503 / 504" order: - "502_bad_gateway" - "503_service_unavailable" @@ -22,64 +22,64 @@ symptoms: - "500_internal_error" - id: "cert_error" - label: "Error de certificado / TLS en el navegador" + label: "Browser certificate / TLS error" order: - "cert_expired" - "cert_mismatch" - id: "site_down" - label: "Sitio caído / connection refused / timeout" + label: "Site down / connection refused / timeout" order: - "service_down" - "container_down" - "port_not_listening" - id: "disk_full" - label: "Disco lleno / escritura falla" + label: "Disk full / writes fail" order: ["disk_full"] - id: "oom" - label: "Proceso muerto / matado / memoria agotada" + label: "Process terminated / killed / out of memory" order: ["oom_kill"] - id: "high_load" - label: "CPU / load alto, lentitud general" + label: "High CPU / load, general slowdown" order: ["runaway_process"] - id: "slow" - label: "Respuestas lentas" + label: "Slow responses" order: ["slow_backend", "slow_db"] - id: "db_error" - label: "Fallo de conexión a base de datos" + label: "Database connection failure" order: ["db_unreachable"] - id: "crash_loop" - label: "Contenedor en crash loop / reinicios" + label: "Container crash loop / restarts" order: ["crash_loop"] - id: "dns_error" - label: "Errores DNS (EAI_AGAIN / ENOTFOUND)" + label: "DNS errors (EAI_AGAIN / ENOTFOUND)" order: ["dns_failure"] - id: "log_flood" - label: "Logs creciendo sin control / disco por logs" + label: "Uncontrolled log growth / disk filled by logs" order: ["log_growth"] - id: "backup_gap" - label: "Sospecha de backups inexistentes / no probados" + label: "Suspected missing / untested backups" order: ["backup_missing"] - id: "teleport_agent_failure" - label: "Agente Teleport desconectado o fuera de servicio" + label: "Teleport agent disconnected or unavailable" order: ["teleport_service_failure"] - id: "database_cluster_flap" - label: "Failover frecuente / backend PostgreSQL intermitente / Patroni sin primario" + label: "Frequent failover / intermittent PostgreSQL backend / no Patroni primary" order: ["distributed_consensus_latency", "database_backend_flap"] - id: "credential_theft" - label: "Sospecha de robo de credenciales (.env / GitHub keys)" + label: "Suspected credential theft (.env / GitHub keys)" order: - "env_files_exposed" - "git_credentials_stolen" @@ -92,390 +92,390 @@ hypotheses: 502_bad_gateway: label: "502 Bad Gateway" checks: - - name: "Upstream backend caído o no escuchando" + - name: "Upstream backend unavailable or not listening" how: > - El proxy (Apache/nginx) llegó al upstream pero no obtuvo respuesta válida. - El contenedor puede estar 'up' pero su proceso de app muerto. + The proxy (Apache/nginx) reached the upstream but received no valid response. + The container may be 'up' while its application process has terminated. evidence: ["web_server_analysis.upstream_health", "web_server_analysis.proxy_upstream_map"] confirm: "curl -s -o /dev/null -w '%{http_code}' http://:/ -> 000/refused" skills: ["web_server_analysis", "docker_troubleshooting", "container_log_analysis", "log_analysis"] - remediation: "Levantar el backend (Level 3: reiniciar servicio/contenedor) y eliminar pid obsoleto si aplica." - - name: "Proxy apunta a host/puerto equivocado" - how: "Config drift entre el vhost (ProxyPass) y el puerto real donde escucha la app." + remediation: "Bring up the backend (Level 3: restart the service/container) and remove a stale PID file if applicable." + - name: "Proxy points to the wrong host/port" + how: "Configuration drift between the vhost (ProxyPass) and the application's actual listening port." evidence: ["web_server_analysis.proxy_upstream_map", "network_analysis.port_process_map"] - confirm: "Comparar ProxyPass target vs ss -tlnp y docker port." + confirm: "Compare the ProxyPass target with ss -tlnp and docker port." skills: ["web_server_analysis", "network_analysis"] - remediation: "Corregir la directiva ProxyPass/proxy_pass al puerto correcto (Level 3)." - - name: "Upstream muere al recibir la petición (OOM/segfault)" - how: "El backend responde a ping pero crashea al procesar (memoria, DB lenta)." + remediation: "Point ProxyPass/proxy_pass to the correct port (Level 3)." + - name: "Upstream terminates while handling the request (OOM/segfault)" + how: "The backend responds to ping but crashes during processing (memory pressure, slow database)." evidence: ["log_analysis.oom_in_logs", "container_log_analysis.container_crash_logs"] confirm: "dmesg | grep -i oom; docker inspect OOMKilled." skills: ["log_analysis", "docker_troubleshooting"] - remediation: "Reducir consumo de memoria / habilitar swap / subir RAM (Level 3)." + remediation: "Reduce memory usage / enable swap / increase RAM (Level 3)." 503_service_unavailable: label: "503 Service Unavailable" checks: - - name: "Sin backends sanos / workers agotados" - how: "Todos los workers ocupados o el pool de backend vacío." + - name: "No healthy backends / exhausted workers" + how: "All workers are busy or the backend pool is empty." evidence: ["web_server_analysis.upstream_health"] - confirm: "Logs del proxy muestran 'no live upstreams' / max_children alcanzado." + confirm: "Proxy logs show 'no live upstreams' / max_children reached." skills: ["web_server_analysis", "log_analysis"] - remediation: "Escalar workers/backends o revisar por qué están saturados." - - name: "Mantenimiento o app en arranque" - how: "La app devuelve 503 explícito (maintenance mode, migraciones en curso)." + remediation: "Scale workers/backends or investigate why they are saturated." + - name: "Maintenance or application startup" + how: "The application explicitly returns 503 (maintenance mode, migrations in progress)." evidence: ["http_health_analysis.endpoint_status"] - confirm: "Revisar la respuesta de la app directamente." + confirm: "Inspect the application's response directly." skills: ["http_health_analysis"] - remediation: "Esperar fin de mantenimiento / completar migraciones." + remediation: "Wait for maintenance to finish / complete migrations." 504_gateway_timeout: label: "504 Gateway Timeout" checks: - - name: "Backend lento / colgado (DB lenta, N+1, deadlock)" - how: "El upstream aceptó pero no respondió a tiempo." + - name: "Slow / stalled backend (slow database, N+1, deadlock)" + how: "The upstream accepted the request but did not respond in time." evidence: ["http_health_analysis.response_times", "capacity_analysis.headroom"] - confirm: "curl -w '%{time_total}' al backend directo; revisar slow query log." + confirm: "Run curl -w '%{time_total}' against the backend directly; inspect the slow query log." skills: ["http_health_analysis", "capacity_analysis", "log_analysis"] - remediation: "Optimizar consultas / índice / timeout del proxy (Level 3)." + remediation: "Optimize queries / indexes / proxy timeout (Level 3)." 500_internal_error: label: "500 Internal Server Error" checks: - - name: "Error de aplicación (stack trace en logs)" - how: "Excepción no capturada en el framework (Rails/Django/Node)." + - name: "Application error (stack trace in logs)" + how: "Unhandled framework exception (Rails/Django/Node)." evidence: ["log_analysis.journal_errors", "container_log_analysis.container_error_logs"] - confirm: "tail del log de la app: stack trace / excepción." + confirm: "Tail the application log for a stack trace / exception." skills: ["log_analysis", "container_log_analysis"] - remediation: "Corregir el bug; puede requerir deploy (Level 3)." + remediation: "Fix the bug; deployment may be required (Level 3)." cert_expired: - label: "Certificado expirado" + label: "Expired certificate" checks: - - name: "Certificado vencido o por vencer" - how: "La fecha de expiración ya pasó o está a <30 días sin auto-renovación." + - name: "Expired or soon-to-expire certificate" + how: "The expiry date has passed or is less than 30 days away without automatic renewal." evidence: ["tls_certificate_analysis.cert_expiry"] confirm: "openssl x509 -enddate -noout -in fullchain.pem." skills: ["tls_certificate_analysis", "backup_analysis"] - remediation: "Ejecutar renovación (certbot renew) y verificar el timer de auto-renovación." + remediation: "Renew the certificate (certbot renew) and verify the automatic renewal timer." cert_mismatch: - label: "Certificado no coincide con el dominio" + label: "Certificate does not match the domain" checks: - - name: "SAN no contiene el ServerName" - how: "El vhost usa un dominio que no está en el SAN del certificado." + - name: "SAN does not include ServerName" + how: "The vhost uses a domain missing from the certificate SAN." evidence: ["tls_certificate_analysis.cert_sans", "tls_certificate_analysis.cert_host_match"] - confirm: "Comparar ServerName vs SAN list." + confirm: "Compare ServerName with the SAN list." skills: ["tls_certificate_analysis", "web_server_analysis"] - remediation: "Re-emitir certificado para el dominio correcto." + remediation: "Reissue the certificate for the correct domain." service_down: - label: "Servicio systemd caído" + label: "Systemd service unavailable" checks: - - name: "Unidad en estado failed/inactive" - how: "El servicio que expone el puerto no está corriendo." + - name: "Unit in failed/inactive state" + how: "The service exposing the port is not running." evidence: ["systemd_analysis.services_failed", "reliability_analysis.recovery_mechanisms"] confirm: "systemctl status ." skills: ["systemd_analysis", "reliability_analysis"] - remediation: "Arrancar el servicio y configurar Restart=on-failure (Level 3)." + remediation: "Start the service and configure Restart=on-failure (Level 3)." container_down: - label: "Contenedor detenido / sin proceso" + label: "Container stopped / no application process" checks: - - name: "Contenedor exited o app interna muerta" - how: "El contenedor puede estar 'running' con el proceso interno muerto." + - name: "Exited container or terminated internal application" + how: "The container may be 'running' while its internal application process has terminated." evidence: ["docker_troubleshooting.container_exit_codes", "docker_analysis.containers"] - confirm: "docker ps -a (estado) + curl al container-IP:puerto." + confirm: "docker ps -a (status) + curl to container-IP:port." skills: ["docker_analysis", "docker_troubleshooting", "container_log_analysis"] - remediation: "docker start / compose up y revisar por qué murió (exit code)." + remediation: "Run docker start / compose up and investigate why it terminated (exit code)." port_not_listening: - label: "Nada escuchando en el puerto esperado" + label: "Nothing listening on the expected port" checks: - - name: "Binding en interface/puerto incorrecto" - how: "La app escucha en 127.0.0.1 o en otro puerto, no donde el proxy espera." + - name: "Bound to the wrong interface/port" + how: "The application listens on 127.0.0.1 or another port rather than the proxy's expected destination." evidence: ["network_analysis.open_ports", "network_analysis.port_process_map"] - confirm: "ss -tlnp | grep ." + confirm: "ss -tlnp | grep ." skills: ["network_analysis", "web_server_analysis"] - remediation: "Ajustar bind de la app al puerto/interface correctos." + remediation: "Bind the application to the correct port/interface." disk_full: - label: "Disco lleno" + label: "Disk full" checks: - - name: "Partición al 100% / inodes agotados" - how: "Sin espacio, las apps fallan al escribir (DB, logs, sesiones)." + - name: "Partition at 100% / exhausted inodes" + how: "Without free space, application writes fail (database, logs, sessions)." evidence: ["disk_analysis.fs_usage", "disk_analysis.inodes", "disk_analysis.large_dirs"] confirm: "df -h; du -x / | sort -h | tail." skills: ["disk_analysis", "observability_analysis"] - remediation: "Rotar/limpiar logs y artefactos viejos; ampliar disco (Level 3)." + remediation: "Rotate/clean logs and old artifacts; expand the disk (Level 3)." oom_kill: - label: "Proceso matado por OOM" + label: "Process killed by OOM" checks: - - name: "Kernel OOM-killer mató un proceso" - how: "Sin swap + varios procesos grandes, el kernel mata uno para sobrevivir." + - name: "Kernel OOM killer terminated a process" + how: "Without swap and with several large processes, the kernel kills a process to recover memory." evidence: ["log_analysis.oom_in_logs", "memory_analysis.swap", "reliability_analysis.spof_list"] - confirm: "dmesg | grep -i 'killed process'; free -h (sin swap)." + confirm: "dmesg | grep -i 'killed process'; free -h (no swap)." skills: ["log_analysis", "memory_analysis", "reliability_analysis"] - remediation: "Habilitar swap, limitar memoria de contenedores, subir RAM (Level 3)." + remediation: "Enable swap, limit container memory, increase RAM (Level 3)." runaway_process: - label: "Proceso consumiendo CPU" + label: "CPU-consuming process" checks: - - name: "Bucle infinito / proceso runaway" - how: "Un proceso acapara CPU y degrada al resto." + - name: "Infinite loop / runaway process" + how: "One process monopolizes CPU and degrades other workloads." evidence: ["cpu_analysis.cpu_per_process", "process_analysis.top_cpu_processes"] - confirm: "top/ps ordenado por %CPU sostenido." + confirm: "Observe sustained usage in top/ps sorted by %CPU." skills: ["cpu_analysis", "process_analysis"] - remediation: "Investigar el proceso; reiniciar si corresponde (Level 3)." + remediation: "Investigate the process; restart if appropriate (Level 3)." slow_backend: - label: "Backend lento" + label: "Slow backend" checks: - - name: "Respuesta lenta de la app (no de red)" - how: "time_total alto en el backend directo." + - name: "Slow application response (not network latency)" + how: "High time_total when accessing the backend directly." evidence: ["http_health_analysis.response_times", "capacity_analysis.headroom"] - confirm: "curl -w '%{time_total}' al backend directo vs proxy." + confirm: "Compare curl -w '%{time_total}' for the direct backend and proxy." skills: ["http_health_analysis", "capacity_analysis", "log_analysis"] - remediation: "Optimizar app / escalar recursos / cache (Level 3)." + remediation: "Optimize the application / scale resources / add caching (Level 3)." slow_db: - label: "Base de datos lenta" + label: "Slow database" checks: - - name: "Queries lentas / sin índices / conexiones saturadas" - how: "La DB es el cuello de botella." + - name: "Slow queries / missing indexes / saturated connections" + how: "The database is the bottleneck." evidence: ["database_analysis.db_connections", "database_analysis.db_settings"] confirm: "Slow query log / pg_stat_activity." skills: ["database_analysis", "capacity_analysis"] - remediation: "Indexar / optimizar queries / pooling." + remediation: "Add indexes / optimize queries / use connection pooling." db_unreachable: - label: "Base de datos inalcanzable" + label: "Unreachable database" checks: - - name: "DB remota caída / red / credenciales" - how: "La app apunta a una DB fuera del host que no responde." + - name: "Remote database unavailable / network / credentials" + how: "The application points to a database outside the host that does not respond." evidence: ["database_analysis.db_location", "database_analysis.db_connections"] - confirm: "test TCP al host:puerto de la DB." + confirm: "Test TCP connectivity to the database host:port." skills: ["database_analysis", "network_analysis"] - remediation: "Restaurar conectividad o la DB remota." + remediation: "Restore connectivity or recover the remote database." crash_loop: - label: "Contenedor en crash loop" + label: "Container crash loop" checks: - - name: "Exit code no-cero recurrente / OOM / app error" - how: "El contenedor arranca y muere en bucle." + - name: "Repeated nonzero exit code / OOM / application error" + how: "The container repeatedly starts and terminates." evidence: ["docker_troubleshooting.container_exit_codes", "container_log_analysis.container_crash_logs"] confirm: "docker ps (RestartCount) + docker logs ." skills: ["docker_troubleshooting", "container_log_analysis"] - remediation: "Corregir la causa (config, migraciones, dependencias) y relanzar." + remediation: "Fix the cause (configuration, migrations, dependencies) and relaunch." dns_failure: - label: "Fallo de resolución DNS" + label: "DNS resolution failure" checks: - - name: "Nameserver inalcanzable / resolv.conf roto" - how: "EAI_AGAIN / ENOTFOUND en la app o contenedores." + - name: "Unreachable nameserver / broken resolv.conf" + how: "EAI_AGAIN / ENOTFOUND in the application or containers." evidence: ["docker_troubleshooting.container_dns_config", "network_analysis.dns"] - confirm: "nslookup desde host y desde el contenedor." + confirm: "Run nslookup from the host and from the container." skills: ["docker_troubleshooting", "network_analysis"] - remediation: "Corregir /etc/resolv.conf o el DNS de Docker (Level 3)." + remediation: "Fix /etc/resolv.conf or Docker DNS settings (Level 3)." log_growth: - label: "Crecimiento descontrolado de logs" + label: "Uncontrolled log growth" checks: - - name: "Log sin rotación llenando disco" - how: "Un log (app/log de contenedor) crece sin límite." + - name: "Unrotated log filling the disk" + how: "An application/container log grows without a bound." evidence: ["observability_analysis.log_rotation", "disk_analysis.large_dirs"] confirm: "find /var/log -size +500M." skills: ["observability_analysis", "disk_analysis"] - remediation: "Configurar logrotate / max-size de logs de Docker (Level 3)." + remediation: "Configure logrotate / Docker log max-size (Level 3)." backup_missing: - label: "Backups inexistentes o no probados" + label: "Missing or untested backups" checks: - - name: "Sin mecanismo de backup para datos persistentes" - how: "Datos (DB, uploads) sin respaldo o sin restore probado." + - name: "No backup mechanism for persistent data" + how: "Data (database, uploads) has no backup or tested restore procedure." evidence: ["backup_analysis.backup_mechanisms", "backup_analysis.restore_readiness"] - confirm: "Verificar cron/timer de backup y artefacto reciente." + confirm: "Check the backup cron/timer and a recent artifact." skills: ["backup_analysis"] - remediation: "Implementar backups + test de restauración (Level 3)." + remediation: "Implement backups and a restore test (Level 3)." teleport_service_failure: - label: "Agente Teleport no operativo" + label: "Teleport agent not operational" checks: - - name: "Servicio detenido o configuracion invalida" - how: "La unidad systemd no puede iniciar por configuracion, permisos o parametros incompatibles." + - name: "Stopped service or invalid configuration" + how: "The systemd unit cannot start because of configuration, permissions or incompatible parameters." evidence: ["teleport_analysis.teleport_service_state", "teleport_analysis.teleport_config_validity", "teleport_analysis.teleport_errors"] - confirm: "Cruzar ActiveState/ExecMainStatus, fecha de configuracion, inicio efectivo y el primer error causal del journal." + confirm: "Correlate ActiveState/ExecMainStatus, configuration timestamp, actual startup and the first causal journal error." skills: ["teleport_analysis", "systemd_analysis", "log_analysis"] - remediation: "Corregir la configuracion o permisos y reiniciar Teleport (Level 3)." - - name: "Fallo de identidad o registro" - how: "La identidad expiro, fue revocada o el metodo de join no puede registrar el agente." + remediation: "Fix configuration or permissions and restart Teleport (Level 3)." + - name: "Identity or registration failure" + how: "The identity expired, was revoked, or the join method cannot register the agent." evidence: ["teleport_analysis.teleport_errors", "teleport_analysis.teleport_roles"] - confirm: "Los logs muestran errores x509, certificado, join, token o CA pin de forma repetida." + confirm: "Logs repeatedly show x509, certificate, join, token or CA pin errors." skills: ["teleport_analysis"] - remediation: "Renovar la identidad mediante el metodo de join autorizado y reiniciar Teleport (Level 3)." - - name: "Proxy o Auth Server inalcanzable" - how: "DNS, ruta, firewall o puerto remoto impiden que el agente mantenga el tunel reverso." + remediation: "Renew the identity through the authorized join method and restart Teleport (Level 3)." + - name: "Unreachable Proxy or Auth Server" + how: "DNS, routing, firewall or the remote port prevents the agent from maintaining its reverse tunnel." evidence: ["teleport_analysis.teleport_connectivity", "teleport_analysis.teleport_errors"] - confirm: "La resolucion o prueba TCP falla y coincide temporalmente con timeout/refused/no route en logs." + confirm: "Resolution or TCP testing fails at the same time as timeout/refused/no-route log events." skills: ["teleport_analysis", "network_analysis", "dns_analysis", "firewall_analysis"] - remediation: "Restaurar DNS/ruta/ACL al endpoint Teleport correcto (Level 3)." + remediation: "Restore DNS/routing/ACL access to the correct Teleport endpoint (Level 3)." distributed_consensus_latency: - label: "etcd pierde quorum o cambia de lider por latencia" + label: "etcd loses quorum or changes leader because of latency" checks: - - name: "Latencia de disco o red supera los tiempos de Raft" - how: "Fsyncs lentos o perdida/retransmision entre peers retrasa heartbeats y elecciones." + - name: "Disk or network latency exceeds Raft timing limits" + how: "Slow fsyncs or peer packet loss/retransmission delays heartbeats and elections." evidence: ["etcd_analysis.etcd_latency", "etcd_analysis.etcd_quorum", "network_analysis.tcp_retransmits"] - confirm: "Cruzar cambios de lider y timeouts con histogramas WAL/backend, ss -tin y una serie de salud." + confirm: "Correlate leader changes and timeouts with WAL/backend histograms, ss -tin and a health time series." skills: ["etcd_analysis", "io_analysis", "network_analysis", "log_analysis"] - remediation: "Asegurar almacenamiento de baja latencia y una red privada estable entre miembros; ajustar timeouts solo despues de corregir la infraestructura." + remediation: "Provide low-latency storage and a stable private network between members; adjust timeouts only after fixing infrastructure." database_backend_flap: - label: "HAProxy pierde intermitentemente el primario Patroni" + label: "HAProxy intermittently loses the Patroni primary" checks: - - name: "El check /master alterna entre 200 y timeout" - how: "El primario existe, pero su API de salud o el camino TCP deja de responder dentro del timeout." + - name: "The /master check alternates between 200 and timeout" + how: "The primary exists, but its health API or TCP path stops responding within the timeout." evidence: ["web_server_analysis.tcp_backend_health", "network_analysis.tcp_retransmits"] - confirm: "Comparar eventos DOWN/no-server de HAProxy con probes directos a :8008 y sockets TCP hacia :5432." + confirm: "Compare HAProxy DOWN/no-server events with direct :8008 probes and TCP sockets to :5432." skills: ["web_server_analysis", "network_analysis", "database_analysis", "etcd_analysis"] - remediation: "Corregir la perdida/latencia hacia el primario y validar el host Patroni; no ocultar el fallo aumentando el health-check timeout." + remediation: "Fix loss/latency to the primary and validate the Patroni host; do not hide the fault by increasing the health-check timeout." # === CREDENTIAL THEFT HYPOTHESES === env_files_exposed: - label: "Archivos .env expuestos" + label: "Exposed .env files" checks: - - name: ".env en directorio web-accessible" - how: "El servidor web puede servir directamente el archivo .env si está en el DocumentRoot sin protección." + - name: ".env in a web-accessible directory" + how: "The web server can serve .env directly when it is unprotected inside DocumentRoot." evidence: ["credential_exposure_analysis.web_exposed_env", "web_secret_exposure.web_env_access"] - confirm: "curl -I http://localhost/.env retorna 200 en vez de 404/403." + confirm: "curl -I http://localhost/.env returns 200 instead of 404/403." skills: ["credential_exposure_analysis", "web_secret_exposure"] - remediation: "Bloquear acceso a .env en nginx/apache (deny all) y mover .env fuera del DocumentRoot." + remediation: "Block .env access in nginx/apache (deny all) and move .env outside DocumentRoot." - name: ".env world-readable" - how: "El archivo .env tiene permisos 644/777 y cualquier usuario local puede leerlo." + how: "The .env file has mode 644/777 and any local user can read it." evidence: ["credential_exposure_analysis.env_permissions"] - confirm: "ls -la /ruta/.env muestra permisos que incluyen world-read." + confirm: "ls -la /path/.env shows world-readable permissions." skills: ["credential_exposure_analysis"] - remediation: "Cambiar permisos a 600 (owner-only) y verificar que no está en un repo git." - - name: ".env en directorio git" - how: "El .env está en un repositorio git y puede haber sido commiteado." + remediation: "Set mode 600 (owner-only) and check that the file is not tracked in Git." + - name: ".env in a Git directory" + how: "The .env file is inside a Git repository and may have been committed." evidence: ["credential_exposure_analysis.env_files", "git_credential_analysis.git_repos"] - confirm: "git -C /ruta/log check-attr -a .env; git -C /ruta/log log --all -- .env" + confirm: "git -C /path/repo check-attr -a .env; git -C /path/repo log --all -- .env" skills: ["credential_exposure_analysis", "git_credential_analysis"] - remediation: "Eliminar .env del historial git (git filter-branch o BFG) y agregar a .gitignore." - - name: ".env en /tmp o ubicación temporal" - how: "El .env fue copiado a /tmp o /var/tmp, posiblemente por un proceso de deployment o un atacante." + remediation: "Remove .env from Git history (git filter-branch or BFG) and add it to .gitignore." + - name: ".env in /tmp or a temporary location" + how: "The .env file was copied to /tmp or /var/tmp, possibly by a deployment process or an attacker." evidence: ["credential_exposure_analysis.env_files", "filesystem_forensics.file_timeline"] - confirm: "Verificar ownership y timestamp del archivo en /tmp." + confirm: "Check file ownership and timestamps in /tmp." skills: ["credential_exposure_analysis", "filesystem_forensics"] - remediation: "Eliminar .env de /tmp y verificar por qué fue copiado ahí." + remediation: "Remove .env from /tmp and investigate why it was copied there." git_credentials_stolen: - label: "Credenciales Git robadas" + label: "Stolen Git credentials" checks: - - name: ".git-credentials existe en el servidor" - how: "El archivo .git-credentials contiene credenciales en texto plano para GitHub/GitLab." + - name: ".git-credentials exists on the server" + how: "The .git-credentials file contains plaintext GitHub/GitLab credentials." evidence: ["git_credential_analysis.git_credentials"] confirm: "find / -name '.git-credentials' -type f" skills: ["git_credential_analysis"] - remediation: "Eliminar .git-credentials, usar credential helper con cifrado o SSH keys." - - name: "Token GitHub en .git/config" - how: "El .git/config contiene una URL con token embebido (https://ghp_TOKEN@github.com/...)." + remediation: "Remove .git-credentials; use an encrypted credential helper or SSH keys." + - name: "GitHub token in .git/config" + how: "The .git/config file contains a URL with an embedded token (https://ghp_TOKEN@github.com/...)." evidence: ["git_credential_analysis.git_credentials"] confirm: "cat .git/config | grep 'url.*@github.com'" skills: ["git_credential_analysis"] - remediation: "Eliminar token del .git/config, revocar el token en GitHub, usar SSH." - - name: "GitHub token en bash_history" - how: "Se usó un token de GitHub en un comando y quedó registrado en .bash_history." + remediation: "Remove the token from .git/config, revoke it in GitHub and use SSH." + - name: "GitHub token in bash_history" + how: "A GitHub token used in a command was recorded in .bash_history." evidence: ["git_credential_analysis.github_tokens", "filesystem_forensics.bash_history"] confirm: "grep 'ghp_' /root/.bash_history" skills: ["git_credential_analysis", "filesystem_forensics"] - remediation: "Revocar el token inmediatamente en GitHub, limpiar bash_history." - - name: "SSH key sin passphrase" - how: "Una SSH key sin passphrase fue encontrada, permitiendo acceso directo si se roba el archivo." + remediation: "Revoke the token immediately in GitHub and clean bash_history." + - name: "SSH key without a passphrase" + how: "An SSH key without a passphrase was found, allowing direct use if the file is stolen." evidence: ["git_credential_analysis.ssh_keys"] - confirm: "ssh-keygen -y -f /ruta/id_rsa (si pide passphrase está protegida)." + confirm: "ssh-keygen -y -f /path/id_rsa (a passphrase prompt indicates protection)." skills: ["git_credential_analysis"] - remediation: "Agregar passphrase a la key, rotar la key en GitHub." - - name: "Agent forwarding habilitado" - how: "ForwardAgent yes en SSH config permite abusar la agent del usuario para firmar commits." + remediation: "Add a passphrase and rotate the key in GitHub." + - name: "Agent forwarding enabled" + how: "ForwardAgent yes in SSH configuration can expose the user's agent to abuse for signing commits." evidence: ["git_credential_analysis.ssh_keys"] confirm: "grep -r 'ForwardAgent' ~/.ssh/config" skills: ["git_credential_analysis"] - remediation: "Deshabilitar ForwardAgent o restringir a hosts específicos." + remediation: "Disable ForwardAgent or restrict it to specific hosts." ssh_key_compromised: - label: "SSH key comprometida" + label: "Compromised SSH key" checks: - name: "SSH key world-readable" - how: "La clave privada SSH tiene permisos que permiten lectura por otros usuarios." + how: "The SSH private key permissions allow other users to read it." evidence: ["git_credential_analysis.ssh_keys"] confirm: "ls -la ~/.ssh/id_* | grep -v '600'" skills: ["git_credential_analysis"] - remediation: "chmod 600 la clave privada, 644 la pública." - - name: "Authorized_keys con keys desconocidas" - how: "Se agregaron keys SSH no reconocidas al authorized_keys." + remediation: "Use chmod 600 for the private key and 644 for the public key." + - name: "Unknown keys in authorized_keys" + how: "Unrecognized SSH keys were added to authorized_keys." evidence: ["security_analysis.persistence_indicators", "ssh_hardening_analysis.authorized_keys"] - confirm: "Comparar authorized_keys actual con el conocido." + confirm: "Compare current authorized_keys with the known baseline." skills: ["security_analysis", "ssh_hardening_analysis"] - remediation: "Remover keys no reconocidas, revocar en el servicio correspondiente." + remediation: "Remove unrecognized keys and revoke them in the corresponding service." docker_secret_leak: - label: "Secrets expuestos a través de Docker" + label: "Secrets exposed through Docker" checks: - - name: ".env montado como volumen en contenedor" - how: "El archivo .env está montado como volumen Docker, exponiendo secrets al contenedor." + - name: ".env mounted as a container volume" + how: "The .env file is mounted as a Docker volume, exposing secrets to the container." evidence: ["docker_secrets_analysis.secret_mounts"] confirm: "docker inspect --format '{{range .Mounts}}{{.Source}}' | grep .env" skills: ["docker_secrets_analysis"] - remediation: "Usar Docker secrets (Swarm) o named secrets en vez de montar .env." - - name: "Docker socket montado en contenedor" - how: "El docker.sock está montado, permitiendo al contenedor controlar Docker." + remediation: "Use Docker secrets (Swarm) or named secrets instead of mounting .env." + - name: "Docker socket mounted inside a container" + how: "The mounted docker.sock allows the container to control Docker." evidence: ["docker_secrets_analysis.privileged_containers"] confirm: "docker inspect --format '{{range .Mounts}}{{.Source}}' | grep docker.sock" skills: ["docker_secrets_analysis"] - remediation: "No montar docker.sock en contenedores de aplicación." - - name: "Contenedor privileged" - how: "Un contenedor tiene privilegios completos sobre el host." + remediation: "Do not mount docker.sock in application containers." + - name: "Privileged container" + how: "A container has full privileges over the host." evidence: ["docker_secrets_analysis.privileged_containers"] confirm: "docker inspect --format '{{.HostConfig.Privileged}}'" skills: ["docker_secrets_analysis"] - remediation: "Eliminar --privileged, usar capabilities específicas." + remediation: "Remove --privileged and use specific capabilities." web_secret_exposure: - label: "Secrets expuestos vía servidor web" + label: "Secrets exposed through the web server" checks: - - name: "Servidor web sirve .env directamente" - how: "HTTP request a /.env retorna 200 con el contenido del archivo." + - name: "Web server serves .env directly" + how: "An HTTP request to /.env returns 200 with the file contents." evidence: ["web_secret_exposure.web_env_access"] confirm: "curl -I http://localhost/.env" skills: ["web_secret_exposure"] - remediation: "Bloquear .env en nginx/apache config, eliminar .env del DocumentRoot." - - name: "phpinfo() expuesto" - how: "phpinfo.php está accesible y expone variables de entorno del servidor." + remediation: "Block .env in nginx/apache configuration and remove .env from DocumentRoot." + - name: "Exposed phpinfo()" + how: "Accessible phpinfo.php exposes server environment variables." evidence: ["web_secret_exposure.phpinfo_exposed"] confirm: "curl -I http://localhost/phpinfo.php" skills: ["web_secret_exposure"] - remediation: "Eliminar phpinfo.php de producción." + remediation: "Remove phpinfo.php from production." exfiltration_detected: - label: "Exfiltración de datos detectada" + label: "Detected data exfiltration" checks: - - name: "curl/wget en cron a endpoint desconocido" - how: "Un cron job ejecuta curl/wget hacia un endpoint que no es del sistema." + - name: "Cron curl/wget to an unknown endpoint" + how: "A cron job runs curl/wget against an endpoint outside the system." evidence: ["network_exfiltration.cron_network_usage"] - confirm: "Revisar /etc/cron.d/* y /var/spool/cron/* por comandos curl." + confirm: "Inspect /etc/cron.d/* and /var/spool/cron/* for curl commands." skills: ["network_exfiltration"] - remediation: "Eliminar el cron job, investigar origen, rotar credenciales." - - name: "SSH tunnel activo" - how: "Hay un proceso ssh con flags -R/-L/-D activo (tunel inverso/proxy)." + remediation: "Remove the cron job, investigate its origin and rotate credentials." + - name: "Active SSH tunnel" + how: "An active ssh process uses -R/-L/-D flags (reverse tunnel/proxy)." evidence: ["network_exfiltration.ssh_tunnels"] confirm: "ps aux | grep 'ssh.*-[RLD]'" skills: ["network_exfiltration"] - remediation: "Cerrar el túnel, investigar quién lo abrió." - - name: "Conexiones outbound a puertos no estándar" - how: "Conexiones salientes a puertos como 4444, 1337, 31337 (comunes en C2)." + remediation: "Close the tunnel and investigate who opened it." + - name: "Outbound connections to non-standard ports" + how: "Outbound connections use ports such as 4444, 1337 or 31337 (common in C2)." evidence: ["network_exfiltration.outbound_connections"] confirm: "ss -tnp | grep -E ':4444|:1337|:31337'" skills: ["network_exfiltration"] - remediation: "Bloquear el tráfico, investigar el proceso origen." + remediation: "Block the traffic and investigate the originating process." diff --git a/scripts/gen_report.py b/scripts/gen_report.py index 0a93cde..33b20c9 100755 --- a/scripts/gen_report.py +++ b/scripts/gen_report.py @@ -159,13 +159,13 @@ def detect_components(evidence): } def build_nav(sections): - items = [("exec-summary", "Resumen Ejecutivo")] + items = [("exec-summary", "Executive Summary")] for sid, label in sections: items.append((sid, label)) - items.append(("findings", "Hallazgos")) - items.append(("evidence", "Evidencia")) + items.append(("findings", "Findings")) + items.append(("evidence", "Evidence")) links = "".join(f'{label}' for id, label in items) - return f'' + return f'' def kv_row(k, v): return f'
{cesc(k)}{cesc(v)}
' @@ -382,7 +382,7 @@ def gen_html(run_dir, findings=None, inventory=None, migration=None): evidence = read_evidence(run_dir) comp = detect_components(evidence) n_skills, conditional_skills, all_skill_ids = load_skill_catalog() - skills_exec = "no registrado (falta skills-used.yaml)" + skills_exec = "not recorded (skills-used.yaml missing)" skills_used_path = os.path.join(run_dir, "skills-used.yaml") if os.path.exists(skills_used_path): skills_used = load_yaml(skills_used_path) or {} @@ -390,7 +390,7 @@ def gen_html(run_dir, findings=None, inventory=None, migration=None): s.get("id", "") for s in skills_used.get("skills", []) if s.get("status") == "executed" and s.get("id") ] - skills_exec = ", ".join(executed) if executed else "ninguno" + skills_exec = ", ".join(executed) if executed else "none" host = "unknown" if inventory: @@ -425,12 +425,12 @@ def gen_html(run_dir, findings=None, inventory=None, migration=None): # Build sections list dynamically sections = [] - sections.append(("infra-overview", "Infraestructura")) + sections.append(("infra-overview", "Infrastructure")) # OS summary card os_card = "" if os_info: - os_card = '

Sistema Operativo

' + os_card = '

Operating System

' for k in ["hostname","os_pretty","os","kernel","arch","virt","chassis"]: if k in os_info: os_card += kv_row(k.replace("os_pretty","os"), os_info[k]) @@ -446,16 +446,16 @@ def gen_html(run_dir, findings=None, inventory=None, migration=None): hw_card = '

Hardware

' if "nproc" in cpu_ram: hw_card += kv_row("CPU cores", cpu_ram["nproc"]) if "cpus" in cpu_ram: hw_card += kv_row("CPUs", cpu_ram["cpus"]) - if "mem_total" in cpu_ram: hw_card += kv_row("RAM total", cpu_ram["mem_total"]) - if "mem_avail" in cpu_ram: hw_card += kv_row("RAM disponible", f'{cpu_ram["mem_avail"]} (WARNING)' if cpu_ram.get("swap_used") == "255Mi" or "0.0Ki" in cpu_ram.get("swap_total","") else cpu_ram["mem_avail"]) - if "swap_total" in cpu_ram: hw_card += kv_row("Swap total", cpu_ram["swap_total"]) - if "swap_used" in cpu_ram: hw_card += kv_row("Swap usado", f'{cpu_ram["swap_used"]} LLENO' if cpu_ram.get("swap_used","") == "255Mi" and cpu_ram.get("swap_total","") == "255Mi" else cpu_ram["swap_used"]) + if "mem_total" in cpu_ram: hw_card += kv_row("Total RAM", cpu_ram["mem_total"]) + if "mem_avail" in cpu_ram: hw_card += kv_row("Available RAM", f'{cpu_ram["mem_avail"]} (WARNING)' if cpu_ram.get("swap_used") == "255Mi" or "0.0Ki" in cpu_ram.get("swap_total","") else cpu_ram["mem_avail"]) + if "swap_total" in cpu_ram: hw_card += kv_row("Total swap", cpu_ram["swap_total"]) + if "swap_used" in cpu_ram: hw_card += kv_row("Used swap", f'{cpu_ram["swap_used"]} FULL' if cpu_ram.get("swap_used","") == "255Mi" and cpu_ram.get("swap_total","") == "255Mi" else cpu_ram["swap_used"]) hw_card += '
' # Disk card disk_card = "" if disk_info: - disk_card = '

Disco

' + disk_card = '

Disk

' for k in ["device","size","fs","mount","fs_size","fs_used","fs_avail","fs_use_pct"]: if k in disk_info: label = k.replace("fs_","") @@ -477,12 +477,12 @@ def gen_html(run_dir, findings=None, inventory=None, migration=None): swap_pct = 100 if swap_total > 0 and swap_free == 0 else round((swap_total - swap_free) / swap_total * 100) if swap_total > 0 else 0 avail_pct = round(avail / total * 100) - mem_html = '

Memoria

' - mem_html += kv_row("RAM total", f'{total // 1024 // 1024:.0f} GB') - mem_html += kv_row("RAM disponible", f'{avail // 1024 // 1024:.0f} GB ({avail_pct}%)') + mem_html = '

Memory

' + mem_html += kv_row("Total RAM", f'{total // 1024 // 1024:.0f} GB') + mem_html += kv_row("Available RAM", f'{avail // 1024 // 1024:.0f} GB ({avail_pct}%)') sw_label = "CRITICAL" if swap_pct >= 90 else "WARNING" if swap_pct >= 50 else "OK" sw_cls = "crit" if swap_pct >= 90 else "warn" if swap_pct >= 50 else "ok" - mem_html += kv_row("Swap usado", f'{swap_pct}% {sw_label}') + mem_html += kv_row("Used swap", f'{swap_pct}% {sw_label}') mem_html += kv_row("Committed_AS", f'{committed // 1024 // 1024:.0f} GB') mem_html += kv_row("CommitLimit", f'{commit_limit // 1024 // 1024:.0f} GB') if committed > commit_limit: @@ -499,45 +499,45 @@ def gen_html(run_dir, findings=None, inventory=None, migration=None): cpu_lines = cpu_html.split("\n")[:16] cpu_text = "\n".join(cpu_lines) - sections.append(("resources", "Recursos")) + sections.append(("resources", "Resources")) # Docker section (conditional) docker_html = "" if comp["docker"]: - sections.append(("containers", "Contenedores")) + sections.append(("containers", "Containers")) docker_info_out = extract_stdout(evidence, "docker-info") docker_html = '

Docker Info

' docker_html += kv_row("Info", docker_info_out) - docker_html += f'

{len(containers)} contenedores corriendo

' + docker_html += f'

{len(containers)} running containers

' docker_html += '
' if containers: - docker_html += '
' + docker_html += '
NombreImagenEstado
' for c in containers[:50]: docker_html += f'' if len(containers) > 50: - docker_html += f'' + docker_html += f'' docker_html += '
NameImageStatus
{cesc(c["name"])}{cesc(c["image"])}{cesc(c["status"])}
... y {len(containers)-50} mas
... and {len(containers)-50} more
' else: - docker_html = '

No se detecto Docker en este servidor.

' + docker_html = '

Docker was not detected on this server.

' # Network section - sections.append(("network", "Red")) + sections.append(("network", "Network")) network_html = "" if listening: - network_html = '

Puertos expuestos

' + network_html = '

Exposed Ports

' host_ports = [p for p in listening if "0.0.0.0:" in p or "*:" in p or "[::]:" in p] local_ports = [p for p in listening if "127.0.0." in p] non_docker = [p for p in host_ports if "docker-proxy" not in p] - network_html += f'

{len(non_docker)} servicios host + {len(host_ports) - len(non_docker)} puertos Docker expuestos

' + network_html += f'

{len(non_docker)} host services + {len(host_ports) - len(non_docker)} exposed Docker ports

' for p in non_docker[:25]: network_html += f'
{cesc(p)}
' - network_html += f'

+ {len(host_ports) - len(non_docker)} puertos Docker (ver seccion Contenedores)

' + network_html += f'

+ {len(host_ports) - len(non_docker)} Docker ports (see Containers)

' network_html += '
' # Firewall fw_out = extract_stdout(evidence, "net-firewall") ufw_match = re.search(r'(Status:\s*\w+)', fw_out) - ufw_status = ufw_match.group(1) if ufw_match else "Status: desconocido" + ufw_status = ufw_match.group(1) if ufw_match else "Status: unknown" network_html += f'

Firewall

' network_html += kv_row("UFW", f'{ufw_status}') network_html += kv_row("iptables default", "INPUT ACCEPT") @@ -546,76 +546,76 @@ def gen_html(run_dir, findings=None, inventory=None, migration=None): # --- NEW: Web Server section --- web_html = "" if comp["web"]: - sections.append(("web-server", "Servidor Web")) - web_html = '

Servidor Web / Reverse Proxy

' + sections.append(("web-server", "Web Server")) + web_html = '

Web Server / Reverse Proxy

' if web_vhosts: web_html += f'

{len(web_vhosts)} vhosts/proxy mappings

' for v in web_vhosts[:20]: web_html += f'
{cesc(v)}
' else: - web_html += '

Sin vhosts / proxy mappings detectados

' + web_html += '

No vhosts / proxy mappings detected

' web_html += '
' # --- NEW: TLS section --- tls_html = "" if comp["tls"]: - sections.append(("tls", "TLS / Certificados")) - tls_html = '

Certificados TLS

' + sections.append(("tls", "TLS / Certificates")) + tls_html = '

TLS Certificates

' if tls_certs: - tls_html += f'

{len(tls_certs)} certificados

' + tls_html += f'

{len(tls_certs)} certificates

' for c in tls_certs[:15]: tls_html += f'
{cesc(c)}
' else: - tls_html += '

Sin certificados detectados

' + tls_html += '

No certificates detected

' tls_html += '
' # --- NEW: HTTP Health section --- http_html = "" if comp["web"]: - sections.append(("http-health", "Salud HTTP")) - http_html = '

Salud HTTP / Endpoints

' + sections.append(("http-health", "HTTP Health")) + http_html = '

HTTP Health / Endpoints

' if http_checks: http_html += f'

{len(http_checks)} endpoints

' for h in http_checks[:20]: http_html += f'
{cesc(h)}
' else: - http_html += '

Sin checks HTTP

' + http_html += '

No HTTP checks recorded

' http_html += '
' # --- NEW: DNS section --- dns_html = "" if comp["dns"]: sections.append(("dns", "DNS")) - dns_html = '

DNS / Resolución

' + dns_html = '

DNS / Resolution

' if dns_info: for d in dns_info[:20]: dns_html += f'
{cesc(d)}
' else: - dns_html += '

Sin info DNS detallada

' + dns_html += '

No detailed DNS information

' dns_html += '
' # --- NEW: Firewall deep-dive section --- fw_deep_html = "" if comp["firewall"]: - sections.append(("firewall-deep", "Firewall (detalle)")) - fw_deep_html = '

Firewall (detalle)

' + sections.append(("firewall-deep", "Firewall Details")) + fw_deep_html = '

Firewall Details

' if firewall_info: for f in firewall_info[:25]: fw_deep_html += f'
{cesc(f)}
' else: - fw_deep_html += '

Sin reglas de firewall detectadas

' + fw_deep_html += '

No firewall rules detected

' fw_deep_html += '
' # --- NEW: DB Tuning section --- db_tuning_html = "" if comp["db_tuning"]: sections.append(("db-tuning", "DB Tuning")) - db_tuning_html = '

Ajuste de Base de Datos

' + db_tuning_html = '

Database Tuning

' if db_tuning_info: for d in db_tuning_info[:20]: db_tuning_html += f'
{cesc(d)}
' else: - db_tuning_html += '

Sin métricas de tuning

' + db_tuning_html += '

No tuning metrics recorded

' db_tuning_html += '
' # --- NEW: SSH Hardening section --- @@ -627,11 +627,11 @@ def gen_html(run_dir, findings=None, inventory=None, migration=None): for s in ssh_hardening_info[:25]: ssh_hardening_html += f'
{cesc(s)}
' else: - ssh_hardening_html += '

Sin info de hardening SSH

' + ssh_hardening_html += '

No SSH hardening information

' ssh_hardening_html += '
' # Security section - sections.append(("security", "Seguridad")) + sections.append(("security", "Security")) sec_html = '
' ssh_out = extract_stdout(evidence, "sec-ssh") @@ -640,7 +640,7 @@ def gen_html(run_dir, findings=None, inventory=None, migration=None): line = line.strip() if line and "=" not in line and "keys" not in line: if line.startswith("Port "): - ssh_html += kv_row("Puerto", line.replace("Port ","")) + ssh_html += kv_row("Port", line.replace("Port ","")) elif "yes" in line.lower() and ("password" in line.lower() or "root" in line.lower() or "x11" in line.lower()): ssh_html += kv_row(line.split()[0], f'{line}') else: @@ -688,15 +688,15 @@ def gen_html(run_dir, findings=None, inventory=None, migration=None): forensic_html = "" if has_forensic: - sections.append(("forensic", "Investigacion Forense")) + sections.append(("forensic", "Forensic Investigation")) forensic_html = '
' # .env files found if cred_out: env_lines = [l.strip() for l in cred_out.split("\n") if l.strip() and not l.startswith("===")] env_count = len([l for l in env_lines if l.startswith("/")]) - forensic_html += f'

Archivos .env Encontrados

' - forensic_html += kv_row("Total encontrados", str(env_count)) + forensic_html += f'

Discovered .env Files

' + forensic_html += kv_row("Total found", str(env_count)) for l in env_lines[:15]: forensic_html += f'
{cesc(l[:120])}
' forensic_html += '
' @@ -705,7 +705,7 @@ def gen_html(run_dir, findings=None, inventory=None, migration=None): if cred_out2: perm_lines = [l.strip() for l in cred_out2.split("\n") if l.strip() and not l.startswith("===")] world_readable = [l for l in perm_lines if "-rw-r--r--" in l or "-rw-rw-rw" in l or "-rwxrwxrwx" in l] - forensic_html += f'

Permisos .env

' + forensic_html += f'

.env Permissions

' forensic_html += kv_row("World-readable", f'{len(world_readable)}' if world_readable else '0') for l in perm_lines[:15]: forensic_html += f'
{cesc(l[:130])}
' @@ -714,7 +714,7 @@ def gen_html(run_dir, findings=None, inventory=None, migration=None): # Web exposed .env if web_env_out: web_lines = [l.strip() for l in web_env_out.split("\n") if l.strip() and not l.startswith("===")] - forensic_html += f'

.env en Directorios Web

' + forensic_html += f'

.env in Web Directories

' for l in web_lines[:10]: forensic_html += f'
{cesc(l[:120])}
' forensic_html += '
' @@ -723,8 +723,8 @@ def gen_html(run_dir, findings=None, inventory=None, migration=None): if git_creds_out: git_lines = [l.strip() for l in git_creds_out.split("\n") if l.strip() and not l.startswith("===")] has_creds = any("FOUND" in l or ".git-credentials" in l or ".netrc" in l for l in git_lines) - forensic_html += f'

Credenciales Git

' - forensic_html += kv_row("Credenciales encontradas", f'SI' if has_creds else 'NO') + forensic_html += f'

Git Credentials

' + forensic_html += kv_row("Credentials found", f'YES' if has_creds else 'NO') for l in git_lines[:15]: forensic_html += f'
{cesc(l[:120])}
' forensic_html += '
' @@ -732,7 +732,7 @@ def gen_html(run_dir, findings=None, inventory=None, migration=None): # GitHub tokens if git_tokens_out: tok_lines = [l.strip() for l in git_tokens_out.split("\n") if l.strip() and not l.startswith("===")] - forensic_html += f'

Tokens GitHub

' + forensic_html += f'

GitHub Tokens

' for l in tok_lines[:10]: forensic_html += f'
{cesc(l[:120])}
' forensic_html += '
' @@ -740,7 +740,7 @@ def gen_html(run_dir, findings=None, inventory=None, migration=None): # Filesystem timeline if fs_timeline_out: tl_lines = [l.strip() for l in fs_timeline_out.split("\n") if l.strip() and not l.startswith("===")] - forensic_html += f'

Timeline de Archivos

' + forensic_html += f'

File Timeline

' for l in tl_lines[:15]: forensic_html += f'
{cesc(l[:130])}
' forensic_html += '
' @@ -748,7 +748,7 @@ def gen_html(run_dir, findings=None, inventory=None, migration=None): # Bash history if bash_hist_out: bh_lines = [l.strip() for l in bash_hist_out.split("\n") if l.strip() and not l.startswith("===")] - forensic_html += f'

Bash History Analisis

' + forensic_html += f'

Bash History Analysis

' for l in bh_lines[:15]: forensic_html += f'
{cesc(l[:130])}
' forensic_html += '
' @@ -758,7 +758,7 @@ def gen_html(run_dir, findings=None, inventory=None, migration=None): wp_lines = [l.strip() for l in web_probe_out.split("\n") if l.strip() and not l.startswith("===")] critical_probes = [l for l in wp_lines if "[CRITICAL]" in l] forensic_html += f'

Web Secret Probes

' - forensic_html += kv_row("Exposiciones criticas", f'{len(critical_probes)}' if critical_probes else '0') + forensic_html += kv_row("Critical exposures", f'{len(critical_probes)}' if critical_probes else '0') for l in wp_lines[:15]: forensic_html += f'
{cesc(l[:120])}
' forensic_html += '
' @@ -766,7 +766,7 @@ def gen_html(run_dir, findings=None, inventory=None, migration=None): # Network exfiltration if net_exfil_out: ne_lines = [l.strip() for l in net_exfil_out.split("\n") if l.strip() and not l.startswith("===")] - forensic_html += f'

Red / Exfiltracion

' + forensic_html += f'

Network / Exfiltration

' for l in ne_lines[:15]: forensic_html += f'
{cesc(l[:130])}
' forensic_html += '
' @@ -783,39 +783,39 @@ def gen_html(run_dir, findings=None, inventory=None, migration=None): # Logs section sections.append(("logs", "Logs")) - logs_html = '

Errores recientes del sistema

' - errores_ssh = [l for l in journal if "ssh" in l.lower() or "authentication failure" in l.lower()] - logs_html += f'

Eventos con referencias a SSH/autenticacion: {len(errores_ssh)}. Requieren correlacion; no confirman fuerza bruta.

' + logs_html = '

Recent System Errors

' + ssh_events = [l for l in journal if "ssh" in l.lower() or "authentication failure" in l.lower()] + logs_html += f'

Events referencing SSH/authentication: {len(ssh_events)}. Correlation is required; these do not confirm brute force.

' for l in journal[:20]: css_cls = "warn" if "failure" in l.lower() or "error" in l.lower() else "" logs_html += f'
{cesc(l[:130])}
' logs_html += '
' # Services section - sections.append(("services", "Servicios")) - svc_html = '

Servicios systemd activos

' + sections.append(("services", "Services")) + svc_html = '

Active Systemd Services

' for s in services: svc_html += f'{cesc(s)} ' svc_html += '
' # Build HTML body - html = f''' + html = f''' Infrastructure Audit — {cesc(host)}{CSS} {build_nav(sections)}

Infrastructure Audit Report

-

Generado: {now} · Host: {cesc(host)} · Run: {cesc(run_id)}

+

Generated: {now} · Host: {cesc(host)} · Run: {cesc(run_id)}

-
{f_by_sev['CRITICAL']}
Criticos
-
{f_by_sev['HIGH']}
Altos
-
{f_by_sev['MEDIUM']}
Medios
-
{f_by_sev['LOW']}
Bajos
-
{len(findings_list)}
Total Hallazgos
+
{f_by_sev['CRITICAL']}
Critical
+
{f_by_sev['HIGH']}
High
+
{f_by_sev['MEDIUM']}
Medium
+
{f_by_sev['LOW']}
Low
+
{len(findings_list)}
Total Findings
-

Resumen Ejecutivo

+

Executive Summary

CRITICAL: {f_by_sev['CRITICAL']} HIGH: {f_by_sev['HIGH']} @@ -824,27 +824,27 @@ def gen_html(run_dir, findings=None, inventory=None, migration=None): INFO: {f_by_sev['INFO']}
-

Diagnostico

-
Resumen{cesc(executive_summary)}
-
Causa raiz{cesc(root_cause)}
-
Estado actual{cesc(current_status)}
+

Diagnosis

+
Summary{cesc(executive_summary)}
+
Root cause{cesc(root_cause)}
+
Current status{cesc(current_status)}
-

Skills ejecutados: {cesc(skills_exec)}

+

Executed skills: {cesc(skills_exec)}

-

Infraestructura

+

Infrastructure

{infra_html} -

Recursos

+

Resources

{mem_html}
-

Procesos (por CPU)

+

Processes (by CPU)

{cesc(cpu_text)}
-

Contenedores

+

Containers

{docker_html} -

Red

+

Network

{network_html}
@@ -857,30 +857,30 @@ def gen_html(run_dir, findings=None, inventory=None, migration=None): {db_tuning_html} {ssh_hardening_html} -

Seguridad

+

Security

{sec_html} -

Investigacion Forense

- {forensic_html if forensic_html else '

No hay datos forenses disponibles.

'} +

Forensic Investigation

+ {forensic_html if forensic_html else '

No forensic data available.

'}

Logs

{logs_html} -

Servicios

+

Services

{svc_html} -

Hallazgos

+

Findings

- - - - - + + + + +
''' for f in findings_list: s = sev(f.get("severity","INFO")) - title = cesc(f.get("title","Sin titulo")) + title = cesc(f.get("title","Untitled")) cat = cesc(f.get("category","")) conf = cesc(f.get("confidence","MEDIUM")) finding_id = cesc(f.get("id","?")) @@ -891,18 +891,18 @@ def gen_html(run_dir, findings=None, inventory=None, migration=None): html += f'''

{finding_id} — {title}

{s}{cat}conf: {conf}
-
Observacion{obs}
-
Impacto{impact}
-
Evidencia
{evidence_text}
-
Recomendacion{rec}
+
Observation{obs}
+
Impact{impact}
+
Evidence
{evidence_text}
+
Recommendation{rec}
\n''' ev_count = len(glob.glob(os.path.join(run_dir, "evidencia", "*.yml"))) - conditional = ", ".join(conditional_skills) if conditional_skills else "ninguno" + conditional = ", ".join(conditional_skills) if conditional_skills else "none" html += f''' -

Evidencia

-

{ev_count} archivos YAML de evidencia almacenados en reportes/{cesc(run_id)}/evidencia/

-

Skills condicionales (se ejecutan solo si se detecta su trigger): {conditional}

+

Evidence

+

{ev_count} YAML evidence files stored in reportes/{cesc(run_id)}/evidencia/

+

Conditional skills (run only when their trigger is detected): {conditional}

{JS}''' return html diff --git a/skills/_index.yaml b/skills/_index.yaml index 07e47be..1b78499 100644 --- a/skills/_index.yaml +++ b/skills/_index.yaml @@ -466,7 +466,7 @@ skills: # ============================================================ workflows: full: - description: "Analisis completo de infraestructura (read-only)" + description: "Comprehensive infrastructure analysis (read-only)" sequence: - "system_inventory" - "systemd_analysis" @@ -505,7 +505,7 @@ workflows: - "migration_assessment" quick: - description: "Triage rapido de salud (inventario + systemd + CPU/mem/disk/io + red + DNS/firewall + web/TLS + logs + seguridad)" + description: "Rapid health triage (inventory + systemd + CPU/memory/disk/I/O + network + DNS/firewall + web/TLS + logs + security)" sequence: - "system_inventory" - "systemd_analysis" @@ -528,7 +528,7 @@ workflows: - "capacity_analysis" discovery: - description: "Solo descubrimiento e inventario" + description: "Discovery and inventory only" sequence: - "system_inventory" - "systemd_analysis" @@ -536,7 +536,7 @@ workflows: - "network_analysis" container: - description: "Enfocado en hosts con contenedores (Docker/K8s)" + description: "Container host focus (Docker/K8s)" sequence: - "system_inventory" - "systemd_analysis" @@ -562,7 +562,7 @@ workflows: - "ssh_hardening_analysis" security: - description: "Auditoria de seguridad completa" + description: "Comprehensive security audit" sequence: - "system_inventory" - "systemd_analysis" @@ -577,7 +577,7 @@ workflows: - "log_analysis" forensic: - description: "Investigacion forense de robo de credenciales (.env / GitHub keys)" + description: "Credential theft forensic investigation (.env / GitHub keys)" sequence: - "system_inventory" - "systemd_analysis" diff --git a/skills/_schema.yaml b/skills/_schema.yaml index e0a694a..3b83e82 100644 --- a/skills/_schema.yaml +++ b/skills/_schema.yaml @@ -19,44 +19,44 @@ optional: - references parameter_types: - string: "texto libre (path, hostname)" - integer: "numero entero (PID, puerto, nucleos)" - float: "numero decimal (umbral % CPU, GB RAM)" + string: "free text (path, hostname)" + integer: "integer (PID, port, core count)" + float: "decimal number (CPU percentage threshold, RAM in GB)" datetime: "timestamp ISO 8601" - duration: "intervalo (1h, 30m, 7d)" + duration: "interval (1h, 30m, 7d)" boolean: "true/false" - enum: "lista cerrada de valores" - filepath: "ruta validada en filesystem remoto" - regex: "expresion regular" + enum: "closed set of values" + filepath: "validated remote filesystem path" + regex: "regular expression" block_risk_levels: - ro: "readonly — solo lectura, cero modificacion al servidor" - info: "readonly — consulta de metadata inofensiva" - probe: "readonly — mediciones repetidas en el tiempo (snapshots), sin carga artificial" + ro: "read-only — no server modifications" + info: "read-only — non-mutating metadata query" + probe: "read-only — repeated measurements (snapshots), without artificial load" execution_modes: - auto: "ejecucion automatica sin confirmacion (solo ro/info/probe)" - confirm: "requiere confirmacion explicita (acciones no read-only)" - manual: "no automatizable, requiere intervencion humana" + auto: "automatic execution without confirmation (ro/info/probe only)" + confirm: "requires explicit confirmation (non-read-only actions)" + manual: "not automated; requires human intervention" severity_levels: - CRITICAL: "puede causar caida, perdida de datos, indisponibilidad" - HIGH: "problema importante, resolverse pronto" - MEDIUM: "optimizacion recomendable o gap de buenas practicas" - LOW: "mejora menor o de conveniencia" - INFO: "observacion sin accion inmediata" + CRITICAL: "may cause an outage, data loss or unavailability" + HIGH: "significant issue requiring prompt resolution" + MEDIUM: "recommended optimization or best-practice gap" + LOW: "minor or convenience improvement" + INFO: "observation without immediate action" confidence_levels: - HIGH: "evidencia directa y reproducible" - MEDIUM: "evidencia indirecta o de un solo snapshot, requiere validacion" - LOW: "indicio debil, no concluyente" - INSUFFICIENT_DATA: "no hay datos suficientes para afirmar nada" + HIGH: "direct, reproducible evidence" + MEDIUM: "indirect or single-snapshot evidence; requires validation" + LOW: "weak, inconclusive indication" + INSUFFICIENT_DATA: "insufficient data to support a claim" capacity_status: - NORMAL: "consumo esperado y estable" - WATCH: "monitorear, sin accion inmediata" - WARNING: "acercandose a limite o con tendencia negativa" - CRITICAL: "en o mas alla del limite, accion inmediata" + NORMAL: "expected, stable usage" + WATCH: "monitor; no immediate action" + WARNING: "approaching a limit or trending negatively" + CRITICAL: "at or beyond a limit; immediate action required" output_schema: type: object @@ -67,7 +67,7 @@ output_schema: risk_level: { type: string, enum: [ro, info, probe] } evidence_files: type: array - items: { type: string, description: "rutas a artefactos de evidencia" } + items: { type: string, description: "paths to evidence artifacts" } findings: type: array items: diff --git a/skills/_template.md b/skills/_template.md index 3928b6d..a4a114f 100644 --- a/skills/_template.md +++ b/skills/_template.md @@ -1,6 +1,6 @@ --- id: "skill_id" -name: "Skill: Nombre descriptivo" +name: "Skill: Descriptive name" version: "1.0" category: "cpu" phase: "analyze" @@ -9,94 +9,94 @@ execution_mode: "auto" depends_on: [] provides: [] triggers: - - "Condicion 1 que activa esta skill" - - "Condicion 2" + - "Condition 1 that triggers this skill" + - "Condition 2" false_positives: - - "FP 1: descripcion y como descartarlo" + - "FP 1: description and how to rule it out" references: - - "URL / doc de kernel o tuning" + - "URL / kernel or tuning documentation" parameters: SAMPLE_INTERVAL: type: "duration" default: "30s" required: false - description: "Intervalo entre snapshots para analisis temporal" + description: "Interval between snapshots for temporal analysis" SAMPLE_COUNT: type: "integer" default: 4 required: false - description: "Cantidad de snapshots (T0, T+30, T+60, T+120...)" + description: "Number of snapshots (T0, T+30, T+60, T+120...)" output: format: "json" schema: "output_schema" --- -# Skill: Nombre descriptivo +# Skill: Descriptive name -## Objetivo -Descripcion concisa (1-2 frases) de que mide y para que esta skill. +## Objective +A concise description (1–2 sentences) of what the skill measures and why. -## Cuando usarla +## When to use - Trigger 1 - Trigger 2 -## Parametros +## Parameters -| Variable | Tipo | Requerido | Default | Descripcion | +| Variable | Type | Required | Default | Description | |----------|------|-----------|---------|-------------| -| `{{SAMPLE_INTERVAL}}` | duration | no | 30s | Intervalo de snapshot | -| `{{SAMPLE_COUNT}}` | integer | no | 4 | Nro de snapshots | +| `{{SAMPLE_INTERVAL}}` | duration | no | 30s | Snapshot interval | +| `{{SAMPLE_COUNT}}` | integer | no | 4 | Number of snapshots | -## Pre-flight (validacion de entorno, read-only) +## Pre-flight (environment validation, read-only) ```bash # [risk:info] [mode:auto] for c in ; do command -v "$c" >/dev/null 2>&1 && echo "OK $c" || echo "MISSING $c"; done ``` -Los bloques describen el payload remoto. El agente los ejecuta exclusivamente con +Blocks describe remote payloads. The agent executes them exclusively through `scripts/ssh_exec.sh [evidence-dir]`; -no ejecutar los ejemplos con `ssh` directo ni redirigir salida remota sin redaccion. -Las series temporales son la excepcion de orquestacion local: usan -`helpers.snapshot_loop`, que invoca el wrapper una vez por muestra para no exceder timeouts. +never execute literal `ssh` examples directly or redirect unredacted remote output. +Time series are the local orchestration exception: use `helpers.snapshot_loop`, +which invokes the wrapper once per sample to stay within command timeouts. -## Comandos +## Commands ### 1. Snapshot T0 ```bash # [risk:ro] [mode:auto] - + ``` -### 2. Serie temporal (T+30s ... T+N) +### 2. Time series (T+30s ... T+N) ```bash # [risk:probe] [mode:auto] -snapshot_loop "{{SKILL_ID}}-trend" "" '' +snapshot_loop "{{SKILL_ID}}-trend" "" '' ``` -### 3. Bloque condicional (si componente presente) +### 3. Conditional block (if the component is present) ```bash # [risk:ro] [mode:auto] [requires:COMPONENT_DETECTED] - + ``` -## Analisis / Interpretacion -- Hallazgo A -> conclusion X -- Hallazgo B -> conclusion Y +## Analysis / interpretation +- Finding A -> conclusion X +- Finding B -> conclusion Y -## Falsos positivos -- FP 1: descripcion y como descartarlo -- FP 2: descripcion y como descartarlo +## False positives +- FP 1: description and how to rule it out +- FP 2: description and how to rule it out -## Umbrales (referenciales, ajustar por contexto) -| Metrica | NORMAL | WATCH | WARNING | CRITICAL | +## Thresholds (reference values; adjust to context) +| Metric | NORMAL | WATCH | WARNING | CRITICAL | |---------|--------|-------|---------|----------| | (%) | < 50 | 50-70 | 70-85 | > 85 | -## Evidencia producida -- `.yml` en `{{RUN_DIR}}/evidencia/`, generado por `scripts/ssh_exec.sh` +## Evidence produced +- `.yml` in `{{RUN_DIR}}/evidencia/`, generated by `scripts/ssh_exec.sh` -## Seguridad -Todos los bloques son read-only. Si aparece algo sospechoso (miner, proceso desconocido): FLAG + COLLECT + REPORT, no modificar. +## Security +All blocks are read-only. If something looks suspicious (miner, unknown process): FLAG + COLLECT + REPORT; do not modify it. -## Referencias +## References - doc / URL diff --git a/skills/analysis/configuration-analysis.md b/skills/analysis/configuration-analysis.md index f7cfdcf..5f06760 100644 --- a/skills/analysis/configuration-analysis.md +++ b/skills/analysis/configuration-analysis.md @@ -36,13 +36,13 @@ ssh {{SSH_TARGET}} 'echo "=== /etc/security/limits.conf ==="; grep -v "^#" /etc/ ### Nginx config (if present) ```bash # [risk:ro] [mode:auto] [requires:nginx] -ssh {{SSH_TARGET}} 'nginx -T 2>/dev/null | grep -E "worker_connections|worker_processes|keepalive|gzip|error_log|access_log|listen|server_name|proxy_pass" | head -60 || echo "nginx -T no disponible"' +ssh {{SSH_TARGET}} 'nginx -T 2>/dev/null | grep -E "worker_connections|worker_processes|keepalive|gzip|error_log|access_log|listen|server_name|proxy_pass" | head -60 || echo "nginx -T unavailable"' ``` ### Apache config (if present) ```bash # [risk:ro] [mode:auto] [requires:apache2] -ssh {{SSH_TARGET}} 'apachectl -S 2>/dev/null || apache2ctl -S 2>/dev/null || httpd -S 2>/dev/null || echo "apache no disponible"' +ssh {{SSH_TARGET}} 'apachectl -S 2>/dev/null || apache2ctl -S 2>/dev/null || httpd -S 2>/dev/null || echo "apache unavailable"' ``` ### Ulimits per running process (top memory consumers) diff --git a/skills/common/helpers.md b/skills/common/helpers.md index 271083f..1b058c4 100644 --- a/skills/common/helpers.md +++ b/skills/common/helpers.md @@ -1,17 +1,17 @@ # Common Helpers — Infrastructure Expert -Modulos reutilizables inyectables en skills/workflow mediante ``. -Ejecucion **read-only** sobre SSH. Nada instala, reinicia ni modifica nada en el servidor. +Reusable modules included in skills/workflows through ``. +Execution is **read-only** over SSH. Do not install, restart or modify anything on the server. --- ## MODULE:helpers.ssh_run -Unico punto de entrada para comandos remotos. Delega captura y redaccion al wrapper -canonico; ninguna skill implementa su propio SSH ni escribe salida remota directamente. +The single entry point for remote commands. Delegate capture and redaction to the +canonical wrapper; skills must not implement their own SSH or write raw remote output. ```bash -# Uso: ssh_run +# Usage: ssh_run ssh_run() { local evidence_id="$1" category="$2" level="$3" cmd="$4" scripts/ssh_exec.sh "$evidence_id" "$category" "$level" "$cmd" "{{RUN_DIR}}/evidencia" @@ -22,16 +22,16 @@ ssh_run() { ## MODULE:helpers.redact -La redaccion esta centralizada en `scripts/redact.py` y es invocada por -`scripts/ssh_exec.sh` antes de persistir evidencia. No duplicar expresiones regulares -en skills: las implementaciones parciales divergen y pueden filtrar secretos. +Redaction is centralized in `scripts/redact.py` and invoked by `scripts/ssh_exec.sh` +before evidence is persisted. Do not duplicate regular expressions in skills: +partial implementations diverge and can leak secrets. --- ## MODULE:helpers.detect -Deteccion dinamica de componentes presentes en el host (read-only). -El workflow usa esto para decidir que skills ejecutar y cuales SKIPear. +Dynamically detect components on the host (read-only). +The workflow uses this to decide which skills to execute and which to skip. ```bash detect_components() { @@ -55,7 +55,7 @@ detect_components() { ## MODULE:helpers.snapshot_loop -Loop de snapshots temporales SIN carga artificial (solo `sleep` + medicion). +Time-series snapshot loop without artificial load (`sleep` + measurement only). ```bash snapshot_loop() { @@ -67,24 +67,24 @@ snapshot_loop() { } ``` -El workflow coordina las series de CPU, memoria e I/O en una misma ventana temporal. -Puede ejecutar las tres mediciones en paralelo, con maximo 3 comandos, pero nunca -iniciar otra serie de la misma metrica ni repetir snapshots ya frescos. +The workflow coordinates CPU, memory and I/O series in the same time window. +It may run the three measurements in parallel, with at most three commands, but +must not start another series for the same metric or repeat fresh snapshots. --- ## MODULE:helpers.evidence_reuse -Antes de ejecutar, consultar los registros en `{{RUN_DIR}}/evidencia/`. Reusar dentro -del mismo run solo si coinciden target, payload normalizado, parametros y privilegio. -El primer skill topologicamente ordenado es owner del comando; consumidores posteriores -guardan `evidence_refs`, no vuelven a ejecutarlo. No reutilizar entre runs por defecto. +Before execution, check records in `{{RUN_DIR}}/evidencia/`. Reuse within the same +run only when target, normalized payload, parameters and privileges match. +The first topologically ordered skill owns the command; later consumers store +`evidence_refs` instead of rerunning it. Do not reuse across runs by default. --- ## MODULE:helpers.finding -Emite un finding estructurado al directorio de hallazgos. +Emit a structured finding to the findings directory. ```bash emit_finding() { @@ -109,18 +109,18 @@ EOF ## MODULE:helpers.safety_guard -Antes de ejecutar cualquier comando que no sea claramente read-only: STOP -> ANALYZE -> ASK. +Before executing any command that is not clearly read-only: STOP -> ANALYZE -> ASK. ``` -Comandos prohibidos en fase read-only: +Commands prohibited during the read-only phase: apt/dpkg/yum/dnf/pacman -i/-r/-u, pip/npm install, systemctl start/stop/restart/enable/disable, sysctl -w, iptables/firewalld --add/--remove, docker restart/stop/rm/prune, kubectl apply/delete/edit, rm, chmod/chown, mount/umount, mkfs, dd, reboot/halt, - kill/pkill, sed -i sobre configs, - cualquier redireccion > >> hacia /etc /var /root /opt - fuera del directorio de evidencia. + kill/pkill, sed -i on configuration files, + any > >> redirection to /etc /var /root /opt + outside the evidence directory. -Si aparece un comando de modificacion: NO ejecutar. Registrar como recomendacion. +If a mutating command is encountered: do not execute it. Record it as a recommendation. ``` diff --git a/skills/discovery/system-inventory.md b/skills/discovery/system-inventory.md index d7833d8..bed533d 100644 --- a/skills/discovery/system-inventory.md +++ b/skills/discovery/system-inventory.md @@ -86,7 +86,7 @@ ssh {{SSH_TARGET}} 'for d in /etc/nginx /etc/traefik /etc/apache2 /etc/httpd /et ### Kubernetes presence check (1 command only — full analysis in kubernetes_analysis) ```bash # [risk:ro] [mode:auto] [requires:kubectl] -ssh {{SSH_TARGET}} 'kubectl get nodes -o wide 2>/dev/null || echo "kubectl no disponible"' +ssh {{SSH_TARGET}} 'kubectl get nodes -o wide 2>/dev/null || echo "kubectl unavailable"' ``` ## Analysis diff --git a/skills/discovery/systemd-analysis.md b/skills/discovery/systemd-analysis.md index 16508bf..bbc83f0 100644 --- a/skills/discovery/systemd-analysis.md +++ b/skills/discovery/systemd-analysis.md @@ -16,13 +16,13 @@ output: { format: "json", schema: "output_schema" } --- # Systemd Analysis -Skill unificado que combina el inventario de services (running/enabled/failed/timers/sockets) -con el analisis de recursos por unidad (MemoryCurrent, CPUUsageNSec, NRestarts, TasksCurrent). -Un solo skill evita ejecutar `systemctl list-units` 6 veces por auditoria. +A unified skill combining service inventory (running/enabled/failed/timers/sockets) +with per-unit resource analysis (MemoryCurrent, CPUUsageNSec, NRestarts, TasksCurrent). +One skill avoids running `systemctl list-units` six times per audit. -## Comandos +## Commands -### Running services (una sola vez) +### Running services (once only) ```bash # [risk:ro] [mode:auto] ssh {{SSH_TARGET}} 'systemctl list-units --type=service --state=running --no-pager --no-legend 2>/dev/null' diff --git a/skills/platform/etcd-analysis.md b/skills/platform/etcd-analysis.md index e8c30c7..1483332 100644 --- a/skills/platform/etcd-analysis.md +++ b/skills/platform/etcd-analysis.md @@ -10,8 +10,8 @@ depends_on: ["system_inventory", "network_analysis"] provides: ["etcd_version", "etcd_members", "etcd_endpoints", "etcd_quorum", "etcd_alarms", "etcd_latency"] triggers: ["PRESENT:etcd", "PRESENT:etcdctl", "SERVICE:etcd"] false_positives: - - "Un endpoint remoto inaccesible desde redes ajenas puede estar protegido correctamente; probar desde un miembro del cluster." - - "Un cambio de lider aislado no implica degradacion; correlacionar con timeouts y una serie temporal." + - "A remote endpoint unreachable from external networks may be correctly protected; test from a cluster member." + - "A single leader change does not imply degradation; correlate with timeouts and a time series." parameters: OUTPUT_DIR: { type: "filepath", default: "{{RUN_DIR}}/etcd" } SSH_TARGET: { type: "string", required: true } @@ -22,67 +22,67 @@ output: { format: "json", schema: "output_schema" } # etcd Cluster Analysis -## Objetivo -Verificar membresia, quorum, lider, salud, latencia, alarmas y exposicion de un cluster -etcd independiente sin leer claves ni modificar estado. +## Objective +Check membership, quorum, leader, health, latency, alarms and exposure of a +standalone etcd cluster without reading keys or modifying state. -## Comandos +## Commands -### Version y configuracion efectiva +### Version and effective configuration ```bash # [risk:ro] [mode:auto] ssh {{SSH_TARGET}} 'command -v etcd; command -v etcdctl; etcd --version 2>/dev/null | head -5; etcdctl version 2>/dev/null; systemctl show etcd.service -p FragmentPath -p ExecStart -p EnvironmentFiles -p ActiveState -p NRestarts 2>/dev/null' ``` -### Miembros y estado de endpoints +### Members and endpoint status ```bash # [risk:ro] [mode:auto] [requires:etcdctl] ssh {{SSH_TARGET}} 'ETCDCTL_API=3 etcdctl --endpoints=http://127.0.0.1:2379 member list -w table 2>&1; echo ===STATUS===; ETCDCTL_API=3 etcdctl --endpoints=http://127.0.0.1:2379 endpoint status -w table 2>&1; echo ===ALARMS===; ETCDCTL_API=3 etcdctl --endpoints=http://127.0.0.1:2379 alarm list 2>&1' ``` -### Autenticacion y transporte (compatible con etcd 3.4) +### Authentication and transport (compatible with etcd 3.4) ```bash # [risk:ro] [mode:auto] ssh {{SSH_TARGET}} 'echo ===AUTH===; curl -fsS --connect-timeout 2 --max-time 5 http://127.0.0.1:2379/v2/auth/enable 2>&1; echo; echo ===TRANSPORT===; tr "\0" "\n" /dev/null | grep -E "^ETCD_(LISTEN|ADVERTISE|CLIENT_CERT_AUTH|PEER_CLIENT_CERT_AUTH|TRUSTED_CA_FILE|CERT_FILE|KEY_FILE)="' ``` -### Salud y latencia en serie +### Health and latency time series ```bash # [risk:probe] [mode:auto] ssh {{SSH_TARGET}} 'for i in 1 2 3 4; do date -u +%FT%TZ; curl -fsS --connect-timeout 2 --max-time 5 -w " code=%{http_code} connect=%{time_connect} total=%{time_total}\n" http://127.0.0.1:2379/health 2>&1; sleep 10; done' ``` -### Metricas operativas seleccionadas +### Selected operational metrics ```bash # [risk:ro] [mode:auto] ssh {{SSH_TARGET}} 'curl -fsS --connect-timeout 2 --max-time 5 http://127.0.0.1:2379/metrics 2>/dev/null | grep -E "^(etcd_server_has_leader|etcd_server_leader_changes_seen_total|etcd_server_proposals_(failed|pending)_total|etcd_server_slow_apply_total|etcd_disk_backend_commit_duration_seconds|etcd_disk_wal_fsync_duration_seconds|etcd_mvcc_db_total_size_in_bytes|process_resident_memory_bytes)"' ``` -### Errores y elecciones recientes +### Recent errors and elections ```bash # [risk:ro] [mode:auto] ssh {{SSH_TARGET}} 'journalctl -u etcd.service --since "24 hours ago" --no-pager 2>/dev/null | grep -iE "leader|election|timeout|unhealthy|unreachable|failed|slow|took too long|alarm|corrupt|space" | tail -120' ``` -## Analisis / Interpretacion -- `isLeader=true` exactamente una vez y todos los miembros `started`: quorum observable. -- `endpoint health` fallando o `/health` alternando: degradacion confirmada, no un evento aislado. -- Timeouts junto con `leader_changes` creciente: investigar perdida/latencia de red entre peers. -- `proposals_pending > 0`, `proposals_failed` creciente o fsync p99 alto: correlacionar con I/O. -- Cliente o peer en IP publica sin TLS requiere firewall restrictivo; validar reglas antes de reportar exposicion. -- En los histogramas acumulativos, restar cada bucket del `count` permite cuantificar - fsyncs por encima del umbral (por ejemplo, `count - le=1.024` = operaciones >1.024 s). -- La skill nunca ejecuta `put`, `del`, `compact`, `defrag`, `snapshot restore` ni cambios de membresia. +## Analysis / interpretation +- Exactly one `isLeader=true` and all members `started`: observable quorum. +- Failing `endpoint health` or fluctuating `/health`: confirmed degradation rather than a single event. +- Timeouts with increasing `leader_changes`: investigate peer network loss/latency. +- `proposals_pending > 0`, increasing `proposals_failed` or high fsync p99: correlate with I/O. +- A public client/peer IP without TLS needs restrictive firewall rules; validate them before reporting exposure. +- In cumulative histograms, subtract each bucket from `count` to quantify fsyncs + above a threshold (e.g. `count - le=1.024` = operations taking >1.024 s). +- Never execute `put`, `del`, `compact`, `defrag`, `snapshot restore` or membership changes. -## Umbrales -| Metrica | NORMAL | WARNING | CRITICAL | +## Thresholds +| Metric | NORMAL | WARNING | CRITICAL | |---------|--------|---------|----------| -| miembros sanos | todos | uno intermitente con quorum | sin quorum | -| `/health` | 4/4 sanos | 1/4 fallos | >=2/4 fallos | -| propuestas pendientes | 0 | >0 transitorio | >0 sostenido | +| Healthy members | all | one intermittent member, quorum retained | no quorum | +| `/health` | 4/4 healthy | 1/4 failures | >=2/4 failures | +| Pending proposals | 0 | transient >0 | sustained >0 | -## Evidencia producida +## Evidence produced - `version.yml`, `members.yml`, `auth-transport.yml`, `health-series.yml`, `metrics.yml`, `errors.yml` -## Seguridad -Solo metadata y salud. No se enumeran claves ni valores. Toda salida pasa por redaccion. +## Security +Metadata and health only. Do not enumerate keys or values. Redact all output. diff --git a/skills/platform/kubernetes-analysis.md b/skills/platform/kubernetes-analysis.md index 6b3b88f..75aad37 100644 --- a/skills/platform/kubernetes-analysis.md +++ b/skills/platform/kubernetes-analysis.md @@ -103,7 +103,7 @@ ssh {{SSH_TARGET}} 'echo "=== CLUSTERROLEBINDINGS ==="; kubectl get clusterroleb ### Top nodes / pods ```bash # [risk:ro] [mode:auto] -ssh {{SSH_TARGET}} 'echo "=== NODES TOP ==="; kubectl top nodes 2>/dev/null || echo "metrics server no disponible"; echo; echo "=== PODS TOP ==="; kubectl top pods -A --sort-by=cpu 2>/dev/null | head -30 || echo "metrics server no disponible"' +ssh {{SSH_TARGET}} 'echo "=== NODES TOP ==="; kubectl top nodes 2>/dev/null || echo "metrics server unavailable"; echo; echo "=== PODS TOP ==="; kubectl top pods -A --sort-by=cpu 2>/dev/null | head -30 || echo "metrics server unavailable"' ``` ### Resource requests/limits @@ -115,7 +115,7 @@ ssh {{SSH_TARGET}} 'kubectl get pods -A -o jsonpath='"'"'{range .items[*]}{.meta ### Health ```bash # [risk:ro] [mode:auto] -ssh {{SSH_TARGET}} 'kubectl get --raw /healthz 2>/dev/null || echo "healthz no disponible"' +ssh {{SSH_TARGET}} 'kubectl get --raw /healthz 2>/dev/null || echo "healthz unavailable"' ``` ### Node lease vs runtime health diff --git a/skills/platform/patroni-analysis.md b/skills/platform/patroni-analysis.md index 5fa1c54..cced5fe 100644 --- a/skills/platform/patroni-analysis.md +++ b/skills/platform/patroni-analysis.md @@ -17,16 +17,16 @@ output: { format: "json", schema: "output_schema" } # Patroni PostgreSQL HA Analysis -Capacidad conservada tras superar el gate de creacion: cubre estado HA, DCS y lag de -replicacion que no ofrecen las skills genericas de PostgreSQL, usa interfaces estables -de Patroni y es reutilizable entre despliegues y auditorias. +Retained after passing the creation gate: covers HA state, DCS health and +replication lag beyond the generic PostgreSQL skills, uses stable Patroni +interfaces and is reusable across deployments and audits. -## Objetivo -Entender el estado real del cluster PostgreSQL gestionado por Patroni: rol del nodo, -replicacion, exposicion de la REST API, salud del DCS (etcd) y errores recientes. +## Objective +Understand the actual state of a Patroni-managed PostgreSQL cluster: node role, +replication, REST API exposure, DCS (etcd) health and recent errors. -## Cuando usarla -- `command -v patronictl` presente, o unit `patroni.service` activa. +## When to use +- `command -v patronictl` succeeds, or `patroni.service` is active. ## Pre-flight (read-only) ```bash @@ -34,15 +34,15 @@ replicacion, exposicion de la REST API, salud del DCS (etcd) y errores recientes ssh {{SSH_TARGET}} 'command -v patroni patronictl; systemctl is-active patroni' ``` -## Comandos +## Commands -### Estado del cluster (miembros, rol, lag) +### Cluster state (members, role, lag) ```bash # [risk:ro] [mode:auto] ssh {{SSH_TARGET}} 'patronictl -c /etc/patroni/config.yml list 2>&1 | head -20' ``` -### Configuracion (sin secretos: excluye password/token/key) +### Configuration (exclude password/token/key secrets) ```bash # [risk:ro] [mode:auto] ssh {{SSH_TARGET}} 'grep -vE "^\s*#|password|passwd|secret|token|_key" /etc/patroni/config.yml | head -80' @@ -54,44 +54,44 @@ ssh {{SSH_TARGET}} 'grep -vE "^\s*#|password|passwd|secret|token|_key" /etc/patr ssh {{SSH_TARGET}} 'ss -H -tlnp | grep 8008; grep -A3 -i "restapi" /etc/patroni/config.yml' ``` -### DCS health + errores +### DCS health and errors ```bash # [risk:ro] [mode:auto] ssh {{SSH_TARGET}} 'journalctl -u patroni --since "48 hours ago" --no-pager | grep -iE "error|fail|timeout|etcd" | tail -30' ``` -### Rol/estado desde psql +### Role/state through psql ```bash # [risk:ro] [mode:auto] [requires:psql] ssh {{SSH_TARGET}} 'runuser -u postgres -- psql -X -tAc "SELECT pg_is_in_recovery();"' ssh {{SSH_TARGET}} 'runuser -u postgres -- psql -X -P pager=off -c "SELECT client_addr,state,sync_state,replay_lag FROM pg_stat_replication;"' ``` -## Analisis / Interpretacion -- Todos los nodos `Replica` y ninguno `Leader` -> cluster sin lider (quorum perdido). -- `Lag in MB` creciente -> replica no alcanza al leader (I/O o red). -- REST API en `0.0.0.0:8008` sin `restapi.authentication` -> control del cluster sin auth. -- Endpoints etcd con timeouts -> degradacion del DCS; con <2 vivos se pierde quorum y - el cluster pasa a solo lectura / cae. -- Protocolo etcd `http` sin TLS -> DCS en texto claro (posible MITM / control). - -## Falsos positivos -- Nodos `Replica` es lo normal en un standby; no es un fallo. -- `postgresql@-main.service` en `failed` es EXPECTED cuando Patroni gestiona - Postgres directamente (Patroni hace su propio pg_ctl; la unit de distro no se usa). -- Timeout a un endpoint etcd aislado puede ser transitorio; correlacionar con >1 muestra. - -## Umbrales -| Metrica | NORMAL | WATCH | WARNING | CRITICAL | +## Analysis / interpretation +- All nodes are `Replica` and none is `Leader` -> leaderless cluster (quorum lost). +- Increasing `Lag in MB` -> replica cannot keep up with the leader (I/O or network). +- REST API on `0.0.0.0:8008` without `restapi.authentication` -> unauthenticated cluster control. +- etcd endpoint timeouts -> DCS degradation; fewer than two live members in a + three-member cluster loses quorum, causing read-only operation / an outage. +- etcd `http` without TLS -> plaintext DCS traffic (potential MITM / control). + +## False positives +- `Replica` is the normal role for a standby, not a failure. +- `postgresql@-main.service` in `failed` state can be expected when Patroni + manages Postgres directly (Patroni runs pg_ctl; the distribution unit is unused). +- A single etcd endpoint timeout may be transient; correlate more than one sample. + +## Thresholds +| Metric | NORMAL | WATCH | WARNING | CRITICAL | |---------|--------|-------|---------|----------| -| Nodos con Leader | 1 | 1 | 0 | 0 | -| Lag replica | 0 | < 16MB | < 128MB | > 128MB | -| etcd endpoints vivos | 3/3 | 2/3 | 2/3 | 1/3 | +| Leader nodes | 1 | 1 | 0 | 0 | +| Replica lag | 0 | < 16MB | < 128MB | > 128MB | +| Live etcd endpoints | 3/3 | 2/3 | 2/3 | 1/3 | | REST API auth | yes | yes | no | no+0.0.0.0 | -## Evidencia producida -- `patroni-cluster.txt`, `patroni-restapi.txt`, `patroni-errors.txt` en `{{OUTPUT_DIR}}` +## Evidence produced +- `patroni-cluster.txt`, `patroni-restapi.txt`, `patroni-errors.txt` in `{{OUTPUT_DIR}}` -## Seguridad -Read-only. Nunca `patronictl failover/restart/remove`, ni editar `config.yml` (Level 3). -Redactar secretos de `config.yml` antes de almacenar. +## Security +Read-only. Never run `patronictl failover/restart/remove` or edit `config.yml` (Level 3). +Redact `config.yml` secrets before storage. diff --git a/skills/platform/teleport-analysis.md b/skills/platform/teleport-analysis.md index 39993ec..0db27cd 100644 --- a/skills/platform/teleport-analysis.md +++ b/skills/platform/teleport-analysis.md @@ -10,8 +10,8 @@ depends_on: ["system_inventory", "systemd_analysis", "network_analysis"] provides: ["teleport_version", "teleport_service_state", "teleport_config_validity", "teleport_roles", "teleport_connectivity", "teleport_errors", "teleport_kube_agent_state"] triggers: ["PRESENT:teleport", "SERVICE:teleport", "SYMPTOM:teleport_agent_failure"] false_positives: - - "Un agente puede figurar offline durante una rotacion o reinicio breve; correlacionar estado, logs y conectividad." - - "Un puerto Teleport no expuesto publicamente puede ser correcto para un agente que solo inicia conexiones salientes." + - "An agent may appear offline during rotation or a brief restart; correlate state, logs and connectivity." + - "A Teleport port without public exposure may be correct for an agent that only initiates outbound connections." parameters: OUTPUT_DIR: { type: "filepath", default: "{{RUN_DIR}}/teleport" } SSH_TARGET: { type: "string", required: true } @@ -20,44 +20,44 @@ output: { format: "json", schema: "output_schema" } # Teleport Agent Analysis -## Objetivo -Diagnosticar un agente Teleport sin modificar su estado ni exponer tokens, pines de CA -o material de identidad. Correlaciona proceso, unidad systemd, configuracion estructural, -logs, puertos y conectividad saliente. +## Objective +Diagnose a Teleport agent without modifying state or exposing tokens, CA pins or +identity material. Correlate its process, systemd unit, structural configuration, +logs, ports and outbound connectivity. -## Comandos +## Commands -### Version, binario y estado de la unidad +### Version, binary and unit state ```bash # [risk:ro] [mode:auto] ssh {{SSH_TARGET}} 'command -v teleport; teleport version 2>&1; systemctl show teleport.service -p LoadState -p ActiveState -p SubState -p Result -p MainPID -p NRestarts -p ExecMainCode -p ExecMainStatus -p FragmentPath -p ExecStart --no-pager 2>&1; systemctl status teleport.service --no-pager -l 2>&1 | tail -60' ``` -### Configuracion estructural y vigencia +### Structural configuration and timestamps ```bash # [risk:ro] [mode:auto] ssh {{SSH_TARGET}} 'cfg=$(systemctl show teleport.service -p ExecStart --value 2>/dev/null | grep -oE "(-c|--config(=|[[:space:]]+))[^[:space:] ;]+" | sed -E "s/^(--config=|-c|--config[[:space:]]+)//" | head -1); cfg=${cfg:-/etc/teleport.yaml}; echo "config_path=$cfg"; if [ -r "$cfg" ]; then stat -c "mode=%A owner=%U:%G size=%s mtime=%y" "$cfg"; systemctl show teleport.service -p ActiveEnterTimestamp --no-pager 2>&1; grep -E "^[[:space:]]*(version|nodename|data_dir|auth_server|proxy_server|auth_service|ssh_service|proxy_service|app_service|db_service|kubernetes_service|windows_desktop_service|discovery_service|enabled|listen_addr|public_addr|web_listen_addr|tunnel_listen_addr|join_method|method):" "$cfg" | grep -viE "token:[[:space:]]|ca_pin"; else echo "CONFIG_NOT_READABLE"; fi' ``` -### Proceso y sockets +### Process and sockets ```bash # [risk:ro] [mode:auto] ssh {{SSH_TARGET}} 'pid=$(systemctl show teleport.service -p MainPID --value 2>/dev/null); echo "main_pid=${pid:-0}"; [ "${pid:-0}" -gt 0 ] && ps -p "$pid" -o pid,ppid,user,lstart,etime,%cpu,%mem,args --no-headers 2>&1; echo "=== TELEPORT SOCKETS ==="; ss -lntup 2>/dev/null | grep -E "teleport|:(3022|3023|3024|3025|3080)([[:space:]]|$)" || true; echo "=== TELEPORT CONNECTIONS ==="; ss -tnp 2>/dev/null | grep -E "teleport|:(3023|3024|3025|3080)([[:space:]]|$)" || true' ``` -### Errores recientes +### Recent errors ```bash # [risk:ro] [mode:auto] ssh {{SSH_TARGET}} 'echo "=== LAST 200 LINES ==="; journalctl -u teleport.service -n 200 --no-pager -o short-iso 2>&1; echo "=== CURRENT BOOT ERRORS ==="; journalctl -u teleport.service -b -p warning --no-pager -o short-iso 2>&1 | tail -120' ``` -### Resolucion y conectividad hacia el proxy configurado +### Resolution and connectivity to the configured proxy ```bash # [risk:probe] [mode:auto] ssh {{SSH_TARGET}} 'cfg=$(systemctl show teleport.service -p ExecStart --value 2>/dev/null | grep -oE "(-c|--config(=|[[:space:]]+))[^[:space:] ;]+" | sed -E "s/^(--config=|-c|--config[[:space:]]+)//" | head -1); cfg=${cfg:-/etc/teleport.yaml}; endpoint=$(grep -E "^[[:space:]]*(proxy_server|auth_server):" "$cfg" 2>/dev/null | head -1 | sed -E "s/^[[:space:]]*[^:]+:[[:space:]]*//; s/[\"'\''\[\],]//g" | awk "{print \$1}"); host=${endpoint%%:*}; port=${endpoint##*:}; [ "$host" = "$port" ] && port=3080; if [ -z "$host" ]; then echo "NO_PROXY_OR_AUTH_ENDPOINT"; exit 0; fi; echo "endpoint_host=$host endpoint_port=$port"; getent ahosts "$host" 2>&1 | head -6; timeout 5 bash -c "&1 && echo "tcp_connect=ok" || echo "tcp_connect=failed"' ``` -### Agentes Kubernetes +### Kubernetes agents ```bash # [risk:ro] [mode:auto] [requires:kubectl] ssh {{SSH_TARGET}} 'kubectl get statefulset,daemonset,pod -A -o wide 2>&1 | grep -iE "NAMESPACE|teleport"; kubectl get events -A --sort-by=.lastTimestamp 2>&1 | grep -i teleport | tail -80' @@ -68,17 +68,17 @@ ssh {{SSH_TARGET}} 'kubectl get statefulset,daemonset,pod -A -o wide 2>&1 | grep ssh {{SSH_TARGET}} 'kubectl describe pod -n 2>&1; kubectl logs -n --all-containers=true --since=24h --timestamps=true --tail=800 2>&1' ``` -## Analisis / Interpretacion -- `ActiveState=failed` con `ExecMainStatus` no cero confirma fallo local; el journal debe explicar el primer error causal. -- Una configuracion con `mtime` anterior al inicio de un proceso estable fue aceptada por esa version; Teleport 18 no ofrece `teleport config test`. -- Errores `x509`, `bad certificate`, `join`, `token` o `CA pin` indican identidad/registro; no mostrar valores sensibles. -- Errores `no route`, `connection refused`, `timeout` o DNS junto con `tcp_connect=failed` confirman fallo de conectividad. -- `certificate has expired` requiere renovar la identidad del agente siguiendo el metodo de join configurado. -- Un proceso activo y TCP sano no prueban registro; validar en logs la conexion al cluster y ausencia de reintentos. -- Un pod `Running` pero no `Ready`, con timeouts repetidos al `proxy_server`, requiere comparar DNS, ruta y TCP desde el nodo donde fue programado y desde un nodo sano. +## Analysis / interpretation +- `ActiveState=failed` with nonzero `ExecMainStatus` confirms a local failure; use the journal to identify the first causal error. +- Configuration whose `mtime` predates a stable process startup was accepted by that version; Teleport 18 does not provide `teleport config test`. +- `x509`, `bad certificate`, `join`, `token` or `CA pin` errors indicate identity/registration issues; never display sensitive values. +- `no route`, `connection refused`, `timeout` or DNS errors combined with `tcp_connect=failed` confirm connectivity failure. +- `certificate has expired` requires agent identity renewal using the configured join method. +- An active process and healthy TCP do not prove registration; verify cluster connectivity and absence of retries in logs. +- For a `Running` but not `Ready` pod with repeated `proxy_server` timeouts, compare DNS, routes and TCP from its scheduled node and a healthy node. -## Evidencia producida +## Evidence produced - `teleport-service.yml`, `teleport-config.yml`, `teleport-runtime.yml`, `teleport-logs.yml`, `teleport-connectivity.yml`, `teleport-kube-agent.yml` -## Seguridad -Solo lectura. No imprime `token`, `ca_pin`, claves ni contenido de identidades. Toda salida pasa por redaccion. +## Security +Read-only. Do not print `token`, `ca_pin`, keys or identity contents. Redact all output. diff --git a/skills/platform/tls-certificate-analysis.md b/skills/platform/tls-certificate-analysis.md index 8492c5c..296836c 100644 --- a/skills/platform/tls-certificate-analysis.md +++ b/skills/platform/tls-certificate-analysis.md @@ -12,7 +12,7 @@ provides: ["cert_expiry", "cert_issuer", "cert_sans", "cert_chain", "tls_protoco parameters: OUTPUT_DIR: { type: "filepath", default: "{{RUN_DIR}}/tls" } SSH_TARGET: { type: "string", required: true } - WARN_DAYS: { type: "integer", default: 30, description: "Umbral de dias para aviso de expiracion" } + WARN_DAYS: { type: "integer", default: 30, description: "Certificate expiry warning threshold in days" } output: { format: "json", schema: "output_schema" } --- diff --git a/skills/resources/cpu-analysis.md b/skills/resources/cpu-analysis.md index 8ca7e56..88e5c60 100644 --- a/skills/resources/cpu-analysis.md +++ b/skills/resources/cpu-analysis.md @@ -10,7 +10,7 @@ depends_on: ["system_inventory"] provides: ["load_avg", "cpu_per_process", "cpu_trend"] triggers: [] false_positives: - - "CPU alta durante backups/cron windows: correlar con timers activos antes de concluir." + - "High CPU during backup/cron windows: correlate with active timers before drawing conclusions." parameters: OUTPUT_DIR: { type: "filepath", default: "{{RUN_DIR}}/cpu" } SSH_TARGET: { type: "string", required: true } @@ -46,7 +46,7 @@ snapshot_loop "cpu-trend" "cpu" 'cat /proc/loadavg; vmstat 1 2 2>/dev/null | tai ### Per-CPU (if mpstat available) ```bash # [risk:ro] [mode:auto] [requires:mpstat] -ssh {{SSH_TARGET}} 'mpstat -P ALL 1 1 2>/dev/null || echo "mpstat ausente"' +ssh {{SSH_TARGET}} 'mpstat -P ALL 1 1 2>/dev/null || echo "mpstat unavailable"' ``` ### pidstat per process diff --git a/skills/resources/disk-analysis.md b/skills/resources/disk-analysis.md index afd316e..8043a2b 100644 --- a/skills/resources/disk-analysis.md +++ b/skills/resources/disk-analysis.md @@ -50,7 +50,7 @@ ssh {{SSH_TARGET}} 'find / -xdev -type f -size +100M -exec ls -lh {} \; 2>/dev/n ### Disk monitoring (smartctl if available) ```bash # [risk:ro] [mode:auto] [requires:smartctl] -ssh {{SSH_TARGET}} 'for d in $(lsblk -nd -o NAME 2>/dev/null); do smartctl -H /dev/$d 2>/dev/null; done || echo "smartctl no disponible"' +ssh {{SSH_TARGET}} 'for d in $(lsblk -nd -o NAME 2>/dev/null); do smartctl -H /dev/$d 2>/dev/null; done || echo "smartctl unavailable"' ``` ## Analysis diff --git a/skills/resources/io-analysis.md b/skills/resources/io-analysis.md index 1c1e12e..a5a85ec 100644 --- a/skills/resources/io-analysis.md +++ b/skills/resources/io-analysis.md @@ -32,7 +32,7 @@ ssh {{SSH_TARGET}} 'vmstat 1 3 2>/dev/null' ### iostat (if available) ```bash # [risk:ro] [mode:auto] [requires:iostat] -ssh {{SSH_TARGET}} 'iostat -x 1 2 2>/dev/null || echo "iostat ausente"' +ssh {{SSH_TARGET}} 'iostat -x 1 2 2>/dev/null || echo "iostat unavailable"' ``` ### iowait temporal series diff --git a/skills/resources/memory-analysis.md b/skills/resources/memory-analysis.md index b4c7135..882ad02 100644 --- a/skills/resources/memory-analysis.md +++ b/skills/resources/memory-analysis.md @@ -10,7 +10,7 @@ depends_on: ["system_inventory"] provides: ["mem_usage", "swap", "mem_per_process", "psi"] triggers: [] false_positives: - - "used~=total sin presion real si cache+buffers alto y available holgada -> NORMAL." + - "used~=total without actual pressure when cache+buffers is high and available memory is sufficient -> NORMAL." parameters: OUTPUT_DIR: { type: "filepath", default: "{{RUN_DIR}}/memory" } SSH_TARGET: { type: "string", required: true } @@ -38,7 +38,7 @@ ssh {{SSH_TARGET}} 'echo "=== FREE ==="; free -h; echo; echo "=== MEMINFO ==="; ### Top processes by memory (RSS) ```bash # [risk:ro] [mode:auto] -ssh {{SSH_TARGET}} 'ps -eo pid,ppid,user,rss,vsz,pmem,comm,args --sort=-rss | head -25; echo; echo "=== smem (if exists) ==="; command -v smem >/dev/null && smem -t -k | tail -30 || echo "smem ausente"' +ssh {{SSH_TARGET}} 'ps -eo pid,ppid,user,rss,vsz,pmem,comm,args --sort=-rss | head -25; echo; echo "=== smem (if exists) ==="; command -v smem >/dev/null && smem -t -k | tail -30 || echo "smem unavailable"' ``` ### Swap/available trend series @@ -50,7 +50,7 @@ snapshot_loop "memory-trend" "memory" 'awk "/SwapTotal|SwapFree|MemAvailable/{pr ### /proc/pressure/memory (PSI) if exists ```bash # [risk:ro] [mode:auto] [requires:PSI] -ssh {{SSH_TARGET}} 'cat /proc/pressure/memory 2>/dev/null || echo "PSI mem ausente"' +ssh {{SSH_TARGET}} 'cat /proc/pressure/memory 2>/dev/null || echo "memory PSI unavailable"' ``` ## Analysis diff --git a/skills/resources/network-analysis.md b/skills/resources/network-analysis.md index f5a805c..2aeb076 100644 --- a/skills/resources/network-analysis.md +++ b/skills/resources/network-analysis.md @@ -59,7 +59,7 @@ ssh {{SSH_TARGET}} 'ss -H -tnp state established 2>/dev/null | head -60' ### Firewall ```bash # [risk:ro] [mode:auto] -ssh {{SSH_TARGET}} 'echo "=== UFW ==="; command -v ufw >/dev/null && ufw status verbose 2>/dev/null || echo "ufw no presente"; echo; echo "=== IPTABLES ==="; iptables -S 2>/dev/null | head -60; echo; echo "=== NFT ==="; nft list ruleset 2>/dev/null | head -80' +ssh {{SSH_TARGET}} 'echo "=== UFW ==="; command -v ufw >/dev/null && ufw status verbose 2>/dev/null || echo "ufw unavailable"; echo; echo "=== IPTABLES ==="; iptables -S 2>/dev/null | head -60; echo; echo "=== NFT ==="; nft list ruleset 2>/dev/null | head -80' ``` ### Connection count summary @@ -94,10 +94,10 @@ ssh {{SSH_TARGET}} 'for host in localhost $(hostname -I 2>/dev/null); do curl -s - Read `kubernetes/netpol.txt` from kubernetes_analysis for NetworkPolicy evidence. - Read `kubernetes/svc.txt` from kubernetes_analysis for service inventory. - No NetworkPolicy = full east-west pod reachability. -- Counters acumulados prueban historial, no tasa actual. Correlacionar con `sar -n EDEV` - o dos snapshots antes de atribuir un incidente a drops/retransmisiones. -- Retransmisiones/RTO altos en `ss -tin` sobre el mismo destino del fallo aportan la - segunda fuente necesaria para confirmar degradacion del camino TCP. +- Cumulative counters show history, not the current rate. Correlate with `sar -n EDEV` + or two snapshots before attributing an incident to drops/retransmissions. +- High retransmissions/RTO in `ss -tin` for the failing destination provide the + second source needed to confirm TCP path degradation. ## Evidence - `interfaces.txt`, `routes.txt`, `dns.txt`, `listening.txt`, `established.txt`, `firewall.txt`, `conn-count.txt`, `transport-errors.txt`, `k8s-hostnet.txt`, `edge-curl.txt` diff --git a/templates/executive-summary.md b/templates/executive-summary.md index 3145a8e..901bfd1 100644 --- a/templates/executive-summary.md +++ b/templates/executive-summary.md @@ -1,17 +1,17 @@ # Executive Summary — {{SERVER_NAME}} -**Generado:** {{DATE}} · **Host:** {{HOSTNAME}} · **Espec SSH:** {{SSH_TARGET}} · **Read-only** +**Generated:** {{DATE}} · **Host:** {{HOSTNAME}} · **SSH target:** {{SSH_TARGET}} · **Read-only** --- -## Sistema +## System | | | |---|---| | **OS** | {{OS}} | | **Kernel** | {{KERNEL}} | | **Uptime** | {{UPTIME}} | -| **CPU** | {{CPU_MODEL}} ({{NPROC}} nucleos · {{CPU_ARCH}}) | +| **CPU** | {{CPU_MODEL}} ({{NPROC}} cores · {{CPU_ARCH}}) | | **RAM** | {{RAM_TOTAL}} (available {{RAM_AVAIL_PCT}}%) | | **Swap** | {{SWAP_TOTAL}} (used {{SWAP_USED_PCT}}%) | | **Storage** | {{DISK_SUMMARY}} | @@ -24,7 +24,7 @@ > {{OVERALL_BUCKET}} — {{OVERALL_TREND}} -| Axis | Bucket | Trend | Nota | +| Axis | Bucket | Trend | Note | |------|--------|-------|------| | CPU | {{CPU_BUCKET}} | {{CPU_TREND}} | {{CPU_NOTE}} | | Memory | {{MEM_BUCKET}} | {{MEM_TREND}} | {{MEM_NOTE}} | @@ -32,11 +32,11 @@ | I/O | {{IO_BUCKET}} | {{IO_TREND}} | {{IO_NOTE}} | | Network | {{NET_BUCKET}} | {{NET_TREND}} | {{NET_NOTE}} | -Leyenda: `NORMAL` · `WATCH` · `WARNING` · `CRITICAL` +Legend: `NORMAL` · `WATCH` · `WARNING` · `CRITICAL` --- -## Hallazgos por prioridad +## Findings by priority | P0 Critical | P1 High | P2 Medium | P3 Low | P4 Info | |-------------|---------|-----------|--------|---------| @@ -44,11 +44,11 @@ Leyenda: `NORMAL` · `WATCH` · `WARNING` · `CRITICAL` --- -## Recommended Actions (orden) +## Recommended actions (in order) -1. {{ACTION_1}} — prioridad {{P1}}, riesgo {{RISK_1}}, esfuerzo {{EFFORT_1}} +1. {{ACTION_1}} — priority {{P1}}, risk {{RISK_1}}, effort {{EFFORT_1}} 2. {{ACTION_2}} 3. {{ACTION_3}} -> El detalle completo esta en el reporte HTML generado. -> Ningun cambio fue aplicado al servidor. Este analisis fue **read-only**. +> Full details are available in the generated HTML report. +> No changes were applied to the server. This analysis was **read-only**. diff --git a/templates/findings-template.md b/templates/findings-template.md index 3e007d2..c658b86 100644 --- a/templates/findings-template.md +++ b/templates/findings-template.md @@ -1,6 +1,6 @@ # Findings Template -Cada finding sigue este formato. Confidence: `HIGH | MEDIUM | LOW | INSUFFICIENT_DATA`. +Each finding follows this format. Confidence: `HIGH | MEDIUM | LOW | INSUFFICIENT_DATA`. Severity: `P0 | P1 | P2 | P3 | P4`. --- @@ -20,34 +20,35 @@ P0 / P1 / P2 / P3 / P4 HIGH / MEDIUM / LOW / INSUFFICIENT_DATA ### Evidence (FACT) -- Comando: `...` -- Output (extracto): ``` +- Command: `...` +- Output (excerpt): +``` ``` ### Observation (FACT) -Que se observo, sin interpretacion. +What was observed, without interpretation. ### Analysis (INFERENCE) -Por que probablemente ocurre. Citar skills correlacionadas. +Why it likely occurs. Cite correlated skills. ### Root Cause (INFERENCE) -Causa probable; si no se puede afirmar -> `INSUFFICIENT_DATA`. +Likely cause; if it cannot be established -> `INSUFFICIENT_DATA`. ### Recommendation (RECOMMENDATION) -Que hacer. +What to do. ### Expected Benefit -Antes: X. Despues esperado: Y. +Before: X. Expected after: Y. ### Risk -Riesgo de aplicar la recomendacion. +Risk of applying the recommendation. -### Implementation (no ejecutado en este framework) -Comando/config sugerido. +### Implementation (not executed by this framework) +Suggested command/configuration. ### Rollback -Como deshacer el cambio. +How to undo the change. ### Validation -Como comprobar que funciono (antes/despues). +How to verify the result (before/after). diff --git a/templates/optimization-comparison.md b/templates/optimization-comparison.md index 96f3d14..39c4700 100644 --- a/templates/optimization-comparison.md +++ b/templates/optimization-comparison.md @@ -2,45 +2,45 @@ **Baseline:** {{BASELINE_DATE}} (`{{RUN_DIR_A}}`) **Post-optimization:** {{POST_DATE}} (`{{RUN_DIR_B}}`) -**Cambios aplicados:** {{CHANGES_SUMMARY}} +**Applied changes:** {{CHANGES_SUMMARY}} --- -## Resumen ejecutivo +## Executive summary -| Axis | Baseline | Post | Delta | Estado | +| Axis | Baseline | Post | Delta | Status | |------|----------|------|-------|--------| | CPU (load/nproc) | {{CPU_A}} | {{CPU_B}} | {{CPU_D}} | {{CPU_STATUS}} | | Memory available % | {{MEM_A}} | {{MEM_B}} | {{MEM_D}} | {{MEM_STATUS}} | | Swap used % | {{SWAP_A}} | {{SWAP_B}} | {{SWAP_D}} | {{SWAP_STATUS}} | -| Disk uso % | {{DISK_A}} | {{DISK_B}} | {{DISK_D}} | {{DISK_STATUS}} | +| Disk usage % | {{DISK_A}} | {{DISK_B}} | {{DISK_D}} | {{DISK_STATUS}} | | I/O %wait | {{IO_A}} | {{IO_B}} | {{IO_D}} | {{IO_STATUS}} | | Network retrans % | {{NET_A}} | {{NET_B}} | {{NET_D}} | {{NET_STATUS}} | -| Containers con limits | {{CTR_LIM_A}} | {{CTR_LIM_B}} | {{CTR_LIM_D}} | {{CTR_LIM_STATUS}} | +| Containers with limits | {{CTR_LIM_A}} | {{CTR_LIM_B}} | {{CTR_LIM_D}} | {{CTR_LIM_STATUS}} | -Leyenda estado: `IMPROVED` · `NO CHANGE` · `REGRESSED` · `NEW ISSUE` +Status legend: `IMPROVED` · `NO CHANGE` · `REGRESSED` · `NEW ISSUE` --- -## Detalle por recomendacion aplicada +## Applied recommendation details {{#CHANGES}} ### {{ID}} — {{TITLE}} -- **Esperado:** {{EXPECTED}} -- **Medido antes:** {{BEFORE}} -- **Medido despues:** {{AFTER}} -- **Resultado:** {{STATUS}} -- **Notas:** {{NOTES}} +- **Expected:** {{EXPECTED}} +- **Measured before:** {{BEFORE}} +- **Measured after:** {{AFTER}} +- **Result:** {{STATUS}} +- **Notes:** {{NOTES}} {{/CHANGES}} --- -## Nuevos hallazgos post-optimizacion +## New post-optimization findings {{#NEW_FINDINGS}} - **{{ID}}** — {{TITLE}} ({{PRIORITY}}) {{/NEW_FINDINGS}} -## Proximos pasos -- Regresiones -> investigar causa y rollback si necesario. -- Sin mejora en metrica esperada -> validar que el cambio se aplico correctamente y volver a medir. +## Next steps +- Regressions -> investigate the cause and roll back if necessary. +- No improvement in the expected metric -> verify that the change was applied correctly and measure again. diff --git a/templates/optimization-report.md b/templates/optimization-report.md index fe05457..646b73b 100644 --- a/templates/optimization-report.md +++ b/templates/optimization-report.md @@ -1,15 +1,15 @@ # Optimization Report — {{HOSTNAME}} -**Fecha:** {{DATE}} · **Server:** {{SERVER_NAME}} · **Read-only / advisory** +**Date:** {{DATE}} · **Server:** {{SERVER_NAME}} · **Read-only / advisory** -> Ningun cambio fue aplicado. Las configuraciones/comandos listados son **sugerencias**. -> Cada recomendacion incluye validacion y rollback. +> No changes were applied. Listed configurations/commands are **suggestions**. +> Each recommendation includes validation and rollback. --- -## Tabla resumen +## Summary table -| ID | Area | Problema | Evidencia | Impacto | Riesgo | Esfuerzo | Prioridad | +| ID | Area | Problem | Evidence | Impact | Risk | Effort | Priority | | -- | ---- | -------- | --------- | ------- | ------ | -------- | --------- | {{#OPTIMIZATION_ROWS}} | {{ID}} | {{AREA}} | {{PROBLEM}} | {{EVIDENCE_SHORT}} | {{IMPACT}} | {{RISK}} | {{EFFORT}} | {{PRIORITY}} | @@ -17,27 +17,27 @@ --- -## Detalle por recomendacion +## Recommendation details {{#OPTIMIZATION_ITEMS}} ### {{ID}} — {{TITLE}} -- **Categoria:** {{CATEGORY}} · **Prioridad:** {{PRIORITY}} · **Riesgo:** {{RISK}} · **Esfuerzo:** {{EFFORT}} · **Confianza:** {{CONFIDENCE}} +- **Category:** {{CATEGORY}} · **Priority:** {{PRIORITY}} · **Risk:** {{RISK}} · **Effort:** {{EFFORT}} · **Confidence:** {{CONFIDENCE}} -**Problema** +**Problem** {{PROBLEM}} -**Evidencia** +**Evidence** ``` {{EVIDENCE}} ``` -**Impacto esperado** +**Expected impact** {{IMPACT}} -**Recomendacion** +**Recommendation** {{RECOMMENDATION}} -**Configuracion / comando sugerido (no ejecutado)** +**Suggested configuration / command (not executed)** ``` {{CONFIG_SUGGESTED}} ``` @@ -45,16 +45,16 @@ **Rollback** {{ROLLBACK}} -**Validacion (before -> after)** +**Validation (before -> after)** - Before: {{BEFORE_METRIC}} -- Cambio: {{CHANGE}} -- After esperado: {{AFTER_METRIC}} -- Como medir: {{VALIDATION_CMD}} +- Change: {{CHANGE}} +- Expected after: {{AFTER_METRIC}} +- How to measure: {{VALIDATION_CMD}} --- {{/OPTIMIZATION_ITEMS}} -## Proximos pasos -1. Aplicar primero las P0 (CRITICAL) seguidas de P1. -2. Re-ejecutar el analisis (fase POST-OPTIMIZATION) y comparar. -3. Generar `optimization-comparison.md`. +## Next steps +1. Address P0 (CRITICAL) recommendations first, followed by P1. +2. Rerun analysis (POST-OPTIMIZATION phase) and compare. +3. Generate `optimization-comparison.md`. diff --git a/templates/server-report.md b/templates/server-report.md index b5279c5..539f0db 100644 --- a/templates/server-report.md +++ b/templates/server-report.md @@ -1,6 +1,6 @@ # Server Health Report — {{HOSTNAME}} -**Fecha:** {{DATE}} · **Espec SSH:** {{SSH_TARGET}} · **Read-only** +**Date:** {{DATE}} · **SSH target:** {{SSH_TARGET}} · **Read-only** --- @@ -20,14 +20,14 @@ - nproc: {{NPROC}} · load avg: {{LOADAVG}} · ratio load/nproc: {{LOAD_RATIO}} - %user / %system / %iowait (1m): {{CPU_US}} / {{CPU_SY}} / {{CPU_WA}} - trend: {{CPU_TREND}} -- top procesos: {{TOP_CPU_TABLE}} +- top processes: {{TOP_CPU_TABLE}} ## 5. Memory - total/used/available/cache+buffers: {{MEM_TABLE}} - swap: {{SWAP_DETAIL}} - swappiness: {{SWAPPINESS}} - PSI: {{PSI_DETAIL}} -- OOM historicos: {{OOM_DETAIL}} +- historical OOM events: {{OOM_DETAIL}} ## 6. Storage {{STORAGE_TABLE}} @@ -63,9 +63,9 @@ {{CAPACITY_SECTION}} ## 17. Findings -Resumen por prioridad: +Summary by priority: | P0 | P1 | P2 | P3 | P4 | |----|----|----|----|----| | {{P0}} | {{P1}} | {{P2}} | {{P3}} | {{P4}} | -Ver `findings.md` para el detalle con evidencia, analisis, recomendacion, validacion y rollback. +See `findings.md` for evidence, analysis, recommendations, validation and rollback details. diff --git a/tests/test_safety.py b/tests/test_safety.py index 12efb7e..25cf17e 100644 --- a/tests/test_safety.py +++ b/tests/test_safety.py @@ -126,14 +126,15 @@ def test_untrusted_metadata_is_escaped_and_execution_is_not_invented(self): html = report.gen_html(str(run), inventory=inventory) self.assertNotIn('', html) + self.assertIn('not recorded', html) + self.assertNotIn('Executed skills: system-inventory', html) (run / 'skills-used.yaml').write_text(yaml.safe_dump({'skills': [ {'id': '', 'status': 'executed'}, {'id': 'never-ran', 'status': 'pending'}, ]})) html = report.gen_html(str(run), inventory=inventory) - self.assertIn('Skills ejecutados: <completed>', html) + self.assertIn('Executed skills: <completed>', html) self.assertNotIn('never-ran', html) diff --git a/workflows/advanced-credential-theft-v2.md b/workflows/advanced-credential-theft-v2.md index 8788b60..0108f9a 100644 --- a/workflows/advanced-credential-theft-v2.md +++ b/workflows/advanced-credential-theft-v2.md @@ -1,17 +1,17 @@ # Workflow: Advanced Credential Theft Investigation v2.0 -Workflow forense avanzado para determinar CÓMO se robaron las .env o las claves -para push de GitHub. Combina skills existentes con un skill nuevo y mejorado -que realiza análisis completo de vectores de ataque. +Advanced forensic workflow to investigate how .env files or GitHub push keys were +stolen. Combines discovery and platform skills with the advanced credential-theft +investigation capability to analyze attack vectors. -## Objetivo -Reconstruir el vector de ataque completo: -1. Cómo entró el atacante -2. Qué credenciales accedió -3. Cómo exfiltró los datos -4. Si dejó mecanismos de persistencia +## Objective +Reconstruct the attack vector: +1. How the attacker gained access. +2. Which credentials were accessed. +3. How data was exfiltrated. +4. Whether persistence mechanisms were left behind. -## Diagrama de ejecución +## Execution diagram ``` PHASE 1: DISCOVERY (existing skills) @@ -111,41 +111,41 @@ PHASE 8: REPORT └── Recommended remediations ``` -## Reglas de ejecución por fase +## Per-phase execution rules -### Fase 1-2 (Discovery + Security Base) -- Ejecutar TODOS los skills sin condicionales -- Son la base del inventario y postura de seguridad +### Phases 1–2 (Discovery + Security Baseline) +- Run all unconditional skills. +- They establish inventory and security posture. -### Fase 3 (Advanced Credential Theft Investigation) -- Ejecutar EL skill `advanced_credential_theft_investigation` -- Este skill es autocontenido y ejecuta todas las fases internas -- NO requiere skills adicionales (pero puede complementarlos) +### Phase 3 (Advanced Credential Theft Investigation) +- Run `advanced_credential_theft_investigation`. +- This skill is self-contained and covers its internal phases. +- It does not require additional investigative skills, but can complement them. -### Fase 4 (Platform) -- Ejecutar SOLO si el componente fue detectado en Fase 1 -- Seguir triggers de `_index.yaml` +### Phase 4 (Platform) +- Run only if the component was detected in Phase 1. +- Follow `_index.yaml` triggers. -### Fase 5-6 (Resources + Analysis) -- Ejecutar todos — son cheap y provide contexto +### Phases 5–6 (Resources + Analysis) +- Run all listed skills: they provide low-cost context. -## Reglas duras +## Hard rules -1. **Read-only.** Nada que modifique el servidor. -2. **Evidence first.** Cada afirmación con evidencia almacenada. -3. **Fact vs Hypothesis.** Etiquetar cada claim. -4. **Secret redaction.** Valores nunca en evidencia/reporte. -5. **No assumptions.** Descubrir, nunca asumir. +1. **Read-only.** Do not modify the server. +2. **Evidence first.** Every claim needs stored evidence. +3. **Fact vs hypothesis.** Label every claim. +4. **Secret redaction.** Never include secret values in evidence/reports. +5. **No assumptions.** Discover; never assume. ## Output -Directorio de reportes: `reportes//` -- `reportes//evidencia/` — YAML records por comando -- `reportes//advanced-credential-theft/` — evidencia del skill principal -- `reportes//findings/` — hallazgos -- `reportes//findings.yaml` — findings estructurados -- `reportes//inventory.yaml` — inventario -- `reportes//informe-forense-.html` — reporte HTML forense +Report directory: `reportes//` +- `reportes//evidencia/` — per-command YAML records +- `reportes//advanced-credential-theft/` — primary skill evidence +- `reportes//findings/` — findings +- `reportes//findings.yaml` — structured findings +- `reportes//inventory.yaml` — inventory +- `reportes//informe-forense-.html` — forensic HTML report ## Safety levels @@ -155,8 +155,8 @@ Directorio de reportes: `reportes//` | 2 | TEST | Non-destructive tests (HTTP probes) | On by default | | 3 | CHANGE | Mutating actions | Off — requires explicit approval | -## Tecnologias sin skill +## Technology without a dedicated skill -No crear una skill por cada producto detectado. Reutilizar evidencia y capacidades -forenses genericas; cubrir huecos concretos con checks ad-hoc L1/L2 acotados. Solo -persistir una nueva skill cuando supere el gate completo de `WORKFLOW.md`. +Do not create a skill for every detected product. Reuse evidence and generic +forensic capabilities; cover concrete gaps with bounded L1/L2 ad-hoc checks. +Persist a new skill only after the complete gate in `WORKFLOW.md` passes. diff --git a/workflows/credential-theft-investigation.md b/workflows/credential-theft-investigation.md index 0c928c3..4f12e77 100644 --- a/workflows/credential-theft-investigation.md +++ b/workflows/credential-theft-investigation.md @@ -1,16 +1,16 @@ # Workflow: Credential Theft Investigation -Investigación forense de robo de credenciales (.env / GitHub push keys). -Ejecuta skills existentes + 7 skills forenses nuevos para reconstruir el vector de ataque. +Forensic investigation of credential theft (.env / GitHub push keys). +Uses discovery, security and forensic catalog skills to reconstruct the attack vector. -## Entrada mínima +## Minimum input -| Variable | Requerido | Default | Descripción | +| Variable | Required | Default | Description | |----------|-----------|---------|-------------| -| `SSH_TARGET` | si | — | `user@host` o alias SSH configurado | -| `MODE` | no | `forensic` | `forensic` (default para este workflow) | +| `SSH_TARGET` | yes | — | `user@host` or a configured SSH alias | +| `MODE` | no | `forensic` | `forensic` (default for this workflow) | -## Diagrama de ejecución +## Execution diagram ``` PHASE 1: DISCOVERY (existing skills) @@ -117,43 +117,43 @@ PHASE 10: REPORT └── Print executive summary ``` -## Reglas de ejecución por fase +## Per-phase execution rules -### Fase 1-2 (Discovery + Security Base) -- Ejecutar TODOS los skills sin condicionales -- Son la base del inventario y postura de seguridad +### Phases 1–2 (Discovery + Security Baseline) +- Run all unconditional skills. +- They establish inventory and security posture. -### Fase 3-5 (Forensic Skills — NUEVOS) -- Ejecutar TODOS los skills forenses -- `docker_secrets_analysis`: solo si Docker está presente (trigger automático) -- `web_secret_exposure`: solo si hay servidor web (trigger automático) -- Los demás se ejecutan siempre +### Phases 3–5 (Forensic Skills) +- Run the forensic skills, subject to their triggers. +- `docker_secrets_analysis`: only when Docker is present (automatic trigger). +- `web_secret_exposure`: only when a web server is present (automatic trigger). +- Run the remaining unconditional skills. -### Fase 6 (Platform) -- Ejecutar SOLO si el componente fue detectado en Fase 1 -- Seguir triggers de `_index.yaml` +### Phase 6 (Platform) +- Run only if the component was detected in Phase 1. +- Follow `_index.yaml` triggers. -### Fase 7-8 (Resources + Analysis) -- Ejecutar todos — son cheap y provide contexto +### Phases 7–8 (Resources + Analysis) +- Run all listed skills: they provide low-cost context. -## Reglas duras (heredadas de infrastructure-audit.md) +## Hard rules (inherited from infrastructure-audit.md) -1. **Read-only.** Nada que modifique el servidor. -2. **Evidence first.** Cada afirmación con evidencia almacenada. -3. **Fact vs Hypothesis.** Etiquetar cada claim. -4. **Secret redaction.** Valores nunca en evidencia/reporte. -5. **No assumptions.** Descubrir, nunca asumir. +1. **Read-only.** Do not modify the server. +2. **Evidence first.** Every claim needs stored evidence. +3. **Fact vs hypothesis.** Label every claim. +4. **Secret redaction.** Never include secret values in evidence/reports. +5. **No assumptions.** Discover; never assume. ## Output -Directorio de reportes: `reportes//` -- `reportes//evidencia/` — YAML records por comando -- `reportes//findings/` — hallazgos -- `reportes//findings.yaml` — findings estructurados -- `reportes//inventory.yaml` — inventario -- `reportes//informe-forense-.html` — reporte HTML forense +Report directory: `reportes//` +- `reportes//evidencia/` — per-command YAML records +- `reportes//findings/` — findings +- `reportes//findings.yaml` — structured findings +- `reportes//inventory.yaml` — inventory +- `reportes//informe-forense-.html` — forensic HTML report -## Safety levels (ver SAFETY.md) +## Safety levels (see SAFETY.md) | Level | Name | Scope | Default | |-------|------|-------|---------| @@ -161,9 +161,9 @@ Directorio de reportes: `reportes//` | 2 | TEST | Non-destructive tests (HTTP probes) | On by default | | 3 | CHANGE | Mutating actions | Off — requires explicit approval | -## Tecnologias sin skill +## Technology without a dedicated skill -La presencia de una tecnologia no justifica crear una skill. Reutilizar primero las -capacidades forenses genericas y ejecutar checks ad-hoc L1/L2 acotados cuando falte -evidencia. Persistir una skill solo si cumple todos los criterios de necesidad, -reutilizacion, no solapamiento, estabilidad y validacion de `WORKFLOW.md`. +Technology presence alone does not justify a new skill. Reuse generic forensic +capabilities first and run bounded L1/L2 ad-hoc checks when evidence is missing. +Persist a skill only if it meets every necessity, reuse, non-overlap, stability +and validation criterion in `WORKFLOW.md`. diff --git a/workflows/incident-triage.md b/workflows/incident-triage.md index d595621..21c3292 100644 --- a/workflows/incident-triage.md +++ b/workflows/incident-triage.md @@ -1,79 +1,79 @@ -# Workflow: Incident Triage (síntoma -> causa raíz) +# Workflow: Incident Triage (symptom -> root cause) -Entrada para cuando el operador reporta un **síntoma** (no "haceme un audit", sino -"el sitio da 502", "el disco se llenó", "un contenedor se reinicia solo"). El objetivo -es llegar a la **causa raíz** y una **remediación**, no listar todo el inventario. +Use when the operator reports a **symptom**, such as "the site returns 502", +"the disk is full" or "a container keeps restarting", rather than requesting a +full audit. The goal is a **root cause** and **remediation**, not a full inventory. -Data-driven: este workflow lee `lib/diagnosis.yaml` (mapa síntoma -> hipótesis -> evidencia --> skills) y ejecuta **solo** los skills que ese síntoma requiere. No hay lógica hardcodeada: -agregar un síntoma nuevo es editar `diagnosis.yaml`. +This data-driven workflow reads `lib/diagnosis.yaml` (symptom -> hypotheses -> +evidence -> skills) and runs only the required skills. Adding a symptom is a +change to `diagnosis.yaml`, not hardcoded workflow logic. -## Entrada mínima +## Minimum input -| Variable | Requerido | Descripción | -|----------|-----------|-------------| -| `SYMPTOM` | si | El síntoma reportado (p.ej. "502 en descubrisannicolas.com.ar") | -| `SSH_TARGET` | si | `user@host` o alias configurado | +| Variable | Required | Description | +|----------|----------|-------------| +| `SYMPTOM` | yes | Reported symptom, e.g. "502 on app.example.test" | +| `SSH_TARGET` | yes | `user@host` or a configured alias | ## Loop -``` -1. NORMALIZAR el síntoma -> mapear a un id de diagnosis.yaml +```text +1. NORMALIZE the symptom -> map it to a diagnosis.yaml ID (502 -> http_5xx/502_bad_gateway, cert -> cert_error, etc.) | v -2. LEER diagnosis.yaml: obtener la lista ordenada de hipótesis para ese id. +2. READ diagnosis.yaml: obtain the ordered hypotheses for that ID. | v -3. POR CADA hipótesis (en orden de probabilidad): - - mirar qué evidence necesita y qué skills la producen - - si la evidencia ya existe en reportes//, usarla; si no, correr el skill - - correr la prueba confirmatoria NO destructiva ("confirm") - - si se confirma -> causa raíz encontrada; salir - - si se descarta -> pasar a la siguiente hipótesis +3. FOR EACH hypothesis (in likelihood order): + - identify required evidence and the skills that produce it + - reuse existing evidence in reportes//; otherwise run the skill + - run the non-destructive confirmation check ("confirm") + - if confirmed -> root cause found; exit + - if ruled out -> continue to the next hypothesis | v -4. VERIFICAR con una segunda fuente (anti-falso-positivo): - evidencia + contexto + exposición + impacto (lib/severity.md) +4. VERIFY with a second source to reduce false positives: + evidence + context + exposure + impact (lib/severity.md) | v -5. GENERAR el finding (FACT/OBSERVATION/HYPOTHESIS/RISK) + severidad + confianza +5. GENERATE a finding (FACT/OBSERVATION/HYPOTHESIS/RISK) + severity + confidence | v -6. GENERAR la remediación (WHAT/WHY/HOW/RISK/PRIORITY/VALIDATION/ROLLBACK) - - si requiere Level 3 -> STOP, DOCUMENTAR, PEDIR APROBACIÓN +6. GENERATE remediation (WHAT/WHY/HOW/RISK/PRIORITY/VALIDATION/ROLLBACK) + - if Level 3 is required -> STOP, DOCUMENT, REQUEST APPROVAL | v -7. REPORTAR: causa raíz + evidencia + remediación (resumen en consola) +7. REPORT root cause + evidence + remediation (console summary) ``` -## Reglas duras +## Hard rules -1. **Read-only hasta el final.** El diagnóstico NUNCA arregla solo. Si la confirmación - o la remediación es Level 3, se documenta y se pide aprobación (SAFETY.md). -2. **Evidencia primero.** Ninguna hipótesis se da por confirmada sin un registro de - evidencia almacenado. -3. **Anti-falso-positivo.** Una hipótesis es una *hipótesis* hasta que la prueba - confirmatoria (no destructiva) la valida. 1 snapshot no es tendencia. -4. **Skills existentes primero.** Cada "how" de `diagnosis.yaml` referencia capacidades - existentes. Si falta una comprobacion, ejecutar un check ad-hoc L1/L2 acotado; crear - una skill solo si supera el gate de necesidad y reutilizacion de `WORKFLOW.md`. -5. **No asumir arquitectura.** El 502 puede ser Apache, nginx, o un ingress de K8s; - dejar que `web_server_analysis` / `ingress_nginx_analysis` lo descubran. +1. **Read-only throughout.** Diagnosis never applies fixes automatically. If + confirmation or remediation requires Level 3, document it and request approval + (`SAFETY.md`). +2. **Evidence first.** No hypothesis is confirmed without a stored evidence record. +3. **False-positive control.** A hypothesis remains a hypothesis until a + non-destructive confirmation check validates it. One snapshot is not a trend. +4. **Existing skills first.** Each `how` in `diagnosis.yaml` references existing + capabilities. Cover missing checks with bounded L1/L2 ad-hoc work; create a + skill only if it passes the necessity/reuse gate in `WORKFLOW.md`. +5. **Do not assume architecture.** A 502 may come from Apache, nginx or Kubernetes + ingress; let `web_server_analysis` / `ingress_nginx_analysis` discover it. -## Ejemplo: "502 en el sitio" +## Example: "502 on the site" -``` -síntoma -> http_5xx -hipótesis 1: upstream caído - -> correr web_server_analysis (proxy map + upstream health) - -> confirm: curl al upstream -> 000 (refused) - -> verificar: docker ps -a + curl al container-IP -> nada escuchando - -> causa raíz: contenedor 'up' pero proceso Rails muerto (sin swap -> OOM) - -> remediación: reiniciar contenedor + habilitar swap (Level 3 -> pedir aprobación) +```text +symptom -> http_5xx +hypothesis 1: upstream unavailable + -> run web_server_analysis (proxy map + upstream health) + -> confirm: curl upstream -> 000 (refused) + -> verify: docker ps -a + curl container-IP -> no listener + -> root cause: container 'up' but Rails process terminated (no swap -> OOM) + -> remediation: restart container + enable swap (Level 3 -> request approval) ``` -## Directorio de reportes +## Report directory -Igual que el audit: evidencia en `reportes//evidencia/`, hallazgos en -`reportes//findings.yaml`. Reutiliza el mismo `run-id` si ya existía una corrida. +As with an audit, store evidence in `reportes//evidencia/` and findings in +`reportes//findings.yaml`. Reuse the same `run-id` for an existing run. diff --git a/workflows/infrastructure-audit.md b/workflows/infrastructure-audit.md index 16426ec..64ada62 100644 --- a/workflows/infrastructure-audit.md +++ b/workflows/infrastructure-audit.md @@ -1,31 +1,31 @@ # Workflow: Infrastructure Audit -Flujo principal de analisis de infraestructura. Read-only, reusable contra cualquier servidor Linux accesible por SSH. -La IA lee `skills/_index.yaml` y este documento para orquestar la ejecucion. +The main infrastructure analysis workflow. Read-only and reusable across Linux servers accessible over SSH. +The AI session reads `skills/_index.yaml` and this document to coordinate execution. -## Entrada minima +## Minimum input -| Variable | Requerido | Default | Descripcion | +| Variable | Required | Default | Description | |----------|-----------|---------|-------------| -| `SSH_TARGET` | si | — | `user@host` o alias SSH configurado (`~/.ssh/config`) | +| `SSH_TARGET` | yes | — | `user@host` or a configured SSH alias (`~/.ssh/config`) | | `MODE` | no | `full` | `full` / `quick` / `discovery` / `container` / `security` | -## Diagrama de ejecucion +## Execution diagram ``` -CONNECT (verificar SSH, sin asumir OS) +CONNECT (verify SSH without assuming the OS) | v -DISCOVER (skills/discovery — amplio, barato, read-only) +DISCOVER (skills/discovery — broad, low-cost, read-only) | v CLASSIFY -> BUILD INVENTORY -> BUILD GRAPH | v -DETECT COMPONENTS -> SELECT SKILLS (solo los que aplican) +DETECT COMPONENTS -> SELECT SKILLS (applicable skills only) | v -RUN ANALYSIS (skills seleccionados, tests no destructivos) +RUN ANALYSIS (selected skills, non-destructive tests) | v FIND ANOMALIES -> CREATE HYPOTHESES -> TEST -> VERIFY @@ -34,56 +34,56 @@ FIND ANOMALIES -> CREATE HYPOTHESES -> TEST -> VERIFY GENERATE FINDINGS + REMEDIATIONS | v -[si migration] MIGRATION ANALYSIS +[if migration] MIGRATION ANALYSIS | v GENERATE REPORT -> PRINT EXECUTIVE SUMMARY ``` -## Reglas duras +## Hard rules -1. **Read-only.** Si un comando no es claramente `ro|info|probe` -> STOP -> registrar como recomendacion, no ejecutar. -2. **Deteccion dinamica.** Ejecutar skills condicionales solo si su `trigger` se cumple. Si no -> SKIP. -3. **Sin asunciones.** Distribucion, init system, container runtime, orquestador, ingress, databases, WAF, firewall, cloud provider: todo debe ser *descubierto*, nunca asumido. -4. **Evidencia primero.** Ninguna afirmacion sobre el servidor sin un registro de evidencia almacenado. -5. **Hecho vs Hipotesis.** Etiquetar cada afirmacion como `FACT`, `OBSERVATION`, `HYPOTHESIS`, `RISK`, o `RECOMMENDATION`. -6. **Redaccion de secretos.** Los secretos se *detectan y reportan como metadata* (ubicacion, tipo, riesgo). Los valores se redactan antes de cualquier salida. -7. **No hardcodear servidores.** Cero `if hostname==`. Toda decision por deteccion de componentes. -8. **Anti-falsos-positivos.** 1 snapshot no es tendencia. Usar `SAMPLE_COUNT >= 4` para inferencias. -9. **Reusar evidencia.** Una skill consume evidencia fresca de sus dependencias; no repite comandos para obtener la misma vista. -10. **Diagnostico bajo demanda.** La presencia de una tecnologia habilita postura/inventario, no troubleshooting, logs profundos ni forense sin sintoma o anomalia. -11. **Skills excepcionales.** Tecnologia sin soporte -> skill generica o check ad-hoc acotado. Solo persistir una skill si supera el gate completo de `WORKFLOW.md`. -12. **Concurrencia acotada.** Maximo 3 comandos L1 livianos e independientes; serializar scans globales, logs, DB, dumps de cluster y pruebas del mismo subsistema. +1. **Read-only.** If a command is not clearly `ro|info|probe` -> STOP -> record a recommendation; do not execute it. +2. **Dynamic detection.** Execute conditional skills only when their `trigger` is satisfied. Otherwise -> SKIP. +3. **No assumptions.** Discover the distribution, init system, container runtime, orchestrator, ingress, databases, WAF, firewall and cloud provider; never assume them. +4. **Evidence first.** No claim about the server without a stored evidence record. +5. **Fact vs hypothesis.** Label every claim as `FACT`, `OBSERVATION`, `HYPOTHESIS`, `RISK` or `RECOMMENDATION`. +6. **Secret redaction.** Detect and report secrets as metadata only (location, type, risk). Redact values before output. +7. **No hardcoded servers.** No `if hostname==`. Base decisions on detected components. +8. **False-positive control.** One snapshot is not a trend. Use `SAMPLE_COUNT >= 4` for inferences. +9. **Reuse evidence.** A skill consumes fresh dependency evidence instead of repeating commands for the same view. +10. **On-demand diagnosis.** Technology presence enables posture/inventory checks, not troubleshooting, deep logs or forensics without a symptom or anomaly. +11. **Exceptional skill creation.** Unsupported technology -> generic skill or bounded ad-hoc check. Persist a skill only after the complete gate in `WORKFLOW.md` passes. +12. **Bounded concurrency.** At most three lightweight independent L1 commands; serialize global scans, logs, database checks, cluster dumps and tests of the same subsystem. -## Modos +## Modes -| Modo | Seleccion | Descripcion | +| Mode | Selection | Description | |------|-----------|-------------| -| `full` | candidatos de `_index.yaml` + triggers | Analisis completo, condicionado por evidencia | -| `quick` | conjunto minimo + dependencias | Triage rapido | -| `discovery` | inventario, systemd, procesos, red | Solo descubrimiento e inventario | -| `container` | candidatos Docker/K8s + dependencias | Host de contenedores; diagnostico solo ante anomalías | -| `security` | postura de seguridad + dependencias | Auditoria de seguridad | -| `forensic` | candidatos forenses + dependencias | Solo con objetivo/indicadores forenses explicitos | +| `full` | `_index.yaml` candidates + triggers | Comprehensive evidence-driven analysis | +| `quick` | minimal set + dependencies | Rapid triage | +| `discovery` | inventory, systemd, processes, network | Discovery and inventory only | +| `container` | Docker/K8s candidates + dependencies | Container host; diagnosis only for anomalies | +| `security` | security posture + dependencies | Security audit | +| `forensic` | forensic candidates + dependencies | Explicit forensic objective/indicators required | -Los conteos no se hardcodean: se derivan del catalogo y pueden cambiar. La secuencia del modo es un conjunto candidato; el agente agrega dependencias, ordena topologicamente y aplica triggers antes de ejecutar. +Counts are derived from the catalog and may change. Each mode's sequence is a candidate set; the agent adds dependencies, sorts topologically and evaluates triggers before execution. -## Directorio de reportes +## Report directory -Toda la evidencia y reportes se guardan en `reportes//`: -- `reportes//evidencia/` — registros YAML por comando -- `reportes//findings/` — hallazgos -- `reportes//inventory.yaml` — inventario -- `reportes//graph.yaml` — grafo de infraestructura -- `reportes//informe-.html` — reporte HTML offline +Store evidence and reports in `reportes//`: +- `reportes//evidencia/` — per-command YAML records +- `reportes//findings/` — findings +- `reportes//inventory.yaml` — inventory +- `reportes//graph.yaml` — infrastructure graph +- `reportes//informe-.html` — offline HTML report -## Tecnologia sin skill +## Technology without a dedicated skill -No crear una skill por presencia de producto. Registrar la tecnologia en inventario, reutilizar skills genericas y, si queda una pregunta concreta, ejecutar un check ad-hoc L1/L2 acotado mediante `scripts/ssh_exec.sh`. +Do not create a skill merely because a product is present. Record the technology in inventory, reuse generic skills and, if a concrete question remains, run a bounded L1/L2 ad-hoc check through `scripts/ssh_exec.sh`. -Persistir una skill solo cuando sea necesaria para el objetivo actual, reutilizable entre hosts/runs, no se solape con capacidades existentes, use interfaces estables, minimice comandos y supere validacion + ejecucion. Ver el gate vinculante en `WORKFLOW.md`. +Persist a skill only when it is necessary for the current objective, reusable across hosts/runs, non-overlapping, based on stable interfaces, command-efficient and validated through review and execution. See the binding gate in `WORKFLOW.md`. -## Safety levels (ver SAFETY.md) +## Safety levels (see SAFETY.md) | Level | Name | Scope | Default | |-------|------|-------|---------| diff --git a/workflows/server-resource-analysis.md b/workflows/server-resource-analysis.md index 9c49144..37d39aa 100644 --- a/workflows/server-resource-analysis.md +++ b/workflows/server-resource-analysis.md @@ -1,9 +1,9 @@ # Workflow: Server Resource Analysis -Flujo enfocado en analisis de recursos y performance de servidores Linux. -Read-only, reusable contra cualquier servidor. +Workflow focused on Linux server resource and performance analysis. +Read-only and reusable across servers. -## Diagrama +## Diagram ``` PRE-FLIGHT CHECK (SSH reachable? tools present?) @@ -36,19 +36,19 @@ OPTIMIZE (optimization_analysis) FINDINGS + REPORT ``` -## Modos de ejecucion +## Execution modes -| Modo | Skills | Cuando | +| Mode | Skills | When | |------|--------|--------| -| `full` | 22 | Analisis completo | -| `quick` | 6 | Triage rapido (inventario + CPU/mem/disk/io + logs) | -| `container` | 6 | Host de contenedores (Docker + K8s + process + net + capacity) | +| `full` | 22 | Comprehensive analysis | +| `quick` | 6 | Rapid triage (inventory + CPU/memory/disk/I/O + logs) | +| `container` | 6 | Container host (Docker + K8s + processes + network + capacity) | -## Segunda ejecucion (post-optimizacion) +## Second run (post-optimization) ``` BASELINE (reportes/run-1/) - aplicar cambios (externo, con aprobacion) + apply changes (outside the framework, with approval) POST-OPTIMIZATION (reportes/run-2/) COMPARISON (optimization-comparison.md) ```