Contents · Forum Home · StreamSec Tools 4.1.5.364 documentation

Get a certificate from Let's Encrypt

TsmAcmeClient obtains a certificate from a CA that speaks ACME (RFC 8555), such as Let's Encrypt, for a server you run - and with TsmAcmeRenewalManager keeps it renewed. In managed mode, shown here, the client proves to the CA that you control the names by answering its challenge on your own HTTPS server, and installs the certificate in it.

Before you start:

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,
  stOIDs,                              // prime256v1
  stSecUtils,                          // tDualSecretKey
  StreamSec.DSI.ArithComp,             // TstECDSAKey
  StreamSec.Mobile.TlsInternalServer,  // TsmSimpleTLSInternalServer
  StreamSec.Mobile.AsyncTLSServer,     // TsmAsyncTLSServer
  StreamSec.Mobile.Acme,               // TsmAcmeClient
  StreamSec.Mobile.AcmeRenewal,        // TsmAcmeRenewalManager
  TaskKeyFile;                         // OpenOrCreateKey: the account key file

Reaching the CA

constructor tTaskAcme.Create(aServer: TsmAsyncTLSServer; const aDataDir, aSecret,
  aCARootFile, aDirectoryUrl, aContact: string; const aDomains: array of string;
  aTermsAgreed: Boolean);
var
  lDomain: string;
begin
  inherited Create;
  { The ACME client reaches the CA over HTTPS through the application-wide
    TLS engine, GlobalServer. It must trust the root the CA's own server
    certificate chains to - for Let's Encrypt, ISRG Root X1 - and nothing
    more is needed. }
  fDirectoryTrust := TsmSimpleTLSInternalServer.Create(nil);
  if fDirectoryTrust.LoadRootCertsFromFile(aCARootFile) = 0 then
    raise eAcmeError.CreateFmt('No certificate in %s', [aCARootFile]);
  fDirectoryTrust.IsGlobalServer := True;
  fDirectoryTrust.TLSSetupClient;

The account

{ The ACCOUNT key identifies you to the CA. Keep it: a new key is a new
  account. It is created on the first run and read back on every later
  one; OpenOrCreateKey sets Enabled to True, which MUST happen before the
  key is handed to the client below, which takes it as TComponent. }
fAccountKey := OpenOrCreateKey(TPath.Combine(aDataDir, 'acme-account.key'), aSecret);
fAcme := TsmAcmeClient.Create(nil);
fAcme.AccountKey := fAccountKey;
{ Develop against the staging directory: production limits how many
  certificates a domain gets per week, and failed attempts count. }
fAcme.DirectoryUrl := aDirectoryUrl;
if aContact <> '' then
  fAcme.Contact.Add('mailto:' + aContact);   // expiry and account notices
{ Agreeing to the CA's terms of service is the user's decision: show the
  terms (Acme.Directory.TermsOfService names them) and pass what the user
  answered. Registration is refused while this is False. }
fAcme.TermsOfServiceAgreed := aTermsAgreed;

The account key is kept in a password-protected file, read back on every start - see Create a key and a certificate signing request for how OpenOrCreateKey works. Back that file up: losing it means a new account.

Enabled MUST be True on a key component before it is assigned to
AccountKey or CertificateKey. The client takes the keys as
TComponent and cannot set it; OpenOrCreateKey does it for the account
key, and the code below for the certificate key.

The certificate and the server

  { The CERTIFICATE key is the server's key, a new one for each certificate;
    the client keeps it, with the certificate, in the PFX below. Enabled MUST
    be True before it is handed over as TComponent; for a key generated in
    memory it just confirms that a key is held. }
  fCertificateKey := TstECDSAKey.Create(nil);
  fCertificateKey.GenerateNewKeys(prime256v1, False);
  fCertificateKey.Enabled := True;
  fAcme.CertificateKey := fCertificateKey;
  for lDomain in aDomains do
    fAcme.Domains.Add(lDomain);    // the names the certificate is for
  { MANAGED MODE: the client answers the CA's tls-alpn-01 challenge on this
    server - which must be reachable from the Internet on port 443 under
    every name above - and installs the certificate in it. }
  fAcme.AsyncTLSServer := aServer;
  fAcme.PfxFileName := TPath.Combine(aDataDir, 'server.pfx');
  fAcme.PfxPassword := aSecret;
end;

The certificate and its key are written to the PFX file as soon as they arrive, protected with the password you give.

Start

procedure tTaskAcme.Start;
begin
  { The manager obtains the first certificate if there is none, and renews
    it from then on - on its own thread, so this returns at once. }
  fRenewal := TsmAcmeRenewalManager.Create(nil);
  fRenewal.Acme := fAcme;
  fRenewal.ManageClientCertificate := True;
  fRenewal.OnRenewalFailed := RenewalFailed;
  fRenewal.OnLog := RenewalLog;
  fRenewal.Start;
end;

{ Both events run on the manager's thread, so what they report is queued to
  the main thread. }
procedure tTaskAcme.RenewalFailed(Sender: TObject; aCert: tAcmeManagedCert;
  const aError: string);
begin
  { The certificate in service stays in service; the manager retries a
    passing failure itself, and stops on a lasting one until RetryNow. }
  Post('Certificate renewal failed: ' + aError);
end;

procedure tTaskAcme.RenewalLog(Sender: TObject; const aMessage: string);
begin
  Post(aMessage);
end;

procedure tTaskAcme.Post(const aMessage: string);
var
  lMessage: string;
  lHandler: TProc<string>;
begin
  lMessage := aMessage;
  lHandler := fOnMessage;
  if Assigned(lHandler) then
    TThread.Queue(nil,
      procedure
      begin
        lHandler(lMessage);
      end);
end;

destructor tTaskAcme.Destroy;
begin
  fRenewal.Free;   // stops its thread
  fAcme.Free;
  fCertificateKey.Free;
  fAccountKey.Free;
  fDirectoryTrust.Free;
  inherited;
end;
function StartWithLetsEncrypt(aServer: TsmAsyncTLSServer; const aDataDir, aSecret,
  aCARootFile: string; aUserAgreed: Boolean): tTaskAcme;
begin
  aServer.BindPort := 443;
  StartServerFromPfx(aServer, aDataDir, aSecret);
  Result := tTaskAcme.Create(aServer, aDataDir, aSecret, aCARootFile,
    cLetsEncryptStaging, 'ops@example.com', ['www.example.com'], aUserAgreed);
  Result.Start;
end;

The sample uses the staging directory. To move to production, stop the server, pass cLetsEncrypt instead, and delete the staging certificate's PFX (server.pfx here) before the next start. The manager starts from the certificate in that file, so a staging certificate left in it would stay in service until it is due for renewal, and browsers do not trust it.

The server can start without a certificate: on the first run the manager obtains one while the server is running, and installs it. How renewal works, and what to do after a restart, is on Keep a certificate renewed.

A wildcard name, or a server that is not reachable on port 443, needs a different challenge that the application answers itself; the ACME notes describe it.

Reference

TsmAcmeClient · TsmAcmeRenewalManager · TsmAsyncTLSServer · StreamSec.Mobile.Acme · StreamSec.Mobile.AcmeRenewal

Related tasks