When you build a self-hosted PaaS, nearly everything important travels over SSH.
Bootstrapping Docker. Uploading a Compose file. Streaming a backup archive. Cancelling a build that took too long.
Early on, it is tempting to wrap ssh2 in a small helper:
conn.exec(command, (err, stream) => { // collect stdout and stderr }); That abstraction holds until the first time a user clicks Cancel during a slow docker compose build, or a command hangs inside a broken container, or a file write touches a symlinked directory on the remote host.
Closing the SSH channel does not necessarily stop the remote process tree.
These problems shaped the SSH executor and managed-file scripts in Nitrobase.
Nitrobase has only recently launched and is still in Beta. SSH automation still relies on trusted server credentials and OS behavior, so the executor focuses on making cancellation, host verification, and remote file writes predictable rather than pretending SSH is a sandbox.
OpenSSH does not always honor channel signals
The SSH protocol includes a signal message so a client can ask the server to send SIGTERM or SIGKILL to the command running inside a channel.
In practice, that mechanism has two sharp edges:
- OpenSSH refuses channel signal requests on
rootsessions ("requires privilege separation") or ignores them depending on server configuration and subsystem. - Closing the client stream leaves grandchildren running if a shell spawned a build,
docker, or backup pipeline without process-group coordination.
If the panel reports "Job cancelled" while docker build continues consuming CPU and disk on the VPS for another ten minutes, the control plane and the server are now out of sync.
Tagging the command so another channel can find the tree
Nitrobase handles remote timeouts and cancellation from two angles in withRemoteTimeout() and SshExecutor:
Channel 1 (command): exec timeout --kill-after=10s 300s sh -c ': nitrobase-job-<tag>; <command>' Cancel / Timeout fires: | +--> Channel 2 (signal): pkill -TERM -f nitrobase-job-<tag> | | | +--> grace period expires? --> pkill -KILL -f nitrobase-job-<tag> | +--> stream.resume() if paused for backpressure Three small details make this reliable in practice:
- In-shell GNU
timeout: Wrapping the command intimeout --kill-after=10splaces the job in a process group that cleanly signals child processes when the deadline expires, with a local Slack timer as a fallback iftimeoutis missing on the host. - An innocuous
argvmarker (: nitrobase-job-<tag>;): The colon built-in in POSIXshis a no-op, yet the tag remains embedded in thesh -cprocess arguments. If a user aborts the job, Nitrobase opens a second channel on the same SSH connection and runspkill -TERM -f(thenKILLafter a grace window) targeting that exact run's unique tag. - Unblocking paused streams on abort: When streaming large binary outputs like backups, backpressure may pause the SSH channel (
stream.pause()). On cancellation,SshExecutorcallschannel.resume()so a blocked remote writer isn't stuck waiting on full buffers whenSIGTERMarrives.
The shell itself stays POSIX-quoted (shellQuote) and job tags are strictly validated ([a-z0-9]{8,32}) so the marker can never expand into another command.
Writing remote files without following symlinks
Uploading a .env or compose.yml file over SSH often gets written as:
cat > /etc/nitrobase/apps/my-app/compose.yml That breaks silently in three ways:
- If a parent directory or the target file was replaced by a symlink pointing to
/etc/passwdor another application's directory,cat >follows the symlink and overwrites the target outside/etc/nitrobase. - If the SSH connection drops mid-stream, the target file is left half-written.
- Leading or trailing whitespace in read files gets stripped if you simply
.trim()command stdout.
Nitrobase uploads and reads managed files through managedWriteScript() and managedReadScript() restricted strictly to /etc/nitrobase/:
stdin bytes | v 1. assertManagedPath() reject "..", relative paths, outside /etc/nitrobase/ | v 2. realpath -m "$dir" refuse if any parent component is a symlink | v 3. mkdir -p && realpath -e re-verify resolved directory still matches | v 4. mktemp -> cat -> chmod write safely to a temp file in the same dir | v 5. mv -fT "$tmp" "$target" atomic swap; -T replaces target symlink instead of following Look closely at step 5 (mv -fT): without -T, if $target happens to be a symlink to a directory, mv moves the temp file inside that directory instead of replacing the path itself. And on reads, managedReadScript() verifies realpath -e equals the path, checks -f (regular file), and outputs base64 so every trailing newline survives stdout trimming intact.
Host key verification is not () => true
Many SSH client examples include one fatal shortcut:
// Silent MITM vulnerability hostVerifier: () => true Disabling host-key checks turns every automated deployment into an unauthenticated connection vulnerable to man-in-the-middle interception—even if the VPS was reprovisioned cleanly with a brand new identity that the administrator expects to verify.
Nitrobase uses Trust On First Use (TOFU) via openClient():
- On the very first connection to a new server (
expectedabsent),hostVerifiercomputes the SHA-256 fingerprint and persists it viaonFirstSeenbefore resolving the connection as ready. - Every subsequent command, test, or shell session compares the observed key against the stored fingerprint.
- If a VPS key unexpectedly changes, Nitrobase throws
HostKeyMismatchErrorand refuses the connection instead of silently trusting the new key.
One SSH connection per job, with clean UTF-8 and flow control
Opening a fresh SSH TCP handshake and key exchange for every small docker inspect or mkdir call slows down deployments and triggers MaxStartups rate limits on OpenSSH.
SshExecutor lazily opens one SSH connection per job, reuses it across channels (exec, upload, readFile), clears the cached promise immediately on close so the next step reconnects if dropped, and pairs each stream with:
-
StringDecoder("utf8"): Prevents multibyte UTF-8 log characters from splitting into replacement characters across TCP packet boundaries. - Explicit flow control (
onFlowControl): Exposespause()andresume()hooks to callers like streaming backups, keeping memory flat when the S3 or disk sink is slower than the VPS network interface.
What an SSH executor still assumes
An executor guarantees how Nitrobase sends commands, cancels them, writes files under /etc/nitrobase, and checks host keys.
It does not restrict what commands are valid once authenticated as the SSH user—if an attacker compromises the control plane database and encryption key, or already holds root on the VPS, host-key pinning and managedWriteScript cannot prevent deliberate misuse. Security at that layer still depends on protecting the control plane and VPS credentials.
My checklist for running remote commands over SSH
Before trusting an automated SSH execution layer in production, these are the edge cases I check:
- [ ] Are host keys verified against a stored SHA-256 fingerprint instead of accepting every key?
- [ ] Does job cancellation terminate grandchildren on the VPS rather than just closing the local socket?
- [ ] Is there a fallback timeout inside the remote host in case network connectivity drops mid-command?
- [ ] Are remote file paths normalized and checked with
realpathto prevent symlink escapes? - [ ] Are remote file writes staged to a temp file and atomically swapped with
mv -T? - [ ] Do long binary streams expose
pause()/resume()backpressure so large backups don't OOM the server? - [ ] Are UTF-8 log streams decoded with a stateful decoder across packet boundaries?
Running conn.exec("docker compose up -d") works on day one. Handling timeouts, symlinks, cancellation, and MITM protection is what turns an SSH wrapper into infrastructure software.
Nitrobase source code: https://github.com/AydenGroup/nitrobase
