Contents · Forum Home · StreamSec Tools 4.1.5.365 documentation

Resume a TLS 1.3 connection with a session ticket

Reuse a ticket from an authenticated TLS 1.3 connection when reconnecting to the same service. The server decides whether to accept the ticket. Read IsResumedSession after the handshake to see which path it took.

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.

Bind the client to one service

uses
  System.SysUtils, StreamSec.Mobile.TLSClient, StreamSec.Mobile.TlsClass,
  StreamSec.Mobile.TlsConst;

type
  tTlsTicketClient = class(TsmTLSClient)
  private
    fServiceHost, fServiceName, fProtocol: string;
    fServicePort: Word;
    fNext, fOffered: TTls13ClientTicket;
    procedure SaveTicket(Sender: TObject; aTicket: TTls13ClientTicket);
    function GetHasTicket: Boolean;
  protected
    procedure ConfigureLayer(const aLayer: TCustomTLS_ContentLayer); override;
  public
    constructor CreateForService(const aHost, aServerName: string; aPort: Word;
      const aCAFile, aProtocol: string);
    destructor Destroy; override;
    procedure Connect; override;
    procedure Disconnect; override;
    property HasTicket: Boolean read GetHasTicket;
  end;
constructor tTlsTicketClient.CreateForService(const aHost, aServerName: string;
  aPort: Word; const aCAFile, aProtocol: string);
begin
  inherited Create(nil);
  if (aHost = '') or (aServerName = '') or (aPort = 0) or (aProtocol = '') then
    raise EArgumentException.Create('Supply a host, port, DNS name and ALPN protocol');
  if TLSServer.LoadRootCertsFromFile(aCAFile) = 0 then
    raise eTLSClientError.CreateFmt('No trust anchors in %s', [aCAFile]);
  fServiceHost := aHost;
  fServiceName := aServerName;
  fServicePort := aPort;
  fProtocol := aProtocol;
  Host := aHost;
  ServerName := aServerName;
  Port := aPort;
  ALPNProtocols.Add(aProtocol);
end;

Create one client with the address and port to dial, the DNS name on the server certificate, a trusted CA file and the service's ALPN identifier. For a local status service, use 127.0.0.1 as the address, localhost as the expected name and status/1 as the protocol. The first connection checks the certificate chain and name. Reuse the client sequentially. Create a new one if the service, certificate trust policy or client identity changes.

The client checks, on every connection, that the server's certificate is issued for the host name it connects to. Give it the DNS name the certificate carries, not the server's IP address: with an address the connection fails although the server's certificate is valid. To connect by address, set ServerName to the name in the certificate - see Download a page over HTTPS.

Keep a ticket for the next connection

procedure tTlsTicketClient.SaveTicket(Sender: TObject; aTicket: TTls13ClientTicket);
var
  lCopy: TTls13ClientTicket;
begin
  if (aTicket.LifetimeSecs = 0) or (aTicket.LifetimeSecs > 604800) or
     not SameText(aTicket.ServerName, fServiceName) or
     (TEncoding.ASCII.GetString(aTicket.ApplicationProtocol) <> fProtocol) then Exit;
  lCopy := aTicket.Clone;
  fNext.Free;
  fNext := lCopy;
end;

function tTlsTicketClient.GetHasTicket: Boolean;
var
  lNow: TDateTime;
begin
  lNow := Now;
  Result := Assigned(fNext) and (lNow >= fNext.ReceivedAt) and
    (lNow < fNext.ReceivedAt + fNext.LifetimeSecs / 86400);
end;

procedure tTlsTicketClient.ConfigureLayer(const aLayer: TCustomTLS_ContentLayer);
begin
  inherited ConfigureLayer(aLayer);
  aLayer.OnNewSessionTicket := SaveTicket;
  if HasTicket then begin
    fOffered := fNext;
    fNext := nil;
    aLayer.ResumptionTicket := fOffered;
  end
  else
    FreeAndNil(fNext);
end;

The server can send one or more NewSessionTicket messages after the handshake. The client processes them when it reads TLS records. The callback receives a ticket owned by the content layer. Clone it in the callback to keep it. This example keeps the latest usable ticket in memory, checks its lifetime and offers it once. Each ticket contains a secret used to authenticate resumption.

procedure tTlsTicketClient.Connect;
begin
  if Connected then
    raise eTLSClientError.Create('Disconnect before reconnecting');
  if not ImplicitTLS or not RequireTLS or
     not SameText(Host, fServiceHost) or not SameText(ServerName, fServiceName) or
     (Port <> fServicePort) or (ALPNProtocols.Count <> 1) or
     (ALPNProtocols[0] <> fProtocol) then
    raise eTLSClientError.Create('A ticket client is bound to one TLS service');
  try
    inherited Connect;
    if not Secure or (ContentLayer.Version.major <> 3) or
       (ContentLayer.Version.minor <> cTLS13vmm) or (NegotiatedProtocol <> fProtocol) then
      raise eTLSClientError.Create('Expected TLS 1.3 and the configured application protocol');
  except
    Disconnect;
    raise;
  end;
end;

procedure tTlsTicketClient.Disconnect;
begin
  inherited Disconnect;
  FreeAndNil(fOffered);
end;

destructor tTlsTicketClient.Destroy;
begin
  Disconnect;
  fNext.Free;
  inherited Destroy;
end;

The content layer borrows the offered ticket for the connection. Disconnect releases that copy after closing the session. The client keeps any new ticket it received for the next connection.

Check whether the connection resumed

function ReadServiceStatus(aClient: tTlsTicketClient; out aResumed: Boolean): string;
begin
  aClient.Connect;
  try
    aResumed := aClient.ContentLayer.IsResumedSession;
    aClient.SendLine('STATUS');
    if not aClient.ReadLine(Result, aClient.IOTimeout, 32) then
      raise eTLSClientError.Create('No complete status reply');
  finally
    aClient.Disconnect;
  end;
end;

Call ReadServiceStatus twice with the same client. It sends a CRLF-terminated STATUS request after each handshake and reads the reply. A new client reports aResumed = False. If HasTicket is true, the next call offers that ticket. A server that accepts it gives aResumed = True. A server that has forgotten it can complete another full handshake, in which case the request still works. Free the client when finished.

To offer a replay-safe query during a resumed handshake, see Send a replay-safe request with TLS 1.3 0-RTT.

Reference

TsmTLSClient · StreamSec.Mobile.TLSClient · StreamSec.Mobile.TlsClass · StreamSec.Mobile.TlsConst

Related tasks