Contents · Forum Home · StreamSec Tools 4.1.5.365 documentation

Run an asynchronous TLS server

A TsmAsyncTLSServer can serve your own protocol over TCP. This example returns each byte the client sends after the TLS handshake. One listener handles the connections, and each accepted connection gets its own session.

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.

Prepare the listener

You need a PFX containing the server's certificate and private key, its password, and the CA certificate for the chain. Choose a local address and TCP port. Use a loopback address to make the service available only on this machine.

uses
  stDERUtils, stSecUtils, StreamSec.Mobile.TlsInternalServer,
  StreamSec.Mobile.AsyncTLSServer;

Give each connection a session

type
  tEchoSession = class(TInterfacedObject, iAppSession)
  private
    fTransport: iAppTransport;
  public
    constructor Create(const aTransport: iAppTransport);
    procedure Opened;
    procedure DataReceived(aData: Pointer; aLen: Integer);
    procedure EarlyDataReceived(aData: Pointer; aLen: Integer);
    procedure Closed(aGraceful: Boolean);
    function Instance: TObject;
  end;

  tEchoProtocol = class(TInterfacedObject, iAppProtocol)
  public
    function GetToken: OctetString;
    function GetDescription: string;
    function CreateSession(const aTransport: iAppTransport): iAppSession;
  end;
function tEchoProtocol.GetToken: OctetString;
begin
  Result := 'echo';
end;

function tEchoProtocol.GetDescription: string;
begin
  Result := 'Byte echo';
end;

function tEchoProtocol.CreateSession(const aTransport: iAppTransport): iAppSession;
begin
  Result := tEchoSession.Create(aTransport);
end;

The listener holds the registered iAppProtocol. Its token is what a client offers through ALPN. This port is dedicated to echo, so fbpFirstRegistered also serves a client that omits ALPN.

constructor tEchoSession.Create(const aTransport: iAppTransport);
begin
  inherited Create;
  fTransport := aTransport;
end;

procedure tEchoSession.Opened;
begin
end;

procedure tEchoSession.DataReceived(aData: Pointer; aLen: Integer);
begin
  fTransport.Send(aData, aLen);
end;

procedure tEchoSession.EarlyDataReceived(aData: Pointer; aLen: Integer);
begin
  { This service accepts application input only after the handshake. }
end;

procedure tEchoSession.Closed(aGraceful: Boolean);
begin
  fTransport := nil;
end;

function tEchoSession.Instance: TObject;
begin
  Result := Self;
end;

DataReceived receives a chunk of the decrypted byte stream. A single callback can contain part of a line or several lines. Echo can send each chunk back immediately. A command parser would keep its unfinished line in the session. The reactor calls these methods on an I/O thread, so keep the callbacks short. Closed releases this session's transport reference.

Register the protocol and start listening

type
  tEchoListener = class(TsmAsyncTLSServer)
    procedure ConfigureEngine(Sender: TObject; aIndex: Integer;
      aEngine: TsmSimpleTLSInternalServer);
  end;

procedure tEchoListener.ConfigureEngine(Sender: TObject; aIndex: Integer;
  aEngine: TsmSimpleTLSInternalServer);
begin
  aEngine.Options.RequestClientCertificate := False;
  aEngine.Options.RequireClientCertificate := False;
end;

function StartAsyncEcho(const aBindIP: string; aPort: Word;
  const aCAFile, aPfxFile, aPassword: string): TsmAsyncTLSServer;
var
  lServer: tEchoListener;
begin
  lServer := tEchoListener.Create(nil);
  try
    lServer.BindIP := aBindIP;
    lServer.BindPort := aPort;
    lServer.Protocols.AddProtocol(tEchoProtocol.Create);
    lServer.FallbackPolicy := fbpFirstRegistered;
    lServer.OnConfigureEngine := lServer.ConfigureEngine;
    lServer.LoadRootCertsFromFile(aCAFile);
    lServer.ImportFromPFX(aPfxFile, tDualSecretKey.CreateForPFX(aPassword));
    lServer.Active := True;
    Result := lServer;
  except
    lServer.Free;
    raise;
  end;
end;

StartAsyncEcho returns an active listener owned by the caller. A port of zero asks the operating system to pick one. Read BoundPort after activation to tell a client where to connect.

Register the protocol and record the trust anchors and PFX before setting Active. The server applies them in that order as it creates its TLS engines. OnConfigureEngine runs once per engine and sets the client certificate policy. This service authenticates the server only. For a service that authenticates its clients in the handshake, see Require client certificates.

Connect and stop

Connect a TLS client with certificate checks shows a client for this listener. To stop it, set Active to False on the owning thread. Free the listener when you are finished with it. The async TLS server notes describe protocol selection, connection limits and shutdown.

Reference

TsmAsyncTLSServer · StreamSec.Mobile.AsyncTLSServer · StreamSec.Mobile.TlsInternalServer

Related tasks