Contents · Forum Home · StreamSec Tools 4.1.5.364 documentation

Upload and download files over SFTP

SFTP transfers files over an SSH connection. Two components do it: TstSSHSocketClient makes the connection and signs in, and TstSFTPClient, whose Transport is the SSH client, moves the files.

The components on this page are normally placed on a form or a data module at design time and set up in the Object Inspector. The sample creates them in code instead, because code shows at a glance which properties are changed from their default values.

The units

uses
  System.SysUtils,
  { The public-key algorithms: without them the client has no key exchange
    and cannot check a host key. }
  StreamSec.DSI.Arith, StreamSec.DSI.IFC, StreamSec.DSI.ECArith,
  StreamSec.DSI.CurveXArith, StreamSec.DSI.CurveEdArith, StreamSec.DSI.EdDSA,
  stSecComp,                  // TstCustomMPKey: a key component
  StreamSec.SSH.PublicKeyList, // TstSSHPublicKeyList: known host keys
  StreamSec.SSH.SocketClient, // TstSSHSocketClient
  StreamSec.SFTP.Transport,   // eSFTPClientError
  StreamSec.SFTP.Client;      // TstSFTPClient

The algorithm lists of the SSH client are filled by the units linked into the program. The ones above give it key exchange over Curve25519, Curve448 and the NIST curves, and RSA, ECDSA and EdDSA host keys. For the ML-KEM key exchanges add StreamSec.DSI.MLC; the hybrid ones, such as mlkem768x25519-sha256, need StreamSec.DSI.CompositeKEM as well.

The server's host key

An SSH client that accepts any host key can be talked to by anyone between it and the server, and that is what this client does until a key is pinned. Ask the server's administrator for the host key and keep it in a file; a TstSSHPublicKeyList reads it.

function LoadHostKeys(const aFileName: string): TstSSHPublicKeyList;
begin
  { The servers' host keys, as their administrators gave them to you, kept
    in a file of RFC 4716 blocks, each under the name you gave it. }
  Result := TstSSHPublicKeyList.Create(nil);
  try
    Result.AutoSave := False;   // only read here, never written back
    Result.RSAPublicKeyFormat.SelectedOptionNames := 'SSH-Base64-RSA';
    Result.PublicKeyFileName := aFileName;
    { Enabled MUST be set to True here, before the list is passed on.
      Setting it is what reads the file, and Connect takes the list as a
      TstCustomMPKey, a base class that cannot set it. A list passed on
      without it holds no key, and every server is refused. }
    Result.Enabled := True;
  except
    Result.Free;
    raise;
  end;
end;
Enabled MUST be set to True before a key component is passed to
anything that takes it as a base type - TstCustomMPKey or TComponent,
as Connect below does. Setting it is what reads the key from its file,
and code that holds only the base type cannot set it. A list passed on
without it holds no key, and every server is refused, the right one
included. On a form, set EnabledRunTime in the Object Inspector.

Connect and sign in

constructor tTaskSftp.Create;
begin
  inherited Create;
  fSsh := TstSSHSocketClient.Create(nil);
  fSftp := TstSFTPClient.Create(nil);
  fSftp.Transport := fSsh;   // SFTP runs over the SSH connection
end;

procedure tTaskSftp.Connect(const aHost: string; aPort: Integer;
  aHostKeys: TstCustomMPKey; const aHostKeyName: string;
  const aUser, aPassword: string);
begin
  fSsh.Host := aHost;
  fSsh.Port := aPort;
  { THE SERVER'S HOST KEY. Without a pinned key the client accepts whatever
    key the server presents - and so would talk to anyone in between. Pin
    the key you obtained from the server's administrator: once a key is
    pinned, only pinned keys are accepted. aHostKeys is an enabled key
    component - the list from LoadHostKeys - and aHostKeyName the name the
    server's key is filed under. This is an RSA key; use ServerECDSAKey or
    ServerEdDSAKey, with their identifiers, for those kinds. }
  fSsh.ServerRSAKey := aHostKeys;
  fSsh.ServerRSAKeyIdentifier := aHostKeyName;
  { Pinning registers the key's algorithms; select them. Selecting all is
    safe: the entries without a key are dropped once a key is pinned. }
  fSsh.ServerKeyOptions.SelectedOptionNames := fSsh.ServerKeyOptions.AllOptionNames;
  { A client created in code has no algorithms selected - on a form the
    Object Inspector shows these lists. Offer every one that is linked in. }
  fSsh.KexOptions.SelectedOptionNames := fSsh.KexOptions.AllOptionNames;
  fSsh.CipherC2SOptions.SelectedOptionNames := fSsh.CipherC2SOptions.AllOptionNames;
  fSsh.CipherS2COptions.SelectedOptionNames := fSsh.CipherS2COptions.AllOptionNames;
  fSsh.MacC2SOptions.SelectedOptionNames := fSsh.MacC2SOptions.AllOptionNames;
  fSsh.MacS2COptions.SelectedOptionNames := fSsh.MacS2COptions.AllOptionNames;
  fSsh.UserAuthOptions.SelectedOptionNames := 'password';
  fSsh.Password := aPassword;   // as typed
  fSsh.ConnectToHost;           // key exchange; raises if the key is not the pinned one
  if not fSsh.Login(aUser) then
    raise eSFTPClientError.Create('The server did not accept the sign-in');
end;

Move files

procedure tTaskSftp.Upload(const aLocalFile, aRemoteFile: string);
begin
  fSftp.PutFile(aLocalFile, aRemoteFile);
end;

procedure tTaskSftp.Download(const aRemoteFile, aLocalFile: string);
begin
  { True: replace aLocalFile if it exists. Without it, an existing local
    file raises eSFTPFileAlreadyExists. }
  fSftp.GetFile(aRemoteFile, aLocalFile, True);
end;

The calls block until the transfer is complete, and raise when the server refuses - a path that does not exist, a file you may not write. List returns a directory's entries, and MakeDir, Rename and Delete do what their names say.

Close

procedure tTaskSftp.Close;
begin
  fSsh.Close;   // safe when not connected
end;

destructor tTaskSftp.Destroy;
begin
  Close;
  fSftp.Free;
  fSsh.Free;
  inherited;
end;

Close may also be called from another thread to cancel a connection or a sign-in that is taking too long.

The SSH notes and the SFTP notes cover the algorithms, keys and the server side.

Reference

TstSSHSocketClient · TstSFTPClient · StreamSec.SSH.SocketClient · StreamSec.SFTP.Client