Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions .github/workflows/verify.yml
Original file line number Diff line number Diff line change
@@ -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
67 changes: 56 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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.
Expand All @@ -25,14 +30,16 @@ SSH es solo el transporte de las tools.
## Puesta en marcha (solo en la workstation)

```bash
git clone <repo> 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
Expand All @@ -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)
Expand Down Expand Up @@ -79,19 +89,30 @@ 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`.

## Backups y estado

- Backups **en el target**: `/var/backups/server-hardener/<run-id>/` 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
Expand All @@ -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

Expand All @@ -125,6 +167,9 @@ bun run inspect <target> # 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)

Expand Down
29 changes: 21 additions & 8 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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/<run-id>/`
(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

Expand All @@ -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),
Expand Down
29 changes: 29 additions & 0 deletions docs/VERIFICATION.md
Original file line number Diff line number Diff line change
@@ -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.
6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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 .",
Expand Down
28 changes: 12 additions & 16 deletions src/hardening/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -177,7 +181,9 @@ async function assessHost(
deps: AgentDeps,
): Promise<Assessment> {
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 } };
Expand Down Expand Up @@ -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<string> {
export async function reconnectCheck(host: Host, request: ExecuteRequest): Promise<string> {
const attempts = 3;
let connection = await host.verifyConnection();
for (let i = 1; i < attempts && connection.status !== "ok"; i++) {
Expand All @@ -403,22 +409,12 @@ async function reconnectCheck(host: Host, request: ExecuteRequest): Promise<stri
return "\nreconnect check: OK — a new SSH session from the workstation succeeded.";
}

// A listening socket does not prove reachability through the firewall or
// successful authentication. Use the retained connection to attempt recovery.
const kind = connection.failureKind ?? connection.status;
if (kind === "auth" || kind === "host-key") {
const rollback = await rollbackControl(request);
return `\nreconnect check: FAILED (${kind}). Automatic rollback attempted: ${rollback.message}`;
}

// connection/timeout: may be transient rate limiting. Confirm the authorized
// administrative port is still listening before deciding.
const port = request.context.management.sshPort ?? null;
const ss = await host.exec("ss", ["-tln"]);
const listening = port !== null && new RegExp(`:${port}\\s`).test(ss.stdout);
if (listening) {
return `\nreconnect check: not confirmed (${kind}); the authorized port ${port} is still listening, so the change was kept. Retry SSH if the session drops.`;
}
const rollback = await rollbackControl(request);
return `\nreconnect check: FAILED (${kind}) and port ${port ?? "?"} is not listening. Automatic rollback attempted: ${rollback.message}`;
const recovered = await host.verifyConnection();
return `\nreconnect check: FAILED (${kind}). Automatic rollback attempted: ${rollback.message}. Fresh connection after rollback: ${recovered.status === "ok" ? "OK" : "NOT CONFIRMED; use the secondary management path"}.`;
}

// --- Misc ------------------------------------------------------------------
Expand Down
Loading
Loading