Feature notes
Certificate reload from PFX files on disk
CERTIFICATE FILE RELOADING
==========================
StreamSec.Mobile.CertificateReload supplies tCertificateReloader, a runtime
class for following one or more independently published PKCS#12/PFX files.
Each file has its own path and password. Every registered TLS target receives
every accepted file. The application supplies the host names to check.
This service only reads PFX files. It neither obtains nor renews certificates.
The file publisher remains responsible for issuance and for durable storage.
Publish through a sibling temporary file and atomic replacement, for example
stAcmeStorage.SaveFileAtomic. A certificate and its private key must match.
STARTUP AND WIRING
------------------
Keep initial provisioning in the application: ImportFromPFX for both RSA and
ECDSA files, followed by TLSSetupServer. A shared TsmSimpleTLSInternalServer
can serve SMTP, IMAP and POP3 STARTTLS listeners. Create the reloader after
that engine, register the engine once, then register both files and the
configured host names. The reloader keeps a separate accepted digest and
certificate for each file, including files with the same DNS names.
Engine.ImportFromPFX(RsaPath,tDualSecretKey.CreateForPFX(RsaPassword));
Engine.ImportFromPFX(EcdsaPath,tDualSecretKey.CreateForPFX(EcdsaPassword));
Engine.TLSSetupServer;
Reloader := tCertificateReloader.Create;
Reloader.AddTarget(Engine);
Reloader.HostNames.Assign(ConfiguredHostNames);
Reloader.AddFile(RsaPath,RsaPassword);
Reloader.AddFile(EcdsaPath,EcdsaPassword);
Reloader.LogCallback := CertificateLog;
Reloader.FatalCallback := CertificateWorkerFatal;
Reloader.Start;
The passwords above are strings. ImportFromPFX takes protected iSecretKey
values; retain application configuration appropriately and wipe temporary
password strings with ProtectClear. AddFile stores a protected secret key. For
startup code that already has the current leaf and the exact bytes it
imported, AddFile(path,password,currentLeaf,currentContent) seeds reporting
and the accepted digest, avoiding a redundant first replacement. Do not pass
bytes merely read after a startup import: they may name a different identity.
AddTarget is overloaded for TsmCustomTLSInternalServer descendants and
TsmAsyncTLSServer. Provision an async server with ImportFromPFX while stopped,
then activate it before starting the reloader. The runtime path never calls
the active async server's ImportFromPFX. Registering an async target replaces
its engine bank shard by shard through its component hot-swap method.
TsmAsyncQUICServer is not a reload target; restart or reprovision that
listener separately when its certificate changes.
ONE RELOADER FOR STARTTLS AND IMPLICIT TLS
------------------------------------------
Register every component that presents the same certificate with one
reloader. Each file is read and parsed once per change and applied to every
target in turn. Mail clients offer no ALPN, so implicit TLS needs one
TsmAsyncTLSServer per protocol with the mail component as its fallback
(MAIL.txt section 10). The STARTTLS engine and the three implicit-TLS servers
are four targets of one reloader:
Bytes := TFile.ReadAllBytes(Path); { one read, kept for the seed }
Engine.ImportFromPFX(Bytes,tDualSecretKey.CreateForPFX(Password));
Engine.TLSSetupServer;
Smtps.BindPort := 465; { Imaps 993, Pop3s 995 }
Smtps.FallbackPolicy := fbpUseFallback;
Smtps.OnConfigureEngine := ConfigureShard;
Smtps.ImportFromPFX(Path,tDualSecretKey.CreateForPFX(Password));
SMTP.TLSServer := Engine; { 25 and 587: STARTTLS }
SMTP.IsFallback := True;
SMTP.Server := Smtps; { 465: implicit TLS }
SMTP.Active := True;
Smtps.Active := True;
{ IMAP with Imaps and POP3 with Pop3s the same way }
Reloader := tCertificateReloader.Create;
Reloader.AddTarget(Engine);
Reloader.AddTarget(Smtps);
Reloader.AddTarget(Imaps);
Reloader.AddTarget(Pop3s);
Reloader.AddFile(Path,Password,nil,Bytes);
ProtectClear(Bytes);
Reloader.Start;
...
Reloader.Stop; { before any target is stopped }
Smtps.Active := False;
An async server records ImportFromPFX while it is stopped and replays the
record into each new bank of shards, reading the file as it is then; record
it once, not at every activation. ConfigureShard sets each shard's options,
for example from Engine.Options, and its OnWorkerFatal. Register only targets
that are serving: an async target that is not active refuses the apply, and
the file is applied to it again after it is reactivated.
AddFile's optional arguments describe what the targets were started from.
The content seeds the file's digest, so an unchanged file is not applied
again, and names the leaf being served when no certificate is passed, so the
first replacement retires it. The seed is best effort: content that is not
one decodable PFX identity (encoding, MAC, work limits, key and leaf, usage)
seeds nothing and is logged as a warning, so assign LogCallback first, and
the first check then applies or rejects the file as it would any version.
Chain, validity and host-name checks are not applied to a seed. Without
either, the leaf the targets were started from is never retired. An
async server reads the file itself when it goes active; if the file changed
after the seed was read, the first check applies it to every target, which
is a no-op on a target that already holds it.
Configure targets, paths, passwords, host names, callbacks and PollIntervalMs
while stopped. Targets must outlive Stop and destruction of the reloader. Stop
the reloader before deactivating or freeing any listener or engine. Stop
interrupts the polling wait. If its join deadline expires, it records an
overrun warning before returning. Retain the reloader, targets and callbacks
until the worker has finished and a later Stop completes. LogCallback calls
from one reloader never overlap. CheckOnce logs on its caller; polling logs on
the worker. Stop tries the callback lock once to deliver its overrun warning
through LogCallback. If a callback holds that lock, it uses a native
diagnostic and returns. Native diagnostics call no application callback. On
Windows they go to the debugger. POSIX writes once to file descriptor 2
without reopening it or changing its flags. Delivery is best-effort and
depends on the OS sink; blocking pipes and terminals are skipped unless
already nonblocking; regular-file I/O can delay the caller. Fatal reporting
uses separate threads. Fatal logging tries the logging lock once, then uses
the native diagnostic immediately if that lock is busy. FatalCallback does not
take that lock and can overlap a stuck LogCallback. Both callbacks must return
promptly, must not call Stop, and must not wait for main-thread dispatch. Read
CurrentCertificate and AcceptedFingerprint only while stopped. CheckOnce
supports single-threaded application polling.
SNAPSHOT, VALIDATION AND REPLACEMENT
------------------------------------
The watched path must name a regular file. Windows reparse points, including
file symlinks, are refused. Existing 8.3 paths are normalized to long names.
Each poll inspects metadata without opening the watched PFX. Windows lists the
parent directory for file identity, size, last-write and change times. It
needs FILE_LIST_DIRECTORY permission on that directory. Reliable Windows
change detection requires a local NTFS volume. FAT/exFAT timestamps can hide
same-size changes; ReFS and network shares are outside this metadata contract.
On NTFS, file identity detects replacement even if size and last-write time
are preserved. No idle target handle can obstruct atomic replacement. POSIX
stat supplies device/inode identity, size and nanosecond last-write/change
times where the target RTL exposes them. Metadata failures produce one warning
per distinct error until recovery. A missing path or denied directory listing
can indicate a configuration error to the operator.
A file is modified while its bytes differ from the identity accepted by every
target. While a valid file has not reached every target, each check-up may
make one exclusive-read attempt and retry the pending apply. Accepted files
with unchanged metadata cause no read. Failures decided by bytes alone are
memoized and cause no reopen until metadata changes. Metadata changes permit
one new exclusive read; the content hash avoids reapplying identical accepted
bytes. Windows uses share mode zero for this read. If another handle shares
only reading, or a publisher is writing, the exclusive open fails. A sharing
or lock conflict produces a debug deferral; persistent open or lock errors
produce one warning per distinct reason. The reloader tries again at the next
check-up, without a retry loop or backoff. During the exclusive read, a
publisher's replacement can also fail. This window is normally a few
milliseconds per attempt; publishers should retry a failed replacement. The
bounded snapshot closes before hashing, parsing or target changes. All targets
consume those snapshot bytes without reopening the source file.
On Delphi POSIX, the read-only equivalent of RTL fmShareExclusive is a
nonblocking fcntl advisory read lock. A cooperating publisher must take an
fcntl write lock; other readers and rename are not excluded. FPC POSIX uses a
nonblocking advisory exclusive flock; its publisher must use flock too. On
Linux, flock and fcntl locks do not exclude each other: a publisher serving
both implementations must take both lock types. Noncooperating opens and
rename remain possible. Only regular files are accepted. Nonblocking native
open prevents a FIFO from hanging the worker. A content hash decides whether
new bytes differ from the accepted bytes; metadata changes alone do not
reapply identical content.
A new snapshot must have a valid password-derived PKCS#12 MAC, one
unambiguous non-CA leaf with its matching private key, a usable chain and
TLS server usage. Exactly one private-key bag is accepted. Encoding depth,
node count, bag count and KDF work are bounded before expensive work.
Variable-size IF and DL key operands are bounded in every certificate bag
before verification or filing, including CAs outside the leaf chain. Other
off-chain CA key algorithms follow startup acceptance policy. Missing upper
issuers are permitted when the remaining chain is usable. An issuer may
already be present in a target store; the target import and replacement use
the same chain policy as startup. Current-time leaf validity follows
startup import: expired and not-yet-valid leaves are rejected.
Out-of-period CA bags are omitted as leaf-first startup imports do.
Issuer/child validity enclosure uses the application's process-wide
tCertificate.SetVerifyValidityPeriodMismatch policy; set it before loading
certificates. The reloader does not change that policy.
A configured DNS name absent from the leaf produces a warning naming every
missing name; the certificate is still loaded. DNS wildcards cover exactly one
leftmost label. Expiry warnings include the fingerprint and UTC not-after.
Accepted logs include old/new SHA-256 fingerprints, names and UTC not-after.
Rejected reasons are deduplicated until recovery; recovery is logged.
Every target gets the same sequence from the one parsed snapshot, whatever
its kind; an async target gets each step on every shard. Parsing, MAC checks,
PKCS#12 KDFs and decryption finish before any target is locked. The reloader
first stores the parsed private key through the target's iKeyAndCertStore,
using the key ring's lock, then calls AddCertificate for the leaf. It
forwards all parsed certificate and CRL bags through the component's
internal StoreReloadCertificate and StoreReloadCRL paths, including CAs
outside the leaf's chain, then calls ReplaceTLSServerCertificate, then
validates key pairs again under the same locks, so that a key type only a
retired leaf covered is no longer advertised. For a
TsmCustomTLSInternalServer it first finds the exact stored leaf and its
matching private key. The reloader never calls ImportFromPFX on a target, and
a store change alone never completes the hot swap. Each bag is filed under
that engine's TLSLock and setup lock. For an async target the whole sequence
runs under the component's bank lock, which Deactivate also takes before it
frees the shards: a Deactivate on another thread waits for the reload to
leave them. CRL bags are filed after
every certificate bag, with the startup CRL rules (MyCerts, then RootCerts,
then CollectedCertificates). A CRL bag that does not hold a DER
CertificateList rejects the attempt. Before any target is touched, a PFX
whose own CRL bag, signed by an issuer in the same file, revokes the leaf or a
certificate in the leaf's chain is rejected ("PFX CRL revokes the leaf
certificate"), because the same file cannot start a server. Each CA uses
that engine's LocalExplicitTrustByDefault and duplicate-key-identifier rule.
Key-first filing places the leaf in MyCerts. A key or leaf refusal rejects the
attempt. A CA uniformly refused by all shards is ignored as at startup;
disagreement across shards raises an error. No refused CA gains explicit
trust. All-or-nothing replacement applies only to the serving-cache rows
within one engine. Import and replacement are separate steps: added keys,
certificates, CAs and CRLs can remain in the stores after a later refusal.
Import can also update key-pair and cipher-suite options before serving rows
change. No rollback of those additions or options is promised. Async fan-out
switches one shard at a time under its own TLSLock; no lock spans shards, and
a later failure leaves earlier shards updated. Independent targets can also
complete at different times. The reloader tracks the digest per target and
retries targets that have not applied the snapshot. Recovery is reported only
when all targets serve the accepted identity. Start resets per-target apply
state so recreated async shards receive the watched identity again, even when
the bytes and metadata have not changed. A seeded first Start can skip the
initial replacement; later starts reapply it. CheckOnce also detects a new
async engine bank and reapplies the watched identity. An unchanged bank keeps
the normal metadata-only idle polls. Target activation and deactivation must
be serialized with CheckOnce, Start and Stop.
Use one certificate writer per target. A reloader, application hot swap, ACME
renewal manager or second reloader can otherwise interleave their updates
shard by shard. Shards can remain on different identities after both calls
return. A successful reloader digest records its own apply, not another
writer's later changes; unchanged file metadata does not make it reapply.
Serialize all writers to the same target outside the component if they must
coexist.
Replacement follows the component's name/algorithm placement rules. Every
leaf a target may serve from the same file is retired when the replacement
completes: the one it served before, and one a failed apply may have
published to some shards. A leaf that another watched file still holds is
kept. Every serving row that holds a retired leaf is removed, on every shard,
including rows for names and algorithms only it covered, and the engine
stops counting it: PublicKeyAlgorithms no longer advertises a key type only
retired leaves covered, and TLSSetupServer does not serve a retired leaf
again, so an in-process restart of a target does not bring it back. A
handshake for a name only a retired leaf covered gets what the target serves
for a name it has no row for. The stores keep a retired leaf, it is only no
longer offered; the next process restart starts without it.
StoreCertificate, ImportFromPFX and ReplaceTLSServerCertificate make a
retired leaf servable again; AddCertificate and LoadMyCertsFromFile do not.
An application that sets an engine up again in the same process, with a
leaf an earlier run served, calls TsmStreamSecII.RetireServerCert for that
leaf before it imports the file: an import of the same leaf serves it again,
a new leaf leaves the old one retired. Selected sessions
retain their certificate/key references, including handshakes already in
progress. Subsequent full handshakes select the published cache. Session
resumption can retain the prior negotiated identity; use a full handshake
to observe a swap.
Failures never advance the accepted digest. Wrong MAC, malformed encoding,
wrong key, unusable usage and immutable content limits are memoized until
metadata changes. Validity, chain-policy and target failures retry at the poll
cadence, making one exclusive-read attempt per check-up while the file has not
been applied everywhere. Issuer selection depends on CA validity, so its
failures are retried as time passes. Chain and revocation checking follow the
same engine policy and fetch behavior as startup and ordinary handshakes,
including CRL and AIA fetching and stapled OCSP validation. Per-engine
preparation files the leaf under that engine's TLSLock; a network fetch can
delay handshakes on that engine. OCSP warming follows publication. Warm-up
requests are serialized and coalesced on one worker per engine. The worker
exits when its queued passes finish; an idle engine retains no warm-up thread.
Publication does not join an earlier fetch. Warming uses the Ocsp component
the application assigned, including its descendant state, TrustedCertificates,
linked stores and hooks. It does not copy the responder or rebuild RootCerts
per leaf. Changing or detaching Ocsp, including component destruction
notification, waits for an in-flight warm-up fetch before detaching the
source. The responder's Timeout applies to its reads (15000 ms by default),
not the whole exchange: slow-drip peers and custom descendants can extend the
wait without a finite total bound. Custom descendants must detach Ocsp before
their destructor frees state used by CheckCertificate: inherited TComponent
destruction notification occurs after descendant teardown. Stop the reloader
before changing or freeing its dependencies. Ordinary worker errors do not
reject an accepted swap. Ordinary scheduling errors are contained. A
process-state fault while scheduling propagates on the publishing caller
without worker reporting or automatic exit; the serving cache remains
committed. If that caller is the reloader worker, its outer worker boundary
applies. OnWorkerError reports ordinary worker errors after the fetch locks
are released. It also observes the LOG phase of a classified fatal worker
fault, before OnWorkerFatal notification and exit 70. Engine destruction joins
before freeing the stores the worker uses.
WORKER ERRORS AND SHUTDOWN
--------------------------
Ordinary worker exceptions are contained and reported. Ordinary logging
exceptions are contained. Process-state exceptions reaching the warm-up or
reloader worker boundary invoke stWorkerFatal: bounded logging, bounded
application notification, then immediate process termination with exit code
70. These classes are EAccessViolation, EPrivilege, EStackOverflow,
EExternalException and EInvalidPointer. A watchdog bounds stalled dispatch.
The boundary applies only to the reloader's polling worker and the OCSP
warm-up worker. Synchronous CheckOnce, ordinary handshake staple refresh,
component AddCertificate, ValidateMyCert and destructor wrappers retain their
ordinary caller behavior. The emit-time OCSP fetch swallows exceptions as
before and calls no worker event. Existing inner PKIX/OCSP handlers may
convert faults to status values before a worker boundary sees them. Arithmetic
exceptions, Ctrl-C and EOutOfMemory are outside this class set. The TLS engine
exposes OnWorkerError and OnWorkerFatal for OCSP warming; configure these for
every async engine in OnConfigureEngine. The reloader exposes LogCallback and
FatalCallback. Existing component event properties default to unassigned;
existing form resources need no event assignment.
Stop allows the worker a bounded join interval. If application callbacks or
in-progress import/verification cannot finish within it, Stop records the
overrun warning before returning. This overrun alone does not notify a fatal
observer or terminate the process. The worker and its dependencies remain live
until it finishes; call Stop again before freeing them. Free waits for a
remaining worker after Stop returns, so destruction can exceed the Stop
deadline. Process termination remains reserved for the process-state exception
classes above. No shutdown path depends on GUI message pumping.
TIMING AND RESOURCE LIMITS
--------------------------
Every value below is chosen, not measured. They are defaults, not estimates of
normal I/O, network or cryptographic performance.
Constant Default Small/short; large/long
------------------------------------ --------- ----------------------------
cCertificateReloadPollMs 5000 ms more I/O; slower adoption
cCertificateReloadStopMs 10000 ms early return; slower shutdown
cCertificateReloadMaxPfxBytes 4 MiB rejects PFX; parse/memory cost
cCertificateReloadMaxCertificates 32 rejects chains; check cost
cCertificateReloadMaxBags 64 rejects bags; decrypt cost
cCertificateReloadMaxAsnDepth 32 rejects nesting; stack cost
cCertificateReloadMaxAsnNodes 65536 rejects encoding; parse cost
cCertificateReloadMaxKdfIterations 1000000 rejects KDF; stop/CPU delay
cCertificateReloadMaxKdfWork 2000000 rejects KDF; total CPU delay
cCertificateReloadMaxScryptBytes 64 MiB rejects scrypt; memory cost
cCertificateReloadMaxDerivedBytes 1024 rejects KEK; KDF block cost
cCertificateReloadMaxKeyBits 8192 rejects keys; signature cost
cCertificateReloadMaxGroupWords 2048 rejects groups; compute cost
cCertificateReloadExpiryDays 14 days late notice; early noise
cWorkerFatalPhaseTimeout 1000 ms cuts reporting; later exit
cWorkerFatalWatchdogTimeout 5000 ms cuts dispatch; damaged uptime
cWorkerFatalExitCode 70 other codes mislead monitors
Configure shorter polling only after considering every target's import and
validation work. A Stop deadline limits the caller's join wait; it does not
cancel in-progress work. Fatal-observer deadlines apply only to classified
process-state faults.