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
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)
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;
procedure WByte(aValue: Byte);
procedure WUInt32(aValue: UInt32);
procedure WUInt64(const aValue: Int64);
procedure WBytes(const aValue: tBytes);
procedure WUtf8(const aValue: string);
procedure WRaw(const aValue: tBytes; aOffset, aCount: Integer);
function Finish: tBytes;
property Len: Integer read fLen;
Bounds-checked packet reader over the decoders in StreamSec.SSH.Types.
procedure Init(const aBuf: tBytes; aOffset, aCount: Integer);
function RByte: Byte;
function RUInt32: UInt32;
function RUInt64: Int64;
function RBytes: tBytes;
function RUtf8: string;
function More: Boolean;
property Left: Integer read fLeft;
Decoded / to-be-encoded file attributes, version neutral.
HaveSize: Boolean;
HavePerm: Boolean;
HaveTimes: Boolean;
HaveOwner: Boolean;
IsDir: Boolean;
Size: Int64;
Mode: UInt32;
ATime: Int64;
MTime: Int64;
CTime: Int64;
Uid, Gid: UInt32;
Owner, Group: string;
procedure Clear;
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;
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);
function MapToPhysical(const aSftpPath: string; out aPhysical: string): Boolean;
function MapToVirtual(const aPhysical: string; out aVirtual: string): Boolean;
function OpenStream(const aSftpPath: string; aWrite: Boolean; out aStream: TStream; out aVerdict: tJailVerdict): Boolean;
property Root: string read GetRoot;
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;
destructor Destroy; override;
procedure Configure(const aRoot: string; aReadOnly: Boolean);
procedure ReadData(const aChannel: iSSHServerChannel); override;
procedure ChannelClosed; override;
property Version: Integer read fVersion;
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;
property RootDir: string read fRootDir write fRootDir;
property ReadOnly: Boolean read fReadOnly write fReadOnly;
property PerUserSubDir: Boolean read fPerUserSubDir write fPerUserSubDir default False;
property RequireUserAuthorization: Boolean read fRequireUserAuthorization write fRequireUserAuthorization default True;
property OnResolveRoot: tSFTPResolveRootEvent read fOnResolveRoot write fOnResolveRoot;
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.
Which kind of object an open server handle backs: hkFile an open file stream,
hkDir an open directory-listing cursor.
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 "/".