Skip to content
Repos

TOSV

Markdown 45.0 KB448 lines Opens in site

Directory Raw Download

TOSV Standalone SFTP Server: Integration Requirements

  • Version: 0.2.0 (round 2: SFTP IDs corrected, KEX plus chacha constructions pinned, strict-kex required)
  • Status: Draft for owner implementation
  • Date: 2026-10-31
  • Owner: retoor (implements); this document is the contract

0. Control

0.1 Owner decisions (settled, not re-asked)

# Decision
OD-01 Transport: standalone SSH daemon. The owner implements the SSH transport and the SFTP subsystem. No wolfSSH, no libssh, no OpenSSH code linkage.
OD-02 Home: this repo, same discipline. Second single-file C++17 program plus one shared include, static libsodium only, same CI gates.
OD-03 Auth: SSH layer authenticates a gateway identity; SFTP paths carry the grant; a second in-band credential check binds the two.

0.2 Normative IDs

  • SF-NN: requirements on the new server (this document defines SF-01 onward, never reused once retired).
  • INT-NN: requirements on existing tosv.cpp and repo files, needed for integration.
  • Every SF and INT below traces to a tosv.cpp line or a SPEC.md ID in section 12. No open gaps: each would-be gap is a decided default with rationale inline.

0.3 Scope effect on the spec (process, not optional)

Adopting this work retires SPEC NG-01, D-06, and PIN-10 (SFTP excluded), and amends NFR-01 and PIN-03 (single file) to "one file per binary plus one shared vault.inc". ADR-0008 records the retirement with rationale before any merge, then SPEC bumps to 0.4.0 in the same commit, per DOC-01 and the ADR-before-merge register rule.

0.4 Non-goals in v1 (decided, not deferred)

  • No SSH shell, exec, PTY, port forwarding, X11, agent, or other subsystem. SFTP only, always.
  • No SSH algorithms beyond section 1. No RSA, ECDSA, FFDH groups, GSSAPI, or certs.
  • No second crypto format. Byte-identical v2 blobs, section 5.
  • No separate credential store. The DB stays canonical, section 2.
  • No Windows or macOS target. Linux x86_64 only, same as tosv.

1. SSH transport subset

The server implements exactly this profile, negotiates nothing else, and fails closed (DISCONNECT or CHANNEL_FAILURE, no fallback) on any peer proposal outside it. Rationale: libsodium provides every primitive below and nothing above; one algorithm per slot keeps the audit surface minimal; stock OpenSSH clients speak all of it.

Slot REQUIRED value libsodium primitive
KEX mlkem768x25519-sha256 (preferred, SF-61), curve25519-sha256, plus curve25519-sha256@libssh.org alias mlkem-native (ML-KEM-768) plus crypto_scalarmult
KEX strict REQUIRED both directions, disconnect peers that omit it, see SF-58 sequence reset plus disconnect
Host key ssh-ed25519 only crypto_sign
Cipher both directions chacha20-poly1305@openssh.com only crypto_stream_chacha20_ietf_xor_ic plus crypto_onetimeauth, see SF-60 (NOT the RFC 7539 AEAD: OpenSSH uses a custom two-key layout)
MAC negotiate minimal list, then ignore (AEAD integrates auth); see SF-52 none computed, ever
Compression none only n/a
Userauth publickey with ssh-ed25519 keys only crypto_sign_verify_detached
Channel session, then one subsystem request with name sftp n/a
Service ssh-userauth, then ssh-connection n/a
  • SF-01: version string SSH-2.0-TOSV_<VERSION> with VERSION from the repo VERSION file. No OS, library, or patchlevel text.
  • SF-02: host key file sftp_host_ed25519 in BASE (same dir as .env.json). Generated once at first start if missing, 0600, Ed25519, never overwritten, never logged. The .pub companion may exist for operator convenience and carries no authority.
  • SF-03: maximum SSH packet 262144 bytes on receipt; beyond that DISCONNECT with reason, no reply. RFC 4253 section 6.1 only requires 35000; we accept up to 262144 for stock-client parity. All KEXINIT names, strings, and cookies are length-checked before any alloc.
  • SF-04: rekey after 2^30 bytes in either direction or 3600 seconds, whichever comes first. Failed rekey disconnects. Rekey state machine tolerates exactly one in-flight KEX.
  • SF-05: every rejected channel request (shell, exec, pty-req, env, tcpip-forward, direct-tcpip, x11, auth-agent-req, subsystems other than sftp, global requests) gets CHANNEL_FAILURE or REQUEST_FAILURE, plus audit line sftp-ssh-reject <type>, plus no retry path. Shell and exec are never implemented, not merely disabled.
  • SF-06: DEBUG and DISCONNECT messages carry generic text only (parity with UX-03: denied, blocked, too early, expired, missing, failure). Never echo key material, paths, or grant ids in disconnect text.
  • SF-07: handshake timeouts: 30 seconds to complete KEX (parity with the 30s recv timeout in tosv.cpp main), 120 seconds to first authenticated channel request, then idle 300 seconds per connection. Timeout closes, no wipe (parity with D-04).
  • SF-08: loopback default bind, port argv[1] default 2222 (parity with OPS-01 shape). AF_INET 127.0.0.1 only, no v6 listen in v1 (parity with the tosv.cpp bind call). DTAP uses separate ports plus data dirs with zero shared state (parity with OPS-05).

1B. SSH channels, packets, and crypto construction

  • SF-49: exactly one session channel per connection; a second CHANNEL_OPEN gets OPEN_FAILURE administratively prohibited (decided: one channel keeps audit attribution trivial). Non-session channel types get OPEN_FAILURE unknown type. Initial window 2097152 bytes, maximum packet 262144, WINDOW_ADJUST top-up sent eagerly before the window halves. CHANNEL_DATA beyond the window is a protocol error: disconnect, no reply.
  • SF-50: strict RFC 4251 type codec on both directions: every string, mpint, and name-list length is bounds-checked before alloc; short reads give disconnect pre-auth and CHANNEL_FAILURE post-auth, never an over-alloc. Client version line max 255 bytes or drop. KEXINIT cookie is 16 libsodium random bytes; first-kext-packet-follows is always ignored (never act on a guess). Service requests accept ssh-userauth then ssh-connection only. CHANNEL_REQUEST honors want-reply (reply only when true). No USERAUTH_BANNER is ever sent. Partial success (value 1 in USERAUTH_FAILURE) is never sent. Rekey pauses channel data until NEWKEYS both directions per RFC 4253.
  • SF-51: the chacha20-poly1305@openssh.com construction follows the OpenSSH implementation (cipher-chachapoly.c plus packet.c, filed as T1 in Appendix C) exactly, as pinned in SF-60. Verification is the stock-client interop test (SF-39) plus a captured-session decrypt check in tests: no hand-waving, the client either talks or the gate is red.
  • SF-52: MAC negotiation offers hmac-sha2-256 only and accepts the peer overlap normally, then never computes or checks any MAC while the AEAD cipher is active. If a future cipher ever needs a MAC, that cipher ships its own ADR; in v1 the agreed name is agreed-and-ignored, which matches OpenSSH behavior (packet.c sets mac to NULL when cipher_authlen is nonzero) and is proven by interop.
  • SF-58: strict key exchange is REQUIRED, not preferred. The server offers kex-strict-s-v00@openssh.com and disconnects (code 2 PROTOCOL_ERROR, audit sftp-ssh-reject kex-strict) any peer whose KEXINIT omits kex-strict-c-v00@openssh.com. Rationale: our only cipher is chacha20-poly1305, which the Terrapin researchers name as affected by prefix-truncation when strict kex is absent; a vault takes no downgrade-by-truncation risk. Compatibility floor: stock OpenSSH 9.6 and later, verified by SF-39 negotiation against the local client.
  • SF-59: curve25519-sha256 key exchange (RFC 8731 over RFC 5656 section 4): messages SSH_MSG_KEX_ECDH_INIT 30 (client ephemeral key Q_C as SSH string) and SSH_MSG_KEX_ECDH_REPLY 31 (K_S host key blob string, Q_S server ephemeral key string, signature over H). Exchange hash H is SHA-256 over string V_C, string V_S (CR LF excluded), string I_C, string I_S (raw KEXINIT payloads), string K_S, string Q_C, string Q_S, mpint K. K is encoded as mpint per RFC 4251: length-prefixed, with a leading zero byte when the top bit is set (32-byte secrets with top bit set encode as 33 bytes). Abort rules: peer key not exactly 32 bytes, or shared secret all-zero, or libsodium reports failure, gives immediate disconnect with code 3 KEY_EXCHANGE_FAILED and audit sftp-kex-fail. Host signature uses ssh-ed25519 per RFC 8709; the K_S blob and signature blob encodings follow that RFC and are proven by interop.
  • SF-61: mlkem768x25519-sha256 hybrid key exchange (draft-ietf-sshm-mlkem-hybrid-kex, FIPS 203): same messages 30 and 31 as SF-59. Q_C is one string of exactly 1216 bytes: ML-KEM-768 encapsulation key (1184) then X25519 public key (32). Q_S is one string of exactly 1120 bytes: ML-KEM ciphertext (1088) then server X25519 public key (32). Shared secret K is SHA-256 over ML-KEM shared secret (32) then X25519 shared secret (32), and K is encoded as a plain SSH string (not mpint) in H and in every KDF input. Negotiation: the first client KEX entry the server also offers wins; server offers mlkem768x25519-sha256, curve25519-sha256, curve25519-sha256@libssh.org. Abort rules as SF-59 plus: Q_C length wrong, ML-KEM encapsulation key rejected by the modulus check, or X25519 secret all-zero gives disconnect code 3 and audit sftp-kex-fail. Audit sftp-kex mlkem768x25519 or sftp-kex curve25519 on the first exchange, sftp-rekey pq on PQ rekey. Library: mlkem-native v2.0.0 pinned (ADR 0009). Proof: OpenSSH 10.2 negotiates it with host signature verified, Gate 2 pq-only and classic fallback asserts.
  • SF-63: channel EOF from the client ends the subsystem: the server replies EOF then CHANNEL_CLOSE (RFC 4254 section 5.3) and keeps serving until the peer CLOSE or disconnect (dropping the TCP connection at once resets unread data and truncates transfers, seen in gate2). Before 0.5.3 it replied EOF only, so OpenSSH 10.2 sftp -b hung forever after any failed batch command (found 2026-11-05, reproduced on 2bb51c0, deterministic).
  • SF-62: PQ-only by default: only mlkem768x25519-sha256 (plus the strict-kex marker) is offered and accepted; TOSV_SFTP_ALLOW_CLASSICAL=1 (exactly the string 1) re-adds curve25519-sha256 and its libssh alias. Clients without ML-KEM get "no matching algorithm". ADR 0011
  • SF-60: packet protection construction (from cipher-chachapoly.c): per direction, 64 bytes of key material from the RFC 4253 section 7.2 KDF with SHA-256, letters C (client to server) or D (server to client), extended K1 plus K2 to 64 bytes; first 32 bytes are the main key, last 32 the header key. Letters A, B, E, F are never derived (no IVs, no MAC; documented, safe: KDF outputs are independent). Per packet with sequence number N as 8-byte big-endian: Poly1305 one-time key is ChaCha20 main-key block at counter 0; the 4 length bytes are encrypted with the header key at counter 0; the payload is encrypted with the main key at counter 1; the 16-byte tag is Poly1305 over ciphertext (length plus payload) and is verified BEFORE any decryption. libsodium mapping: crypto_stream_chacha20_ietf_xor_ic with 12-byte nonce 00000000 plus N and initial counters 0 or 1, plus crypto_onetimeauth; the 8-byte wire nonce maps to the low 8 bytes of the IETF nonce. Any deviation fails interop, so the Gate is the proof.

2. Authentication and authorization

Two layers, both mandatory, in this order. Rationale: OD-03 splits transport identity (SSH key, long-lived, operator-managed) from grant rights (DB rows, short windows, per-fetcher), so key rotation never touches grants and grant expiry never touches keys.

2.1 SSH layer: gateway identity

  • SF-09: userauth none is always answered with failure listing publickey only (method discovery, never access). password, keyboard-interactive, hostbased are answered with failure and audited as sftp-auth-reject <method>. Only publickey with ssh-ed25519 blob type proceeds to signature check.
  • SF-10: gateway keys file sftp_gateway_keys in BASE, 0600, one entry per line: ssh-ed25519 <base64> <label> gids=<gid>[,<gid>...]. Unknown key, malformed line, or missing gids field denies. No wildcard in v1 (decided: least privilege; a wildcard needs its own ADR).
  • SF-11: the label is free text without spaces; the gids list binds this SSH identity to grant ids (the gid column of grant rows, tosv.cpp load_db). An identity with no listed gid authorizes nothing, not everything.
  • SF-12: signature verification is constant-time libsodium verify over the session id plus the signed blob per RFC 4252 section 7. The signed session id MUST equal the current session id or the signature is rejected even if mathematically valid (replay across sessions). Signed-data field order per RFC 4252 section 7: session id, byte 50, user name, service name, "publickey", boolean TRUE, algorithm name, public key blob. The boolean-FALSE probe (acceptable-key query) is answered without counting an attempt. Session id is H from the FIRST key exchange and never changes across rekeys (RFC 4253 section 7.2). Failure counts as an auth strike (SF-33).

2.2 SFTP layer: in-band grant proof

Stock clients must work with zero extensions, so the grant proof rides in the path. SFTP paths are encrypted on the wire; the server MUST redact the proof where it rests.

  • SF-13: namespace root / lists one directory per gid this SSH identity is bound to (SF-11). OPENDIR or REALPATH on / never reveals other gids. Unknown gid in path behaves exactly like missing file (NO_SUCH_FILE), never like denied (no oracle).
  • SF-14: grant root form is /<gid>/<gp>/ where gp is the 22-char grant pass from the DB row. The server compares gp in constant time against the row. Wrong gp behaves exactly like missing file (NO_SUCH_FILE), never like denied. Correct gid plus gp plus identity binding opens the grant root, which mirrors /dav/ exactly (section 3).
  • SF-15: audit lines and any error text MUST redact gp: log <gid>/... with the gp segment replaced by *. Lines stay under 4096 bytes for O_APPEND atomicity (INT-02).
  • SF-16: after grant proof, the server enforces the grant IP list then the time window on EVERY operation, not just at open (parity with /fetch checks in tosv.cpp, which DAV skips for windows; SFTP follows the stricter fetch order: IP, then frm, then to, using ip_ok and valid_ts semantics).
  • SF-17: store-credential access (su:sp) over SFTP is FORBIDDEN in v1 (decided: DAV already grants su:sp full file rights without windows; SFTP stays fetch-model pure so every SFTP byte is windowed and attributed to a gid; revisit via ADR).

2.3 Duress in-band

  • SF-18: reserved path /!duress/<suffix>/: if duress:<suffix> equals the DB duress value, the server audits duress, creates the wipe sentinel (INT-03), performs wipe_store semantics (SF-32), and disconnects with generic text. Wrong suffix behaves exactly like missing file. Any SFTP op type touching the path triggers the check. Rationale: D-15 says the coercion path is never blocked; SFTP must not strand a coerced fetcher.

3. Namespace and path mapping

One store, two protocols: the SFTP grant root mirrors the DAV tree byte for byte in naming, so a file written by either is readable by both (proven by cross-surface tests, SF-41).

  • SF-19: /<gid>/<gp>/ maps to STORED (tosv_store/). Names are literal store names including the .bin suffix. Subdirectories map to subdirectories. .tag sidecars are NEVER listed, NEVER readable, NEVER writable through SFTP; direct reference to a .tag name behaves like missing file.
  • SF-20: path resolution strips every .. segment (parity with dav_path), then confines to STORED; escape attempts behave like missing file and audit sftp-escape <gid>. Symlink ops (READLINK, SYMLINK) return OP_UNSUPPORTED; the store has no symlinks. LSTAT and STAT behave identically.
  • SF-21: REALPATH resolves . and .. lexically within the grant root and returns the canonical /<gid>/*/... form with gp redacted as *. Clients that cache the redacted form re-supply gp per SF-14 on next use; the server MUST accept the redacted * segment only on the same connection that already proved that gp, else NO_SUCH_FILE.
  • SF-22: file sizes in ATTRS are PLAINTEXT lengths: v2_plain_len math for version 2 blobs, file size for v1 (parity with dav_len). Mtime, atime, uid, gid, and permissions are synthesized (mtime real, rest 0600 root-equivalent); SETSTAT and FSETSTAT on times or modes return OK and change nothing (decided: stock clients stay quiet; the store keeps no modes). SETSTAT on any other attribute returns OP_UNSUPPORTED.

4. SFTP v3 operation matrix

Protocol: SFTP version 3 only (INIT any version gets VERSION 3). Packet and status constants per draft-ietf-secsh-filexfer-02, pinned in Appendix A. Every op below re-checks SF-16 gates first.

SFTP op Maps to Gates and behavior
OPENDIR/READDIR/CLOSE(dir) PROPFIND depth 1 10000-entry cap per dir (PROPFIND parity); skip .tag; READDIR state per handle; EOF at end
OPEN read fetch path v2 verify-before-serve pre-pass, then stream; v1 legacy read path; missing tag backfills transparently (FR-13 parity)
READ offset/len fetch range plaintext offsets; per-handle pull state with resync on seek; max len 262144 per reply; EOF past end
OPEN w/c/t, WRITE, CLOSE(file) store path sequential offsets only, else FAILURE; seal incrementally into temp <name>.part.<rand16> plus rename on CLOSE with FINAL tag; non-sequential or APPEND flag returns OP_UNSUPPORTED (decided: DAV has no append either, parity over novelty)
REMOVE, RMDIR DELETE needs tw (two_way), else PERMISSION_DENIED (append-only parity); remove <path>.tag with the file
MKDIR MKCOL always allowed (MKCOL parity, even append-only)
RENAME MOVE needs tw always, else PERMISSION_DENIED (MOVE parity); move <path>.tag with the file; no cross-grant rename (same gid both sides)
LSTAT/STAT/FSTAT entry attrs SF-22 sizes; missing gives NO_SUCH_FILE
SETSTAT/FSETSTAT n/a SF-22 rule
REALPATH canonicalize SF-21 rule
READLINK/SYMLINK n/a OP_UNSUPPORTED, always
EXTENDED n/a OP_UNSUPPORTED, always (no extensions in v1)
  • SF-23: error mapping: bad auth or gates to PERMISSION_DENIED, missing to NO_SUCH_FILE, tamper or tag mismatch to FAILURE plus aead-fail or integrity-fail audit (FR-13 parity), append-only refusal to PERMISSION_DENIED, store-full (100000 blobs) and oversize (512MB) to FAILURE with message text store full or too large, unknown blob version to FAILURE plus audit. No SSH_FX code outside v3.
  • SF-24: pipelining: at most 64 outstanding SFTP requests per connection; the 65th waits, never drops (backpressure, no new failure mode). Request ids echoed exactly; out-of-order replies permitted only where SFTP allows (READ/WRITE by id).
  • SF-25: unknown or malformed SFTP packet gets STATUS BAD_MESSAGE on that id and the request is dropped; five bad packets per connection disconnects (parity with strike philosophy, bounded).
  • SF-26: all SFTP integer and string decodes are bounds-checked before alloc; declared lengths beyond remaining bytes give BAD_MESSAGE, never a short read or over-alloc. Max single alloc 262144 plus header.

4B. SFTP handles, attrs, flags, and edges

  • SF-53: handles are opaque 16-byte libsodium random per OPEN or OPENDIR, held in a per-connection table capped at 1024 entries (103rd OPEN gets FAILURE, no eviction). CLOSE frees. Unknown or cross-connection handle gets FAILURE without a strike (client bug class, not attack class). Handles never embed paths, gids, or offsets.
  • SF-54: ATTRS replies always carry SIZE plus UIDGID plus PERMISSIONS plus ACMODTIME: size is the SF-22 plaintext length, uid and gid are 0, permissions are 0600 files or 0700 dirs, atime equals mtime which is the real store mtime. NAME longname uses ls -l shape (-rw------- 1 0 0 <size> <Mon DD HH:MM> <name>, d plus rwx------ for dirs); Gate asserts ls -l parses.
  • SF-55: OPEN flag matrix (checked after SF-16 gates): READ alone opens existing for fetch; WRITE or CREAT or TRUNC on an existing path needs tw, else PERMISSION_DENIED (PUT-over-existing parity); EXCL with an existing path gets FAILURE; CREAT on missing creates via the SF-56 temp flow; TRUNC truncates only with tw; APPEND always gets OP_UNSUPPORTED (section 4 table); OPEN attrs (permissions on create) are accepted and ignored (SF-22 parity: the store keeps no modes).
  • SF-56: uploads seal incrementally into <name>.part.<rand16> unique per handle (no two handles share a temp; last-CLOSE-wins on rename, both closes audited). Temps are hidden from READDIR exactly like .tag. CLOSE writes the FINAL tag, renames over the target, writes the sidecar tag, and removes the temp; a CLOSE with zero WRITEs still yields a valid empty v2 blob (store_v2 empty parity). Disconnect or FAILURE removes the temp. Startup scans STORED and removes orphan *.part.* before serving.
  • SF-57: path and edge rules: max SFTP path 4096 bytes, beyond gets FAILURE; empty path means the single bound grant root when its gp is already proven this connection, else the namespace root (stock clients probe startup with empty and relative paths; grant roots always need proof first); relative paths resolve against root; gid segments are uuid-shape-checked and gp segments charset-checked ([A-Za-z0-9-_], exactly 22) before any DB scan, malformed gives NO_SUCH_FILE; REMOVE on a directory and RMDIR on a file give FAILURE (POSIX unlink/rmdir parity); RENAME overwrites an existing target like rename() when tw allows (MOVE parity); sftp_gateway_keys is re-read at every connection (rotation without restart; parse failure denies that connection with audit).

5. Crypto and storage reuse (no second implementation)

Rationale: two crypto copies drift; drift breaks blobs. One shared include, byte-identical formats, cross-surface proof.

  • SF-27: new blobs are v2 only, byte-identical to store_v2: 0x02, random salt16, secretstream header24, 64KB MESSAGE chunks, FINAL terminator, tag line <sha256> 0 2 with real SHA256. The SFTP server MUST NOT contain its own copy of this logic; it includes vault.inc (INT-01).
  • SF-28: reads verify before serving with the same two-return discipline as fetch_v2: tag mismatch, crypto fail, and bad size/header stay distinct internally and map per SF-23 externally. Verification is never skipped, never cached as a verdict; only KDF output is memoized (SEC-02 parity).
  • SF-29: keys are Argon2id INTERACTIVE from su:sp plus per-blob salt, mlock held, wiped after use (SEC-02 parity). The SFTP process keeps its OWN key cache instance (128 LRU, 300s TTL, salt-bound, guarded allocs, wipe-on-evict); caches are never shared across processes. One KDF at a time per process (KDFM parity) bounding transient RAM to 64MB per process.
  • SF-30: v1 blobs stay readable through the frozen legacy path only (leg_* plus layers 1 to 8 from tag). No new v1 blob is ever written by any surface. Layers stay inert for v2 (SEC-01 parity).
  • SF-31: plaintext exists only in RAM chunks (64KB), mlock-held keys, and the incremental sealed temp file during upload (ciphertext, <name>.part.<rand16> per SF-56, renamed on CLOSE, removed on disconnect or failure). No plaintext temp file, ever, on any path including crash paths (temp removed at next startup scan too).
  • SF-32: wipe_store semantics on duress: flush own key cache, 3-pass overwrite (0x00, 0xFF, random, first 1MB per file), remove blobs plus tags plus DB, keep the sentinel (INT-03). Same order as tosv.cpp wipe_store: cache first, files, DB, sentinel already created before starting.

6. Caps and limits (parity with SPEC 0.3)

Every ceiling below equals the SPEC value; the SFTP server enforces its own copy (per-process state, same numbers).

Cap Value SFTP enforcement
connections 64 concurrent max 65th gets SSH DISCONNECT, no banner delay games
single blob 512MB max WRITE past cap gets FAILURE too large, temp removed
blobs per store 100000 max CREATE past cap gets FAILURE store full
grants per DB 10000 max read-only surface, no grant creation; unchanged
sessions n/a (no cookies) each SSH connection is one session; idle 300s close
rate auth 5 fails per 300s per IP further attempts get disconnect, see SF-33
rate store 20 per 300s per peer CREATE past rate gets FAILURE blocked
block strikes 20 per 300s closes IP for 3600s, duress first same Strike plus BLK semantics, own tables
rate entries 10000 ATT plus 10000 BLK max, oldest evicted own tables, same caps
dir entries 10000 per READDIR cycle EOF after cap (PROPFIND parity)
stream chunk 64KB READ replies and WRITE buffering in 64KB units
audit line under 4096 bytes truncation never splits a line; overlong action names rejected at format time
  • SF-33: strike and block semantics equal tosv.cpp exactly: 20 strikes per 300s per IP, block 3600s, duress path evaluated before any block (D-15 parity). Auth failures, bad packets beyond SF-25, and escape attempts (SF-20) all strike. Blocks live per process; both processes audit blocked <ip> so the union is visible in one file. Evasion buys nothing: gates are identical per surface, so a sprayer blocked on SFTP earns a fresh block on HTTP within the same 20 strikes.

7. Audit

  • SF-34: same file AUDF (tosv_audit.log), same line shape %FT%TZ <ip> <action>, same newline sanitizing (\n and \r become _, from audit()). One write per line, O_APPEND, under 4096 bytes (INT-02). No secrets (never gp, keys, salts, plaintext) and no PII beyond IP (FR-11 parity).
  • SF-35: action vocabulary (fixed, lowercase, no variants): sftp-connect, sftp-auth-ok <label>, sftp-auth-fail <label>, sftp-auth-reject <method>, sftp-ssh-reject <type>, sftp-open <gid>/<path>, sftp-read <gid>/<path>, sftp-write <gid>/<path>, sftp-close <gid>/<path>, sftp-list <gid>/<path>, sftp-mkdir <gid>/<path>, sftp-remove <gid>/<path>, sftp-rename <gid>/<from>-><to>, sftp-escape <gid>, sftp-bad-packet <ip>, sftp-kex-fail, blocked <ip>, aead-fail <gid>/<path>, integrity-fail <gid>/<path>, duress. Paths redact gp per SF-15.
  • SF-36: stdout gets the bind line plus memlock probe only (OPS-02 parity). No debug file in v1. Log levels fixed.

8. tosv.cpp and repo integration changes (INT, owned with this work)

The SFTP server is not done until the vault side meets it. Each INT below is a requirement on existing files, verified by the same Gate.

  • INT-01: new file vault.inc in repo root holds the shared logic: DB load plus save, audit, rate plus strike plus block, ip_ok, valid_ts, window_now (the UTC %FT%H:%M formatter now inline in tosv.cpp fetch), hexr, uuid4, v2 crypt core (derive, seal-push, pull-verify, length math), key cache as an instantiable struct, wipe_store core, NTP check. tosv.cpp and tosv-sftp.cpp both #include it. No logic duplicated across the two mains beyond routing. tosv.cpp refactor is mechanical and behavior-identical; Gate 2 before and after must pass unchanged (192/192) to prove it.
  • INT-02: audit() in vault.inc uses one O_APPEND write per line (single write syscall, no iostream splitting) so two processes appending concurrently never interleave. Lines stay under 4096 bytes; longer input is rejected at format time, never truncated mid-line.
  • INT-03: wipe sentinel file .wiped in BASE. Duress in EITHER process creates .wiped FIRST (0600, contains UTC time), then wipes. BOTH processes refuse to serve while .wiped exists (tosv: every route 403 wiped; sftp: disconnect after banner), because a wiped DB otherwise re-enters bootstrap and resurrects the vault. Only the operator clears .wiped manually (floor parity: automation never crosses deletion floors). Gate proves: wipe via HTTP then SFTP refuses; wipe via SFTP then HTTP 403s.
  • INT-04: DB load plus save in vault.inc takes an exclusive flock on tosv_db.txt around the reload-modify-save critical section in BOTH processes, including the temp-file write plus rename (both processes share the tosv_db.txt.tmp name, so the lock must cover it). Reads take the same exclusive lock (critical sections are short; one lock mode, no reader starvation analysis). Lock ordering: flock before in-process mutex, never held across socket IO. Gate hammers 50 parallel grant creates plus 50 parallel SFTP stats and diffs the DB.
  • INT-05: tosv.cpp fetch_v2 splits into a transport-free core (verify plus pull-to-callback) in vault.inc plus the HTTP header plus send loop in tosv.cpp. The SFTP server consumes the same core with an SFTP DATA callback. No behavior change on HTTP; Gate 2 proves byte-identical fetch bodies across HTTP and SFTP for v1, v2, empty, exact-chunk, and multi-chunk fixtures.
  • INT-06: source file tosv-sftp.cpp in repo root, binary tosv-sftp, version macro TOSV_SFTP_VERSION from the same VERSION file. Makefile gains build-sftp, smoke-sftp, lint-sftp with the identical HARDEN flags; build builds both; ci gates both; clean removes both. Static libsodium include path identical; no new third-party anything.
  • INT-07: sftp_gateway_keys and sftp_host_ed25519 join the protected-paths floor (SPEC 0.4) and the backup set (OPS-03): backed up, never auto-pruned, 0600 enforced at every startup like ENVF plus DBF.
  • INT-08: NTP skew check shared via vault.inc: both processes honor TOSV_NTP with identical hourly audit-only semantics (FR-14 parity), because grant windows in two processes need one clock story.

9. Build, tests, docs, process

  • SF-37: build is make build-sftp, under 60s on 2-core from scratch including sodium (NFR-05 parity covers both binaries together). Binary under 5MB combined budget with tosv (same NFR-05 line, both measured). Compiler warnings are zero (-Wall -Wextra, no suppressions without dated comment).
  • SF-38: ASan plus UBSan build target build-sftp-fuzz (same source, sanitizers plus no PIE conflict flags documented in Makefile). CI runs the packet fuzzer under it on every change to tosv-sftp.cpp or vault.inc.
  • SF-39: Gate 2 gains an SFTP section, all against scratch BASE dirs, all with the STOCK OpenSSH sftp client (default algorithms, proving negotiation lands on section 1; plus one constrained-algorithms run pinning the exact profile). Minimum asserts: connect plus REALPATH; list root shows only bound gids; wrong gp indistinguishable from missing; expired and future windows refuse; wrong-IP grant refuses; fetch round-trip byte-identical to HTTP; store round-trip readable by HTTP and DAV; append-only PUT-over-existing and REMOVE and RENAME refuse without tw and pass with tw; tampered blob gives FAILURE plus aead-fail audit; truncated blob gives FAILURE plus integrity-fail audit; 10000-entry dir caps with EOF; escape path stays jailed plus sftp-escape audit; unknown version 500-equivalent FAILURE plus audit; duress path on scratch wipes and both binaries refuse after (INT-03); rate and block behavior (5 auth fails then disconnect; strikes to block); .tag and .part never visible; gp never in audit; ls -l longname parses; EXCL-on-existing fails; APPEND unsupported; empty upload yields valid empty blob; second channel refused; AES-only client fails to negotiate (subset proof); raw KEXINIT without kex-strict gets disconnect code 2; short or all-zero KEX public key gets disconnect code 3 (raw probes, no stock client needed).
  • SF-40: packet fuzzer feeds random plus mutated SSH binary packets and SFTP packets at the parser seams (both directions, pre-auth and post-auth): no crash, no hang past timeouts, no alloc above SF-26 caps, no secret in output, exit fail-closed. Corpus seeds from real stock-client sessions captured in tests.
  • SF-41: cross-surface round-trips are REQUIRED asserts, not nice-to-haves: store-by-HTTP then fetch-by-SFTP, put-by-SFTP then fetch-by-HTTP and DAV-GET, DAV-PUT then SFTP-READ, for sizes 0, 1, 65536, 65537, and 5MB. Byte-identical or red.
  • SF-42: perf parity: NFR-04 p95 fetch under 2s for 10MB on loopback applies to SFTP READ; memory flat vs blob size (FR-06/NFR-03 parity) proven by a 100MB SFTP fetch with flat RSS. Numbers recorded in SPEC 0.4.0 NFR-04 row on measure day, never copied from HTTP.
  • SF-43: docs ship in the same commit (DOC-01): ADR-0008 (retires NG-01, D-06, PIN-10; records OD-01 through OD-03 and the vault.inc amendment to NFR-01/PIN-03), SPEC 0.4.0 (new FR/SEC/OPS rows, caps table gains SFTP column values, section 9 D-21), runbook docs/runbooks/sftp.md (keys provisioning, gid binding, duress drill, incident lines), BUILD-TRACK milestone row, CHANGELOG row, tosv.AGENTS.md pointer plus new sftp.AGENTS.md subsystem file (AGENTS.md three-layer rule). This document (sftpserver.md) becomes the SFTP appendix reference and stays versioned.
  • SF-44: threat model section in ADR-0008 names every excluded SSH feature and algorithm with one-line why, the Terrapin posture (SF kex-strict), the length-leak parity (R-02), the no-forward-secrecy parity (R-03), the gp-in-path tradeoff (encrypted on wire, redacted at rest, client-history caveat with wrapper guidance), and the two-process rationale (DB flock plus sentinel plus per-process caches).

10. Startup and operations

  • SF-45: startup prints the bind line (TOSV-SFTP <VERSION> on 127.0.0.1:<port>) plus the memlock probe line (parity with tosv.cpp main). Fatal bind failure exits nonzero (no silent retry). Signals close only, never wipe (D-04 parity).
  • SF-46: file permissions enforced at every startup: 0600 on sftp_host_ed25519, sftp_gateway_keys, plus (via vault.inc) .env.json and tosv_db.txt. World-readable key material refuses to load: the server exits nonzero naming the file, rather than serving weak.
  • SF-47: thread model mirrors tosv.cpp: one accept thread plus short-lived threads per connection, 64 cap, mutexes never held across socket IO. Shared maps (rates, blocks) plus audit hold one mutex each.
  • SF-48: DTAP separation (OPS-05 parity): BASE per environment from cwd at startup, separate ports, host keys never copied between environments (each BASE generates its own; copying is an operator error the runbook calls out).

11. Verification checklist (all green or no merge)

  1. make ci green including new SFTP lint, smoke, and Gate section.
  2. scripts/doc-check.sh green (this file carries its header; forbidden scan clean).
  3. Gate 2 SFTP asserts per SF-39 plus cross-surface SF-41 plus INT-03 both-directions plus INT-04 hammer.
  4. Fuzzer SF-40 clean under ASan plus UBSan for at least 10M execs or 30 minutes, whichever first, with corpus committed.
  5. Perf SF-42 measured and recorded, not copied.
  6. ADR-0008 plus SPEC 0.4.0 plus runbook plus CHANGELOG plus BUILD-TRACK in the same commit.
  7. Owner runs the duress drill on scratch and signs the runbook drill line.

12. Traceability (requirement to code or spec)

Req Traces to
SF-01 OPS-01 shape; Makefile -DTOSV_VERSION
SF-02 FR-01 keygen-once shape; tosv.cpp main ENVF block
SF-03 FR-15 64KB header cap idea, widened to SSH max 262144
SF-04 static ceiling rule (base rules); new bound, rationale inline
SF-05 section 0.4 non-goals; FR-11 audit
SF-06 UX-03 plain errors
SF-07 tosv.cpp main 30s timeout; D-04
SF-08 OPS-01, OPS-05
SF-09 PG-05 grant-auth idea; FR-11
SF-10 FR-03 gid issuance; new file, INT-07
SF-11 DB grant row gid column, tosv.cpp load_db
SF-12 RFC 4252 section 7 verify; SF-33 strikes
SF-13 SEC-05/SEC-06 least knowledge; no-oracle rule
SF-14 FR-03 gp 22-char; DB row; SF-15 redaction
SF-15 FR-11 never secrets; INT-02 4096
SF-16 tosv.cpp /fetch IP plus window order (stricter than DAV)
SF-17 decided default, rationale inline
SF-18 FR-08 duress; D-15 coercion path
SF-19 STORED layout; FR-09 DAV tree; FR-13 sidecars
SF-20 tosv.cpp dav_path dot-dot strip; FR-11
SF-21 REALPATH per draft; SF-15 redaction
SF-22 tosv.cpp dav_len; decided SETSTAT default
SF-23 tosv.cpp fetch/DAV error discipline; FR-13 audits
SF-24 static ceiling rule; 64 mirrors CONN cap
SF-25 strike philosophy; FR-10
SF-26 FR-15 robustness; 262144 mirrors SF-03
SF-27 tosv.cpp store_v2; PIN-08
SF-28 tosv.cpp fetch_v2 returns; SEC-02
SF-29 SEC-02; tosv.cpp KCM/KCC/KCL/KDFM
SF-30 SEC-01; frozen leg_* block
SF-31 FR-06 streaming; NFR-03
SF-32 tosv.cpp wipe_store order
SF-33 FR-10; D-15 duress-first
SF-34 FR-11; tosv.cpp audit(); INT-02
SF-35 FR-11 vocabulary; SF-15
SF-36 OPS-02
SF-37 NFR-05; Makefile HARDEN
SF-38 base rules proof habit; new target
SF-39 Gate 2 mechanics, SPEC 6.5
SF-40 base rules proof habit; new target
SF-41 FR-04/FR-05/FR-09 equivalence
SF-42 NFR-04; NFR-03
SF-43 DOC-01; TRK-01; AGENTS.md layers
SF-44 SPEC section 8 risks; status-doc R-02 R-03
SF-45 OPS-01; tosv.cpp main; D-04
SF-46 FR-15 0600 rule, hardened to refuse
SF-47 SPEC section 5 flow
SF-48 OPS-05
SF-49 RFC 4254 channels; one-channel decided default
SF-50 RFC 4251/4253 codec strictness; FR-15 robustness
SF-51 OpenSSH PROTOCOL.chacha20poly1305 (T1 at implement time); SF-39 interop
SF-52 OpenSSH AEAD MAC behavior; proven by interop
SF-53 static ceiling rule; 1024 handle cap
SF-54 SF-22 sizes; ls -l stock-client compat
SF-55 tosv.cpp PUT append-only rule; SF-56
SF-56 tosv.cpp store_v2 incl empty; FR-13 sidecars
SF-57 fid_ok charset idea; POSIX unlink/rmdir; SF-10
SF-58 Terrapin research site; strict-kex countermeasure list
SF-59 RFC 8731; RFC 5656 section 4 and 7.1; RFC 4251 mpint; RFC 8709
SF-60 OpenSSH cipher-chachapoly.c; RFC 4253 section 7.2 KDF
SF-61 draft-ietf-sshm-mlkem-hybrid-kex; FIPS 203; RFC 4251 string
SF-62 ADR 0011
SF-63 RFC 4254 section 5.3
INT-01 NFR-01/PIN-03 amendment via ADR-0008
INT-02 FR-11; two-process append safety
INT-03 FR-08; floors (blob delete, DB delete)
INT-04 SPEC section 8 grant-race mitigation, extended cross-process
INT-05 tosv.cpp fetch_v2; SF-28
INT-06 Makefile targets; PIN-04 HARDEN
INT-07 SPEC 0.4 floors; OPS-03
INT-08 FR-14

Appendix A. Pinned wire constants (SFTP v3)

From draft-ietf-secsh-filexfer-02, verified at implementation time against the stock-client interop test (SF-39), which fails if any value here is wrong. No trust needed.

Requests: INIT 1, OPEN 3, CLOSE 4, READ 5, WRITE 6, LSTAT 7, FSTAT 8, SETSTAT 9, FSETSTAT 10, OPENDIR 11, READDIR 12, REMOVE 13, MKDIR 14, RMDIR 15, REALPATH 16, STAT 17, RENAME 18, READLINK 19, SYMLINK 20, EXTENDED 200. Replies: VERSION 2, STATUS 101, HANDLE 102, DATA 103, NAME 104, ATTRS 105, EXTENDED_REPLY 201. Status: OK 0, EOF 1, NO_SUCH_FILE 2, PERMISSION_DENIED 3, FAILURE 4, BAD_MESSAGE 5, NO_CONNECTION 6, CONNECTION_LOST 7, OP_UNSUPPORTED 8. Open flags: READ 0x01, WRITE 0x02, APPEND 0x04, CREAT 0x08, TRUNC 0x10, EXCL 0x20. SSH messages used: DISCONNECT 1, SERVICE_REQUEST 5, SERVICE_ACCEPT 6, KEXINIT 20, NEWKEYS 21, KEX_ECDH_INIT 30, KEX_ECDH_REPLY 31, USERAUTH_REQUEST 50, USERAUTH_FAILURE 51, USERAUTH_SUCCESS 52, USERAUTH_PK_OK 60, CHANNEL_OPEN 90, CHANNEL_OPEN_CONFIRMATION 91, CHANNEL_OPEN_FAILURE 92, CHANNEL_WINDOW_ADJUST 93, CHANNEL_DATA 94, CHANNEL_EOF 96, CHANNEL_CLOSE 97, CHANNEL_REQUEST 98, CHANNEL_SUCCESS 99, CHANNEL_FAILURE 100. Disconnect reason codes (RFC 4253 section 11.1, full table there): PROTOCOL_ERROR 2, KEY_EXCHANGE_FAILED 3, CONNECTION_LOST 10, BY_APPLICATION 11. Others are never sent in v1.

Appendix B. File inventory (new files this work adds)

  • tosv-sftp.cpp: the server, repo root, single file.
  • vault.inc: shared logic, repo root, included by both mains.
  • sftp_gateway_keys, sftp_host_ed25519 (+.pub): runtime files in BASE, 0600, git-ignored (INT-07, .gitignore update in same commit).
  • .wiped: sentinel in BASE, git-ignored, operator-cleared.
  • docs/runbooks/sftp.md, sftp.AGENTS.md, ADR-0008, SPEC 0.4.0 rows: docs per SF-43.
  • Gate SFTP section in tests/gate2.sh plus fuzzer plus corpus under tests/sftp/.

Appendix C. Research log (round 2, 2026-10-31)

Primary sources fetched and applied to this document (v0.2.0):

Source Tier Pinned
RFC 4253 (transport): sections 6.1, 6.3, 6.4, 7.2, 7.3, 11.1 T1 35000/32768 floor, KDF letters A-F plus K1/K2 expansion, session id immutable, reason codes
RFC 4252 (auth): section 7 T1 publickey probe plus signed-data field order
RFC 5656 (ECC): section 4, 7.1 T1 ECDH messages 30/31, H formula V_C/V_S/I_C/I_S/K_S/Q_C/Q_S/K
RFC 8731 (curve25519-sha256) T1 @libssh.org alias equivalence, 32-byte checks, abort with code 3
RFC 4251 (architecture): section 5 T1 mpint leading-zero rule for K, quoted verbatim
RFC 8709 ssh-ed25519 (cited, not fetched) T1 K_S and signature blob encodings; fetch at implement time
OpenSSH cipher-chachapoly.c (portable master) T1 two-key 64B layout, seqnr nonce, counters 0/1, verify-before-decrypt
OpenSSH packet.c (portable master) T1 mac set to NULL when authlen nonzero (SF-52 proof)
draft-ietf-secsh-filexfer-02 T1 SFTP v3 IDs: REALPATH 16, STAT 17, RENAME 18, READLINK 19, SYMLINK 20; status and flag values
terrapin-attack.com (researchers) T1 chacha affected, strict-kex is the fix; drove SF-58 upgrade
tinyssh.org T2 prior art: same three-algorithm profile, pubkey-only, libsodium-compatible, public domain; suggested reading for the implementer, transport only (no SFTP there)

Not found online (tried cvsweb plus three mirrors, all 404): OpenBSD PROTOCOL.chacha20poly1305 as a standalone document. The cipher source above supersedes it as evidence; no requirement depends on the missing text.

Appendix D. Implementation log (round 3, 2026-11-01)

Bugs found by Gate 2 interop plus stock-client probes, all fixed same day with regression asserts:

  • D1 SSH window both directions: client stalls past the 2MB offer without WINDOW_ADJUST (5MB put died at 30s); server must also wait for the client window on big downloads instead of disconnecting. Fix: top-up on consume plus a bounded 256-packet pending queue, never recursion.
  • D2 SETSTAT/FSETSTAT double flag read: skip_attrs reads the flags word itself; the handlers pre-read it too, so every chmod failed Bad message. Fix: return flags from the helper. Raw-probe extended-attrs case passed by luck before the fix.
  • D3 Readdir cap counted hidden .tag entries toward the 10k return cap (order-dependent count). Fix: 20k dirent scan cap plus exactly 10k visible names.
  • D4 Stock-client rendering differs per op: REALPATH failures echo the server message (realpath <p>: denied), OPEN failures render generic text (Permission denied). Gate asserts both shapes.
  • D5 sftp put /dev/null fails client-side (not a regular file); ssh takes lowercase -p; OpenSSH 10.2 rejects kex-strict-c-v00 in explicit -oKexAlgorithms but sends the signal implicitly. Gate uses a real empty file and the minimal explicit list.
  • D6 Gate subshell leak: (cd dir && server &) backgrounds the list, so $! is the subshell and kill misses the server; orphans held ports and poisoned the next run's HTTP sections. Fix: exec the server in the subshell, plus disjoint wipe ports 18773-18776.
  • D7 One x-surface 0-byte DAV-put/get leg flaked once (299/300) with no repro under exact-prefix replication; PUT-code and store-id asserts were added to the legs so any recurrence arrives with evidence.
  • D8 Rekey window self-deadlock (asyncssh 5MB GET at TOSV_REKEY=50000, flow control exceeded): SFTP reads plus the client's WINDOW_ADJUST queued in pend during kex; the drain stalled on window 0 before reaching the credit packet, while the client stayed quiet waiting for replies. Server held its own unblocker. Three adjusts received, zero applied, proven by ledger. Fix: WINDOW_ADJUST (type 93) is applied inline in kex_recv via a shared apply_adjust helper (main loop, chan_wait, kex_recv all use it); credits never queue. Post-fix: asyncssh 5MB put/get byte-identical across 84 rekeys, stock sftp 5MB get byte-identical across 39 rekeys, zero flow deaths. Rule: window-credit packets are order-independent admin traffic and must never wait behind data in any queue.
  • D9 rclone close-deadlock (CHANNEL_EOF unanswered): stock sftp and asyncssh fire CHANNEL_CLOSE directly, but Go clients send EOF(96) and wait for the server to move first. We acked EOF with silence, so rclone stalled 30s per command then died on the idle close. Fix: answer EOF with EOF (symmetric half-close, RFC 4254 5.3); the client then sends CLOSE and the existing 97 path finishes cleanly. Post-fix: rclone lsd in 0.02s, 1MB copyto up plus down sha-identical. Regression leg rclone sftp roundtrip in raw_probe.py (SKIPs when rclone is absent, 30s stall budget). Rule: every channel message that can end a session gets an answer; a client waiting on us while we wait on it is always our bug.
  • D10 Double SFTP replies on truncated packets: per-op parse failures sent their own status AND the shared bad-message status (e.g. CLOSE got status 4 plus status 5, same id). Strict clients can misalign on the second reply. Fix: single-reply discipline, every op returns silently on !r.ok and only the shared path sends status 5. Regression probe does a full raw SSH handshake (cryptography lib) and asserts exactly one reply per malformed request; proven 2 replies pre-fix, 1 post-fix. Rule: one request, one reply, no matter how it parses.
113.1ms