Contents · Forum Home · StreamSec Tools 4.1.5.363 documentation

StreamSec.SFTP.ServerSubSystem

A server-side "sftp" subsystem for TstSSHServer.

  Design notes:

  * Single identity. Every filesystem operation executes under the account the
    server process itself runs as -- there is no impersonation of the
    authenticated SSH user. Consequently the subsystem needs no special Windows
    privileges. Users are separated from each other only by the jail root they
    are given (see TstSFTPServerSubSystem.OnResolveRoot).

  * Jailed. Every client-supplied path is mapped through tSFTPJail, which
    resolves '.'/'..' purely inside the virtual namespace and then verifies that
    the canonical physical result is still under the root. It fails closed.

  * Protocol versions 3 and 5. Version 3 is what OpenSSH (and therefore most of
    the world) speaks, so the wire shapes are branched on the negotiated
    version: v3 OPEN carries pflags where v5 carries desired-access + flags, v3
    STAT/RENAME have no trailing flags field, and v3 SSH_FXP_NAME carries a
    longname column that v5 dropped.

  * Close semantics. ReadData is non-blocking: it drains, dispatches, and returns.
    Peer half-close is observed through iSSHServerChannel.PeerEOF (SSH_MSG_CHANNEL_EOF),
    which tSSHServerChannel signals us about, whereupon we Close -- a real
    sftp-server would exit at that point and sshd would send CHANNEL_CLOSE. If the
    peer sends CHANNEL_CLOSE instead, the channel completes the close handshake
    itself and calls ChannelClosed. Never block in ReadData: the broker's teardown
    path waits for this thread to finish and would deadlock against it.

  * Attributes are encoded here rather than via tFileAttributes3/5 because the
    set-based tPermissionFlags cannot express the POSIX S_IFMT type bits
    (S_IFDIR/S_IFREG). A v3 client has no separate type byte and relies on those
    bits to tell a directory from a file, so the server needs full 32-bit mode
    control. The Types units are still used for all protocol constants.

Feature notes: SFTP implementation notes

Classes, interfaces and records

classeSFTPServerError

inherits from Exception

Distinct exception type declared for the SFTP server subsystem so a host application could tell subsystem faults apart from other SSH or file-IO exceptions. No code path in this unit currently raises it: request handlers report faults to the client as SSH_FXP_STATUS rather than raising. Purely server-side -- there is no client here.

(no public members)

recordtSFTPWriter

Minimal growable packet writer. Avoids the error-prone manual length arithmetic of the client transport: build the body, then Finish prepends the 4-byte SFTP length prefix.

procedure Init;
reset to an empty body; call once before building each response packet
procedure WByte(aValue: Byte);
append one byte, e.g. an SSH_FXP_* packet-type or a v4+ file-type tag
procedure WUInt32(aValue: UInt32);
append a 32-bit big-endian value: request-id, status code, flags or count
procedure WUInt64(const aValue: Int64);
append a 64-bit big-endian value, e.g. a file size
procedure WBytes(const aValue: tBytes);
append a length-prefixed byte string (4-byte count then the raw bytes)
procedure WUtf8(const aValue: string);
append a length-prefixed UTF-8 string: filenames, status messages, longnames
procedure WRaw(const aValue: tBytes; aOffset, aCount: Integer);
append raw bytes with NO length prefix, e.g. the SSH_FXP_DATA read payload
function Finish: tBytes;
prepend the 4-byte SFTP length prefix and return the packet ready to hand to Send
property Len: Integer read fLen;
current body length so far, excluding the prefix Finish will add

recordtSFTPReader

Bounds-checked packet reader over the decoders in StreamSec.SSH.Types.

procedure Init(const aBuf: tBytes; aOffset, aCount: Integer);
point the reader at one decoded request body before pulling its fields
function RByte: Byte;
read the next byte (packet-type or v4+ type tag); bounds-checked, raises on underrun
function RUInt32: UInt32;
read a 32-bit big-endian value: request-id, flags, v3 pflags or v5 access mask
function RUInt64: Int64;
read a 64-bit big-endian value, e.g. a read/write offset
function RBytes: tBytes;
read a length-prefixed byte string, e.g. an opaque file/dir handle from the client
function RUtf8: string;
read a length-prefixed UTF-8 string, e.g. a client-supplied path or filename
function More: Boolean;
True while unconsumed bytes remain; used to probe for optional trailing fields
property Left: Integer read fLeft;
bytes still unread in the current request body

recordtSFTPAttrs

Decoded / to-be-encoded file attributes, version neutral.

HaveSize: Boolean;
Size is present/should be encoded; gates the SIZE flag on the wire
HavePerm: Boolean;
Mode is present/should be encoded; gates the PERMISSIONS flag
HaveTimes: Boolean;
the time fields are present; gates the v3 ACMODTIME or v4+ A/C/M-TIME flags
HaveOwner: Boolean;
Owner/Group are present (v4+ OWNERGROUP only); the server itself leaves this False
IsDir: Boolean;
directory vs regular file; drives the v4+ type byte and the longname leading 'd'
Size: Int64;
file size in bytes, valid only when HaveSize
Mode: UInt32;
full POSIX mode incl. S_IFMT
ATime: Int64;
seconds since Unix epoch
MTime: Int64;
last-modification time, seconds since the Unix epoch
CTime: Int64;
creation/change time (encoded on v4+ only), seconds since the Unix epoch
Uid, Gid: UInt32;
numeric POSIX owner/group ids as read from a v3 client; never applied on this Windows server
Owner, Group: string;
textual owner/group names (v4+ OWNERGROUP); valid only when HaveOwner, never applied here
procedure Clear;
reset every field to its empty/absent state before decoding a request or stat'ing a path

classtSFTPServerHandle

One live entry in the server's handle table: the state behind an opaque handle the server returned for an SSH_FXP_OPEN (a file) or SSH_FXP_OPENDIR (a directory cursor). Purely internal to the server; applications never construct or see these, only the random handle bytes that key them.

destructor Destroy; override;
closes the open file stream and any live find handle when the handle is dropped or the session ends

classtSFTPJail

The security boundary: virtual (client) path <-> physical path.

NOW AN ADAPTER over stFileJail, which is the library's single path- confinement implementation. This class used to carry its own copy of the algorithm; two implementations of a security boundary is one more than a library should have, and this one had drifted - it hard-coded '\' in two places (so it could not serve a POSIX build) and folded case with SameText on every platform (so on POSIX it accepted 'FOO' for a root named 'foo').

Rule set is cJailRulesLegacy, which is faithful to what this class refused before: wildcards and redirection characters, NUL, ':' and '\' in a segment, and any '..' below the root - but NOT device names or 8.3 shapes, which an existing client may legitimately hold. See that constant for the one deliberate tightening.

Extension mode is emUngated: an SFTP jail root IS the authenticated user's own home, so the kind of a file carries no meaning here.

WHAT THIS MIGRATION DOES NOT DO. stFileJail's handle-returning entry points (OpenVerified / OpenStream) close the check-then-open race; this adapter still hands back a PATH, because every caller below opens by name and enumerates with FindFirst. So SFTP gains one shared, cross-platform, link-aware algorithm and loses nothing - but it does not yet gain TOCTOU freedom. Moving the callers onto handles is the follow-up that would.

constructor Create(const aPhysicalRoot: string);
Establishes the sandbox for one connection. Fails CLOSED: if aPhysicalRoot cannot be opened and pinned, every later mapping refuses rather than the server starting and discovering it per-request.
function MapToPhysical(const aSftpPath: string; out aPhysical: string): Boolean;
Maps a client-supplied virtual (POSIX slash) path to a physical path, resolving single-dot and double-dot purely inside the namespace and failing closed (Result False) on any path that would escape the root or carry characters the OS would reinterpret - and on one that leads out of the root on di... Full description »
function MapToVirtual(const aPhysical: string; out aVirtual: string): Boolean;
The reverse mapping: turns a physical path back into the slash-rooted virtual path the client sees. Used to answer SSH_FXP_REALPATH with a canonical name; Result is False if the physical path lies outside the jail.
function OpenStream(const aSftpPath: string; aWrite: Boolean; out aStream: TStream; out aVerdict: tJailVerdict): Boolean;
Opens an EXISTING file and hands back the stream over the descriptor the jail itself verified - so the object that was checked is the object that is read, with no second resolution in between. Full description »
property Root: string read GetRoot;
The canonical physical directory the jail is rooted at, no trailing delimiter, AS THE OPERATING SYSTEM REPORTS IT - which on Windows is an extended-length '\\?\' form. Full description »

classtSFTPServerSubSystem

inherits from tSSHBaseServerSubSystem

The per-channel SFTP engine: frames and dispatches SFTP requests arriving on one SSH channel and executes them against the jailed filesystem. One instance is created per accepted 'sftp' channel by TstSFTPServerSubSystem.NewSubSystem; applications drive the component below, not this class directly.

constructor Create(const aController: iSSHSubSystemController; const aChannel : iSSHServerChannel); override;
Constructs the subsystem for one channel; the framework calls this via TstSFTPServerSubSystem.NewSubSystem and applications do not call it directly. Full description »
destructor Destroy; override;
Releases the live handle table (closing any open files and directory find handles) and the jail when the session object is destroyed.
procedure Configure(const aRoot: string; aReadOnly: Boolean);
Installs the jail root and read-only policy for this connection; called once by NewSubSystem right after construction, before any request is dispatched.
procedure ReadData(const aChannel: iSSHServerChannel); override;
The framework's readiness callback, invoked on the subsystem thread whenever the channel has inbound data: it drains the channel non-blockingly, frames and dispatches every complete SFTP request, then closes the channel on peer EOF. Must never block or the broker's teardown deadlocks against it.
procedure ChannelClosed; override;
Framework notification that the channel has closed; drops all open handles so files and directory cursors are released.
property Version: Integer read fVersion;
The SFTP protocol version negotiated with the client during SSH_FXP_INIT: the client's offer clamped to at most cSFTPServerMaxVersion (5) and at least 3, so 3, 4 or 5 (4 and 5 share one wire path). Reads 3 until INIT completes.

classTstSFTPServerSubSystem — component reference

inherits from TstCustomSSHSubSystem

Drop-in server component that offers the 'sftp' subsystem on a TstSSHServer. Set the jail root and policy through the published properties below; it spawns one tSFTPServerSubSystem per accepted sftp channel via NewSubSystem.

constructor Create(aOwner: TComponent); override;
Standard component constructor; sets the advertised subsystem Identifier to 'sftp' and defaults RequireUserAuthorization to True (fail closed). Drop this component alongside your TstSSHServer and it offers the 'sftp' subsystem to authorized users. » member page
property RootDir: string read fRootDir write fRootDir;
Physical directory that becomes the client's "/". » member page
property ReadOnly: Boolean read fReadOnly write fReadOnly;
Refuse every mutating request with SSH_FX_PERMISSION_DENIED. » member page
property PerUserSubDir: Boolean read fPerUserSubDir write fPerUserSubDir default False;
Jail each authenticated user into RootDir\<username> instead of RootDir. » member page
property RequireUserAuthorization: Boolean read fRequireUserAuthorization write fRequireUserAuthorization default True;
Refuse to serve unless the SSH server has a TstSSHServerUsers attached, so that the per-user 'sftp' grant is actually enforced. Full description »
property OnResolveRoot: tSFTPResolveRootEvent read fOnResolveRoot write fOnResolveRoot;
Last word on the jail root for a connection; overrides the above. » member page

Types (enumerations, sets, aliases)

proctSFTPServerTraceProc

Opt-in diagnostics. Assign StreamSec.SFTP.ServerSubSystem.SFTPServerTrace to get a line per received request / sent response; leave it nil in production. Called from the subsystem thread, so the hook must be thread-safe.

  tSFTPServerTraceProc = procedure (const aMsg: string);

enumtSFTPHandleKind

Which kind of object an open server handle backs: hkFile an open file stream,
hkDir an open directory-listing cursor.

  tSFTPHandleKind = (hkFile, hkDir);

proctSFTPResolveRootEvent

Signature for TstSFTPServerSubSystem.OnResolveRoot: fired once per connection with the authenticated user name in aUser and the jail root computed so far in aRoot; the handler may overwrite aRoot to pick the physical directory that becomes that user's "/".

  tSFTPResolveRootEvent = procedure (Sender: TObject;
                               const aUser : string;
                                 var aRoot : string) of object;

Routines