# SPEC: scorpiox-scorpioplayer-ssh-transport-client (row 49)

An SSH-2 **client** transport in pure C99 for SCORPIO PLAYER 2027. It opens a TCP
connection, performs version exchange and key exchange, **verifies the server host key
against a caller-pinned fingerprint (TOFU)**, authenticates, and opens `session`
channels for `subsystem` (row 41 `sftp-file-client` plugs in here) and `exec`. It is the
client twin of row 48 `scorpiox-scorpioplayer-ssh-transport-server` (`spsshs`), which
shipped v1.0.1 on 2026-09-30.

Written **spec-first**. The implementation followed this document, and the numbered
decisions below are what the tests check.

## 0. What the legacy code says (code-as-spec)

The client-side spec comes from four corpora. All of them are **client-only** and all use
`Renci.SshNet.2020` 1.0.0 (`tplayer/TPlayer/TPlayer.csproj:1644`).

| Legacy fact | Where | Consequence here |
|---|---|---|
| Password auth only — `new PasswordAuthenticationMethod(username, password)` wrapped in `ConnectionInfo` | `bosxixi.toolkit20/Handlers/SFTPRuntimeConfigHandler.cs:26-29, 83-85`; `tplayer/TPlayer/ContentDialogs/SftpDialog.xaml.cs:152-154`; `tplayer/TPlayer/Views/Pane.cs:597-599` | `spsshc_auth_password` is first-class. But `keyboard-interactive` must also work because many NAS (Synology DSM, QNAP) refuse plain `password` on newer OpenSSH — legacy code silently failed there |
| 🔴 **No host-key check** — no `HostKeyReceived` handler anywhere in tplayer / toolkit / toolkit20 / IOSLegacy / Platform | `git grep HostKeyReceived` across all corpora = 0 hits | 🔴 Our client **must** verify. `connect` returns the SHA256 fingerprint; the caller pins it on the next call; mismatch → hard error `HOSTKEY_CHANGED` (D2). This closes the legacy MITM hole |
| Legacy port validation off by one: `mport > 0 && mport < 65535` rejects port 65535 | `SFTPRuntimeConfigHandler.cs:22`, `SftpDialog.xaml.cs:147-148`, `Pane.cs:592-593` | We accept `1..65535`. The off-by-one is not copied |
| Empty host name proceeds to `new ConnectionInfo(...)` and throws deep inside Renci | `SFTPRuntimeConfigHandler.cs:15-26` (guard is only on the outer `hostname.IsNotEmptyItems()` in one path) | Empty/NULL host refused immediately at the API boundary with `E_ARG` |
| Directory listing hides dot-files (`!c.Name.StartsWith(".")`) and splits files vs folders | `SFTPPlayListFolder.cs:53,68`, `Class1.cs:689,709` | Not a transport concern — that policy belongs to row 41, which vendors this repo |
| 🔴 `SFTPFolderFileAccesssor.ContentSource => ContentSource.Smb` (wrong enum) | `tplayer/bosxixi.Toolkit14/Class1.cs:667` | Recorded in row 26. Not a transport concern |
| No reconnect logic anywhere — a dropped connection just throws and the folder goes dead until the app is restarted | All corpora | `spsshc_reconnect()` reconnect + re-auth helper (D9) |
| Exec is only used by the AI SSH chat feature | `Platform/Platform.Shared/Services/AISSHService.cs:152` `sshClient.CreateCommand(command); cmd.CommandTimeout = 5 min; cmd.Execute()` → `ExitStatus`, `Result`, `Error` | `spsshc_exec` returns exit status and fills stdout/stderr buffers, with caller timeout and output cap (5 min timeout is too long — we default 30 s, caller overrides) |
| AI SSH feature passes whatever the LLM generated straight into `CreateCommand` | `AISSHPageViewModel.cs:179` | ☢️ We add `spsshc_exec_argv(argv, argc)` which quotes each element for a POSIX shell (D8). **The client never builds a command from untrusted input by string concatenation.** Documented limitation: the remote side may still be a shell |
| No keep-alive — Renci has a background heartbeat but nothing the caller controls | All corpora | `spsshc_keepalive(interval_s)` sends `keepalive@openssh.com` global requests |

So the protocol behaviour is specified by RFC 4253 (transport), RFC 4252 (auth), RFC 4254
(connection), RFC 8308 (ext-info), OpenSSH PROTOCOL.chacha20poly1305 / kex-strict, and the
**oracles** are real servers (§9).

## 1. Scope / non-goals

- **In:** RFC 4253 transport + re-key + strict KEX; RFC 4252 `none`/`password`/`publickey`/`keyboard-interactive`; RFC 8308 `ext-info-c` + `server-sig-algs` parsing; RFC 4254 `session` channels with window/flow control, `EOF`/`CLOSE`, `exit-status`/`exit-signal`; `subsystem` open with a duplex read/write handle; `exec` with stdout/stderr/exit-status, timeout and output cap; keep-alive; reconnect helper.
- **Out:** `shell`, `pty-req`, `x11-req`, `env`, agent forwarding, `direct-tcpip`/`forwarded-tcpip`/`tcpip-forward` (the client *refuses to request* these — no PTY, no forwarding), compression (we never offer it), `ssh-rsa` (SHA-1) signature algorithms, DSA, ECDSA, CBC ciphers, SHA-1 MACs, `diffie-hellman-group1/14-sha1`, `diffie-hellman-group-exchange-*`, SSH-1.
- **No file operations** in this engine. Read-only. `subsystem` returns a duplex data handle; SFTP protocol itself is row 41's job.

## 2. Algorithms (offered in this order)

| Kind | Client offer (required first) | Also (old NAS compat: Synology DSM 6, QNAP, old dropbear) |
|---|---|---|
| KEX | `curve25519-sha256`, `curve25519-sha256@libssh.org` | `diffie-hellman-group14-sha256`, `diffie-hellman-group16-sha512` |
| Host key | `ssh-ed25519` | `rsa-sha2-256`, `rsa-sha2-512` (**verify only**; the server may offer an RSA host key only if the caller supplies one) |
| Cipher | `chacha20-poly1305@openssh.com` | `aes128-ctr`, `aes256-ctr`, `aes128-gcm@openssh.com`, `aes256-gcm@openssh.com` |
| MAC | (AEAD) | `hmac-sha2-256-etm@openssh.com`, `hmac-sha2-256` |
| Compression | `none` | — |

Extensions: `ext-info-c` is offered so we can learn `server-sig-algs` (RFC 8308);
`kex-strict-c-v00@openssh.com` + `kex-strict-s-v00@openssh.com` are **required on both
sides** — if the server does not echo strict support we still enforce strict rules on our
side (we never weaken; a server that refuses is fine, one that ignores the marker but
behaves loose is still safe because we enforce our own gate).

Negotiation follows RFC 4253 §7.1: the first **server** algorithm that we also support
wins (client preference order applies server-side; from the client side we accept the
server's first entry that appears in our list — same result either way, and the server
row-48 does exactly this so the pair always agrees). `first_kex_packet_follows` guess is
honoured: a wrong guess means the next KEX packet is ignored.

**Crypto, all zero-dep:** vendored **Monocypher 4.0.2** (`vendor/monocypher/`: X25519,
Ed25519 via `monocypher-ed25519`, SHA-512, ChaCha20-DJB, Poly1305, wipe) — **byte-identical
copy of the row 48 server's vendored copy** (`monocypher.c` md5 `f17984a6…`, verified with
`md5sum` both sides). In-tree `src/crypto.c` is the **byte-identical copy** of the server's
(md5 `1af3cbac…`) providing SHA-256, HMAC-SHA-256, AES-128/256 with CTR and GCM, a
Montgomery bignum (constant-time conditional select, up to 8320 bits) and RSA PKCS#1 v1.5
(sign + verify). KATs run in `spsshc_selftest()`. Randomness from `/dev/urandom` or
`BCryptGenRandom`. **No OpenSSL, libssh, libssh2.**

## 3. Decisions

- **D1 Connect.** `spsshc_connect(host, port, pinned_fp, timeout_ms)`. DNS resolution is
  allowed for the host (the legacy SFTP dialog takes a hostname), but a numeric IP is
  always accepted. Port must be `1..65535` (the legacy off-by-one `port < 65535` is NOT
  copied). Port 0 is refused. `timeout_ms` budgets the whole connect+banner+KEX phase.
- **D2 Host-key TOFU pinning.** `connect` always reports the peer's SHA256 fingerprint via
  `spsshc_host_fingerprint()`. If `pinned_fp` is non-empty and does **not** equal the
  peer's fingerprint → hard `SPSSHC_E_HOSTKEY` with "HOSTKEY_CHANGED: ..." and the
  connection is torn down **before** auth or any channel traffic. If pinned is NULL/empty
  → TOFU: connect succeeds and the caller stores the fingerprint for next time. A pinned
  value with wrong format (no `SHA256:` prefix) is an argument error. **This is the 🔴 P0
  the legacy code never had.**
- **D3 Version exchange.** We send `SSH-2.0-spsshc_1.0`. We accept the server's ident up
  to 255 bytes after up to 32 pre-banner lines. `SSH-1.x` from the server → disconnect
  (protocol error). NUL in the server ident → disconnect.
- **D4 Packets.** Same framing rules as the server (row 48 D4): `5 ≤ L ≤ 256 KiB`, block
  alignment (8 for none/chacha, 16 for AES; length excluded for AEAD/EtM), `padding_length
  ≥ 4`, MAC/tag verified **before** payload decrypt (chacha, GCM, EtM), first-block
  decrypt for CTR+E&M to read the length. Any violation → `DISCONNECT 2/5` and the
  connection is dead.
- **D5 Strict KEX (Terrapin, CVE-2023-48795).** We always offer
  `kex-strict-c-v00@openssh.com` in the first KEXINIT. Rules we enforce on our side:
  (a) our KEXINIT is our packet 0; (b) any non-KEX message from the peer before the first
  NEWKEYS disconnects (including IGNORE/DEBUG); (c) both sequence numbers reset to 0 at
  each NEWKEYS. If the server offers `kex-strict-s-v00@openssh.com` we know it is safe;
  if it does not, we still enforce our own gate (we never weaken).
- **D6 Channels.** Only `session` channels. Up to 8 concurrent per connection. The local
  window is 2 MiB, max packet 32 KiB; we re-open the window when it drops below half.
  Peer data beyond our window → disconnect. Output respects the peer's window and max
  packet.
- **D7 Auth order.** The caller drives auth explicitly: `password` →
  `keyboard-interactive` → `publickey` is the recommended retry ladder in the CLI. No
  automatic fallback inside the engine beyond: after `password` is refused, the engine
  offers `keyboard-interactive` (answering every prompt with the password) **automatically
  once** inside `spsshc_auth_password`, because Synology DSM 6 / QNAP refuse plain
  `password` but accept keyboard-interactive with the same secret. If that also fails,
  `E_AUTH` with the server's failure names in `last_error()`.
- **D8 Exec + argv quoting.** `spsshc_exec(ch, cmd, ...)` sends the command string
  verbatim. `spsshc_exec_argv(argv, argc, ...)` builds the string by quoting each element
  with POSIX single-quote escaping (`'` → `'\''`), joining with spaces — **the client
  never builds a command from untrusted input by string concatenation**. Documented
  limitation: the remote side may still be a shell (server row-48 runs execve with no
  shell; a real sshd runs the user's shell). The quoted string is capped at 4096 B to
  match the server's `MAX_CMD_LEN`; a single element containing NUL is refused
  (`EXEC_ARGV_NUL`), a quoted total over the cap is refused (`EXEC_ARGV_LONG`).
  `spsshc_exec_argv_quote(arg, out, cap)` is the single-element primitive.
- **D9 Reconnect.** `spsshc_reconnect()` redials the last host:port with the same pin and
  re-runs the last successful auth (password or key or keyboard-interactive), reusing the
  stored credentials. It never silently retries more than once per call. If the stored pin
  mismatches on redial → same `HOSTKEY_CHANGED` hard error as D2.
- **D10 Re-key.** The client answers server-initiated re-keys (KEXINIT arriving while
  connected) at any time, and initiates its own after 1 GiB in either direction or 1 h
  (`spsshc_set_timeouts` rekey param, 0 = off). While our KEXINIT is outstanding, non-KEX
  output is held and flushed after our NEWKEYS (RFC 4253 §7.1), mirroring the server.
- **D11 Limits.** Output cap default 16 MiB per exec (stdout+stderr combined), exec
  timeout default 30 s (legacy AI SSH used 5 min — too long; caller overrides per call).
  Read buffer caps mirror the server: packet ≤ 256 KiB, name-list ≤ 4096, user ≤ 64,
  password ≤ 256.
- **D12 Threading.** One reader thread per connection feeding an in-queue; API calls
  serialize behind one mutex. The API is a **process singleton**, like rows 30/32/34/36/48.
- **D13 Keep-alive.** `spsshc_keepalive(interval_s)` schedules `keepalive@openssh.com`
  global requests (want_reply=0, fire-and-forget, matching what OpenSSH clients do); if
  the socket is dead the next API call reports the transport failure. 0 disables.

## 4. State machine (per connection)

```
CLOSED ──connect──▶ VERSION ──ident──▶ KEX0 ──NEWKEYS──▶ NEED_SERVICE ──ssh-userauth──▶ AUTH
AUTH ──success──▶ CONNECTED ──(KEXINIT either side)──▶ REKEY ──NEWKEYS──▶ CONNECTED
any ──hostkey mismatch / protocol error / auth exhausted / timeout / disconnect──▶ CLOSED
```

Message classes checked by `dispatch()`: 1-4 always (except under D5); 20/21/30-49 only
in a KEX; 5/6 before auth; 50-79 only after SERVICE_REQUEST; 80-127 after auth.
Anything else → `UNIMPLEMENTED`. A `DISCONNECT` from the server always tears the
connection down and marks it dead.

## 5. Error taxonomy

| API code | Meaning |
|---|---|
| `0` OK | |
| `-1 E_ARG` | NULL/out-of-range argument, port out of range, malformed pin, bad argv |
| `-2 E_STATE` | not connected / already connected / channel not open |
| `-3 E_IO` | socket failure, EOF from peer, connect timeout |
| `-4 E_HOSTKEY` | host key refused: unsupported type, or **pin mismatch (HOSTKEY_CHANGED)** |
| `-5 E_AUTH` | all offered auth methods refused by the server |
| `-6 E_PROTOCOL` | peer sent a malformed/off-protocol message |
| `-7 E_LIMIT` | output cap reached, table full, name-list too big |
| `-8 E_KEY` | private key parse failure, wrong passphrase, unsupported key type |
| `-9 E_CRYPTO` | self-test failure |
| `-10 E_TIMEOUT` | exec/read timeout expired |

Distinct errors for **auth failure** (`E_AUTH`) vs **network failure** (`E_IO`) vs
**protocol** (`E_PROTOCOL`) vs **host-key** (`E_HOSTKEY`). A network failure is never
reported as an empty folder or an auth failure.

## 6. Exec (client side)

- `spsshc_exec(ch, cmd, timeout_ms, max_out)` sends the command string as-is on the
  channel, then reads channel output until EOF/CLOSE, `exit-status`, timeout, or cap.
- `spsshc_exec_argv(argv, argc, timeout_ms, max_out)` quotes each argv element
  (single-quote escaping, `'` → `'\''`) and joins with spaces. **The client never builds
  a command from untrusted input by string concatenation.** NUL in an element →
  `EXEC_ARGV_NUL`; quoted total over 4096 B → `EXEC_ARGV_LONG`.
- **Documented limitation:** the remote side may still be a shell (real sshd runs the
  user's shell; our row-48 server runs execve with no shell). Quoting protects against
  splitting/injection in the shell, but a shell can still do anything the user could.
- **`--test` runs exec only against our own server (row 48) or a container sshd, never
  our LAN.**
- Output cap: stdout+stderr combined, default 16 MiB, caller sets per call. When the cap
  is hit the engine stops buffering, drains until EOF, and reports `SPSSHC_EXEC_CAP`.

## 7. Client rules (same across every SP2027 file client)

1. **Read-only**: the client never issues a write/delete/rename op. Asserted by a test
   that greps the op table (`spsshc_read_only()` returns 1 and the op table in
   `src/client.c` contains no write verb).
2. Distinct errors for auth failure / not found / network / protocol. A network failure is
   never "empty folder".
3. `TestXConnection` native-handler semantics: connect + list root; non-empty ⇒ valid.
   (This is row 41's consumer behaviour; this engine provides connect + subsystem.)
4. **Tests never target our LAN** (.205 NAS, .3, .60, .90 and others all expose these
   ports). Use loopback servers on this machine only.

## 8. Deliberate divergences from OpenSSH client (`ssh`)

| ssh | spsshc | Why |
|---|---|---|
| Verifies host key from `known_hosts`, interactive prompt for new keys | TOFU pinning via API parameter; caller stores | No interactive UI in a DLL; legacy had no check at all, so we add the minimal safe model |
| Offers `sntrup761x25519` / `mlkem768x25519` (PQ hybrid) | Not offered | Out of the required set (follow-up, same as row 48) |
| GSSAPI, hostbased, agent auth | Not offered | Legacy only ever used password |
| Interactive keyboard-interactive prompts | Every prompt answered with the caller's password | NAS auto-login; no UI in a DLL |
| Shell / PTY / port forwarding | Not offered — session channels only, subsystem + exec | ☢️ user rule: no shell |
| Retries KEX automatically on transport error | `spsshc_reconnect()` explicit helper | Caller decides |

## 9. Oracles and test plan

- **Unit** (`tests/test_spsshc.c`, `make unit`): KATs (crypto), wire buffers, name-lists,
  key file round-trip (ed25519 + RSA, unencrypted + bcrypt-encrypted), fingerprint
  formatting, exec_argv quoting matrix (spaces, quotes, `$`, newlines, empty, unicode),
  known_hosts line parse, API argument validation, and the client state machine driven
  in-process against a **mock server** (loopback TCP with scripted replies) covering
  version exchange, real KEX, auth ladder, channels, exec.
- **Loopback interop** (`tests/interop.sh`): real servers on 127.0.0.1 high ports only:
  1. **row 48 spsshs** (the sibling server, `spsshs` binary) — the primary oracle; full
     auth + subsystem echo + exec matrix.
  2. **OpenSSH sshd** (8.9p1 in this container) — password + publickey + keyboard-interactive, ed25519 and RSA user keys, chacha/GCM/CTR, re-key under load, wrong pin → hard fail.
  3. **dropbear 2020.81** — password auth, ed25519 host key.
  4. **RSA-only NAS-style server** (OpenSSH sshd configured `HostKey` RSA only + `HostKeyAlgorithms rsa-sha2-512,rsa-sha2-256`, Synology DSM 6 style) — proves the RSA-only fallback path.
- **Fuzz** (`tests/fuzz_spsshc.c`, libFuzzer + UBSAN, corpus replayed under gcc ASAN):
  version line, decrypting packet framer, KEXINIT parse, host-key signature verification
  blob, userauth reply parse, exec argv quoting, known_hosts/fingerprint parsing.

## 10. Open questions (written down, not guessed)

1. **PQ KEX** (`mlkem768x25519-sha256`): needs ML-KEM, which Monocypher does not have.
   Same follow-up as row 48 — skip for v1.
2. **exec stdin**: should `spsshc_channel_write` to an exec channel feed the program's
   stdin? Row 48's server reads stdin from `/dev/null`, so for our pair stdin is write-only
   dead. For real sshd it would work. Keep `channel_write` generic (it already is) and
   document that our own server ignores exec stdin.
3. **Key rotation**: TOFU pin mismatch today is a hard error. A "pin update" API
   (`spsshc_accept_new_hostkey()`) would let callers opt into rotation. Not in v1 — the
   caller can just pass the new fingerprint explicitly.
4. **Proxy / jump host**: not needed for the player today. Follow-up.
