DEV Community

Karan Yadav
Karan Yadav

Posted on Originally published at nandai.org

CIS OpenSSH sshd_config Auditing & Zero-Lock PostgreSQL Migration Safety in Pure Python

Production infrastructure incidents routinely originate in two text files checked directly into Git: unhardened /etc/ssh/sshd_config daemon configurations and PostgreSQL SQL migrations that acquire unbounded ACCESS EXCLUSIVE locks. Catching both classes deterministically in CI requires zero external packages and zero telemetry egress.

Across nandai.org/commands/cyclonedx-sbom-trojan-source-csp-commands, nandai.org/apple-silicon/macos-sequoia-security-sandboxing-keychain, and nandai.org/decisions/adr-04-sqlite-wal-fts5-soa-buffers-over-cloud-databases, Destiny applies a uniform Python >=3.10 standard-library verification model (0 PyPI dependencies, 0 bytes uploaded) modeled after guard_scan.py (81,019 bytes, 16 domain scanners + all mode) and mcp-20-precommit-hooks-manifest.json.


1. CIS OpenSSH sshd_config Hardening Gates

Static sshd_config auditing follows OpenSSH's first-match directive evaluation rule (ignoring comments and scoping Match blocks explicitly):

  • Authentication & Privilege: PermitRootLogin no, PasswordAuthentication no, PermitEmptyPasswords no, KbdInteractiveAuthentication no, PubkeyAuthentication yes, and MaxAuthTries <= 4.
  • Forwarding Surface Reduction: AllowAgentForwarding no, AllowTcpForwarding no, X11Forwarding no, and bounded ClientAliveInterval (300).
  • AEAD Ciphers & Post-Quantum KEX: Require explicit AEAD ciphers (chacha20-poly1305@openssh.com, aes256-gcm@openssh.com, aes128-gcm@openssh.com), Encrypt-then-MAC (-etm) HMACs, and sntrup761x25519-sha512@openssh.com / curve25519-sha256 key exchange rather than legacy CBC/RC4 modes.

2. Zero-Lock PostgreSQL DDL Migration Safety

Before executing schema changes against live PostgreSQL tables, offline SQL linting flags operations that rewrite heaps or block concurrent queries behind queued lock requests:

DDL Hazard Operational Failure Safe Pattern
Unflagged CREATE INDEX Blocks table writes under SHARE lock CREATE INDEX CONCURRENTLY outside transaction blocks
ALTER COLUMN ... TYPE / VACUUM FULL Full table rewrite under ACCESS EXCLUSIVE Expand-contract dual-column migration + batched backfill
Volatile ADD COLUMN ... DEFAULT (clock_timestamp(), gen_random_uuid()) Forces row-by-row rewrite under ACCESS EXCLUSIVE Nullable add + constant/batched backfill
Inline CHECK / FOREIGN KEY validation Full table scan while holding ACCESS EXCLUSIVE ADD CONSTRAINT ... NOT VALID + separate VALIDATE CONSTRAINT
Missing SET lock_timeout Queued DDL stalls every downstream SELECT/INSERT Enforce SET lock_timeout = '2s'; SET statement_timeout = '30s';

3. Combined Pure-Python Pre-Merge Verifier (0 PyPI Dependencies)

#!/usr/bin/env python3
"""Combined pure-Python CIS sshd_config & zero-lock PostgreSQL DDL verifier (0 B uploaded)."""

from __future__ import annotations

import re

SSH_EXACT = {
    "permitrootlogin": "no",
    "passwordauthentication": "no",
    "permitemptypasswords": "no",
    "pubkeyauthentication": "yes",
    "x11forwarding": "no",
    "allowagentforwarding": "no",
    "allowtcpforwarding": "no",
}
WEAK_CIPHERS = {"3des-cbc", "aes128-cbc", "aes192-cbc", "aes256-cbc", "arcfour"}

PG_RULES = (
    ("PG_CREATE_INDEX_LOCK", re.compile(r"\bCREATE\s+(?:UNIQUE\s+)?INDEX\s+(?!CONCURRENTLY\b)", re.I)),
    ("PG_ALTER_COLUMN_TYPE", re.compile(r"\bALTER\s+TABLE\b[^;]*\bALTER\s+COLUMN\b[^;]*\bTYPE\b", re.I)),
    ("PG_INLINE_CONSTRAINT_SCAN", re.compile(r"\bADD\s+CONSTRAINT\b[^;]*(?:CHECK|FOREIGN\s+KEY)\b(?![^;]*\bNOT\s+VALID\b)", re.I)),
    ("PG_VACUUM_FULL", re.compile(r"\bVACUUM\s+FULL\b", re.I)),
)

def audit_sshd(text: str) -> list[str]:
    opts: dict[str, str] = {}
    for raw in text.splitlines():
        line = raw.split("#", 1)[0].strip()
        if not line or line.lower().startswith("match "):
            continue
        parts = line.split(None, 1)
        if len(parts) == 2:
            opts.setdefault(parts[0].lower(), parts[1].strip())
    fails = [f"SSH_{k.upper()}" for k, v in SSH_EXACT.items() if opts.get(k, "").lower() != v]
    ciphers = {c.strip().lower() for c in opts.get("ciphers", "").split(",") if c.strip()}
    if not ciphers or (ciphers & WEAK_CIPHERS):
        fails.append("SSH_AEAD_CIPHERS")
    return fails

def audit_pg_ddl(sql: str) -> list[str]:
    cleaned = re.sub(r"--[^\n]*", "", re.sub(r"/\*.*?\*/", "", sql, flags=re.S))
    fails = [] if re.search(r"\bSET\s+(?:LOCAL\s+)?lock_timeout\b", cleaned, re.I) else ["PG_MISSING_LOCK_TIMEOUT"]
    fails.extend(rid for rid, pat in PG_RULES if pat.search(cleaned))
    return fails

if __name__ == "__main__":
    good_ssh = "PermitRootLogin no\nPasswordAuthentication no\nPermitEmptyPasswords no\nPubkeyAuthentication yes\nX11Forwarding no\nAllowAgentForwarding no\nAllowTcpForwarding no\nCiphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com\n"
    good_sql = "SET lock_timeout = '2s';\nCREATE INDEX CONCURRENTLY idx_orders_ts ON orders(created_at);\n"
    assert audit_sshd(good_ssh) == []
    assert audit_pg_ddl(good_sql) == []
    print("CIS sshd_config & zero-lock PostgreSQL DDL checks passed (0 B uploaded).")
Enter fullscreen mode Exit fullscreen mode

Companion sovereign specifications & tooling: agent-security-guard-standalone-spec.json, systemd-unit-sandboxing-spec.json, nginx-tls-alias-hardening-spec.json, https://nandai.org/api/mcp (114 live MIT tools), https://nandai.org/git/destiny.git/, https://nandai.org/src/destiny/, https://nandai.org/releases/destiny-verify-2.0.0.tar.gz, https://huggingface.co/nandai-org, and https://zenodo.org/api/records/24642737 (DOI 10.5281/zenodo.24642737).

Top comments (0)