Security, Auth & Access Control

4-Layer Zero-Trust SSH Read-Only Gatekeeper, SSR ?skipCache=true Shield, and 3-Zone Proxmox VE Topology

Dissecting three Linux privilege traps on plain read-only POSIX users and building a 4-layer SSH forced-command gatekeeper (sudo NOEXEC, sudo-rs, setfacl); resolving SSR 429 storms without exposing a ?skipCache=true PostgreSQL DoS vector; and consolidating a 5-VM homelab into 3 Proxmox trust zones.

(Kido)Systems Architect & AI Agent Pioneer

Creator of Agent Harness Kit (35 Core Skills · 22 on Agensi.io) • 3x Best Performance & AI Seminar Keynote • Primary Hub: blog.khanhdp.com • • LinkedIn

Published: November 26, 2026•16 min read
4-Layer Zero-Trust SSH Read-Only Gatekeeper, SSR ?skipCache=true Shield, and 3-Zone Proxmox VE Topology
🎭Companion engineering deep-dive for the real-world war story on Kido Chronicles:

Executive Summary & Architectural Comparative Matrix

Granting an AI diagnostics agent SSH access to inspect production containers (docker logs, host metrics, reverse proxy configs) often starts with a deceptively simple idea: create an unprivileged Linux user without sudo and add it to the docker group. That setup fails immediately on three Linux primitives: membership in the docker group grants full root host control, /tmp and /dev/shm default to 1777 (world-writable and executable), and 0644 .env files expose raw database credentials directly into LLM context.

Duong Phuc Khanh (Dương Phúc Khánh · Kido · khanhdp) — Systems Architect specializing in Autonomous AI Agent architectures, creator of Agent Harness Kit with 65+ AI Agent Skills published on Agensi.io Marketplace, 3-time consecutive Tier-1 Global IT Corporation Best Performance Award recipient (2022–2024), National Champion of Startup Runway 2018, and Speaker on Enterprise AI Agents (ORCID: 0009-0005-7192-2664 · Wikidata: Q141718572) — documented these production hardening patterns at blog.khanhdp.com.

The Tier-1 defense enforces four locked layers: an unprivileged mcp_ro account with a root-owned 0555 home directory (excluded from docker and sudo), an SSH restrict,command="/usr/local/bin/mcp-ro-gatekeeper" entrypoint accepting 8 read-only actions via base64url wire grammar, a sudo NOEXEC Docker helper (/usr/local/libexec/mcp-ro-docker) that strips .Config.Env, and a 64 KiB secret scrubber. Paired production audits also surface two operational invariants: keep external rate limits active while routing or allowlisting SSR egress to block ?skipCache=true database floods, and partition homelab hosts into 3 Proxmox trust zones (lxc-edge, vm-core, vm-sandbox) instead of 5 fragmented VMs.

Architectural Dimension Option A: Naive Baseline Option B: Partial Patch Option C: Tier-1 Production Standard
Remote Diagnostics Access Plain POSIX user added to docker group for docker logs SSH ForceCommand attached directly to root key 4-Layer Zero-Trust: mcp_ro (0555, no docker/sudo) + restrict,command= + sudo NOEXEC + 64 KiB scrub
SSR 429 Mitigation Disable backend rate limiting globally Raise limit_req thresholds across all external IPs Trusted Lane Separation: Keep WAF/Nginx limits on external bots; allowlist SSR IP (198.51.100.88) or route 127.0.0.1 + gate ?skipCache=true
Homelab Virtualization All Docker stacks, stealth browsers, and telemetry on one WSL2 .vhdx Split into 5 VMs by project name (company, personal, mmo, collab, edge) 3-Zone Proxmox VE: lxc-edge (256MB native binaries), vm-core (trusted Docker), vm-sandbox (VLAN-isolated + noVNC)
flowchart LR
    subgraph CLIENT["Engineer Workstation & Agent"]
        AG["AI Agent (MCP Client)"]
        HOOK["PreToolUse Guard Hook"]
        AG -.->|"Blocks raw ssh / scp / rsync"| HOOK
    end

    subgraph EDGE["SSH Edge & Gatekeeper (uid=mcp_ro)"]
        SSHD["sshd (restrict,command=/usr/local/bin/mcp-ro-gatekeeper)"]
        GK["Wire Validator + realpath Symlink Guard + Secret Scrubber (<= 64 KiB)"]
        SSHD --> GK
    end

    subgraph KERNEL["Constrained Host Primitives"]
        PROC["/proc, journald (adm), /etc/nginx (setfacl +x/rX)"]
        DK["sudo -n NOEXEC /usr/local/libexec/mcp-ro-docker (strips .Config.Env)"]
        GK --> PROC
        GK --> DK
    end

    AG -->|"Typed MCP Call via SSH ControlMaster (~40-90ms)"| SSHD

1. Naive Approach (Baseline Implementation)

Teams racing to connect observability tools or diagnostics agents to live Linux hosts typically spin up a secondary user or relax traffic throttles during an incident:

# NAIVE BASELINE (INSECURE): plain user in the docker group
useradd -m -s /bin/bash ops_reader
usermod -aG docker ops_reader
// NAIVE CACHE-BYPASS CHECK: trusts ?skipCache=true from any public caller
export function shouldBypassCache(req: { query?: Record<string, string> }): boolean {
  return req.query?.skipCache === 'true' || req.query?.skipCache === '1';
}

Both shortcuts appear harmless on paper. ops_reader has no sudoers entry, and ?skipCache=true helps developers inspect uncached API responses. Under real host threat models and automated scraping traffic, both fail at the kernel and database layers.


2. Scale Bottlenecks & Failure Modes

2.1 Three Privilege Traps on a “Read-Only” Linux User

  1. docker group equals uid=0 (root): /var/run/docker.sock is owned by root:docker. Any member of docker can run docker run --rm -v /:/host alpine chroot /host sh to obtain an unrestricted root shell across the entire host in under a second.
  2. World-writable execution in /tmp, /var/tmp, and /dev/shm: Standard 1777 permissions allow any interactive user to drop binaries, spawn CPU forkbombs, or scan internal Docker bridge subnets unless mounted noexec.
  3. 0644 secret leakage and symlink escapes: Production .env files frequently retain 0644 permissions, exposing raw DSNs to cat or grep. Prefix-only path checks also break if a symlink inside an allowed directory points to /etc/shadow.

Rolling out the hardened wrapper onto modern Linux distributions running sudo-rs (the Rust sudo implementation) revealed two additional kernel/OS catches:

  • Defaults:mcp_ro !requiretty fails syntax validation under sudo-rs, which rejects legacy !requiretty directives.
  • sudo NOEXEC blocks child execve calls, causing #!/usr/bin/env python3 inside the helper script to fail with /usr/bin/env: 'python3': Permission denied. Meanwhile, control-panel vhost directories with 0700 permissions block mcp_ro traversal into readable Nginx configs.

2.2 The SSR 429 Trap and the ?skipCache=true Cache-Bypass Bomb

Live telemetry gathered via mcp_ro on an application server showed healthy CPU load (0.52 / 0.73 / 0.78) and 4.9 GiB / 19 GiB RAM used, with next-server holding 980 MB RSS, Swap: 0B, and Redis listening on 0.0.0.0:6379. Because every server-side render (SSR) call exited through one shared server IP (198.51.100.88), Nginx limit_req and Cloudflare WAF bucketed all real users’ page renders as a single abusive client and returned 429 Too Many Requests.

Disabling backend rate limiting globally to relieve SSR creates an immediate outage vector:

  • Public API routes honor ?skipCache=true (?skipCache=1). Dropping edge or proxy throttles lets external scrapers bypass Redis completely and saturate PostgreSQL / Prisma connection pools.
  • With Swap: 0B, any memory spike from uncached heavy queries or next-server worker bursts triggers the Linux OOM Killer with zero cushion.

2.3 Resource Tax of 5-VM Homelab Fragmentation

Moving persistent Linux stacks off Windows WSL2 (networkingMode=mirrored, which triggers :6080 hairpin NAT resets and :5433 loopback collisions) onto Proxmox VE with enterprise NVMe ZFS mirrors fixes host networking bugs. However, splitting a solo operator’s homelab into 5 VMs (vm-company, vm-personal, vm-mmo, vm-collab, lxc-edge) adds concrete overhead:

  • ~3–5 GB static RAM tax: Running four independent Linux kernels fragments database and ClickHouse page caches.
  • 4x AI harness synchronization friction: Splitting company and personal across hypervisor VM boundaries forces duplicate vector databases, SSH agents, and MCP tooling for the exact same user behind one keyboard, with zero meaningful security isolation gain.
  • The LXC + Docker trap: Running Docker inside unprivileged Proxmox LXC containers backed by ZFS frequently breaks overlay2 and AppArmor during host kernel upgrades.

3. Tier-1 Production Architecture

Instead of granting an interactive shell, authorized_keys enforces restrict,command="/usr/local/bin/mcp-ro-gatekeeper". Every SSH call passes through a closed parser (validateOpsWireCommand) accepting only <action> [base64url-json], canonicalizes paths with realpath to reject symlink escapes, and strips private keys, DSNs, and bearer tokens before capping payloads at 64 KiB (@kido/tenant-guard/ops-gatekeeper):

// Strict wire validation, symlink containment, and UTF-8 safe 64 KiB output cap
const WIRE_GRAMMAR_RE = /^([a-z_]{3,24})(?: ([A-Za-z0-9_-]{0,4096}))?$/;

export function capOutputBytes(text: string, maxBytes = 65_536): string {
  const buf = Buffer.from(text, 'utf8');
  if (buf.byteLength <= maxBytes) return text;
  const suffix = '\n...[truncated to 64 KiB]\n';
  let end = Math.max(0, maxBytes - Buffer.byteLength(suffix, 'utf8'));
  // Walk past UTF-8 continuation bytes (10xxxxxx) so multi-byte codepoints stay intact
  while (end > 0 && (buf[end] & 0xc0) === 0x80) end -= 1;
  return buf.subarray(0, end).toString('utf8') + suffix;
}

On the Linux host bootstrap, omitting !requiretty restores sudo-rs compatibility, pinning the absolute python3 binary satisfies sudo NOEXEC, and targeted ACLs unlock panel traversal without relaxing 0700 ownership globally:

# Resolve absolute interpreter path for sudo NOEXEC + minimal traversal ACLs
sed -i "1s|.*|#!$(command -v python3)|" /usr/local/libexec/mcp-ro-docker
setfacl -m u:mcp_ro:x /opt/panel /opt/panel/vhost
setfacl -R -m u:mcp_ro:rX /opt/panel/vhost/nginx /var/log/nginx

3.2 Isolating SSR Egress and Locking ?skipCache=true

Keep external rate limiting active for public clients and gate both rate-limit bypasses and ?skipCache=true evaluation behind explicit trusted-caller verification (evaluateCacheBypassAndSsrTrust):

export function evaluateCacheBypassAndSsrTrust(
  ctx: { clientIp: string; wantsSkipCache: boolean; isAuthenticatedAdmin?: boolean; internalBypassToken?: string },
  policy: { trustedSsrIps: ReadonlySet<string>; expectedInternalToken?: string }
) {
  const isTrustedInternal =
    policy.trustedSsrIps.has(ctx.clientIp) ||
    (Boolean(policy.expectedInternalToken) && ctx.internalBypassToken === policy.expectedInternalToken);

  if (isTrustedInternal) {
    return { bypassRateLimit: true, allowSkipCache: true, effectiveCacheBypass: ctx.wantsSkipCache };
  }
  if (ctx.isAuthenticatedAdmin) {
    return { bypassRateLimit: false, allowSkipCache: true, effectiveCacheBypass: ctx.wantsSkipCache };
  }
  // Public callers keep rate limits enforced and cannot trigger ?skipCache=true DB scans
  return { bypassRateLimit: false, allowSkipCache: false, effectiveCacheBypass: false };
}

At the deployment layer, setting SSR’s server-only API_URL to http://127.0.0.1:3106 (while keeping NEXT_PUBLIC_API_URL public for browsers) removes TLS/CDN hairpin latency (~20–50ms saved per render) and eliminates internal 429 throttling.

3.3 Trust-Boundary 3-Zone Proxmox VE Topology

flowchart TB
    WAN["Internet / Client Mesh"] --> LXC
    subgraph HOST["Dedicated Proxmox VE Host (ZFS NVMe Mirror + UPS)"]
        LXC["Zone 1: lxc-edge (LXC · 256MB RAM)<br/>Caddy · cloudflared · Tailscale Router (Zero Docker)"]
        CORE["Zone 2: vm-core (KVM · Trusted)<br/>Docker Compose: Apps + Runners + Observability + Qdrant"]
        SBX["Zone 3: vm-sandbox (KVM · VLAN Quarantined)<br/>Scrapers · Containerized noVNC · Partner SSH"]
    end
    LXC -->|"Allowed Routes"| CORE
    LXC -->|"Isolated DMZ"| SBX
    SBX -.->|"BLOCKED by Tailscale ACL / Firewall"| CORE
    EDGEBOX["Edge Workstation (Windows Native UIAutomation)"] -.->|"Mesh Sync"| CORE
Operational Metric Before Hardening Tier-1 Standard
mcp_ro Escalation Surface docker group (uid=0), readable 0644 .env, /tmp exec 0 write/exec surface (0555 home, NOEXEC, 64 KiB scrub, ~40–90ms ControlMaster)
SSR 429 & ?skipCache=true Exposure Shared-IP 429 storms; unauthenticated cache bypass 0% internal 429 (127.0.0.1 / 198.51.100.88 allowlist), 20–50ms faster SSR, 0% public bypass
Homelab Memory Footprint 4 separate Linux kernels wasting ~3–5 GB RAM + ZFS LXC breakages 3–5 GB RAM reclaimed via shared vm-core KVM page cache + 5s ZFS snapshots on vm-sandbox

Operational Takeaways

Three production invariants anchor both host security and infrastructure sizing:

  1. Enforce remote diagnostics least privilege across all four layers (0555 home outside docker, SSH restrict,command=, sudo NOEXEC with an absolute Python shebang, and 64 KiB secret redaction).
  2. Route or allowlist SSR egress separately from public rate-limit buckets and strip ?skipCache=true from unauthenticated requests instead of disabling throttles globally.
  3. Partition virtualization by actual trust boundary (lxc-edge native binaries, vm-core trusted KVM Docker stacks, vm-sandbox VLAN-quarantined KVM) to maximize shared page cache and avoid Docker-in-LXC ZFS failures.
🎭
Kido Chronicles Flywheel

Read the Companion Manga & Dev War-Story Edition on Kido Chronicles

Looking for the real-world production incidents, late-night debugging war stories, and illustrated manga episodes behind this architecture? Explore the companion chapters below:

Explore all 164+ chapters at truyen.khanhdp.comExplore Manga Universe ↗
🔬

Related Architecture Monographs

More in Security, Auth & Access Control ↗
The Fallacy of Single-Host Patroni HA, pgBackRest PITR Reality, and Constant-Time Webhook Cryptographic Hardening
Security, Auth & Access Control
Nov 11, 2026•16 min read

The Fallacy of Single-Host Patroni HA, pgBackRest PITR Reality, and Constant-Time Webhook Cryptographic Hardening

A deep-dive into database architecture and application security: dissecting the 'Cargo Cult HA' anti-pattern of packing etcd Raft and Patroni into a single constrained VPS, mathematically proving OOM crash risks and WAN consensus latency degradation, establishing the production standard of PostgreSQL 18 + pgBackRest PITR, and remediating 4 critical P0 vulnerabilities (Command Injection, Webhook Fail-Open, and process.env pollution) via constant-time defenses.

Multi-Temporal Tenancy & The 4-Layer Timezone Shield (Duolingo-Grade Architecture): Navigating Asia/Saigon ICU Traps, Cloudflare IP Spoofing, and Rolling Timezone Bucket Sweeps
Security, Auth & Access Control
Oct 15, 2026•14 min read

Multi-Temporal Tenancy & The 4-Layer Timezone Shield (Duolingo-Grade Architecture): Navigating Asia/Saigon ICU Traps, Cloudflare IP Spoofing, and Rolling Timezone Bucket Sweeps

Architectural analysis of global multi-timezone systems (Multi-Temporal Tenancy): Resolving Node.js ICU timezone traps, defeating Cloudflare IP header spoofing, and implementing O(1) rolling timezone bucket sweeps to eliminate midnight database thundering herds.

🎭Chronicles:Ep 87, Ep 128, Ep 129, Ep 130, Ep 131
Author & Systems ArchitectDa Nang, Vietnam

(Dương Phúc Khánh · Kido)

Senior Software Engineer & Systems Architect with 9+ years of experience in high-concurrency distributed architectures, Google Core Web Vitals optimization (0ms TBT, CLS 0.000), and author of the 164+ episode engineering war-story series Kido Chronicles.

⚡ Enterprise Architecture & Turnkey B2B Systems

Need High-Concurrency System Architecture Consulting, AI Automation, or Turnkey B2B Software?

Explore 41 production infrastructure packages (kido-packages (@kido/*)) and 18 turnkey B2B Web App/ERP systems with 100% source code ownership architected by (Dương Phúc Khánh · Kido).

Tags:#Zero Trust#Linux Security#SSH Gatekeeper#Rate Limiting#Proxmox VE#Infrastructure