Contents · Forum Home · StreamSec Tools 4.1.5.364 documentation

Serve HTTPS from a PFX file

TsmAsyncTLSServer accepts TLS connections and hands each one to a protocol component: TsmHTTPSv2 for HTTP/2, TsmHTTPSv1dot1 for HTTP/1.1. The certificate and its private key come from a PFX (PKCS #12) file.

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, System.Classes, System.IOUtils,
  stSecUtils,                          // tDualSecretKey
  StreamSec.Http.Server,               // iHttpRequest, iHttpResponse
  StreamSec.Mobile.TlsInternalServer,  // TsmSimpleTLSInternalServer
  StreamSec.Mobile.AsyncTLSServer,     // TsmAsyncTLSServer
  StreamSec.Mobile.HTTPS;              // TsmHTTPSv2, TsmHTTPSv1dot1

The server

type
  tTaskHttpsServer = class
  private
    fServer: TsmAsyncTLSServer;
    fHttp2: TsmHTTPSv2;
    fHttp11: TsmHTTPSv1dot1;
    fPfxFile, fPfxPassword: string;
    fPfxContent: TBytes;
  protected
    procedure ConfigureEngine(Sender: TObject; aIndex: Integer;
                              aEngine: TsmSimpleTLSInternalServer); virtual;
    procedure Request(Sender: TObject; const aRequest: iHttpRequest;
                      const aResponse: iHttpResponse); virtual;
  public
    constructor Create(const aPfxFile, aPfxPassword: string);
    destructor Destroy; override;
    procedure Start(const aBindIP: string; aPort: Integer);
    procedure Stop;
    property Server: TsmAsyncTLSServer read fServer;
    { The PFX as it was read at Start - what the server is serving. }
    property PfxContent: TBytes read fPfxContent;
  end;
constructor tTaskHttpsServer.Create(const aPfxFile, aPfxPassword: string);
begin
  inherited Create;
  fPfxFile := aPfxFile;
  fPfxPassword := aPfxPassword;
  fServer := TsmAsyncTLSServer.Create(nil);
  fHttp2 := TsmHTTPSv2.Create(nil);
  fHttp11 := TsmHTTPSv1dot1.Create(nil);
  fHttp2.OnRequest := Request;
  fHttp11.OnRequest := Request;
  { The server picks the protocol: the first one registered that the client
    also offers. Register HTTP/2 first, or every client gets HTTP/1.1. }
  fHttp2.Server := fServer;
  fHttp11.Server := fServer;
  { A client that offers no protocol at all gets the first registered. }
  fServer.FallbackPolicy := fbpFirstRegistered;
  fServer.OnConfigureEngine := ConfigureEngine;
end;

procedure tTaskHttpsServer.ConfigureEngine(Sender: TObject; aIndex: Integer;
  aEngine: TsmSimpleTLSInternalServer);
begin
  { Called for each TLS engine the server sets up, before it accepts. The
    PFX holds the certificate, its chain and the private key.
    An engine asks every client for a certificate and refuses one without -
    mutual TLS - unless told otherwise. A server for browsers and ordinary
    clients turns that off. }
  aEngine.Options.RequestClientCertificate := False;
  aEngine.Options.RequireClientCertificate := False;
  aEngine.ImportFromPFX(fPfxContent, tDualSecretKey.CreateForPFX(fPfxPassword));
end;

procedure tTaskHttpsServer.Start(const aBindIP: string; aPort: Integer);
begin
  { Read once, so every engine gets the same certificate even if the file is
    replaced while the server starts. }
  fPfxContent := TFile.ReadAllBytes(fPfxFile);
  fServer.BindIP := aBindIP;   // '' listens on every interface
  fServer.BindPort := aPort;
  fServer.Active := True;
end;

procedure tTaskHttpsServer.Stop;
begin
  fServer.Active := False;
end;

destructor tTaskHttpsServer.Destroy;
begin
  fServer.Active := False;
  fHttp2.Free;
  fHttp11.Free;
  fServer.Free;
  inherited;
end;

Points that matter:

Answer requests

procedure tTaskHttpsServer.Request(Sender: TObject; const aRequest: iHttpRequest;
  const aResponse: iHttpResponse);
var
  lBody: TStream;
  lText: TBytes;
begin
  { Called for every request no route matched, inline on the I/O thread that
    delivered it: several run at once, so keep shared state behind a lock,
    and do slow work elsewhere - a handler that blocks holds that thread. }
  if aRequest.Path = '/hello' then begin
    aResponse.SetContentType('text/plain; charset=utf-8');
    aResponse.SetContentText('hello over ' + aRequest.NegotiatedProtocol);
  end
  else if (aRequest.Path = '/echo') and
          ((aRequest.Method = 'POST') or (aRequest.Method = 'PUT')) then begin
    lBody := aRequest.Body;   // complete, and bounded by Limits.BodyBytes
    SetLength(lText, lBody.Size);
    if Length(lText) > 0 then
      lBody.ReadBuffer(lText[0], Length(lText));
    aResponse.SetContentType('application/json');
    aResponse.SetContent(Pointer(lText), Length(lText));
  end
  else begin
    aResponse.SetStatus(404);
    aResponse.SetContentType('text/plain; charset=utf-8');
    aResponse.SetContentText('not found');
  end;
end;

OnRequest is the catch-all: a route added with AddHandler, AddEvent or AddFile takes precedence, and a request nothing answers gets 404. One handler serves both protocols; NegotiatedProtocol says which.

Start it

function StartHttpsServer(const aPfxFile, aPassword, aBindIP: string;
  aPort: Integer): tTaskHttpsServer;
begin
  Result := tTaskHttpsServer.Create(aPfxFile, aPassword);
  try
    Result.Start(aBindIP, aPort);   // '' for every interface
  except
    Result.Free;
    raise;
  end;
end;

A client for this server: Download a page over HTTPS. The async TLS server notes describe the threads, the limits on connections and how the server sheds load.

Reference

TsmAsyncTLSServer · TsmHTTPSv2 · TsmHTTPSv1dot1 · StreamSec.Mobile.AsyncTLSServer · StreamSec.Mobile.HTTPS

Related tasks