SugarSshServer
SSH server middleware framework
Build TUIs anyone can ssh user@host to run. Leans on the host's OpenSSH daemon (ForceCommand) rather than re-implementing the SSH wire protocol. sshd handles auth, ciphers, host keys, audit logs; blocking brute-forcers stays fail2ban's separate job.
Install
composer require sugarcraft/sugar-ssh-server
Two transports
What the supervisor PHP process does internally is pluggable via the Transport abstraction:
- InProcessTransport (default). Allocates a sugar-pty master/slave pair, spawns the user's cmd as a subprocess with full controlling-terminal semantics (Ctrl+C → SIGINT, SIGWINCH-driven resize, job control), pumps bytes between the supervisor's STDIN/STDOUT and the sugar-pty master. Terminal middleware:
Spawn. - HostSshdTransport (legacy, opt-in). Pre-PTY-upgrade architecture: middleware run inline in the supervisor; the terminal middleware (
BubbleTea) mounts a SugarCraftProgramdirectly on the supervisor's STDIN/STDOUT. Pin viaServer::withTransport(new HostSshdTransport()). Use this for inline-STDIN-reading middleware or zero-subprocess Program mounts.
Quickstart — in-process bash
// /opt/wish/server.php — invoked by sshd ForceCommand
require '/opt/wish/vendor/autoload.php';
use SugarCraft\SshServer\Server;
use SugarCraft\SshServer\Middleware\{Logger, Auth, Spawn};
use SugarCraft\SshServer\Session;
exit(Server::new()
->use(Logger::toFile('/var/log/wish.jsonl'))
->use(new Auth(users: ['wishuser']))
->use(new Spawn(fn (Session $s) => [
'cmd' => ['/bin/bash', '-l'],
'env' => [
'TERM' => $s->term, 'USER' => $s->user, 'HOME' => "/home/{$s->user}",
'PATH' => '/usr/local/bin:/usr/bin:/bin',
],
]))
->serve());
Quickstart — host-sshd legacy
use SugarCraft\SshServer\Transport\HostSshdTransport;
use SugarCraft\SshServer\Middleware\BubbleTea;
exit(Server::new()
->withTransport(new HostSshdTransport())
->use(Logger::toFile('/var/log/wish.jsonl'))
->use(new Auth(users: ['wishuser']))
->use(new BubbleTea(fn($session) => new MyApp($session)))
->serve());
The wishuser in both Auth allowlists is what the sshd Match block makes true: under ForceCommand the entry script runs as the target account, so $s->user is that account on every connection, and an allowlist of human names refuses 100% of logins with exit Server::EXIT_DENIED. Per-user separation needs per-user Match blocks or authorized_keys command= entries, each running its own entry script.
What's in the box
Middleware::handle(Context $ctx, Session $session, callable $next): void.Source & demos
- Source on GitHub
- Full README
- Runnable examples
- Originally inspired by wish (Go); SugarCraft is developed as a native PHP project.
API
| Class | Method | Description |
|---|---|---|
| Server | new() | Start an empty middleware pipeline — this library opens no listener: the pipeline runs inside the process sshd (or your supervisor) spawns under ForceCommand |
| Server | use(Middleware) | Add middleware to the pipeline |
| Server | withTransport(Transport) | Override the active transport (default: InProcessTransport) |
| Server | withKeepalive(int) | Add keepalive middleware with the given interval |
| Server | serve(?Session, ?Context) | Start the server (builds a fresh root Context::background() automatically when none is passed; supply a cancellable context to make cancel-propagation reachable through the public API) |
| Context | background() | Root context — never done, not cancelable |
| Context | withValue(string $k, mixed $v) | Return a new context with $k → $v attached |
| Context | withDeadline(DateTimeImmutable) | Return a new cancelable context that is done when deadline passes |
| Context | withCancelable() | Return a new cancelable context (call cancel() to trigger) |
| Context | cancel(?Throwable) | Mark the context as canceled |
| Context | done(): bool | True when canceled or deadline-exceeded |
| Context | err(): ?Throwable | CancellationException, DeadlineExceededException, or null |
| Context | value(string $k): mixed | Walk parent chain looking for $k; null if not found |
| Session | user, term, cols, rows, clientHost, clientPort, serverHost, serverPort, tty, command, lang, sessionId, authMethod, keyFingerprint, clientVersion, serverVersion | Session metadata. The last five are filled in by withProtocolMetadata() and are honest only so far as the environment is: sessionId is minted per process, authMethod is sniffed from SSH_USER_AUTH, keyFingerprint is always null today, and the two version fields read names stock OpenSSH never exports. |
| Session | withProtocolMetadata(?string $sessionId, ?string $authMethod, ?string $keyFingerprint, ?string $clientVersion, ?string $serverVersion): self | Return a new Session with protocol metadata attached. Nothing negotiates it over a wire: this library does not speak SSH, and InProcessTransport::run() calls it once with locally derived values (fresh random id, method sniffed from the environment, fingerprint hard-wired to null). |
| Session | isInteractive(): bool | True when a TTY is attached |
| Session | toLogContext(): array | Array of session fields for logging |
| Session | markRefused() · refused(): bool | The refusal latch every bundled gate closes (Auth, PasswordAuth, KeyboardInteractive, CertificateAuth, RateLimit, DispatchesMiddlewareStack): mark once at the deny site and do not call $next. One-way — a refused session stays refused. |
| Session | exitStatus(): ?int · recordExitStatus(int): void | The child's exit code once a spawner has run one, else null. Reading belongs to anyone; writing belongs to transports. |
| Session | withSize(int $cols, int $rows): self | Immutable clone carrying new dimensions — the resize door DefaultChannelHandler walks through; it has nothing to do with the exit path. |
| Server | EXIT_DENIED = 129 · resolveStatus(Session): int | The single exit-status contract both transports resolve through: a recorded child status wins, else a refused session leaves 129, else 0. A ForceCommand entry script hands it to exit() so the SSH client sees the real code. |
| Middleware | handle(Context, Session, callable): void|PromiseInterface | All middleware receive Context first, Session second; may return void (sync) or PromiseInterface (async — transport awaits before continuing chain) |
| AsyncMiddleware | extends Middleware | Abstract base for promise-returning middleware — override handleAsync() to perform async I/O (LDAP, OAuth, database auth); the transport settles the promise through PromiseAwait, which enforces a 30-second ceiling and ends its own loop spin at the decision — do not await from inside a loop you already run |
| Spawn | new(callable) | Terminal middleware for subprocess spawning (InProcess only) |
| BubbleTea | new(callable(Session): object) | Terminal middleware for Program mount (HostSshd only). The factory's return must expose a run() method; any other value raises RuntimeException with the Lang key bubbletea.bad_factory at handle time. |
| Auth | new(array $users, array $keyFingerprints, ?resource $stderr, ?callable $fingerprintValidator, array $userKeys) | Allowlist gate. users and keyFingerprints are independent (a cross product, not a pairing) — bob with alice's key is admitted as alice. userKeys (name => that name's keys, or [Auth::ANY_KEY]) is the authoritative pairing. Empty lists arm nothing. |
| PasswordAuth | new(callable, ?resource) | Validates (user, password) against a callback. Wrapper-only. The password arrives through SSH_PASSWORD, which this repo does not set. It is expected to reach the process from a wrapper that exports it, or from a client-supplied value an operator lets through with AcceptEnv SSH_PASSWORD; that value is peer-asserted rather than proven. Whether sshd's ForceCommand path exports it is unverified against OpenSSH. The gate does not authenticate the peer by itself. A session that delivered no variable at all is refused before the callback runs; an explicitly empty one still reaches it. |
| CertificateAuth | new(callable, bool $required = true, $stderr = null) | Reads a client certificate from CertificateAuth::ENV_KEYS (nothing in stock OpenSSH exports them — your wrapper must). Refuses when $required and announces “checked nothing” on either path, so a silent no-op cannot masquerade as a gate. |
| AuthMethods | new(list<string>, ?resource, bool $announce = false) | Stores the declared list in the Context for your own middleware to read. The SSH_AUTH_METHODS publickey,password line on STDOUT is opt-in and off by default: under ForceCommand that stream is the client's data channel, so the line is text in the user's terminal. It is not an RFC 4252 banner (sshd finished authenticating before this process started) and not an auth gate; use sshd's own Banner= for a message users must see. |
| KeyboardInteractive | new(list<array{prompt:string,echo?:bool}|string>, ?callable $validate = null, string $name = '', string $instruction = '', $stdout = null, $stdin = null, $stderr = null) | A bare-string element is a challenge with echo: true; any other shape is refused with InvalidArgumentException. Prints each prompt (and the literal echo flag) to the supervisor's STDOUT and reads a line back from STDIN. That is the whole mechanism: it is not RFC 4256 — no SSH messages are involved, and under HostSshdTransport you get sshd's own keyboard-interactive instead. Echo is a label, not terminal state: input is not hidden (the exchange announces that once when any prompt asks for silence), each answer is capped at MAX_RESPONSE_BYTES, there is no built-in deadline, and without $validate any answer passes. |
| Subsystem | new() | Terminal — parses subsystem <name> from Session::command, dispatches to registered SubsystemHandler; non-subsystem requests pass through to $next |
| SubsystemHandler | handle(Context, Session): void | Interface — implement to handle a named subsystem request |
| SftpStub | new() | Example SubsystemHandler impl — stub demonstrating wiring; not a real SFTP server |
| RateLimit | new(string $statePath, int $burst = 5, float $ratePerSec = 0.5, $stderr = null, bool $failClosed = false, ?int $userBurst = null, ?float $userRatePerSec = null) | Per-IP token bucket (optionally a second per-username bucket). State publishes through an atomic rename behind an exclusive lock on a stable <state-path>.lock sidecar; idle refilled buckets are pruned on every publish. A state error fails open unless failClosed: true. penalize() exists but nothing calls it — wire it yourself after a failed login. |
| Logger | new(string|resource|null) · auto() · toFile() · toStream() · toStderr() · target() | One-line JSON session records. Sink resolution: $SSH_SERVER_LOG when set, else stderr — which under ForceCommand is the connecting client's channel, not journald. Files created here are 0600; an existing file keeps its mode. |
| Keepalive | new(int $intervalSeconds = 60) | When the pump loop idles past the interval, writes a NUL byte to the child's stdin through the PTY master. It is not an SSH-level keepalive: it is a no-op under HostSshdTransport (sshd's own ClientAliveInterval covers that path), and a raw-mode TUI never echoes it, so nothing reaches the wire. Use it to keep a NAT mapping warm in front of a line-oriented shell, not to detect a dead client. |
| Transport | interface — run(Context, Session, array $stack): int | What withTransport() swaps: receives the fully ordered middleware stack and returns the session's exit status. Two implementations ship: InProcessTransport (default) and HostSshdTransport (legacy). |
| Transport\ChildSpawner | interface — runChild(Session, array $cmd, ?array $env = null): int · signalChild(int): void | The two-method pair Spawn type-hints — the narrow contract a transport satisfies for terminal middleware. signalChild() forwards every mapped SignalMsg (SIGWINCH resizes included) to the live child; it is a no-op when no child runs, and delivery falls back to libc kill(2) over FFI rather than ext-posix. A custom spawner written from runChild alone fails at class load — implement both. |
| TransportAware | interface — setTransport(ChildSpawner): void | Middleware that needs the transport implements this. The transport calls setTransport() on every aware middleware at walk time, before the first handle(); implementations must tolerate being called twice because a Server object is reused across sessions. |
| InProcessTransport | new(?PtySystem $system = null) | Default transport — PTY supervisor on sugar-pty. The handler is a setter, not a constructor argument: call setChannelHandler(ChannelHandler $handler) (passing a second constructor argument is silently ignored by PHP and the default handler keeps running). Also exposes withSizeProvider(), setKeepaliveCallback() and pty(). |
| HostSshdTransport | new() | Legacy transport — inline middleware, Program on STDIN/STDOUT |
| ChannelHandler | handlePtyReq / handleWindowChange / handleShell / handleExec / handleSignal / handleEnv / handleBreak | Interface for custom channel-level message handling (InProcessTransport only). Only WindowChangeMsg is produced by the library today — from a SIGWINCH; the other six are dispatched by your own code, not by the wire. |
| ChannelMsg | abstract base | Base for all SSH channel messages (RFC 4254) |
| DefaultChannelHandler | new(?ChildSpawner, ?Session, array $acceptEnv, ?string $shell, array $allowedExec, mixed $execGate, $stderr) | Default impl — tracks PTY dims, env vars, drives ChildSpawner on shell/exec. Exec is default-closed: the peer names the program, so nothing spawns unless $allowedExec holds that exact path and the optional $execGate returns exactly true. The gate is typed mixed on purpose: it is meant to be callable|null, and a value that is neither raises internally and is treated as a refusal (catch-Throwable fail-closed), never a fatal or an approval. decodeCommandString() is the public quoting tokenizer (no shell, no expansion, no globbing) and is also the right entry point for SSH_ORIGINAL_COMMAND. |
| PtyReqMsg | wantPty, term, cols, rows, widthPx, heightPx | PTY allocation request |
| WindowChangeMsg | cols, rows, widthPx, heightPx | Terminal resize (SIGWINCH equivalent) |
| ShellMsg | wantShell, subsystem | Login-shell request |
| ExecMsg | command | Exec request — raw command string |
| SignalMsg | signalName | Signal delivery (SIGINT, SIGTERM, etc.) |
| EnvMsg | name, value | Environment variable request |
| BreakMsg | breakLengthMs | Break request — duration in milliseconds (int, defaults to 0) |
| CancellationException | extends RuntimeException | Thrown when Context is canceled |
| DeadlineExceededException | extends RuntimeException | Thrown when Context deadline passes |
Demos.
VHS-recorded GIFs of the flagship examples — showcase (the middleware-stack tour) and spawn-bash (interactive bash through Spawn) — regenerated automatically on every push that touches the source. The remaining examples are plain CLI scripts without a tape.
Middleware pipeline
Logger → RateLimit → hello against a synthetic Session.
Spawn bash (in-process)
InProcessTransport spawning/bin/bash -l via sugar-pty. Inner shell runs echo / uname / stty size / exit.