From c2dc88fea57c2ba11e43910c99f701c2feb79685 Mon Sep 17 00:00:00 2001 From: Tobias Jurnet <114355588+binaryTob@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:05:17 -0300 Subject: [PATCH] fix(safety): preserve SSH access and verify remediation backups --- .github/workflows/verify.yml | 28 +++++++++ README.md | 67 +++++++++++++++++---- docs/ARCHITECTURE.md | 29 ++++++--- docs/VERIFICATION.md | 29 +++++++++ package.json | 6 +- src/hardening/agent.ts | 28 ++++----- src/hardening/remediation/firewall.ts | 75 +++++++++++++++--------- src/hardening/remediation/fsops.ts | 8 ++- src/hardening/remediation/run.ts | 12 ++-- src/hardening/transport/ssh.ts | 4 +- tests/execution.test.ts | 84 +++++++++++++++++++++++++++ tests/security.test.ts | 34 ++++++++++- 12 files changed, 328 insertions(+), 76 deletions(-) create mode 100644 .github/workflows/verify.yml create mode 100644 docs/VERIFICATION.md diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml new file mode 100644 index 0000000..c902650 --- /dev/null +++ b/.github/workflows/verify.yml @@ -0,0 +1,28 @@ +name: Verify +on: [push, pull_request] +permissions: + contents: read +jobs: + offline: + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + with: + bun-version: '1.4.3' + - run: bun install --frozen-lockfile --ignore-scripts + - run: bun run lint + - run: bun run typecheck + - run: bun test + - run: bun run build + - run: bun audit + secrets: + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + fetch-depth: 0 + - name: Scan history with redacted output + run: docker run --rm -v "$PWD:/repo" zricethezav/gitleaks:v8.30.1 git /repo --log-opts=--all --redact=100 --no-banner diff --git a/README.md b/README.md index a97cdd3..94f9b27 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# server-hardener +# Server-Hardener Agente **de OpenCode que corre en tu workstation** y hardeniza **un servidor Linux objetivo por SSH**. El servidor objetivo **no instala nada**: ni OpenCode, @@ -13,9 +13,14 @@ Workstation (OpenCode + server-hardener) ── SSH ──▶ Servidor objetiv SSH es solo el transporte de las tools. +El código TypeScript implementa discovery, evaluación determinista y operaciones +acotadas; OpenCode aporta la sesión de razonamiento y la interacción con el +operador. No hay un LLM embebido en el runtime ni una ejecución desatendida de +todos los controles. + ## Requisitos -- [Bun](https://bun.sh) ≥ 1.4 **en la workstation**. +- [Bun](https://bun.sh) ≥ 1.4.3, OpenCode y OpenSSH **en la workstation**. - Acceso SSH al target con tu configuración normal: alias de `~/.ssh/config`, `user@host`, `user@IP`, o `host:puerto` para puertos no estándar; ssh-agent, `IdentityFile`, `ProxyJump` y `known_hosts` se respetan tal cual. @@ -25,14 +30,16 @@ SSH es solo el transporte de las tools. ## Puesta en marcha (solo en la workstation) ```bash -git clone server-hardener +git clone https://github.com/binaryTob/server-hardener.git cd server-hardener -bun install +bun install --frozen-lockfile --ignore-scripts opencode ``` Luego, dentro de OpenCode: +Seleccioná el agente `server-hardener` y proporcioná el target: + ```text > Hardenizá srv-ejemplo > Hardenizá admin@192.0.2.10 @@ -51,7 +58,10 @@ Si escribís *"hardenizá este servidor"* sin target, el agente **pregunta cuál (sin score numérico). 4. Pregunta **solo** el contexto operativo que cambia una decisión. 5. Por cada control elegido: `preview` → **confirmación explícita** → `apply` - remoto (con backup en el target) → `verify` → `rollback` si falla. + remoto → `verify`. Los cambios de archivos guardan backups en el target; + servicios/firewall registran su estado previo. Un fallo de sintaxis SSH restaura + la configuración; un fallo de reconexión intenta rollback. Otros fallos deben + revisarse y solicitar rollback explícito: no existe una transacción global. 6. Entrega un resumen final (aplicados / omitidos / fallidos / revertidos). ### CLI (read-only) @@ -79,11 +89,18 @@ argv (sin shell local), con backup y verificación. - Solo aplica controles `non-compliant` / `requires-review`. - **Lockout = stop:** `PasswordAuthentication no` se rechaza sin ruta secundaria confirmada. -- Nunca reemplaza un firewall ni genera reglas nftables automáticamente; nunca - cierra el acceso del operador (nunca default-deny primero). +- No reemplaza firewalls ni genera reglas nftables. La activación automática de + UFW requiere puertos administrativos conocidos y reglas allow exitosas antes + de habilitarlo. Firewalld requiere revisión manual de zonas/interfaces y puertos. - Tras cambios de SSH/firewall, verifica una **conexión SSH nueva** desde la - workstation; si no puede confirmarla, verifica que el puerto admin siga - escuchando y, si no, hace rollback. + workstation, con hasta tres intentos; si falla, intenta rollback mediante la + sesión conservada y vuelve a probar. Un socket escuchando no demuestra acceso. +- El rollback depende de que la sesión conservada siga operativa. No hay un timer + remoto de recuperación: mantené una consola/ruta secundaria verificada para + cambios de acceso. Ningún control garantiza por sí solo ausencia de lockout. +- Cambiar de target o puerto descarta el contexto operativo anterior; las + confirmaciones de un servidor no se reutilizan para otro. Los aliases SSH que + cambien de destino requieren reconfirmar el contexto. - No instala dependencias del framework en el target (instalar `auditd` es una decisión explícita de hardening, no una dependencia). - No captura ni guarda passwords. Requiere root o `sudo -n`. @@ -91,7 +108,11 @@ argv (sin shell local), con backup y verificación. ## Backups y estado - Backups **en el target**: `/var/backups/server-hardener//` con - contenido, owner/group/mode y hash → rollback remoto. + contenido, owner/group/mode y hash → rollback remoto con comprobación de + integridad. Los archivos de backup se escriben con modo `0600`. +- La lectura/edición de configuración y el backup pasan por memoria de la + workstation; no son una transferencia exclusivamente interna al servidor. + Tratá la sesión de OpenCode y los registros operativos como información sensible. - Estado mínimo **en la workstation** (se ignora en git): ```text @@ -106,12 +127,33 @@ argv (sin shell local), con backup y verificación. - sysctl (KRN-001..004) - SSH: perfil de directivas (SSH-001..005) y **SSH-007** (exponer solo el puerto admin), con backup + `sshd -t` + reload + verificación de reconexión -- firewall (FW-001, ufw/firewalld) +- firewall (FW-001, activación UFW; firewalld/nftables son manuales) - servicios inseguros conocidos (SVC-001) - logging/auditoría (AUD-001/002, LOG-001) - fstab (FS-001/002) Todo lo demás es `manual remediation required` (nunca se aplica a ciegas). +Los checks modelan estados desconocidos y precondiciones pendientes; SAFE no +significa “aplicar sin autorización”. `localhost` explícito usa transporte local. + +## Arquitectura y límites + +```text +OpenCode agent + skills -> tools con argumentos acotados + -> agent.ts -> discovery / controls / planning + -> remediation -> Host (SSH por defecto) -> herramientas del SO +``` + +`controls/` y `planning/` separan aplicabilidad, compliance y riesgo de la +ejecución en `remediation/`. `transport/` valida el target y construye argv con +quoting remoto. `store.ts` guarda el estado local mínimo. + +`preview` y `verify` no crean directorios de backup. La verificación automatizada +usa fixtures y `FakeHost`; no equivale a una matriz de validación sobre todas las +distribuciones, firewalls, PAM, includes/Match de SSH o servicios socket-activated. +Una configuración no representada debe revisarse manualmente. El rollback de +firewall restaura activación, no un snapshot completo de reglas; las reglas allow +añadidas necesitan revisión si la operación falla. ## Desarrollo @@ -125,6 +167,9 @@ bun run inspect # evaluación read-only ``` Arquitectura: `docs/ARCHITECTURE.md`. +GitHub Actions ejecuta estos checks sin conectarse a servidores, audita las +dependencias y escanea el historial con Gitleaks. Reiniciá OpenCode después de +cambiar agentes, skills o tools para que recargue las definiciones. ## Fuera de alcance (a propósito) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 617af16..047b181 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -18,15 +18,19 @@ target. ## 1. Product ``` -git clone server-hardener && cd server-hardener && bun install +git clone https://github.com/binaryTob/server-hardener.git +cd server-hardener +bun install --frozen-lockfile --ignore-scripts opencode > harden admin@server.example ``` The agent identifies the target, verifies SSH, runs read-only discovery, groups hardening candidates by risk, asks the decision-critical questions, applies the -selected changes with remote backups and verification, rolls back on failure and -reports. +selected changes with remote file backups and verification, supports per-control +rollback and reports. Syntax failure restores SSH configuration immediately; +failed fresh SSH reconnection triggers a rollback attempt. Other verification +failures require operator review rather than a global automatic transaction. ## 2. Layers @@ -88,15 +92,19 @@ the operator tier (`safe`/`review`/`risky`). No numeric score. Preview → apply → verify → rollback, per control: - **Backups live on the target** at `/var/backups/server-hardener//` - (content + SHA-256 + owner/group/mode), so nothing sensitive is pulled to the - workstation and rollback works remotely. -- sysctl, SSH, firewall (ufw/firewalld only), services (known-insecure only), + (content + SHA-256 + owner/group/mode, mode 0600). Config content passes through + workstation memory while reading, editing and creating/restoring backups. + Restore checks content integrity before writing; config edits preserve mode. +- sysctl, SSH, firewall (UFW activation; firewalld/nftables manual), services (known-insecure only), logging/audit, filesystem fstab. Everything else is `manual remediation required`. - **SSH/firewall reconnection check:** after an access-affecting change the tool opens a NEW ssh connection from the workstation; if it fails it attempts a - rollback. Firewall never closes the operator's access and never defaults-deny - first. + rollback over the retained session and checks a fresh connection again. A + listening port is not accepted as proof of operator access. There is no remote + recovery timer; use a verified secondary management path. UFW activation needs + successful administrative allow rules first; firewalld zone-aware activation + is not implemented. Firewall rollback restores activation, not all rules. ## 7. Privileges @@ -113,6 +121,11 @@ password is ever captured or stored. └── optional-context.json operator-supplied operational context ``` +Context is used only for the selected session target. Connecting to a different +target/explicit port clears old approvals and management details. Explicit SSH +ports are part of rollback host identity. Alias resolution changes are outside +this string-based identity; reconfirm context if an alias is repointed. + ## 9. Tests `tests/`: parsers, discovery, assessment, store (session/last-run/context), diff --git a/docs/VERIFICATION.md b/docs/VERIFICATION.md new file mode 100644 index 0000000..729d344 --- /dev/null +++ b/docs/VERIFICATION.md @@ -0,0 +1,29 @@ +# Verification and operational boundaries + +The offline suite exercises parsers, discovery, pure assessments, state, target +validation, command quoting and bounded remediation against an in-memory +`FakeHost`. It does not connect to an external server or apply host hardening. + +Use Bun 1.4.3 or newer. The committed lockfile requires the v2 lockfile reader. + +```bash +bun install --frozen-lockfile --ignore-scripts +bun run lint +bun run typecheck +bun test +bun run build +bun audit +``` + +Regression checks cover read-only preview/verify, restrictive configuration +modes, backup checksum rejection, context isolation across targets/ports, +conservative reconnect rollback and refusal to activate a firewall after a failed +administrative allow rule. Firewalld activation is manual until zone/interface +and administrative-port handling is implemented and validated. + +Before operational use, validate the applicable controls on disposable Linux +VMs with console access. SSH includes/Match rules, socket activation, distro +service names, PAM, firewall zones and network paths need integration coverage. +Retained-session rollback is best effort, not out-of-band recovery. The local +operator, OpenCode session and source files are trusted; prompts and `confirm` +arguments are not a cryptographic approval mechanism. diff --git a/package.json b/package.json index fd0dfbb..aaee319 100644 --- a/package.json +++ b/package.json @@ -3,7 +3,11 @@ "version": "0.1.0", "private": true, "type": "module", - "description": "Interactive, read-only-first server hardening framework. Phase 1: discovery and inventory.", + "description": "Local OpenCode agent for SSH-based Linux discovery, risk assessment and verified hardening with remote backups.", + "engines": { + "bun": ">=1.4.3" + }, + "packageManager": "bun@1.4.3", "scripts": { "format": "biome format --write .", "lint": "biome check .", diff --git a/src/hardening/agent.ts b/src/hardening/agent.ts index bdcf3eb..03338df 100644 --- a/src/hardening/agent.ts +++ b/src/hardening/agent.ts @@ -124,6 +124,10 @@ export async function connectTarget( sudo: probe.sudo, isLocalhost: spec.isLocalhost, }; + const previousSession = await readSession(storeRoot); + if (previousSession?.target !== info.target) { + await saveContext(storeRoot, emptyContext(now(deps))); + } await writeSession(storeRoot, info); if (spec.port !== null) { const stored = await readContext(storeRoot); @@ -177,7 +181,9 @@ async function assessHost( deps: AgentDeps, ): Promise { const inventory = await runDiscovery({ runner: host, files: host, platform: host.platformHint }); - const stored = await readContext(storeRoot); + const session = await readSession(storeRoot); + // Approval/context for one destination must never authorize another host or port. + const stored = session?.target === spec.raw ? await readContext(storeRoot) : null; let context = withDetectedRoles(stored ?? emptyContext(now(deps)), inventory); if ((context.management.sshPort ?? null) === null && spec.port !== null) { context = { ...context, management: { ...context.management, sshPort: spec.port } }; @@ -390,7 +396,7 @@ export async function domainAction( } /** After an access-affecting change, prove a NEW connection from here works. */ -async function reconnectCheck(host: Host, request: ExecuteRequest): Promise { +export async function reconnectCheck(host: Host, request: ExecuteRequest): Promise { const attempts = 3; let connection = await host.verifyConnection(); for (let i = 1; i < attempts && connection.status !== "ok"; i++) { @@ -403,22 +409,12 @@ async function reconnectCheck(host: Host, request: ExecuteRequest): Promise async function preview(ctx: RemediationContext): Promise { const kind = implementation(ctx); + if (kind === "firewalld") { + return manual( + ctx, + "firewalld requires a reviewed zone/interface and administrative-port policy; automatic activation is disabled", + ); + } if (kind === "nftables") { return manual( ctx, @@ -58,19 +64,10 @@ async function preview(ctx: RemediationContext): Promise { } const ports = administrativePorts(ctx); const warnings: string[] = []; - if (kind === "ufw" && ports.length === 0) { - warnings.push( - "no SSH listener was observed; ensure the administrative port is allowed before enabling the firewall to avoid lockout", - ); + if (ports.length === 0) { + return manual(ctx, "no administrative SSH port is known; refusing to enable a firewall"); } - const commands = - kind === "ufw" - ? [...ports.map((p) => `ufw allow ${p}/tcp`), "ufw --force enable"] - : [ - "firewall-cmd --permanent --add-service=ssh", - "firewall-cmd --reload", - "systemctl enable --now firewalld", - ]; + const commands = [...ports.map((p) => `ufw allow ${p}/tcp`), "ufw --force enable"]; return { controlId: ctx.control.controlId, title: ctx.control.title, @@ -78,11 +75,7 @@ async function preview(ctx: RemediationContext): Promise { manualReason: null, currentState: `implementation: ${kind}`, desiredState: "host firewall active without closing administrative access", - steps: [ - kind === "ufw" - ? "ensure administrative port(s) are allowed, then enable" - : "allow ssh service in the default zone, reload, ensure firewalld is running", - ], + steps: ["ensure administrative port(s) are allowed, then enable"], files: [], commands, warnings, @@ -134,7 +127,7 @@ async function verify(ctx: RemediationContext): Promise { async function apply(ctx: RemediationContext): Promise { const kind = implementation(ctx); - if (kind === "nftables" || kind === null) { + if (kind !== "ufw") { return { changed: false, target: "firewall", @@ -147,20 +140,44 @@ async function apply(ctx: RemediationContext): Promise { message: "manual remediation required for this firewall implementation", }; } - const wasActive = kind === "ufw" ? await ufwActive(ctx) : await firewalldActive(ctx); - if (kind === "ufw") { - for (const port of administrativePorts(ctx)) { - await ctx.runner.run("ufw", ["allow", `${port}/tcp`]); + const wasActive = await ufwActive(ctx); + const ports = administrativePorts(ctx); + if (wasActive === null || ports.length === 0 || wasActive) { + return { + changed: false, + target: kind, + before: null, + after: null, + backupIds: [], + verification: await verify(ctx), + strategy: null, + reversible: false, + message: wasActive + ? "ufw already active; no rules changed" + : "refusing firewall activation: current state or administrative port is unknown", + }; + } + for (const port of ports) { + const allowed = await ctx.runner.run("ufw", ["allow", `${port}/tcp`]); + if (allowed.status !== "ok") { + return { + changed: false, + target: kind, + before: null, + after: null, + backupIds: [], + verification: await verify(ctx), + strategy: null, + reversible: false, + message: + "administrative allow rule failed; firewall was not enabled; review any previously added allow rules", + }; } - await ctx.runner.run("ufw", ["--force", "enable"]); - } else { - await ctx.runner.run("firewall-cmd", ["--permanent", "--add-service=ssh"]); - await ctx.runner.run("firewall-cmd", ["--reload"]); - await ctx.runner.run("systemctl", ["enable", "--now", "firewalld"]); } + await ctx.runner.run("ufw", ["--force", "enable"]); const verification = await verify(ctx); return { - changed: wasActive !== true, + changed: true, target: kind, before: JSON.stringify({ implementation: kind, active: wasActive }), after: JSON.stringify({ implementation: kind, active: true }), @@ -168,7 +185,7 @@ async function apply(ctx: RemediationContext): Promise { verification, strategy: "disable-firewall-if-not-previously-active", reversible: true, - message: `${kind} enabled; administrative access preserved`, + message: `${kind} activation attempted after administrative allow rules; fresh SSH reconnection still required`, }; } diff --git a/src/hardening/remediation/fsops.ts b/src/hardening/remediation/fsops.ts index 97ec5ee..27c0e75 100644 --- a/src/hardening/remediation/fsops.ts +++ b/src/hardening/remediation/fsops.ts @@ -37,9 +37,10 @@ export async function writeConfig( ctx: RemediationContext, file: string, content: string, - mode = 0o644, + mode?: number, ): Promise { - await ctx.host.writeTextPrivileged(file, content, mode); + const existing = mode === undefined ? await ctx.host.stat(file) : null; + await ctx.host.writeTextPrivileged(file, content, mode ?? existing?.mode ?? 0o644); } export async function deleteConfig(ctx: RemediationContext, file: string): Promise { @@ -105,6 +106,9 @@ export async function restoreBackup(ctx: RemediationContext, backupId: string): throw new StateError(`backup ${backupId} is corrupt`, { cause: err }); } const backup = validateBackupRecord(parsed); + if (sha256Hex(backup.content) !== backup.sha256) { + throw new StateError(`backup ${backupId} failed integrity verification`); + } await ctx.host.writeTextPrivileged(backup.originalPath, backup.content, backup.mode ?? 0o644); if (backup.mode !== null) await ctx.host.chmod(backup.originalPath, backup.mode); if (backup.uid !== null && backup.gid !== null) diff --git a/src/hardening/remediation/run.ts b/src/hardening/remediation/run.ts index 78277d5..4294aa9 100644 --- a/src/hardening/remediation/run.ts +++ b/src/hardening/remediation/run.ts @@ -77,10 +77,14 @@ async function ensureBackupDir( return null; } -async function buildContext(request: ExecuteRequest, runId: string): Promise { +async function buildContext( + request: ExecuteRequest, + runId: string, + prepareBackup = false, +): Promise { const hasRoot = request.hasRoot ?? false; const sudo = request.sudo ?? false; - const backupDir = await ensureBackupDir(request.host, runId, hasRoot, sudo); + const backupDir = prepareBackup ? await ensureBackupDir(request.host, runId, hasRoot, sudo) : null; const privileged: CommandRunner = { run: (command, args) => request.host.runPrivileged(command, args) }; const context: RemediationContext = { host: request.host, @@ -155,7 +159,7 @@ export async function applyControl(request: ExecuteRequest): Promise { test("SSH preview changes nothing", async () => { const current = await env(); + const commands: string[] = []; + const exec = current.host.exec.bind(current.host); + current.host.exec = (command, args, options) => { + commands.push(command); + return exec(command, args, options); + }; const before = current.host.files.get("/etc/ssh/sshd_config"); const control = withStatus(evaluate("SSH-005", current.inventory, current.context), "non-compliant"); const outcome = await previewControl(request(current, control)); expect(outcome.preview?.manual).toBe(false); expect(outcome.preview?.desiredState).toContain("MaxAuthTries 4"); expect(current.host.files.get("/etc/ssh/sshd_config")).toBe(before); + await verifyControl(request(current, control)); + expect(commands).not.toContain("mkdir"); }); }); describe("SSH apply / verify / rollback", () => { + test("apply preserves restrictive config permissions", async () => { + const current = await env(); + await current.host.chmod("/etc/ssh/sshd_config", 0o600); + const control = withStatus(evaluate("SSH-005", current.inventory, current.context), "non-compliant"); + await applyControl(request(current, control)); + expect((await current.host.stat("/etc/ssh/sshd_config"))?.mode).toBe(0o600); + }); + + test("tampered backup is rejected before restoring config", async () => { + const current = await env(); + const control = withStatus(evaluate("SSH-005", current.inventory, current.context), "non-compliant"); + await applyControl(request(current, control)); + const entry = (await readLastRun(current.storeRoot))?.entries.at(-1); + const file = `${entry?.backupDir}/${entry?.backupIds[0]}.json`; + const backup = JSON.parse(current.host.files.get(file) ?? "{}"); + backup.content = "tampered fixture content"; + current.host.files.set(file, JSON.stringify(backup)); + const outcome = await rollbackControl(request(current, control)); + expect(outcome.message).toContain("integrity"); + expect(current.host.files.get("/etc/ssh/sshd_config")).toContain("MaxAuthTries 4"); + }); + + test("failed fresh connection rolls back even if a listener could remain", async () => { + const current = await env(); + const control = withStatus(evaluate("SSH-005", current.inventory, current.context), "non-compliant"); + const req = request(current, control); + await applyControl(req); + current.host.verifyConnection = async () => ({ + status: "timeout", + stdout: "", + stderr: "", + exitCode: null, + notRun: false, + failureKind: "timeout", + }); + const result = await reconnectCheck(current.host, req); + expect(result).toContain("Automatic rollback attempted"); + expect(result).toContain("NOT CONFIRMED"); + expect(current.host.files.get("/etc/ssh/sshd_config")).toContain("MaxAuthTries 6"); + expect((await readLastRun(current.storeRoot))?.entries.at(-1)?.action).toBe("rollback"); + }, 10000); + test("apply edits config, backs it up on the target, verifies and records the run", async () => { const current = await env(); const control = withStatus(evaluate("SSH-005", current.inventory, current.context), "non-compliant"); @@ -157,6 +208,39 @@ describe("services", () => { }); describe("firewall safety", () => { + test("firewalld activation is manual until zone-aware access is implemented", async () => { + const current = await env(); + const inventory = structuredClone(current.inventory); + if (inventory.securityControls.data?.firewall) + inventory.securityControls.data.firewall.detectedImplementations = ["firewalld"]; + const control = withStatus(evaluate("FW-001", inventory, current.context), "non-compliant"); + const outcome = await applyControl({ ...request(current, control), inventory }); + expect(outcome.changed).toBe(false); + expect(current.host.firewalldState).toBe("not running"); + }); + + test("failed administrative allow rule prevents firewall activation", async () => { + const current = await env(); + const inventory = structuredClone(current.inventory); + if (inventory.securityControls.data?.firewall) + inventory.securityControls.data.firewall.detectedImplementations = ["ufw"]; + const exec = current.host.exec.bind(current.host); + current.host.exec = (command, args, options) => + command === "ufw" && args[0] === "allow" + ? Promise.resolve({ + status: "error", + stdout: "", + stderr: "fixture failure", + exitCode: 1, + notRun: false, + }) + : exec(command, args, options); + const control = withStatus(evaluate("FW-001", inventory, current.context), "non-compliant"); + const outcome = await applyControl({ ...request(current, control), inventory }); + expect(outcome.changed).toBe(false); + expect(current.host.ufwStatusText).toBe("Status: inactive"); + }); + test("nftables is never changed automatically", async () => { const current = await env(); const inventory = structuredClone(current.inventory); diff --git a/tests/security.test.ts b/tests/security.test.ts index ceaf47e..c5af091 100644 --- a/tests/security.test.ts +++ b/tests/security.test.ts @@ -10,7 +10,7 @@ import path from "node:path"; import hardenSysctl from "../.opencode/tools/harden_sysctl"; import inspectSystem from "../.opencode/tools/inspect_system"; import targetTool from "../.opencode/tools/target"; -import { assess, controlBelongsToDomain } from "../src/hardening/agent"; +import { assess, connectTarget, controlBelongsToDomain } from "../src/hardening/agent"; import { CommandSafetyError, NoTargetError, @@ -18,10 +18,16 @@ import { ToolArgumentError, } from "../src/hardening/errors"; import { assertSafeCommand, ExecCommandRunner } from "../src/hardening/exec"; -import { assertSafeId } from "../src/hardening/store"; +import { assertSafeId, readContext, saveContext } from "../src/hardening/store"; import { buildRemoteCommand } from "../src/hardening/transport/quote"; -import { buildSshArgv, classifyRemoteResult, classifySshFailure } from "../src/hardening/transport/ssh"; +import { + buildSshArgv, + classifyRemoteResult, + classifySshFailure, + SshHost, +} from "../src/hardening/transport/ssh"; import { parseTarget } from "../src/hardening/transport/target"; +import { sampleContext } from "./support"; describe("target validation", () => { test("accepts alias, user@host, user@ip and bare host", () => { @@ -68,6 +74,7 @@ describe("safe ssh argv", () => { expect(argv.at(-1)).toBe("'cat' '/etc/ssh/sshd_config'"); expect(argv).toContain("-o"); expect(argv).toContain("admin@server.example"); + expect(argv.indexOf("--")).toBeLessThan(argv.indexOf("admin@server.example")); }); test("sudo uses non-interactive sudo -n", () => { @@ -183,6 +190,27 @@ describe("domain confinement", () => { }); describe("state id safety", () => { + test("host identity distinguishes explicit SSH ports", () => { + const first = new SshHost(parseTarget("admin@server.example:2200")); + const second = new SshHost(parseTarget("admin@server.example:2222")); + expect(first.label).not.toBe(second.label); + }); + + test("switching target or port discards prior operational approvals", async () => { + const storeRoot = await mkdtemp(path.join(tmpdir(), "hardener-context-")); + const deps = { hostOptions: { sshBinary: "true" } }; // no network: argv consumed by true + try { + await connectTarget(storeRoot, "admin@server.example:2200", deps); + await saveContext(storeRoot, sampleContext()); + await connectTarget(storeRoot, "admin@server.example:2222", deps); + const context = await readContext(storeRoot); + expect(context?.management.secondaryPathConfirmed).not.toBe(true); + expect(context?.management.sshPort).toBe(2222); + } finally { + await rm(storeRoot, { recursive: true, force: true }); + } + }); + test("backup/verification ids cannot escape the store", () => { const pattern = /^(bkp|ver)-[a-z0-9][a-z0-9-]{7,63}$/; for (const bad of ["../../etc", "../bkp", "/tmp/bkp", "bkp", "bkp/a"]) {