Feature notes
Release notes 4.1.3.358
================================================================================
CHANGES - StreamSec Tools
(StreamSec Security Library for Embarcadero Delphi)
================================================================================
Grouped by subject and numbered straight through. Entries marked BEHAVIOUR
CHANGE alter what existing code does without any source change on your part -
read those before upgrading.
WHAT THIS FILE COVERS. Changes made SINCE release 4.1.3.357, which was
released on 2026-09-03. What that release itself brought is in
CHANGES_4.1.3.357.txt
and every earlier release is archived beside it the same way, one file per
version. So this file is always short: it is the difference between the zip
you have and the one you are looking at, and nothing else.
--------------------------------------------------------------------------------
THREE MEMORY DEFECTS BEHIND ONE ACCESS VIOLATION: A SHARED TLS ENGINE'S
NOTIFICATION LIST WAS MUTATED FROM EVERY DELIVERY THREAD, FREEING AN SMTP SERVER
RELEASED ITS DELIVERY AGENT TWICE, AND A BASE64 DECODE WROTE ONE BYTE PAST THE
DESTINATION BUFFER
================================================================================
Three defects, all fixed, none of them needing a source change on your part.
They are reported together because they were found together and because they
produced the SAME symptom, which is the part worth reading even if you use none
of these components directly.
WHAT IT LOOKED LIKE, AND WHY IT WAS SO HARD TO PLACE. All three damage memory
and then return normally. Nothing fails at the site; what fails is whatever
touches the damaged structure NEXT. In practice that was a destructor with no
connection to the cause - most often the TLS engine's, which reported
TsmCustomTLSInternalServer.Destroy failed while inherited Destroy:
EAccessViolation - ... Read of address 00000000
with the inner site moving between runs (inherited Destroy, FMyCerts.Free,
FStreamSecII.Free), the faulting address sometimes being a piece of TEXT rather
than an address at all, and some runs dying outright somewhere later still. IF
YOU HAVE SEEN THAT MESSAGE, OR AN UNPLACEABLE ACCESS VIOLATION IN A DESTRUCTOR
IN A PROGRAM THAT SENDS OR RECEIVES MAIL OR READS PEM, THIS IS ITS LIKELY
CAUSE, and there is nothing to change but the version: the engine destructor
was never at fault and its teardown order is unchanged. It has been given one
extra diagnostic - the two collector passes at the end now carry their own
stage names instead of the previous statement's, so a fault raised in the
collector no longer reads as a fault in TComponent's teardown.
WHICH ONE YOU ARE MOST LIKELY TO HAVE MET is the first: it needs only a sender
that delivers on more than one thread through one shared engine, which is what
tSmtpSpool with DeliveryThreads above 1 does.
1. FIXED - a shared TLS engine's free-notification list was mutated from every
thread that used it (StreamSec.Mobile.TLSClient, StreamSec.Mobile.
TlsInternalServer)
TComponent.FreeNotification is reciprocal and unsynchronised: it adds to the
notified component's list AND to the notifier's, and RemoveFreeNotification -
which TComponent.Destroy reaches through RemoveFreeNotifications - does the
same in reverse. The list is a plain TList<TComponent> with no lock.
TsmCustomTLSClient registers with its TLSServer on attach and deregisters as
it dies. ONE ENGINE SERVING A CLIENT PER DELIVERY IS THE SHIPPED
ARRANGEMENT, not an abuse of it - tSmtpSmarthostAgent is documented to build
a client per delivery precisely so that one engine can carry a deployment's
outbound trust - so every delivery thread was mutating the same list at the
same time. The list was then corrupted, and what faulted was the engine's own
teardown walking it: an access violation inside
TComponent.RemoveFreeNotifications or TComponent.Notification, or a call
through a list slot that no longer held a component at all.
Measured on a purpose-built stress harness - eight threads delivering
through one shared engine, the engine freed after each round of 64
deliveries - the engine free raised on 83 of 100 rounds before the fix and
on none of 100 after it. The engine was freed on the main thread in every
round, which is where it is supposed to be freed: the corruption came from
the attach and detach traffic, not from the free.
Every such mutation this library makes now runs under one lock, and the
engine holds it across its own teardown. It is taken on attach, detach and
teardown only - never on a data path - so it costs one uncontended acquire
per delivery. TsmCustomTLSInternalServer.NotifyLock / NotifyUnlock are
public: if your own component registers for free notification on an engine
that other threads are using, take the same lock around the call.
2. FIXED - freeing an SMTP server released its delivery agent twice
(StreamSec.Mail.SMTPServer)
TsmCustomSMTPServer.Destroy - so TsmSMTPServer, and any descendant - freed
its delivery queue and then, four statements later, assigned nil to a
property OF THAT FREED QUEUE. The assignment read the interface reference
still lying in the freed memory and released it a second time, which took
the delivery agent's reference count one below zero: the agent was destroyed
there, while the component's own reference still pointed at it, and the
release of that reference a moment later freed the same object again.
A double free is not a crash, it is a corrupted allocator, so the cost was
paid later and elsewhere - see above. IT HAPPENED ON EVERY FREE OF EVERY
INSTANCE, on every platform, whether or not the server had ever been
started, so a program that creates one server at startup and frees it at
shutdown was affected exactly once and a program that creates one per test
or per configuration reload was affected every time.
The queue's reference to the agent is now dropped BEFORE the queue is freed,
after stopping it so that no delivery worker can be inside the agent when
its reference goes. Nothing else in the teardown order changed.
3. FIXED - a base64 decode wrote one byte past the destination buffer
(stBase64)
MIME64ToBuf and the DecodeBuf / DecodeLine primitives beneath it turn each
group of four base64 characters into three bytes. They did it by storing a
32-BIT WORD and advancing the destination pointer by three - correct for
every group but the last, where the fourth byte of that store (always zero)
landed one byte beyond everything the decode had been given room for.
So ANY caller whose destination is exactly the decoded length took a
one-byte overwrite. Where that byte fell is the allocator's business: it
could be the header of the next heap block, another live object, or nothing
that mattered that run - which is why this had survived. Callers inside the
library that are affected include SASL credential decoding on the SMTP
server (which is how it was found), MIME body decoding, DKIM signature and
key parsing, and the published plaintext-resource bundle.
PEM READING WAS AFFECTED ON EVERY PLATFORM, and separately: the line decoder
writes into a 57-byte buffer, which is exactly what a 76-character base64
line - the standard wrap, and this library's default - decodes to, so every
full line of every PEM file overwrote the byte after it. Measured over 200
PEM reads before the fix: 261 overwrites. After: none.
Both primitives now store three bytes per group. THE ANSWERS ARE UNCHANGED,
which was verified rather than assumed: RFC 4648 sec.10 in both directions,
a round trip at every length from 0 to 300 (so every padding shape), and the
PEM stream path, all run against the library before and after the change and
compared by digest - identical on Win32, on Win64 and on the assembler-free
build that the LLVM targets use.
--------------------------------------------------------------------------------
A SUBMISSION CAN NOW SAY HOW FAR IT GOT: A STAGE MARKER ON THE SMTP CLIENT, A
DELIVERY REPORT AND A COMMISSIONING PROBE ON THE SMARTHOST AGENT, AND THE AGE OF
THE OLDEST QUEUED MESSAGE
================================================================================
Five additions on the submission path. EVERY ONE OF THEM IS ADDITIVE: no
existing signature changes and no existing behaviour changes. Every outcome,
every error text and the order in which a delivery client is configured are
what they were, and code that does not name the new members compiles and runs
exactly as it did.
WHAT THEY ARE FOR. A queue that hands its mail to a smarthost has two policy
questions the old interface could not answer: was this failure the host's or
this one letter's, and may what the far end said be shown to anybody. Both turn
on how far the session got. At or before MAIL FROM nothing recipient-specific
has crossed the wire - the reverse path is the configured sender - so a refusal
there is the host's or the account's; from RCPT onwards it may be this one
letter's. Until now the only place that information existed was the text of an
exception, "SMTP RCPT TO:<...> failed: 550 ...", and a consumer that reads it
by matching on the string fails unsafe in both directions: a queue that
abandons on the wrong side of that boundary destroys good mail when an account
fault is reported, and a retry breaker that counts the wrong side of it becomes
a denial-of-service handle for whoever gets to choose a recipient.
4. ADDED - how far a session got: tSmtpDeliveryStage and the Stage property
StreamSec.Mail.SMTPClient declares
tSmtpDeliveryStage = (sdsSession, sdsAuth, sdsMail, sdsRcpt, sdsData);
and TsmCustomSMTPClient publishes a read-only Stage of that type.
sdsSession connecting, TLS, the greeting, EHLO, STARTTLS - nothing of
the credential and nothing of the message had been offered
sdsAuth the credential was being offered
sdsMail the session was open and MAIL FROM was being sent
sdsRcpt a recipient had been named
sdsData the body was being sent, or the message was accepted
EACH STAGE IS MARKED BEFORE THE COMMAND IT DESCRIBES, never after its reply,
so a command that is never answered is still attributed to itself - a
timeout is a failure OF that stage, and it raises carrying no reply code at
all. Open resets it to sdsSession, and it is NOT cleared when the transport
drops: after Open or SendMail has raised and torn the connection down, a
caller can still read where it stopped. It is meaningful until the next
Open.
IT HAD TO BE THE CLIENT THAT RECORDS THIS, because nothing outside it can
recover the same fact. The command name is not a field of eSMTPClientError -
it is formatted into the message text - and SendMail runs MAIL, RCPT and
DATA inside one call, so sdsMail, sdsRcpt and sdsData are otherwise
distinguishable only by parsing that text. Authentication runs inside Open,
which leaves SessionOpen False whether the session or the credential was
refused, so sdsAuth and sdsSession are otherwise not distinguishable at all.
A submission client's consumer can now tell "my credential was refused" -
stop retrying, tell an operator - from "the server refused the session" -
back off - from "that recipient was refused" - this one letter is dead and
the queue is fine - without matching on a message string the library never
promised to keep.
5. ADDED - TsmCustomSMTPClient.TryMailFrom
function TryMailFrom(const aFrom: string): Integer;
MAIL FROM:<aFrom> AND NOTHING AFTER IT, so a deployment can ask "would this
server take mail from this sender" without submitting a message. It returns
that reply's code and resets the transaction - RSET, best effort - whatever
the code was; it never sends RCPT or DATA.
A NEGATIVE REPLY IS RETURNED, NOT RAISED. The question being asked is what
the code is, and an exception would make the ordinary answer the exceptional
path. A transport failure still raises.
Its preconditions are SendMail's - the session open, the RequireTLS gate -
and a control character in the reverse path is refused before anything is
sent, since it would otherwise put a command line of the caller's choosing
on the wire. LastReplyCode and LastReplyText afterwards describe the RSET
rather than the refusal, which is what the returned code is for.
6. ADDED - a delivery report, and a Deliver overload on tSmtpSmarthostAgent
The agent builds and frees an SMTP client per delivery, so the stage and the
reply code die inside Deliver and the caller is left with the outcome and a
string. StreamSec.Mail.SMTPSpool adds
tSmtpDeliveryReport = record
Stage: tSmtpDeliveryStage;
ReplyCode: Integer;
SmtpError: Boolean;
end;
and a four-argument Deliver that fills one in:
function Deliver(const aEnvelope: iSmtpEnvelope; const aData: tBytes;
var aError: string;
out aReport: tSmtpDeliveryReport): tSmtpDeliveryOutcome;
Stage is the client's own, never inferred from the exception's text.
ReplyCode is the code behind the failure, 0 when the failure was not a reply
at all, and on success the final reply's code.
SmtpError SAYS WHETHER THE SMTP LAYER ITSELF FAILED - a reply the far end
sent, a malformed reply line, or one of the client's refused local
preconditions - as against anything underneath it, in which case aError
holds the library's own words about a socket, a timeout or a certificate.
IT IS NOT DERIVABLE FROM ReplyCode: an eSMTPClientError carries 0 both for a
malformed reply and for a refused precondition, so a consumer that must not
print server-chosen text cannot decide on the code alone. That is the whole
reason it is a field rather than something a caller works out.
THE EXISTING THREE-ARGUMENT Deliver IS UNCHANGED and now calls the new one
with a report it discards, so the two cannot drift: same outcomes, same
aError texts, one body. iSmtpDeliveryAgent is untouched.
THE CLASSIFICATION IS ALSO UNCHANGED, deliberately. A 5xx is still permanent
wherever it arrives, at AUTH and at MAIL FROM included, and anything without
a reply code is still transient. A deployment that wants a different policy
per stage - keeping a queue alive through an account fault, say - can now
express it on its own side of the interface, which is better than the
library deciding it for everyone.
tSmtpDeliveryStage is re-exported by StreamSec.Mail.SMTPSpool rather than
redeclared there, so a consumer of the queue and a consumer of the client
see one type and cannot end up holding two enumerations that drift.
7. ADDED - tSmtpSmarthostAgent.Probe, and tSmtpProbeResult
function Probe(const aMailFrom: string;
var aError: string): tSmtpProbeResult;
THE COMMISSIONING QUESTION, ASKED WITHOUT SENDING ANYTHING: does this host
answer, does its certificate validate against the configured anchors, does
it take this credential, and would it take mail from this sender. The result
reports Opened, Authenticated, SenderTried, SenderAccepted, the EHLO
keywords learned under TLS, and a tSmtpDeliveryReport saying where it
stopped. When aMailFrom is empty the sender is not asked about.
IT OPENS THE SESSION WITH EXACTLY THE CONFIGURATION Deliver USES - the same
private client factory, the same OnConfigure - so what it reports cannot
drift from what a real delivery would meet. That is the reason for it to be
here rather than assembled by each application out of a client and a copy of
the agent's settings.
It never raises for a network outcome: aError receives what Deliver would
have put there, and the caller decides what of it may be printed. What it
cannot prove is that a letter would be DELIVERED beyond the smarthost - that
is the smarthost's business with the rest of the internet - nor anything
about spam filtering or a recipient's own policy.
8. ADDED - tSmtpSpool.OldestReceivedAt
function OldestReceivedAt: TDateTime;
The arrival time of the oldest queued message, which is the standard
queue-health number and the one a status row wants. It is read under the
queue's own lock and is safe from any thread while the delivery workers run
- which Snapshot's items, being the live objects, are not.
ITEMS WHOSE ARRIVAL TIME IS 0 ARE IGNORED rather than treated as infinitely
old. An envelope recovered from a truncated or hand-written spool file
carries none, and letting one drag the minimum to 0 would make a full queue
report exactly what an empty one reports. So 0 means an empty queue, for a
queue this spool filled itself, and nothing else.
--------------------------------------------------------------------------------
MAIL: THE STORE BUILDS ON LINUX, AND DKIM SIGNING ACCEPTS KEY COMPONENTS
================================================================================
9. FIXED - the mail store did not compile for Linux
StreamSec.Mail.Maildir called GetCurrentProcessId - a Windows API - at two
sites without a platform guard: composing the unique name of a message
file, and recording the owner of a lock file.
The unit was otherwise ready for it. Its uses clause already selects
Winapi.Windows on Windows and Posix.Unistd elsewhere, and its other
Windows call, FlushFileBuffers, is guarded at both of its sites. Only
these two were not.
The effect was that StreamSec.Mail.Maildir, and the seven units that rest
on it - the IMAP client, engine and server, the POP3 server, Retrieval,
SMTP delivery and the SMTP server - would not compile for Linux64:
"E2003 Undeclared identifier: 'GetCurrentProcessId'". Nothing on Windows
was affected, which is why it went unnoticed.
Both sites now take getpid on POSIX. On Windows the guard resolves to the
original call and the compiled code is unchanged. All twenty-nine runtime
StreamSec.Mail.* units now compile for Delphi Linux64.
10. FIXED - an SMTP server given a TstRSAKey or TstEdDSAKey as its DkimKey sent
every message unsigned, and DkimDnsRecord refused a TstRSAKey
(StreamSec.Mail.Dkim)
The key components sign mail now, and nothing about them needed fixing.
TstRSAKey and TstEdDSAKey are the same components the SSH and ACME code
signs with, and a key loaded, generated or assigned in one was a working
key throughout. The defect was in how the DKIM signer asked the component
to sign.
A key component holds a private key and hands it out on request:
iIFPrivateKey for RSA, iDLPrivateKey for Ed25519. That key is what signs.
tJoseKey, which signs ACME requests with these same components, asks the
component for its key and then asks the key to sign. tDkimSigner instead
asked the COMPONENT to sign - it queried the component for the library's
signing interface, iSignPrivateKey - and a key component does not answer
that query, because the only thing it forwards is the key interface. So the
signer's "does this key support signing" check failed for every key
component, on every message, whatever key it held and however it got it. No
key file, key format, password, or unit in the project's uses clause
entered into it: the same component signs an SSH session in the same
program, and was refused only here. A bare private-key interface handed to
tDkimSigner.Key directly was never affected, since a key answers for its
own signing.
A signing failure is deliberately not a reason to stop delivering, so every
message went out UNSIGNED, and nothing was logged: the reason was handed to
the delivery agent as error text, which a delivery that succeeds discards.
A receiving domain that enforces DKIM or DMARC may have refused or
quarantined that mail. IF YOU SET SignOutbound AND DkimKey AND YOUR MAIL
CARRIED NO DKIM-Signature, THIS IS WHY, and upgrading is the whole fix.
What this does not cover is a component that holds NO key: a private key
file that is missing, does not open with the password, or is in a format
that no unit linked into the program registers, so that the component has
nothing to hand out. That fails the same silent way, before and after this
fix. The test is whether the component signs anything else: a key component
that signs an SSH session or an ACME request in the same program has its
key, and now signs mail with it.
tDkimSigner now asks the component for its key and the key to sign, as
tJoseKey already did; a bare key interface is used as before. For
ed25519-sha256 the key must also be an Ed25519 key: an ECDSA key, component
or bare, is refused rather than used to produce a signature no verifier
accepts.
DkimPublicKeyRecord, which TsmSMTPServer.DkimDnsRecord uses, refused a
TstRSAKey with "rsa-sha256 needs an RSA key". It was the same kind of
question with the same wrong answer: the record needs only the modulus and
exponent, and asked for them through iIFKey, the face an RSA public key and
private key share. A TstRSAKey forwards iIFPublicKey and iIFPrivateKey,
each of which is an iIFKey, but a component answers only for the interfaces
it names, not for their ancestors. It accepts an RSA key component now, as
it already accepted an EdDSA one.
Checked by carrying a message through TsmSMTPServer with each component
and verifying the signature it added - the Ed25519 one against the RFC
8032 test key, the RSA one against the record DkimPublicKeyRecord built
from the same component - by checking that an ECDSA key component is
refused for ed25519-sha256, and by building the runtime packages of all
fourteen compilers.
--------------------------------------------------------------------------------
A TLS ENGINE SHARED BY MANY COMPONENTS: HELD SAFELY FROM ANY THREAD, SET UP
ONCE, TRUSTED ONCE, AND SWEPT ONCE WHEN FREED
================================================================================
11. FIXED - the REST client, and the components that hold a TLS engine as
configuration, changed the engine's free-notification list outside the
notify lock (StreamSec.Http.Rest, StreamSec.Mobile.CCADB,
StreamSec.Mobile.Acme, StreamSec.Mail.Retrieval,
StreamSec.Mail.SMTPServer, StreamSec.Mobile.CertConfig)
The defect is the one in entry 1: registering
for free notification on a TLS engine, and deregistering, changes the
engine's own unsynchronised list, so every such change has to be made
under TsmCustomTLSInternalServer.NotifyLock. TsmCustomTLSClient takes
it. These did not:
- TsmCustomRESTClient and TsmRESTClient, in the TLSEngine setter and in
TComponent's own teardown. THIS IS THE ONE LIKELY TO MATTER. TLSEngine
is documented as shareable with other clients, and a client per
request or per worker thread over one long-lived engine is the use it
invites. On a purpose-built harness - four threads making HTTPS calls
through one shared engine while eight more attach, re-point and free
clients on two - every run went wrong before the fix, 40 of 40 across
Win32, Win64 and Linux64, and none of 70 after it. In all but one of
the runs that went wrong through real calls, every call had answered
and nothing had raised: the engine was left holding a pointer to a
freed client, for its destructor to walk.
- TsmCCADBTrustAnchors.Engine, TsmAcmeClient.TLSServer, TLSServer on
TsmPOP3Server, TsmIMAPServer and TsmSMTPServer,
TsmSMTPServer.SmarthostTLSServer, and KeysAndCerts on TsmCertConfigIni
and TsmCertConfigReg. Each is set once, as configuration, so the
exposure is narrow: setting or freeing one while other threads attach
clients to the same engine. The likeliest case is SmarthostTLSServer,
whose engine is the one the SMTP server's own delivery threads attach
their clients to. One unlocked change among locked ones is enough. On
the same kind of harness, with REST clients attaching beside it, each
of these went wrong on every run before the fix and none after, and in
most of those runs a REST client - which did take the lock - was among
what raised.
Each of them now takes the lock in its setter and deregisters under it
in its destructor, so every component in this library that holds a
reference to a TLS engine changes that engine's list only under the
lock.
TWO SMALLER DEFECTS IN THE SAME SETTERS ARE FIXED WITH IT:
- TsmPOP3Server, TsmIMAPServer and TsmSMTPServer did not deregister from
an engine when TLSServer was pointed at another one or cleared, so the
old engine kept a registration until the server was freed.
TsmSMTPServer.SmarthostTLSServer had the same omission. Both now
deregister, except that the SMTP server keeps the registration while
the old engine is still held by its other property - TLSServer and
SmarthostTLSServer may be one engine.
- TsmCustomCertConfig did not clear KeysAndCerts when that engine was
freed first, and went on pointing at freed memory. It clears it now.
It also registered the other way round from every other component,
which left an engine with the same Owner unmarked, so the owner did not
report freeing it; it registers on the engine now.
NOTHING TO CHANGE IN YOUR CODE. If your own component registers for free
notification on an engine that other threads may be using, take
TsmCustomTLSInternalServer.NotifyLock around FreeNotification and
RemoveFreeNotification, and deregister under it in your destructor
rather than leaving that to TComponent.Destroy - which is what these
components do.
Checked on Win32, Win64 and Linux64: for each component, the
registration count on the engine after attaching, re-pointing, clearing
and freeing, read from the engine itself, and the reference cleared when
the engine is freed first; then each attached, re-pointed and freed on
four threads while REST clients do the same on four more, with every
engine required to hold no registration afterwards.
12. FIXED - clients preparing one shared TLS engine for their first
connections at the same moment could connect before it had loaded, load
it twice, and corrupt the heap (StreamSec.Mobile.TlsInternalServer)
Every client of a TsmCustomTLSInternalServer created at run time prepares
it before its first connection: CheckLoaded, which runs Loaded - the step
that computes the cipher suites a ClientHello offers and wires the
certificate stores into the session - and TLSSetupClient, which copies
Options into the session. TsmCustomTLSClient does both in EnsureEngine, so
every HTTPS, SMTP and plain TLS client does; the snip client does both,
and the REST client calls CheckLoaded. Neither was safe to run from two
threads at once, and one engine shared by clients on several threads -
the arrangement tSmtpSpool's delivery threads, the REST client's
TLSEngine and TsnipAdvancedTLSClient exist for - has several clients do
both at the same moment when its first connections are made.
CHECKLOADED marked the load done before it did the work, so a second
caller could return at once and go on to connect through an engine that
was still loading, and two callers arriving together could both run the
load.
TLSSETUPCLIENT is not a plain assignment. When an engine's Options differ
from the session's own, as a TsmSimpleTLSInternalServer's do from the
start, every option copied rebuilds the cipher-suite list and a list of
the suites' names, and two copies at once corrupted both: an access
violation in TStringList.InsertItem, EOutOfMemory, or damage found later,
as when freeing the engine failed in TsmStreamSecII.Destroy.
WHAT HAPPENS NOW. CheckLoaded runs Loaded once and makes every other
caller wait until it has returned. TLSSetupClient copies for one caller at
a time, and TLSSetupServer takes the same lock, since it writes the same
options. The lock belongs to the component and is taken only while a
connection is being prepared, never on the data path. Nothing to change in
your code.
Checked on Win32, Win64 and Linux64 with an engine that counts its loads:
eight threads preparing one fresh engine at once, over twenty engines, as
TLS clients, and as TLS, snip and REST clients and plain CheckLoaded calls
together; and HTTPS calls through a fresh shared engine. Before the fix
every run went wrong, with clients returning before the load had and the
concurrent copies raising; after it none did. The runtime packages of all
fourteen compilers, XE3 through 13 Florence, build on Win32 and Win64.
13. BEHAVIOUR CHANGE - REST clients sharing one TLS engine each installed the
engine's trust again, several of them at once
StreamSec.Http.Rest. TsmCustomRESTClient.TLSEngine is documented to run
OnConfigureTrust once per engine, on the first exchange through it. It
ran once per CLIENT: whether an engine had been configured was recorded
on the client that configured it. Every client pointed at an engine
therefore installed the trust again on its own first exchange - the
handler, ExtraAnchorFile and RevocationChecking - and clients whose
first exchanges overlapped, on different threads, installed it at the
same time: the handler ran several times at once on one engine, and so
did the engine's CheckLoaded, which is not written to be run from two
threads. A client per request or per worker thread over one long-lived
engine, which is the use TLSEngine exists for, installed the trust on
every request.
WHAT HAPPENS NOW. The record of the install belongs to the engine. The
first exchange through an engine installs its trust while holding a lock
of that engine's, so a client that reaches the engine meanwhile waits
until the install has finished before it connects, and no later client
installs anything. An install that raises is not recorded, so the next
exchange through the engine tries again. The record is dropped when the
engine is freed, so a new engine is configured even when it is created
at the address of one that was freed.
THE BEHAVIOUR CHANGE: CLIENTS THAT SHARE AN ENGINE SHARE ITS TRUST. The
trust installed is that of the client making the first exchange: its
OnConfigureTrust anchors, its ExtraAnchorFile and its RevocationChecking.
A later client's handler is not run on that engine. Before, each client
added its own anchors, and whichever client made its first exchange last
decided RevocationChecking for all of them. Clients that are configured
alike, or that follow the one engine per trust domain TLSEngine has
always asked for, see no difference; clients that need different trust
need engines of their own.
Checked on Win32, Win64 and Linux64 with a handler that counts how often
it runs, how many runs overlap and whether it has returned: one client,
a second client, a client with a handler of its own, re-pointing, an
install that raises, and engines freed and created again at the address
of a freed one; eight threads making their first exchange through one
fresh engine at once, over twenty engines, where before the fix the
handler ran 80 times on one engine, 8 at once, and after it once; and
HTTPS calls through an engine that holds no anchor until the handler
loads one, which answer only if every client waited for the install. The
runtime packages of all fourteen compilers, XE3 through 13 Florence,
build on Win32 and Win64.
14. FIXED - freeing a TLS engine swept the ASN.1 collector sixteen times, and
deactivating TsmAsyncTLSServer did that once per shard, so stopping a
server whose process holds many certificates could take minutes
StreamSec.Mobile.TlsInternalServer, StreamSec.Mobile.AsyncTLSServer,
stGC. A sweep of the collector (tGCManager.Sweep) marks every live ASN.1
object in the process, so what it costs is the size of everything the
application holds - certificates, keys, lists - and not the garbage it
finds. Freeing a TLS engine (TsmSimpleTLSInternalServer and every other
TsmCustomTLSInternalServer) ran sixteen sweeps: each certificate store it
owns and its TsmStreamSecII swept on the way out, and so did the engine
itself. Setting TsmAsyncTLSServer.Active to False frees its EngineCount
shards one after another, and EngineCount defaults to the reactor's
thread count, so a deactivation ran sixteen sweeps for every shard.
WHO WAS AFFECTED. An application that deactivates a TsmAsyncTLSServer, or
frees TLS engines, while its process holds many ASN.1 objects. The result
was never wrong and every object was still collected; the time grew with
what the process holds multiplied by the number of shards. Measured on
Win64 with these units as they were before this change, in a process
holding 4,000 parsed certificates (284,000 collector objects), where one
pair of sweeps takes 0.42 s: freeing one engine took 3.4 s, and
deactivating 2, 8 and 16 shards took 6.8, 27.2 and 58.1 s. A server that
keeps the certificates of 1,000 clients it has authenticated, on 32
cores, took 70 s to stop on Win64 and 61 s on Linux64 - longer than a
service manager usually waits before killing a process.
In this version freeing an engine sweeps twice however many stores it
owns, and deactivating TsmAsyncTLSServer sweeps twice for all its shards
together. Measured the same way: freeing one engine 0.43 s, deactivating
2, 8 and 16 shards 0.48, 0.42 and 0.48 s, and the server that took 70 s
and 61 s stops in 0.9 s on Win64 and 1.0 s on Linux64.
NOTHING ELSE CHANGES. The same objects are collected, by the same
collector, before the destructor or the assignment to Active returns.
What moves is the moment within that call: an engine's garbage is
collected at the end of its destructor, where it already collected what
its inherited teardown released, and a deactivating server's at the end
of the deactivation, after its last shard is freed. Sweeps called on
other threads are not affected.
For code that frees many objects which each sweep: tGCManager has
BeginSweepDeferral and EndSweepDeferral. Between them, a Sweep called on
that manager from the calling thread is remembered instead of run, and
the outermost EndSweepDeferral runs Sweep twice if any was asked for.
Pairs nest, the deferral belongs to the thread that opened it, and
EndSweepDeferral belongs in a finally.
--------------------------------------------------------------------------------
TLS: CHANNEL BINDING ON THE COMPONENT CLIENT, A FASTER 1.3 TICKET STORE,
FINITE-FIELD DIFFIE-HELLMAN CHECKED AND PADDED CORRECTLY, AND ANONYMOUS KEY
EXCHANGE DEPRECATED
================================================================================
15. ADDED - the RFC 9266 channel binding on the component TLS client, and a
REST session that can be bound to one
A protocol that authenticates INSIDE a TLS tunnel - a challenge in one
request and the answer to it in the next - is only sound if both went down
the same channel. If they did not, whoever relayed the challenge can spend
the answer somewhere else: take a challenge to the party who can answer it,
pass their answer on as your own. RFC 9266 gives a TLS connection a name
that an authentication can be bound to, and this release makes that name
reachable and gives the REST client one connection to name.
The binding itself is not new - snip over TLS has bound its KAPA login to
the tls-exporter value since 4.1.2.355. What is new is that the value is
now reachable from the component client stack, and that REST can hold a
single connection worth binding to.
TsmCustomTLSClient (and so every client on it - HTTPS, SMTP, POP3, IMAP)
gains:
function GetChannelBinding(out aBinding: tBytes): Boolean;
the 32-octet RFC 9266 tls-exporter value for the connection in hand. It is
the client-side counterpart of iAppTransport.ExportKeyingMaterial, which
the async TLS server has offered for the same purpose.
IT FAILS CLOSED and it is not cached. False, with the buffer empty,
whenever there is no completed TLS 1.3 session to export from - not
connected, TLS 1.2, handshake unfinished, connection already gone. Treat
False as "refuse", never as "carry on unbound": unbound is the exact
condition a binding exists to detect. And read it again each time rather
than keeping it, because a transport that reconnected is a different
channel with a different value, and reading it is what makes that visible.
TsmCustomRESTClient gains an opt-in pinned session:
function BeginPinnedSession: Boolean;
procedure EndPinnedSession;
function PinnedSessionLive: Boolean;
function ChannelBinding(out aBinding: tBytes): Boolean;
Between the two, every call goes down one held connection instead of the
usual build-use-free, and ChannelBinding names it.
A LAPSE ENDS THE SESSION AND IS NOT RECONNECTED THROUGH. If the pinned
connection is found closed - a keep-alive that expired, a network that went
- the session is marked broken and every later call in it fails. Opening a
fresh connection instead would complete an authentication on a channel it
was never bound to, which is the attack. A call to a different origin than
the session was pinned to is refused for the same reason. End the session
and start again.
PIN ONLY FOR THE EXCHANGE THAT NEEDS IT. This is not a connection pool and
not a performance feature; a held connection is a resource on the server
too. Nothing changes for code that does not call BeginPinnedSession: the
default is still one connection per call.
All four are virtual, so a test that replaces DoTransport can replace these
as well and exercise the protocol above them without a socket.
16. BEHAVIOUR CHANGE - the TLS 1.3 server's resumption ticket store walked
every ticket it held on each handshake, and a stored ticket's expiry and
identity are now fixed when it is stored
StreamSec.Mobile.StreamSecII. tTls13MemoryTicketStore is the store every
TsmStreamSecII creates for the resumption tickets its TLS 1.3 server
issues, and the one TsmAsyncTLSServer.SharedTicketStore puts behind all of
a server's shards. It kept its tickets in a list, behind one lock: each
Put, Peek, Find, Count and PruneExpired walked the whole list to drop the
expired tickets, and each Peek, Find and Consume walked it to look an
identity up. A server issues SessionTicketCount tickets on each handshake,
six by default, and each is valid for two hours, so the store holds about
43,000 tickets for every handshake a second the server sustains - and
every handshake, on every shard, waited for those walks.
WHAT IT COST. Measured on Win64 with 100,000 tickets held - about 2.3
handshakes a second, sustained - a Put took 0.42 ms and a Peek 0.86 ms, so
the six Puts of one handshake held the lock for 2.5 ms, and both costs
grow in proportion to the tickets held. The store now finds an identity
through a hash index and keeps its tickets ordered by expiry in a heap, so
no lookup and no reap walks the tickets: a Put takes 0.14 microseconds and
a Peek 0.8 with 100,000 tickets held, and 0.3 and 1.4 with 1,000,000 held.
Dropping an expired ticket costs a logarithm of the tickets held, and the
tickets still valid cost nothing.
TWO COSTS THE LIST DID NOT HAVE. The Put that finds the store full doubles
its arrays and walks every identity once, holding the lock while it does:
3 to 9 ms with 100,000 tickets held and 33 to 74 ms with 1,000,000, the
longer figures on Linux64, once per doubling. Once three quarters of the
tickets are gone the arrays shrink again, with a pause of the same kind for
what is left. And the index costs about 40 to 65 bytes a ticket, where the
list cost about 10 - some 40 MB beside the tickets themselves at 1,000,000.
WHAT THE STORE ANSWERS IS UNCHANGED. A ticket is dropped once its
CreatedAt plus LifetimeSecs has passed; of two tickets stored under one
identity, the later is found first; Consume is still the one atomic claim
and does not drop expired tickets; Count drops them before counting.
THE BEHAVIOUR CHANGE: A TICKET'S EXPIRY AND IDENTITY ARE READ ONCE, WHEN
IT IS STORED. Find, and TsmStreamSecII.Tls13FindServerTicket, which calls
it, return the stored instance, not a copy. The list read every ticket's
Identity, CreatedAt and LifetimeSecs afresh on each walk, so code that
changed them on the instance Find returned changed how the store treated
the ticket - setting LifetimeSecs to 0 had it dropped on the next walk.
The store now takes the expiry and a hash of the identity at Put: a
changed LifetimeSecs or CreatedAt does not move the expiry, so the ticket
stays valid until the time it was stored with, and a changed Identity
leaves the ticket found under neither the old identity nor the new one.
The documentation of iTls13TicketStore.Find says so: the caller must not
modify the instance. To withdraw a ticket before it expires, call Consume
with its identity. Nothing in this library changes a stored ticket, and
its TLS 1.3 server reads tickets through Peek, which returns a copy.
Checked on Win32, Win64 and Linux64: the store against a model of the
behaviour above over 150,000 operations; expiry checked against the clock
read before and after each call, among tickets being stored and removed;
many threads claiming one identity, of which exactly one must succeed; the
cost of Put and Peek at 128,000 tickets against 2,000; the memory each
ticket adds, and what is left once the store is emptied; and a million
lookups of identities never stored. The store of 4.1.3.357 passes the
behaviour checks and fails the cost checks on all three platforms.
17. FIXED - a TLS 1.0-1.2 client and server used the peer's finite-field
Diffie-Hellman public value without checking it, 0, 1 and p-1 included
StreamSec.Mobile.Tls. RFC 7919 sec.5.1 requires each peer to validate
the other's public value Y - dh_Ys from the server, dh_Yc from the
client - by ensuring that 1 < Y < p-1. Neither side did: the server
took dh_Yc, and the client dh_Ys or the static Diffie-Hellman key of the
server's certificate, and computed the premaster secret from whatever
value arrived. With Y = 1 that secret is 1, and with Y = p-1 it is 1 or
p-1, whatever the local private key; 0, and values from p up, are not
in the group at all.
WHAT HAPPENS NOW. A value outside 1 < Y < p-1 is refused wherever the
key exchange uses one:
- The client reading a ServerKeyExchange refuses a dh_Ys outside the
range set by the dh_p of the same message, and ends the handshake
with handshake_failure (decrypt_error for an anonymous suite).
- The client keying from the server's value - from ServerKeyExchange or
from a static Diffie-Hellman certificate - produces no
ClientKeyExchange and ends the handshake with internal_error.
- The server reading a ClientKeyExchange refuses a dh_Yc, or the static
Diffie-Hellman key of the client's certificate, outside the range of
its own group, and ends the handshake with illegal_parameter.
In the RFC 7919 and RFC 3526 groups no correctly generated public value
lies outside the range, so a handshake between well-behaved peers is
not refused. For a safe prime p, as in those groups, the check rules
out every small subgroup; for another prime it rules out only those of
order 1 and 2. The client still takes the server's p and g as sent. The
value is public, so the comparison is not fixed-time. TLS 1.3 is not
affected: it does not negotiate finite-field groups.
IMPACT. Not exploitable by a third party between well-behaved peers:
the server's value is signed or certified, a replaced client value
only leaves the two sides with different secrets, and the server's
exponent is fresh per handshake in a safe-prime group. It takes a
peer that itself sends a degenerate value.
Checked on Win32, Win64 and Linux64 at each of the four places above:
0, 1, p-1, p, p+1, a value longer than p and a negative key value are
refused, and 2, p-2 and a valid key are accepted with the exact master
secret, computed independently in Python with the TLS 1.2 and TLS 1.0
PRFs over ffdhe2048.
18. FIXED - a TLS 1.0-1.2 finite-field Diffie-Hellman key exchange kept the
leading zero octets of the shared secret, so about one handshake in 256
with another implementation failed on the Finished message
StreamSec.Mobile.Tls. RFC 5246 sec.8.1.2, and RFC 4346 before it:
"Leading bytes of Z that contain all zero bits are stripped before it
is used as the pre_master_secret." All three places that derive the
master secret from a Diffie-Hellman result Z - the client keying from
dh_Ys or from a static Diffie-Hellman certificate, the client with a
static key of its own, and the server reading dh_Yc or the client
certificate's key - used Z padded to the octet length of p instead.
Whenever Z began with a zero octet, which is one exchange in 256 for a
2048-bit p, the two peers computed different master secrets and the
handshake ended with bad_record_mac on the Finished message. Only the
finite-field exchange was affected: the elliptic-curve exchange pads its
x-coordinate as RFC 8422 requires, and TLS 1.3 never negotiates a
finite-field group here.
WHAT HAPPENS NOW. Z is used with its leading zero octets stripped at all
three places, so the master secret is the one every other TLS 1.0-1.2
implementation derives. RFC 2246 says nothing either way for TLS 1.0;
the strip applies there too, as OpenSSL does, which pads only for TLS
1.3. The public value dh_Yc is still sent padded to the length of p. A
Z of zero is not a key and ends the handshake as an out-of-range public
value does (entry 17); the range check leaves no way to reach it.
IMPACT. Interoperability only. A session that completed had the right
keys on both sides, and a session that failed left nothing behind.
Checked on Win32, Win64 and Linux64 at each of the three places: a peer
value whose Z has exactly one, and exactly two, leading zero octets -
solved in the generator as Z^(1/x mod q) - keys from the stripped Z with
the exact master secret computed independently in Python with the TLS
1.2 and TLS 1.0 PRFs over ffdhe2048, and not from the padded Z; the path
whose private key the library draws is run until its Z begins with a
zero octet. Against OpenSSL 3.5.7 with DHE_RSA on TLS 1.2, 512
handshakes with this library as the client and 512 as the server all
completed; before the fix, one of 128 failed in each direction.
19. FIXED - a TLS client that allowed the anonymous Diffie-Hellman suites
kept none of the server's parameters from a ServerKeyExchange
StreamSec.Mobile.Tls. A DH_anon cipher suite decodes as the key exchange
keaDH. The ServerKeyExchange decoder checked dh_p, dh_g and dh_Ys for
it, but handed the three values back only for the DHE suites, so for
DH_anon it reported success with all three empty. The handshake then
built the server's key from them and the client stopped with an access
violation instead of an alert. The decoder now returns dh_p, dh_g and
dh_Ys for DH_anon exactly as for DHE, and dh_Ys is range-checked in the
same way (entry 17).
The anonymous suites are deprecated (entry 20) and off by default: a
client reaches this code only with both TLSOptions.KeyAgreementDH and
TLSOptions.SignatureAnon allowed.
Checked on Win32, Win64 and Linux64: the same ServerKeyExchange decoded
for DH_anon and for DHE gives the same dh_p, dh_g and dh_Ys, and a
DH_anon message whose dh_Ys is p-1 is refused.
20. DEPRECATED - anonymous key exchange (TLSOptions.SignatureAnon)
StreamSec.Mobile.StreamSecII. The anonymous cipher suites of TLS 1.0-1.2,
DH_anon and ECDH_anon, authenticate neither peer and have long been out
of use. TLSOptions.SignatureAnon, the setting that enables them, stays
in the library unchanged, but it is deprecated, is not maintained, and
is not recommended for new work.
It is prNotAllowed by default, and TsmSimpleTLSInternalServer sets its
own Options.SignatureAnon back to prNotAllowed. Code that leaves the
setting alone is not affected.
--------------------------------------------------------------------------------
INTEGER ARITHMETIC: DIVISION, MODULAR EXPONENTIATION, FIXED-TIME MULTIPLICATION,
CARRIES, INDEX BOUNDS, AND POOL REALLOCATION
================================================================================
21. FIXED - P-521 and P-224 arithmetic, and any division by a shared
modulus whose length is not a multiple of 64 bits, failed when threads
used it at the same time
StreamSec.DSI.Arith. tDSIntegerImpl.ModDivInto, the division that ModTo,
DivTo, ModDivTo, InvModTo, MulModTo and ExpModTo come down to, normalised
its divisor where it lay: it set the divisor positive and, when the
divisor's length in bits was not a multiple of 64, shifted it left for
the length of the division and back again afterwards. The divisor
belongs to the caller. When it is shared - a curve's field prime, of
which the process holds one per curve for every key and every curve
object, or the modulus of a key that several threads use - any other
thread reading it at that moment read a different number.
WHAT IT LOOKED LIKE. Wrong results, and exceptions raised from inside the
arithmetic: EAssertionFailed in StreamSec.DSI.Arith, or eDSInteger with
"Overflow in SubModAddInto" or "Overflow in ShlInto". The damage could
outlast the race, so work done afterwards on a single thread could fail
too, up to an access violation.
WHO WAS AFFECTED. Every scalar multiplication on P-521 or P-224 inverts
modulo the field prime, so any two threads doing P-521 or P-224
arithmetic at the same time were exposed - key agreement, key
generation, signing and the MLKEM1024-ECDH-P521 composite KEM - with
separate keys as much as with a shared one. Measured with 8 threads over
20 rounds on Win32, Win64 and Linux64: all 160 P-521 and all 160 P-224
key agreements returned a wrong result or raised, and so did all 160
MLKEM1024-ECDH-P521 decapsulations; prime239v1 failed the same way.
Concurrent P-521 public-key derivation failed less often, and on Linux64
one such run did not finish. RSA without the CRT representation
(ReprType 0) and with a modulus that is not a multiple of 64 bits was
affected on Win64 and Linux64: 156 to 160 of 160 private-key operations
with 2000- and 2016-bit keys wrong or raising.
NOT AFFECTED, measured under the same load: P-192, P-256 and P-384, whose
primes are multiples of 64 bits; the finite-field Diffie-Hellman groups
of RFC 7919 and RFC 3526; and RSA keys of 2048, 3072 and 4096 bits.
ON ONE THREAD. When the division raised - for instance because its result
did not fit the integer it was written into - a negative divisor was left
positive. That is gone with the rest: the divisor is never written, not
even its reference count.
NOTHING THAT IS COMPUTED DIFFERS. For every division that completes, the
quotient and the remainder are the ones release 4.1.3.357 computes, bit
for bit: compared over 1,760 dividend and divisor pairs - lengths on and
off a multiple of 64 bits, all four sign combinations, and the divisor
being the dividend itself - through each of the operations above, on
Win32, Win64 and Linux64, with every divisor also placed in
write-protected memory. The composite KEM and composite signature test
vectors and the RFC 6979 ECDSA vectors give the same output as before.
NOTHING MEASURABLE IS PAID FOR IT. A negative divisor, or one that has to
be shifted, is copied once per division; any other is read where it
lies. Measured before and after, alternating which ran first: a division
by a 256-, 521- or 2048-bit modulus, and a P-224, P-256, P-384 or P-521
key agreement or public-key derivation, cost the same within the spread
between runs of one build, on Win32, Win64 and Linux64.
For code that calls the iDSInteger methods directly, the rule this
follows: an ...Into method writes into the integer it is called on, so
call one only on an integer no other thread can reach. A method that
receives an integer as an argument - such as a divisor - only reads it.
22. FIXED - integer division returned the divisor's absolute value, not
0, as the remainder of some exact multiples: a correct residue outside
the 0..N-1 range the modular methods rely on, so InvModTo did not
return and a shared secret of 0 was recreated as the modulus
StreamSec.DSI.Arith. iDSInteger.ModDivInto, on which ModInto, ModTo,
DivInto, DivTo and ModDivTo are built, follows the usual convention:
the remainder is the least non-negative residue, from 0 up to but not
including the absolute value of the divisor, whatever the signs of the
dividend and the divisor. For two shapes of dividend, on every
platform, it returned the divisor's absolute value where the
convention calls for 0:
- A positive dividend equal to the absolute value of a divisor longer
than 32 bits. The remainder was that absolute value, and the
quotient 0 instead of 1 or -1.
- A negative dividend that is an exact multiple of the divisor: at
least twice its absolute value, or any multiple of a divisor of 32
bits or less. The remainder was the divisor's absolute value, and
the quotient one further from zero than the convention gives.
WHAT WAS WRONG, AND WHAT WAS NOT. Each such answer was arithmetically
consistent: the quotient times the divisor plus the remainder was the
dividend, and the remainder was in the same residue class as the
dividend, so a caller that only needs a residue got a right value.
What broke the convention was the representative: the class of 0 was
reported as the divisor's absolute value rather than as 0, one past
the end of the range. No exception was raised, and no other dividend
was touched: a dividend that is not an exact multiple of the divisor
always got the canonical remainder, and so did the exact multiples not
listed above.
The modular methods reduce through this division, and some of them
depend on the range, so the two shapes reached them in three ways:
- The Euclidean loops of InvModTo and JacobiSymbol make progress only
because each remainder is smaller than the divisor it came from. Fed
M in place of 0, InvModTo did not return when Self was M, for an M
longer than 32 bits, or a negative multiple of M of at least twice
its value; nor did DivModTo with such a divisor, which inverts
through it. JacobiSymbol recursed until the stack overflowed when
Self was such an M: EStackOverflow on Windows, while on Linux64 the
process was terminated.
- MulModTo, AddModTo and NegModTo returned M, a correct residue but
not the canonical 0, for, among others, 1 times M, -2 times M,
(M-1) + 1 and the negation of -M.
- ExpModTo did the same for a base of M or -2M with exponent 1 on
targets that do not use the Montgomery arithmetic of Win32 and
Win64, Linux64 among them.
A caller that compares such a result with 0, tests its sign or bit
length, or hands it on as the answer, sees M; one that reduces,
multiplies or exponentiates it once more does not.
WHO WAS AFFECTED. tDSSecretSharing.RecreateSecret (StreamSec.DSI.
SecretSharing) adds one term per share and reduces the sum with
ModTo, which is all the handling a sum equal to the field modulus
needs, and it is ModTo that returned the modulus for it. So a secret
of 0, the secret that CreateZeroSharing shares, came back as the field
modulus whenever the terms added up to exactly that: in 20 of 20
trials with threshold 1, and in about half with threshold 2. Share
identifiers that differ by the field modulus made RecreateSecret hang
in InvModTo. Nothing in StreamSec.DSI.SecretSharing was changed, and
nothing else in the library calls either method; they are there for
your code. Signature verification, RSA public-key operations and
Diffie-Hellman key agreement check the range of their input, or
compare the result with a value below the modulus, and so reached the
same outcome as with a correct division.
NOTHING ELSE THAT IS COMPUTED DIFFERS. Compared with Python integer
division over 38,740 calls to the six division methods - divisors from
1 to 4191 bits, on and off the 32- and 64-bit word boundaries;
dividends of both signs equal to the divisor, one away from it, and
multiples of it and one away from those; random dividends up to 200
bits longer than the divisor; and the divisor passed as the dividend
itself - release 4.1.3.357 returns 9,095 results outside the
convention on each of Win32, Win64 and Linux64. This version returns
none, and every other result has the same value as before. In 640 of
those calls, ModInto or ModDivInto on a dividend of minus the divisor,
the remainder of zero left in place had a sign of 1 and now has a sign
of 0.
ModDivInto is not a fixed-time method, and the fixed-time RSA
private-key operation does not divide with it.
23. FIXED - modular exponentiation on Win32 and Win64 gave wrong results for
a base that was negative or longer than the modulus
StreamSec.DSI.Arith. tDSIntegerImpl.ExpModTo, which computes B^E mod M,
works in Montgomery form on Win32 and Win64. That is exact only for a
base from 0 up to, but not including, 2^(32w), where w is the length of
M in 32-bit words, and B was reduced modulo M first only when its
allocation was wider than the working buffer. So these bases went in
unreduced, and the result was wrong with no exception raised:
- A negative base, on Win32 and Win64. The result was the one for its
absolute value, which differs whenever E is odd.
- A positive base longer than w words that still fit the buffer, on
Win32, where the buffer is the width of the Karatsuba multiplication:
w rounded up to the next of 4, 6, 8, 12, 16, 17, 24, 32, 48, 64, 96,
128 words and so on. A modulus whose length in words is one of those
widths - 256, 384, 521, 1024, 2048, 3072 and 4096 bits among them -
was not exposed. Any other was: every modulus of up to 96 bits, a
160-bit subgroup order, the P-224 prime, a 1500-bit modulus.
- A base whose value reaches into the two words of storage above its
Size, on Win32 and Win64 - ShlInto, for one, can leave the top of a
result there. Those words were dropped, or taken in unreduced.
A base from 0 to M-1 was always handled correctly. Every other target,
Linux64 among them, reduces the base before exponentiating and was not
affected.
WHO WAS AFFECTED. RSA in its default configuration was not: the
public-key operations refuse an input outside 0 to N-1, a private-key
operation requires an input below N, and with the CRT representation
and gFixedTime at its default of True it reduces that input modulo P
and Q before exponentiating. Two places in the library could reach the
defect with input from outside:
- DSA and Nyberg-Rueppel signature verification checks r and s but not
the public key's y or g, which are read as signed integers. On Win32
and Win64 a key encoding either one as a negative number was used as
its absolute value, so a signature made for y could verify against a
key that encodes -y.
- The TLS client takes the server's Diffie-Hellman p and g without a
range check, and in release 4.1.3.357 took Ys without one too
(entry 17). On Win32, a g or Ys sent longer than a p whose length
is not one of the widths above made the client compute a wrong
premaster secret.
NOTHING ELSE THAT IS COMPUTED DIFFERS. Compared with Python's pow() over
43,468 calls - moduli from 2 to 4096 bits, bases from 0 to four times
the modulus length and of either sign, exponents 0, 1, 2, 3, 65537 and
longer random ones, the base also in a wider allocation - release
4.1.3.357 returns 8,165 wrong results on Win32, 6,609 on Win64 and none
on Linux64. Over 44,142 further calls, each base in an allocation one or
two words narrower than its value, it returns 12,680 wrong results on
Win32, 11,029 on Win64 and none on Linux64. This version returns none
on any of the three, and every result 4.1.3.357 got right is
unchanged, bit for bit.
AN EXCEPTION WHERE THERE WAS A WRONG RESULT. A base that is not in range
is reduced first, and the division refuses some bases whose value
reaches past their Size with an eDSInteger overflow, as it does on
every target. In the second comparison 2,646 calls raise it, the same
calls on all three platforms. On Win64 and Linux64 those are the calls
that raised it in 4.1.3.357; on Win32, 240 of them returned a wrong
result in 4.1.3.357 instead.
A base that is already in range takes the path it took before. The
added test reads the base's words from w upwards and combines them
without branching on their values: one pass over those words, with no
timing difference that depends on the value of a base in range.
24. FIXED - fixed-time multiplication on Win64 was wrong for an odd number
of 32-bit words, so on Win64 an RSA key of, for instance, 1088, 2112 or
3136 bits signed and decrypted wrongly
StreamSec.DSI.Arith. iDSInteger.FixedMulTo(aSelfSize, aFactor)
multiplies two integers that each fit in aSelfSize 32-bit words. On
Win64 it multiplies in 64-bit limbs, and for an odd aSelfSize it left
out the top 32-bit word of both operands: the product was wrong, with
no exception, whenever either operand had a nonzero word there. An
aSelfSize of 1 ran past the operands and the result and ended in an
access violation. Separately, an aSelfSize of 0 raised an access
violation on Win32 and Win64.
WHO WAS AFFECTED. The RSA private-key operation multiplies at the
length of a prime. On Win64, a key held with its primes (ReprType 1 or
2, which every imported key is) and used with gFixedTime at its default
of True returned a wrong result from every signature and decryption
when its primes are an odd number of 32-bit words - that is, when the
modulus is an odd multiple of 64 bits, such as 1088, 2112, 3136 or 4160
bits. Measured on the code of release 4.1.3.357 with keys of 1088, 2112
and 3136 bits: 60 wrong results in 60 operations on Win64, none on
Win32. A signature made with such a key does not verify, and a
decryption does not recover the plaintext. The wrong results measured
were wrong modulo both primes, which does not reveal either prime the
way a result wrong modulo only one of them would.
Keys of 1024, 1536, 2048, 3072, 4096 and 8192 bits have primes of an
even number of 32-bit words and were not affected, and neither were
Win32, Linux64, or RSA with gFixedTime set to False. Nothing else in the
library calls FixedMulTo with an odd size.
In this version such keys sign and decrypt correctly on Win64: the
fixed-time RSA path multiplies at whole 64-bit limbs (entry 30), and
FixedMulTo multiplies every word of an odd aSelfSize - on Win64 by
rounding the size up to whole limbs, which reads the word above each
operand's top word, a word it already requires to be zero.
NOTHING ELSE CHANGES. For an even aSelfSize, the only size the library
passes, the multiplication runs the same steps over the same words with
the same allocation on every platform, and over 7 alternating runs at
32, 64 and 128 words the timings of the two builds overlapped on Win32
and on Win64. Checked against Python on Win32, Win64 and Linux64: 735
products at every aSelfSize from 1 to 40 words and at 47 to 49, 63 to
65 and 127 to 129, with operands of all ones, zero, one, a lone top
word or top bit, and random values of either sign, each in the tightest
allocation and in a wider one and, for a square, with Self as aFactor;
4,000 random products on each platform; and an aSelfSize of 0. With the
multiplication as released in 4.1.3.357, the same products on Win64 are
wrong at every odd aSelfSize above 1, all but the two at each size that
are zero, and an aSelfSize of 1 ends in an access violation.
NO NEW TIMING DEPENDENCE. How many limbs are multiplied follows from
aSelfSize alone, and the one test added is on aSelfSize, never on the
value of an operand.
For code that calls the iDSInteger methods directly: FixedMulTo takes
any aSelfSize, odd or even, including 0; its refusals are unchanged,
and its result has room for 2*aSelfSize words.
25. FIXED - on Win64, adding to an integer of Size 0 lost the carry out of
its 64 bits, and returned the sum less 2^64 without an exception
StreamSec.DSI.Arith. An iDSInteger of Size 0 - one allocated for 0 words
- stores a single 64-bit unit. On Win64 the assembler that adds a 32- or
64-bit term to an integer's magnitude did not report a carry out of that
unit when it was the only one. So where the sum did not fit in 64 bits:
- AddInt32To, AddUInt32To, AddInt64To and AddUInt64To returned the sum
less 2^64 - for 2^64-1 plus 1, the value 0 - instead of the sum in a
larger integer;
- AddInt32Into, AddUInt32Into, AddInt64Into and AddUInt64Into returned
that same value instead of raising eDSInteger, as they do when the sum
does not fit in Self's storage.
The magnitudes are what is added, so a negative integer with a negative
term was affected in the same way. An integer of Size 2 or more was not,
and Win32 and Linux64 add in other code and were not affected at all.
WHO WAS AFFECTED. Only code that makes an integer of Size 0 itself, holds
a value of 64 bits in it, and adds to it. Nothing in the library does: of
its callers of these methods, those that take an integer from the caller
add to a prime, a modulus or a candidate that no decoder or generator in
the library produces at Size 0, and the rest add to integers they allocate
at Size 2 or more.
Checked on Win32, Win64 and Linux64 against sums computed word by word
apart from the library: all eight methods, on integers of every Size from
0 to 40 words and of 48 to 1024, adding 1 and the largest term of each
type, of both signs where the method takes them, to a value with every
bit of its storage set. With the addition as release 4.1.3.357 has it,
and entry 29's fixes in place, exactly the Size 0 cases fail, and only
on Win64; this version fails none, and the checks of a carry across the
units of a larger integer still pass.
26. FIXED - adding a term of the opposite sign to an integer: AddUInt32To,
AddInt32To and AddInt32Into went wrong when the magnitude had exactly 32
bits, and on Win64 the 64-bit methods went wrong as well
StreamSec.DSI.Arith. When the term's sign is opposite to the integer's -
an unsigned term added to a negative integer, or a signed term of the
other sign - these methods subtract one magnitude from the other. A
magnitude as wide as the term they take in one arithmetic step, and a
wider one by subtracting the term from it in place, where the term can
be neither the larger nor equal. The in-place path was also taken for a
magnitude of exactly 32 bits (AddUInt32To, AddInt32To and AddInt32Into)
or 64 bits (AddUInt64To, AddUInt64Into, AddInt64To and AddInt64Into on
Win64), which can be either:
- equal to the term, the result was a zero with the integer's sign, -1
or 1, instead of a zero with a sign of 0: in hexadecimal, -80000000
plus 80000000 through AddUInt32To, and 80000000 plus -80000000 through
AddInt32To;
- smaller than the term, which only an unsigned term can be, the method
raised eDSInteger "Internal error", or on Win64, for an integer of
Size 0, returned the magnitude less the term wrapped around 2^64,
still negative: -80000000 plus FFFFFFFF gave -FFFFFFFF80000001 instead
of 7FFFFFFF.
On Win64 the 64-bit methods were also wrong for smaller magnitudes:
- AddUInt64Into gave the result the wrong sign whenever the term was the
larger: -5 plus 7 gave -2;
- AddUInt64To, AddUInt64Into, AddInt64To and AddInt64Into left the
magnitude's upper 32 bits in place when the term was equal to it, so
-100000000 plus 100000000 gave a value of 100000000 with a sign of 0.
AddUInt32Into was correct. The assembler that subtracts in place on
Win64 also reports a borrow out of an integer of Size 0 in this version;
with the paths above corrected nothing reaches it with a term that is
the larger.
WHO WAS AFFECTED. Code that adds a term of the opposite sign through
AddUInt32To, AddInt32To or AddInt32Into to an integer whose magnitude
has exactly 32 bits - for the signed methods only 80000000 plus
-80000000 - or on Win64 through any of the 64-bit methods. A zero with a
sign of 1 or -1 does not compare equal to zero, because Compare compares
signs. Nothing in the library calls AddUInt32To or the 64-bit methods;
it calls AddInt32To and AddInt32Into only with small constant terms, and
AddUInt32Into only on a value that is not negative.
Checked on Win32, Win64 and Linux64 against differences worked out on
word arrays apart from the library, reading the result's words and sign
through a raw pointer: the 32-bit methods on magnitudes on both sides of
2^31, 2^32 and 2^33, and on Win64 the 64-bit methods on both sides of
2^63, 2^64 and 2^65, the signed methods on integers of either sign, with
terms of 1, just below, at and just above the magnitude and at the ends
of the term's range, on integers of 0 to 8 words, global and local.
With these methods as release 4.1.3.357 has them, AddUInt32To,
AddInt32To and AddInt32Into fail on every target and all seven of the
methods named above on Win64; this version fails none.
27. FIXED - AddTo and SubTo refused results that needed the spare limb, and
AddTo of two integers of Size 0 ended in an access violation on Win64 and
Linux64
StreamSec.DSI.Arith. An integer of Size words stores Size+2 of them: the
two above Size are a spare limb, and a value may reach into it - ShlInto
can leave the top of a result there, and Data writes it. AddTo and SubTo
return a new integer sized for the result, but gave it room for a carry
out of the operands' storage only in some cases:
- AddTo looked only at aTerm whenever aTerm was at least as long as
Self. With both of the same Size and the same sign, a sum that carried
out of Self's storage - which takes a Self reaching into its spare
limb - raised eDSInteger "Overflow in AddInto" unless aTerm itself
reached the top bit of its last word, or its spare limb. The same sum
with the operands the other way round was computed.
- SubTo never gave its result that room. Operands of opposite sign,
whose magnitudes add, raised eDSInteger "Overflow in SubInto" whenever
the sum did not fit the storage of the longer one, at any pair of
Sizes.
- With both operands of Size 0, AddTo read a word outside both integers.
On Win64 and Linux64 that address lies far away and the read raised an
access violation; on Win32 it happened to read harmlessly. An integer
made from zero octets, by FromBase256 of an empty buffer for instance,
has Size 0.
- On Win32 and Linux64, AddInt64To and AddUInt64To add through AddTo, so
they refused the same sums, and they returned a global integer when
aLocal asked for a local one. On Win64 they have code of their own and
were affected by neither.
Measured with the code of release 4.1.3.357 over every pair of Sizes from
0, 2, 4, 6, 8, 16, 32 and 64 words with fifteen values per operand, 14,400
pairs per operation: AddTo refused 22 sums on Win32 and 247 on Win64 and
Linux64, where the 225 pairs of Size 0 raised as well; SubTo refused
1,010 differences on each platform. On Win32 and Linux64, AddInt64To
refused 7 of 1,080 sums and AddUInt64To 4 of 840, and both returned a
global integer for every local one asked for. Every result that was
returned was exact.
WHAT CHANGES FOR A RESULT THAT WAS ALREADY COMPUTED. Its value, nothing.
Its Size is one limb larger only when the operands' magnitudes add and an
operand reaches into its spare limb - a result that before either raised
or held the top of its value in its own spare limb. For every other pair
that 4.1.3.357 computed, the Size is the one it gives.
Checked on Win32, Win64 and Linux64 against a sign-and-magnitude adder of
the test's own: every pair above through AddTo and SubTo for a local and
a global result, and AddInt64To and AddUInt64To against terms at the
edges of Int64 and UInt64 - the exact value, no refusal, the operands
unchanged, the kind of integer aLocal asks for, and the Size.
For code that calls the iDSInteger methods directly: AddTo and SubTo
accept any two integers, whatever limbs their values use, and AddInt64To
and AddUInt64To return the kind of integer aLocal asks for on every
platform.
28. FIXED - iDSInteger.Data accepted Size+2, an index one word past the
integer's storage, which on a NIST curve constant is the next constant
StreamSec.DSI.Arith. The Data property reads and writes one 32-bit word
of an iDSInteger. An integer of Size words has storage for Size+2 of
them, Data[0] to Data[Size+1], but Data[Size+2] was accepted as well, for
a read and for a write, and reached the word after that storage.
WHAT THAT WORD WAS. An integer the library allocates always sits in a
memory-pool block with at least one word to spare, so for those the
index stayed inside the block: a read returned a word that is not part
of the integer, and a write stored one there. The prime Q, the order R,
the coefficient B and the generator's X and Y of P-192, P-224, P-256,
P-384 and P-521 are not allocated that way. They are records laid out
one after another, so the word after one constant is the first word of
the next: reading Q.Data[Q.Size+2] returned the start of R's header, on
Win32, Win64 and Linux64 alike.
WHO WAS AFFECTED. Only code that indexes Data itself, at Size+2. Nothing
in the library does - no index it passes goes above Size+1, in this
version or in 4.1.3.357 - and no demo uses the property.
Data[Size+2] now raises eDSInteger "Index out of bound", as every higher
index and every negative one already did. Data[0] to Data[Size+1] are
accepted as before.
Checked on Win32, Win64 and Linux64, taking where the storage ends from
the memory pool's own block header and from the records' addresses
rather than from Data: integers from AllocGlobal and AllocLocal of 0 to
40 words and either side of 48, 64, 128, 256, 1024 and 4096, used
directly and through GetAsLocal, and the fifteen curve constants above.
Data[Size+1] reads and writes the integer's top word, which MSB counts,
and a refused write leaves the word after the storage unchanged.
For code that calls the iDSInteger methods directly: Data takes an index
from 0 to Size+1 and raises eDSInteger for any other.
29. FIXED - iDSIPool.Realloc and Trim left an integer pointing at a freed
block when the memory pool moved it, and AddInt32To and its siblings
returned a wrong sum when it carried out of the integer's storage
StreamSec.DSI.Arith. iDSIPool.Realloc gives an iDSInteger room for a
number of 32-bit words, and iDSIPool.Trim the room its value needs. An
integer held by one reference is resized where it is: the memory pool
moves it to a new block whenever the size asked for needs a block of
another capacity, and frees and wipes the old one. The integer's header
went on naming the old block, and every method reaches the value through
the header. So after such a move Size read 0, and every read and write of
the value went to freed memory, which the pool may already have handed to
another integer.
The same two routines had five more defects:
- A grow cleared the wrong words. On a global integer it zeroed words of
the value itself and left the top words of the added storage holding
whatever the block held before. On a local integer it zeroed the top
two words the integer held and left the top two words added uncleared.
- Resizing an integer held by more than one reference, or a constant,
makes a copy. Shrinking one copied 24 octets on Win32, and 32 on Win64
and Linux64, past the end of the new copy's storage, and for small
integers past the end of its block, into whatever memory followed.
- Growing such a copy of a global integer to less than double its size
read past the end of the storage it copied from.
- Resizing the local stub GetAsLocal returns for a global integer took
the size of the value from the memory after the stub, which holds only
a header, and copied that many words.
- A copy kept the reference the resized variable had held. The old
integer - or the stub, and the global integer it refers to - was never
freed: on Win32 and Win64, resizing a 64-word integer held twice to
128 words 100,000 times left about 44 megabytes allocated, and doing
the same through a stub 47 to 50.
WHO WAS AFFECTED. In the library only AddInt32To and AddUInt32To, and on
Win64 also AddInt64To and AddUInt64To, call Realloc, and only when the
sum does not fit in Self's storage of Size+2 words, as when a small term
is added to a value with every bit set. Their result was then wrong, with
no exception: adding 1 to such a value, release 4.1.3.357 returns a wrong
sum for 8 to 11 of the 32 Sizes from 2 to 64 words, depending on the
target and on whether the integer is global or local. Nothing in the
library calls Trim, or calls Realloc on an integer held more than once or
on a stub. Code that calls either method directly met all of the above;
where a copy wrote past its storage the heap was damaged, and on Linux64
the C library then ended the process ("malloc(): invalid next size").
NOTHING ELSE CHANGES. After a resize the integer keeps its sign and every
word its new storage has room for, and every word a grow adds is zero.
Where the four methods above call Realloc, they return the true sum. A
copy releases the reference the variable held, so the old integer is
freed if that was its last one, and a stub is freed with the reference it
holds; a constant is never released. Beyond that, Realloc and Trim
allocate and free the same blocks as before.
Checked on Win32, Win64 and Linux64, reading the words and reference
counts through a raw pointer and the size of each block from the memory
pool's own header rather than through the integer's methods: every pair
of sizes from 0 to 24 words and pairs up to 4098, on an integer held
once, held twice and through GetAsLocal; Trim for every length of value
in integers of up to 40 words, and for some in larger ones; the methods
above where they call Realloc, at Sizes up to 1024 words; 1,000 and 4,000
rounds of resizing a copy and dropping every reference, counting blocks
through a memory manager that forwards to the real one, which leave none
behind; and a variable naming the prime of P-256, resized without
changing the constant. The same checks pass with a memory manager that
faults on a read past the end of a block.
For code that calls iDSIPool.Realloc or Trim directly: afterwards X may
name a different object than before - a new block, or a copy when X was
held more than once or was a GetAsLocal stub - so a pointer into its
words taken before the call, such as one from GetDSIntData, is not valid
after it, and the reference X held on the object it named is given up:
hold another reference to keep that object. Realloc(aSize,X) gives X a
Size of aSize rounded up to an even number of words, with storage for
Size+2 words.
--------------------------------------------------------------------------------
PUBLIC-KEY OPERATIONS: RSA WITH A MODULUS OF ANY LENGTH, RSA AND DSA KEY
GENERATION, AND DIFFIE-HELLMAN PEER VALIDATION
================================================================================
30. FIXED - an RSA private key whose modulus is not a multiple of 64 bits
could not sign or decrypt, and without the Windows assembler a
private-key operation could return a wrong result
StreamSec.DSI.IFC, StreamSec.DSI.Arith. An RSA private key held with its
primes (ReprType 1 or 2) signs and decrypts in fixed time by default
(gFixedTime), and that path accepted only a modulus whose length is a
multiple of 64 bits over two primes of exactly half that length. Any
other key raised before computing anything: EAssertionFailed "RSA
private key must be created with Exportable set to True", or eDSInteger
"Illegal parameter in FixedModInto" or "Overflow in FixedModInto".
WHO WAS AFFECTED. A key loaded from a PKCS#1, PKCS#8 or PKCS#12 (PFX)
file, or from the CAPI, .NET or text key formats, is held with its
primes, so the restriction applied to every imported key:
- Keys of 1023, 1500, 2000, 2016, 2047, 2049, 2080, 3071 and 4095 bits,
for instance, could not be used to sign or to decrypt.
- Nor could a key of a usual length over primes of unequal length, such
as a 2048-bit modulus over primes of 1025 and 1023 bits.
Keys of 1024, 1536, 2048, 3072 and 4096 bits made by this library or by
OpenSSL worked, apart from what follows. With gFixedTime set to False
every key worked, without the fixed-time path.
WITHOUT THE WIN32 AND WIN64 ASSEMBLER, FOR KEYS OF EVERY LENGTH. On
Linux64, and on Windows built with ST4_NO_ASM, a private-key operation
on an input that is a multiple of the prime P returned a wrong result,
and one on the input 1 raised eDSInteger "Illegal parameter". The other
targets that use the same Pascal arithmetic run the same code; they were
not measured. Neither input occurs when signing, and a multiple of P
cannot be produced without knowing P. Win32 and Win64 builds with their
assembler were not affected.
NOTHING ELSE CHANGES. A key that worked before takes the same steps with
the same operand sizes, and every result that was right before is
unchanged. Checked against OpenSSL on Win32, Win64 and Linux64: 23 keys -
OpenSSL keys of 1023 to 4096 bits, and keys built from primes of chosen
lengths, unbalanced, in either order, and with a CRT coefficient shorter
than P - over 460 inputs including 0, 1, N - 1 and multiples of P and of
Q, and 138 random inputs on each platform checked against OpenSSL
directly. Measured over 11 alternating runs of each build, a private-key
operation with a 2048-, 3072- or 4096-bit key costs what it did: medians
within 1.2 per cent on Win32 and 0.5 per cent on Win64, the ranges of the
two builds overlapping on every key, and on Linux64 the spread between
runs was wider than any difference. A 2047- or 2049-bit key costs from 4
per cent less to 12 per cent more than a 2048-bit one, by platform.
NO NEW TIMING DEPENDENCE. The two fixed-time routines underneath now
take a modulus of any length. FixedModInto uses a modulus that is not a
multiple of 32 bits shifted left, as a local copy, runs as many more
steps as the shift and shifts the result back. Every count and every
branch this adds follows from the lengths of the key and of the modulus,
never from the value being processed.
For code that calls the iDSInteger methods directly: FixedModInto and
FixedModTo accept a modulus of any length and refuse with eDSInteger a
SelfSize shorter than the modulus. FixedSubModAddTo accepts a modulus of
any length and marks its result positive whatever the sign of Self.
31. BEHAVIOUR CHANGE - RSA key generation never returned for a modulus of odd
length, and with ifkgNIST an odd length could give a key one bit short
StreamSec.DSI.IFC. iDSIIF.RSAKeys and iIFPrivateKey.IFRSAKeys make a key
pair with a modulus of aBitSize bits. Without ifkgNIST in aKind both primes
were made aBitSize div 2 bits long, and made again until the modulus had
aBitSize bits - which two such primes can never give for an odd aBitSize.
A request for 2047 bits therefore never returned unless aTerminate stopped
it, and neither did one for fewer than 30 bits (0 and 1 raised eDSIRandom
instead), because the prime generator cannot make a prime shorter than 15
bits. With ifkgNIST an odd length was not refused: 2049 and 3073 bits gave
a key of 2048 and 3072 bits, and 2047 raised eKeyGeneration ("ifkgNIST:
Failure generating prime") after the key had been cleared.
WHAT HAPPENS NOW. Without ifkgNIST every length from 30 bits up is made,
and the modulus has exactly the length asked for. For an odd length P is
one bit longer than Q - a 2047-bit key has primes of 1024 and 1023 bits,
the shape OpenSSL gives it - and it signs and decrypts like any other key.
Even lengths are made as before, except that two equal primes, which make
no RSA key, are now drawn again. At the usual lengths two equal primes do
not occur in practice, but about one 30-bit key in 1500 came back made
from such a pair.
THE BEHAVIOUR CHANGE: THREE KINDS OF REQUEST RAISE eKeyGeneration, with a
message naming the length, before the key or aPubl is changed:
- With ifkgNIST, a length the FIPS 186 prime generators have no parameters
for. They have them for 2048, 3072 and 4096 bits, and for 1024 bits for a
key transport key (no ifkgSignatureKey) that is not ifkgProvable. So a
request for 2049 or 3073 bits, which returned a key one bit short, now
raises, and so does every other length.
- An odd length with ifkgExportable. That flag asks for two primes of equal
length, which a modulus of odd length cannot have. Such a key cannot be
written as a CAPI PRIVATEKEYBLOB either, which refuses a prime longer
than half the modulus. Leave out ifkgExportable to get the key.
- A length below 30 bits.
A request for 1024, 2048, 3072 or 4096 bits that made a key before makes
one the same way now. That covers the composite ML-DSA and ML-KEM keys and
the certificate generator, which ask for those lengths only. TstRSAKey,
whose default KeyGenerationKind includes ifkgNIST, follows the first rule
for the length passed to GenerateNewKeys.
NO NEW TIMING DEPENDENCE ON THE KEY. Each prime length follows from the
requested length, and for an odd length P is the longer prime without the
two being compared. The only new branch on the primes is drawing an equal
pair again, which says nothing about the key that is finally returned.
Checked on Win32, Win64 and Linux64: the refused requests, every length
from 250 to 330 bits, lengths either side of 512, 1024 and 2048 bits,
10000 keys of 30 bits and the FIPS 186 kinds at 1024 and 2048 bits - each
modulus and prime measured, N = P * Q multiplied out independently, and a
raw RSA round trip; and 24 keys per platform, of 30 to 3073 bits and of
every kind, checked independently for primality and CRT values and by
OpenSSL: "openssl pkey -check", and raw RSA decryption and encryption with
rsa_padding_mode:none matching this library's results.
32. FIXED - a DSA or Diffie-Hellman key made with newly generated domain
parameters could not be used from more than one thread
StreamSec.DSI.Arith, StreamSec.DSI.FFC. The library's big integers come
from two pools: one private to each thread, for values that do not
outlive a call, and a global one, for values that do. Domain parameters
generated in the process - by tFFSystemParams.Generate, which
iDSIFF.NewKeys(L, N, ...) calls to make a key with parameters of its own
- kept integers from the generating thread's private pool: the subgroup
order q under the default FIPS 186-4 generation, and the modulus p and
the generator g under the generic generation that
tDSIFF.DisableNISTMode selects. A parameter or key object is meant to be
shared, and an integer from a private pool is not safe to share: its
reference count is not atomic, and its memory belongs to the thread that
allocated it.
WHAT IT LOOKED LIKE. Access violations. Verifying or signing with one
such DSA key from 8 threads over 20 rounds raised on as many as 156 of
160 operations, and runs that raised nothing during the work could still
end in an access violation afterwards. With a 160- or 224-bit q the same
load also produced wrong results, from the defect in entry 21.
NOT AFFECTED: the named groups of RFC 7919 and RFC 3526, whose integers
are global.
The prime generators now leave what they hand back in the pool the
call's aLocal asks for: the prime tSubGroupPrimeGenerator returns, which
came from the private pool even when aLocal was False; the Q, Seed, QSeed
and PSeed of tNISTProvablePrimeGeneratorDSS; and the Seed of
tNISTProvablePrimeGeneratorRSA. tFFSystemParams publishes the generator
it computes as a global integer.
NOTHING THAT IS COMPUTED DIFFERS. Only where the integers are allocated
changed. From a fixed seed, tNISTProvablePrimeGeneratorDSS produces the
same p, q, seeds and counters as release 4.1.3.357, for 2048/224 and
2048/256, on Win32, Win64 and Linux64. Under the load above, and on all
three, verification with generated 2048/256, 2048/224 and 1024/160
parameters and signing with 2048/224 and 1024/160 ones now complete
with no wrong result and no exception.
33. FIXED - Diffie-Hellman key agreement (DH1) accepted a peer's public
element outside the prime-order subgroup, and trivial ones such as 0, 1
and P-1
StreamSec.DSI.DiscreteLog, StreamSec.DSI.FFC. KeyAgreementScheme_DH1 of
iDSIDLArith derives a secret from a private key and the peer's public
element W. With aCoFactor False, or with subgroup validation enabled
(tDSIDLArith.EnableSubGroupValidation), it raised W to the group order
but never compared the result with the identity, so that check could
not fail, and nothing else refused W either:
- Finite field: 0, 1, P-1, P and P+1 were accepted in every mode, giving
a secret of 0, 1 or P-1 that anybody can compute. An element of small
order r was accepted too, and the secret it gives is W^S for the
private key S. A peer that sends elements of order 2, 3, 5 and 7 and
learns which of the few possible keys each agreement derived knows
S mod 210. In a group whose cofactor is 2, as in the RFC 7919 and
RFC 3526 groups, what such a peer learns is S mod 2.
- Cofactor mode (aCoFactor True, subgroup validation disabled) accepted
an element of small order with a secret of 1.
- Elliptic curve: the point at infinity was accepted, with an all-zero
secret. A point of another curve was not refused either; the
computation then raised eDSInteger.
WHAT HAPPENS NOW. DH1 returns False, and derives no key, when W is
trivial (IsNonTrivialFieldElement: for a finite field 0, 1, the
generator or P-1, for a curve the point at infinity or a point of
another curve); when W fails IsGroupElement, which is checked unless
aCoFactor is True and subgroup validation is disabled; and when the
secret is the group identity. For a finite field IsGroupElement is the
test W^q = 1. For an elliptic curve it is that the point lies on the
curve, which on the NIST and X9.62 curves in the library, all of
cofactor 1, is the same as membership of the subgroup. In cofactor mode
an element outside the subgroup is still accepted when the cofactor
multiplication takes it to a secret other than the identity, which is
what that mode is for.
iDiscreteLogField.IsNonTrivialFieldElement is documented to refuse P-1
for a finite field, and did not. It does now, and so do DH2, MQV and
IntegratedDecryption, which apply the same check to the peer's element.
WHO WAS AFFECTED. Code that calls KeyAgreementScheme_DH1 over a finite
field, directly or through iMPPrivateKey.DecryptKeyAgreement - most of
all with a static private key, where what successive agreements leak
adds up. TLS and SSH were not: their finite-field Diffie-Hellman
computes the secret without DH1, and the TLS 1.2 and TLS 1.3 ECDHE code,
which does call DH1, refuses the point at infinity and off-curve points
before it gets there. CMS key agreement does not call DH1.
A VALID AGREEMENT DERIVES THE SAME KEY AS BEFORE. On the TLS ECDHE path
DH1 no longer multiplies the peer's point by the group order; the check
that the point lies on the curve takes its place.
Checked on Win32, Win64 and Linux64 over RFC 7919 ffdhe2048, a field
whose cofactor has the factors 2, 3, 5 and 7, and P-256: every hostile
element in all four combinations of cofactor mode and subgroup
validation, and valid agreements against secrets computed independently
in Python. On Win32 and Win64, TLS 1.3 and TLS 1.2 ECDHE handshakes over
P-256, P-384 and P-521 with OpenSSL complete, with this library as the
client and as the server.
--------------------------------------------------------------------------------
CERTIFICATES AND KEYS: EXTENSIONS FOR KEM CERTIFICATES, A CERTIFICATE FROM A
REQUEST, CHAIN AND STORE FIXES, DELEGATED OCSP RESPONDERS, PKCS#8 AND PKCS#11
================================================================================
34. ADDED - a certificate extension recording which signature certificate a
KEM certificate was enrolled against
RFC 9883 is how an end entity obtains a certificate for a key that cannot
sign. An ML-KEM key cannot sign its own certification request, so the
request is signed with a signature key the subscriber already holds, and
a privateKeyPossessionStatement attribute names that key's certificate by
issuer and serial. The CA verifies the two against each other before it
issues. This library has carried that attribute for some time, as
ctRegCtrlPrivateKeyPossessionStatement in StreamSec.DSI.Pkcs10.
The link stops at the request. The statement is a registration control:
it is checked at enrolment and then goes wherever the request goes, which
is usually nowhere. A relying party holding the issued KEM certificate
has no way to learn which signature certificate stood behind it, and RFC
9883 defines no certificate extension to tell it - so two certificates
belonging to one subscriber are, to anyone who did not watch the
enrolment, two certificates that happen to share a subject name.
This release adds an extension that carries the link forward:
id-msc-enrolledAgainst 1.3.6.1.4.1.13085.8.2.1
allocated under a StreamSec arc for application-profile certificate
extensions, 1.3.6.1.4.1.13085.8.2, so that a second extension is an
allocation rather than a decision about where to put it.
EnrolledAgainst ::= SEQUENCE {
issuer Name,
serialNumber CertificateSerialNumber }
The same issuer-and-serial pair the possession statement used, so what
the certificate records is what the CA verified rather than a restatement
of it. It is a StreamSec OID: no standards body has assigned one, and
this is a profile addition rather than an implementation of a
specification. Read or write it through the new evMscEnrolledAgainst
member of tExtnValueEnum:
lEA := aCert.tbsCertificate.extensions
.UniqueItems[evMscEnrolledAgainst].AsMscEnrolledAgainst;
if Assigned(lEA) then
{ lEA.issuer and lEA.serialNumber name the signature certificate }
NOT CRITICAL, and issue it that way. This is provenance rather than a
constraint: a verifier that does not know the extension is missing
something it could have used, not something it must honour, and marking
it critical would make every existing verifier reject a certificate it
can otherwise use.
NOTHING EXISTING CHANGES. The new member is APPENDED to tExtnValueEnum,
which matters more than it looks: an extension's ordinal in that
enumeration is its index in the underlying ASN.1 CHOICE, so a member
inserted anywhere but the end would silently re-tag every extension after
it in every certificate this library parses. Code that names the existing
members, and DER produced by earlier releases, are unaffected.
stOIDs names the OID as id-msc-enrolledAgainst; an unassigned OID under
the same arc still derives a bracketed name as before.
35. ADDED - a certificate extension naming the relays that hold a KEM
certificate's mailbox, and a REST client's Timeout now reaches the
transport it builds
id-msc-mailboxRelays (1.3.6.1.4.1.13085.8.2.2) is the second leaf of the
extension arc that id-msc-enrolledAgainst opened in entry 34: a
non-critical SEQUENCE SIZE (1..3) OF GeneralName, dNSName only, naming
the one to three relay hosts that hold the mailbox a KEM certificate is
addressed at. A relay holding no mailbox for a certificate can refuse a
collect on it, and a sender can pick its last hop from it, without either
being told out of band. The issuing CA composes it from what its
registration side assigned; a request may not ask for it. Non-critical
for the reason the earlier one is: a verifier that does not know it loses
the routing and nothing else.
In stPkixExtension: evMscMailboxRelays, appended to tExtnValueEnum as the
two before it were, and AsMscMailboxRelays on iExtnValue, an
iGeneralNames - the class the alternative-name extensions already use,
here under the SIZE the extension is defined with, so a value naming no
host or more than three fails to parse rather than reaching a relying
party as a list. In stOIDs: id_msc_mailbox_relays, and its name.
iGeneralNames gained AddItem(aChoice), which appends a NEW entry of the
given kind and returns it. UniqueItems finds or creates the FIRST entry
of a kind, so the second dNSName of a subjectAltName covering two hosts -
or of a list of relays - could not be written through the interface at
all; anyone wanting one went to tASN1CustomOFStruct.AddField by hand.
Reading is unchanged.
TsmCustomRESTClient.Timeout was declared, published and never read. Every
transport the client built ran on TsmCustomTLSClient's own defaults -
15 s per handshake round while connecting, 30 s per receive after -
whatever a caller had set, so a peer that accepted the connection and
then said nothing held the caller for the sum of the two. BuildTransport
now hands Timeout to both the ConnectTimeout and the IOTimeout of the
transport it builds, the pinned one included.
BEHAVIOUR CHANGE: a caller that set Timeout now gets it, which it did
not before. The default is still 30000, so at the default the receive
wait is what it was; the handshake wait goes from 15 s to 30 s, a longer
wait for a peer that is not answering and nothing else.
36. ADDED - StreamSec.DSI.PkixRequestCertGenerator, issuing a certificate from
a certification request
TstCertificateGenerator composes a certificate from its OWN properties and
generates the subject key itself. That is the right shape when the issuer
and the subject are the same program, and the wrong one for a CA: a CA
issues to somebody else, over a key it must never see, from a PKCS#10 that
party signed. There was no component for that, so every CA built on this
library hand-rolled it.
TstRequestCertificateGenerator fills the gap. Execute takes an
iCertificationRequest, and six events report what the request carries -
its self-signature, its public key, its subject name, each extension, each
other attribute - plus one for an extension the CA expected and the request
does NOT carry. The verdicts are three-way, because two are not enough:
accept it, ignore it and issue anyway, or refuse and issue nothing. For the
absent case: supply it, omit it, or refuse.
NOTHING A REQUESTER ASKS FOR REACHES THE CERTIFICATE UNLESS SOMETHING SAYS
SO. With no handler attached an extension is IGNORED, not taken, so a
request asking for basicConstraints cA:TRUE cannot mint an intermediate CA
through a component nobody wrote a handler for. The two extensions a
requester may legitimately restate - subjectKeyIdentifier and keyUsage -
are named by AcceptRequestedExtensions, which is where that default lives
and where a CA with different rules changes it. It will not hold an
extension the CA composes for itself, and says so when you try: a request
cannot be given authorityKeyIdentifier, cRLDistributionPoints or
authorityInfoAccess, because it cannot know what they should say.
A RESTATED VALUE IS CHECKED AGAINST THE KEY, NOT TAKEN ON TRUST. A KEM
public key cannot be given digitalSignature; an Ed25519 key cannot be given
keyEncipherment; encipherOnly means nothing without keyAgreement. The
per-algorithm table carries its citation for every row, and where a profile
states only what an algorithm MAY do, the refusal says the key cannot
perform the bit rather than claiming a document forbids what it merely
omits. A subjectKeyIdentifier is accepted when it identifies the key under
one of several named conventions - RFC 5280 offers two and permits others -
rather than only when it equals the one this CA would have written.
Refusing a legitimate request is a defect too, and a harder one to
diagnose.
EVERY REFUSAL HAPPENS BEFORE A SERIAL IS DRAWN OR THE ISSUER PRIVATE KEY IS
OPENED, which on a PKCS#11 token means before the PIN prompt. An admission
rule that runs after the work has started is an apology rather than a rule.
The same checks are available as CLASS functions, so a caller holding
nothing but a request can run them with no CA, no issuer key and no
instance - a registration authority screening a queue, or an enrolment
client checking its own request before it sends it. Both ends of an
enrolment can then apply one statement of the rules instead of two that
drift.
What a requester asked for and did not get is reported in IgnoredItemNames,
by name where the OID is known and by OID otherwise. Silently dropping
something the CA will not honour is worse than refusing it, because the
requester goes on believing it was honoured.
The unit is a member of the runtime package.
37. FIXED - the chain filter refused every expired certificate it had been told
to tolerate, and could accept a forged one when a handler tolerated the
expiry
TstCustomKeyFilterChain.CheckCertificate collects its findings in one error
set: pcvExpired from the validity check, pcvIssuerNotTrusted from the issuer
lookup, then whatever the signature check adds. It handed that same set to
tSigned.CheckSignature - whose BeforeVerify decides on it being EMPTY
("Result := aErrorCodes = []") and which replaces the message on entry.
So a certificate the caller had asked to tolerate as expired - through
CheckValidityDate False, through the aAllowExpired overload, or through an
OnInvalidCertificate handler granting explicit trust for the expiry -
reached the signature check with pcvExpired already in the set, was declared
unverifiable before a byte of it had been verified, and was refused; the
"expired" text was dropped on the way. Every documented way of accepting an
expired certificate through the filter was inert. TstCertificateManager.
ImportFromCMS, which the CMS components drive with AllowExpiredCertificates
(True by default), could therefore never collect an expired signer's
certificate except under explicit trust.
WORSE, WHERE A HANDLER WAS INVOLVED. When the signature check gave up on the
non-empty set it reported that same set - pcvExpired alone, since no
signature had been checked - through OnInvalidCertificate. A handler written
to tolerate expiry and nothing else then granted it a second time, and the
certificate was ACCEPTED with its signature never verified. A forged
certificate claiming an expired validity window passed such a filter.
The signature check now runs on a set and a message of its own, merged into
the caller's afterwards, so it decides on the signature alone and the
earlier findings survive it; and the public CheckCertificate overloads start
from an empty set, so a caller's stale or uninitialised set cannot become a
verdict either. The message parameter is still appended to and never
cleared - ImportFromCMS relies on that to collect one account of a whole
chain. The legacy stPkixKeyFilter carries the same change.
New harness Test\keyfilter\ChainExpiredTest (32 checks) pins every mode;
nine of its checks failed on the previous code.
BEHAVIOUR CHANGE: with CheckValidityDate False, or aAllowExpired True, an
expired but otherwise valid certificate now returns True with pcvExpired in
the set - what the documentation always said. A caller that wants expiry to
be fatal keeps CheckValidityDate True; one that wants to know tests the set,
not only the result. A CMS message signed with an expired certificate now
collects that certificate when AllowExpiredCertificates is True.
FOUND while sweeping the tree for uninitialised error-set locals, after an
application's uninitialised set made its relay refuse every certificate on
Win64 and Linux64 while Win32 passed by luck of the frame layout - the same
accumulate-then-test-empty contract, with stack garbage in the set. The
sweep also tidied the smaller members of the family, none of which decides a
verdict:
- tSigned.CheckSignature(aCACert, var aErrorCodes, aState), stateful, now
caches ErrorCodes as well as ErrorMsg, and LoadFromStream clears the
cached codes with the message, so the two properties describe the same
verification.
- TsmX509TrustedCertificates.ImportFromCMSStream / ImportFromCMSFile (and
the legacy TstX509TrustedCertificates) assign Status on every path; an
empty stream or a load that raised used to leave it as the caller had
it.
- TTLS_HandshakeProtocol.HandleClientCert initialises its status set
before either HandleCert branch, not only on the empty-message branch.
- tASN1BitString.ContentAsSet (and the legacy tAbstractDERData twin)
zeroes the set it was handed before deciding whether the BIT STRING fits
it. Every typed getter built on it - a certificate's key usage, say -
reads the set without looking at the result, so a BIT STRING longer than
the set used to hand back whatever the variable held; an oversized
keyUsage could grant usages at random. It now yields the empty set,
which grants none.
38. FIXED - the trusted-certificate store refused every KEM certificate as a
syntax error
TsmX509TrustedCertificates sizes a certificate's public key before it
admits the certificate, so that LeastKeyBitSize can be enforced. The probe
knew RSA, finite-field and elliptic-curve keys, and since 4.1.3.357 the
signature algorithms that carry none of those - EdDSA, ML-DSA, composite
ML-DSA and SLH-DSA - each assigned a nominal strength. It did not know a
KEM key at all. A certificate carrying an ML-KEM or composite ML-KEM key
fell through every probe and was refused with crcSyntax, whatever its
chain, so a key-establishment certificate could not be added to the store
- not as a leaf to be chained and not as an explicitly trusted entry.
The probe now assigns ML-KEM-512, -768 and -1024 the strengths of NIST
levels 1, 3 and 5, and a composite ML-KEM key the strength of its ML-KEM
half. Nothing else about admission changes: the chain, the constraints,
revocation and the signature are checked exactly as before.
Found by an application that validates its callers' composite ML-KEM
certificates through this store.
39. FIXED - a delegated OCSP responder was accepted without the extended key
usage that authorizes it
RFC 6960 sec. 4.2.2.2 makes a responder authoritative for a CA only when
its certificate is issued by that CA and INCLUDES id-kp-OCSPSigning in an
extendedKeyUsage extension. TstAbstractOcsp.VerifyResponseSignature tested
that with iCertificate.CheckExtKeyUsage, which answers True when the
certificate carries NO extendedKeyUsage extension at all - RFC 5280's
"absent means unconstrained", which is the right answer for a usage test
and the wrong one here.
WHY IT MATTERS. Both the candidate certificate and the responderID it is
matched against are read out of the OCSP response, i.e. supplied by
whoever sent it. So an attacker holding ANY certificate that the CA had
issued and that states no purpose - which is every ordinary end-entity
certificate - could put it in the response, set the responderID to match
it, sign with its key, and have the response accepted as authoritative
revocation status for that CA. That is a forged "revoked" for any
certificate, or a forged "good" for one that really was revoked.
Both call sites now use CheckExtKeyUsagePolicy(...,ekupRequire), which
tests that the extension is present before testing what it names. The
same defect was in TstOcspServer, where the check exists to stop an
operator configuring a delegate that no conforming client will accept -
and passed exactly that delegate.
ALSO FIXED, in the same path: the responder certificate's validity period
was never checked. A delegate normally carries id-pkix-ocsp-nocheck, whose
only sanctioned mitigation (RFC 6960 sec. 4.2.2.2.1) is "a very short
lifetime and renew it frequently" - which buys nothing if the relying
party never looks at notAfter, since nocheck has already told it not to
ask whether the certificate was revoked. An expired delegate is now
refused.
BEHAVIOUR CHANGE: a deployment whose OCSP responder signs with a
certificate that carries no extendedKeyUsage, or one that has expired, now
fails verification where it used to succeed. Both were already outside RFC
6960; a responder that is the CA itself is unaffected, as it always was.
40. CHANGED - an encrypted PKCS#8 private key is derived with 131072 PBKDF2
iterations and an explicit HMAC-SHA256 prf
AssignPBES2EncAlg, which builds the PBES2 parameters for every
PKCS8-Encrypted-* private key format, set
iterationCount.EditContent(1)
and left the prf field absent. The count was deliberate, and the position
behind it has not changed: a passphrase protecting a PKCS#8 or PKCS#12
object has to carry enough entropy on its own. The salt is random per
key, so precomputation - a rainbow table - is out whatever the count is,
and what is left is a search whose cost is set by the passphrase itself.
An iteration count adds a few bits on top of that and no more. If you
want 128 bits it makes little difference whether you choose a 128-bit
passphrase and one iteration or a 111-bit one and the 2^17 iterations
written here - and where the key sits on a server that has to be assumed
secure anyway, neither the passphrase nor the count is what is really
protecting it.
The count has been raised for reasons that are about the file rather than
about that arithmetic. An absent prf is not "unspecified": it
DER-defaults to HMAC-SHA1, so a container that was never asked to name a
PRF was naming the oldest one the standard allows, and that is what
another toolkit, an auditor or a policy check reads out of it. And this
library's own PKCS#12 layer has always written 131072 and HMAC-SHA256, so
the two containers disagreed on a parameter neither of them exposed -
nothing in the API surface said which one you were getting. They now
agree. The salt and IV were always random and the cipher was always
AES-256-CBC; those are unchanged.
None of that argues against a high count where you are writing for a
user base that cannot always be trusted to choose well. A count you
impose applies to every passphrase your users pick, the weak ones
included, and in the best case it buys a little time between a breach
being detected and the keys taken in it becoming usable - which may be
better than nothing.
For that case, prefer scrypt over any PBKDF2 count.
SelectPBES2Scrypt(N,r,p) switches this whole path to id-scrypt, which
is memory-hard and therefore far less helped by an attacker's hardware.
It is pure Pascal, always linked with PKCS#8, and works identically on
every target.
BEHAVIOUR CHANGE: writing is slower by 131071 PBKDF2 iterations - a few
tens of milliseconds, once per key written. Reading is unaffected - the
count and prf are read from the file - so keys written by earlier
versions still load, and nothing rewrites them. Writing such a key again
gives it the new parameters, but a passphrase chosen with the entropy
described above has nothing to repair, and one chosen without it wants a
better passphrase rather than more iterations.
41. DOCUMENTED - PKCS#11 token and HSM keys, in PKIX.txt
The PKCS#11 subsystem shipped in 4.1.3.357. What it did not have was a
place in the documentation, and PKIX.txt's feature matrix actively said
otherwise - it listed PKCS#11 in the "Missing / not implemented" column,
which is the one place a reader looks to settle whether the library can
keep a CA key on a token at all.
PKIX.txt gains section 14, PKCS#11 - PRIVATE KEYS ON A TOKEN OR HSM: how a
token key reaches the rest of the library (a token RSA key is an
iIFPrivateKey and a token EC key an iDLPrivateKey, so the certificate
generator, the CRL signer and the OCSP responder sign with one exactly as
they sign with a software key), the read-only KeyManager store and why it
is addressed by token serial rather than by slot index, capability
discovery, the credential and its byte-counted bounds, provisioning on the
device, and the harnesses. The unit inventory and the summary now list the
four units, and the matrix says implemented.
NO CODE CHANGED. This is the documentation catching up with what the
library already does.
--------------------------------------------------------------------------------
CMS AND PDF: AuthEnvelopedData, A SIGNED ATTRIBUTE NAMING THE RECIPIENT, SIGNING
WITHOUT THE SIGNER CERTIFICATE, AllowCMSv3, S/MIME WRAPPING, AND A PDF
PAGE-COMPOSITION SURFACE
================================================================================
42. ADDED - CMS AuthEnvelopedData (RFC 5083) with an AEAD content cipher,
produced by TstMPEnvelopedData
The EnvelopedData this library has always produced gives a recipient
confidentiality and nothing else: a ciphertext altered in transit decrypts
to different plaintext and says nothing about it. RFC 5083
AuthEnvelopedData closes that - the content is encrypted with an AEAD
cipher and carries an authentication tag, so the recipient learns whether
the bytes are the bytes that were sent.
IT IS THE SAME COMPONENT, and which envelope you get follows from the
content cipher rather than from a second decision:
lEnv := TstMPEnvelopedData.Create(nil);
lEnv.KeysAndCerts := MyStore;
with lEnv.SMIMECapabilities.Add as tSMIMECapabilityItem do begin
CipherAlg := caRijndael;
CipherMode := cmGCM; // <- this is the whole difference
KeyLength := 32;
end;
lEnv.Encrypt(aRecipientCert,lPlain,lCipher);
RFC 5084 leaves nothing to choose: AES-GCM may appear only in
AuthEnvelopedData and the CBC algorithms only in EnvelopedData, and this
library has always enforced that in its ASN.1 metadata with two disjoint
algorithm tables. Asking for the cipher IS asking for the envelope, so
asking for both would be stating one fact twice - and two statements can
disagree.
NOTHING CHANGES IF YOU SAY NOTHING. The default content cipher is still
AES-CBC with the largest available key, so a component that is dropped on
a form and used as before still produces EnvelopedData, byte for byte as
it did.
READ EnvelopeType TO SEE WHICH IT WAS - pEnvelopedData or
pAuthEnvelopedData. After Encrypt it reports what the chosen cipher
produced; after Decrypt it reports what arrived, because the component
reads the content type off the message and opens either kind without being
told. That last part is the reason this is one component: a receiver does
not know in advance what it has been handed.
IT IS AN INPUT IN ONE CASE - a ContentOnly decrypt, where the ContentInfo
has already been stripped and nothing in the stream says which envelope
this is. The caller stripped it and so already knows; that is how the CMS
broker drives the component. Setting it anywhere else does not change the
cipher and is overwritten.
DECRYPT RETURNS FALSE WHEN THE TAG DOES NOT VERIFY, and writes nothing to
the destination stream. It is not distinguishable from "no recipient key
matched", deliberately: a caller cannot act differently on the two.
Everything that addresses a recipient is unchanged and shared - RSA key
transport, RFC 9629 KEMRecipientInfo for ML-KEM and composite ML-KEM, and
RFC 5753/8418 ECDH key agreement - because RFC 5083 gives
AuthEnvelopedData the same RecipientInfos.
AES-256-GCM by default when GCM is asked for, with a 12-octet nonce and a
16-octet tag. Twelve is the one nonce length GCM uses directly (RFC 5116);
sixteen is the largest tag RFC 5084 allows, written out rather than left
to the ASN.1 DEFAULT of twelve so a reader that does not apply defaults
still sees it. Name AES-128 or AES-192 GCM instead for a shorter key.
authAttrs ARE WRITTEN WHEN RFC 5083 REQUIRES THEM - that is, whenever the
enveloped content type is not id-data, in which case a content-type
attribute carrying it is added. This is not bookkeeping: the content type
in authEncryptedContentInfo sits OUTSIDE the encrypted content and outside
the tag, so without an attribute putting it into the authenticated data,
anything in the middle can relabel a message and the tag still verifies.
On the way back the attribute is compared with the field beside it and a
disagreement fails the decrypt. Attributes an application puts in
authAttrs itself are kept and authenticated with the rest.
The CMS broker handles both: TstMPCMSBroker now dispatches
id-ct-authEnvelopedData onto the same EnvelopedData component it has
always used, so a nested structure with an AEAD layer in it decodes
without any extra wiring.
Supporting additions for anyone working at the ASN.1 layer: iContent gains
AsAuthEnvelopedData and tContentEnum gains cAuthEnvelopedData (the CHOICE
alternative was already in the table, with no member able to select it);
tPKCS7DataType gains pAuthEnvelopedData; stOIDs gains
id_ct_authEnvelopedData. All three are APPENDED to their enumerations, so
existing values are unchanged. Note that id-ct-authData is NOT this - that
is RFC 5652 sec 9 AuthenticatedData, a MAC over plaintext with no
encryption at all, and it keeps the name pAuthenticatedData.
43. FIXED - two defects on the AuthEnvelopedData path, neither of which
anything in the library had ever reached
Both are in StreamSec.DSI.CMS, both are public API, and both stood because
until this release nothing in the library produced or consumed an
AuthEnvelopedData. An application that built its own handling directly on
the ASN.1 layer would have met them, and should re-test against this
release rather than assume.
tAuthEncryptedContent.Decrypt RETURNED THE RESULT OF ITS LENGTH PRE-CHECK
ON THE TAG FIELD rather than the result of verifying the tag. So a message
whose content did not authenticate - the one case the whole structure
exists to detect - returned True, having written nothing to the
destination stream. A caller who checked the result and not the stream
would have treated a forged or corrupted message as genuine and empty. It
now returns True only when the tag verifies, and the decrypted buffer is
wiped on the way out, including on the path where the tag failed and the
plaintext is never handed over.
tAuthAttributeValue.set_AsContentType WROTE INTO THE CHOICE INSTEAD OF THE
ALTERNATIVE IT HAD JUST SELECTED, so building an authAttrs content-type
attribute raised "Could not interpret contents" and no such attribute
could be produced at all. The getter beside it had always been right, and
so had the identical setter on tSignedAttributeValue; only this one was
never called.
44. ADDED - a CMS signed attribute naming who a message was written to
A CMS signature says who wrote something. It does not say who they wrote
it TO, and in a sign-then-encrypt layout - where the SignedData sits
inside the recipient's envelope, which is the right order when the
envelope is the only thing that must not name the sender - the envelope
is the only thing that identifies the reader. A recipient can therefore
strip it, keep the intact SignedData, and re-address it to somebody the
author never wrote to, whose software then verifies a perfectly genuine
signature. This is surreptitious forwarding, and it is not a defect in
any one program: it is what sign-then-encrypt costs unless the signature
itself names its reader.
This release adds an attribute that does:
id-msc-intendedRecipient 1.3.6.1.4.1.13085.8.3.1
IntendedRecipient ::= OCTET STRING -- SHA-256 of the recipient's
-- certificate
allocated under a StreamSec arc for application-profile signed attributes,
1.3.6.1.4.1.13085.8.3, beside the extension arc above. Both are StreamSec
OIDs: no standards body has assigned one, and this is a profile addition
rather than an implementation of a specification.
It is choice 13 of tSignedAttributeValue in StreamSec.DSI.CMS, with the
same shape as id-messageDigest, and is read and written through
AsIntendedRecipient: iASN1OctetString
on iSignedAttributeValue. Add it when signing by overriding
ImposeAttributes and setting the attribute BEFORE calling the inherited
method, which is the contract that method documents.
BEHAVIOUR CHANGE: none. Nothing in the library sets or requires the
attribute; a verifier that does not look for it is unaffected, and an
existing signature without one still verifies. An application that wants
the protection has to REQUIRE it - a check that validates the attribute
only when present protects nothing, because a forwarder simply presents a
SignedData that never carried one.
45. ADDED - a signature can now be produced WITHOUT the signer certificate
TstMPSignedData gained
property IncludeCertificates: Boolean (default True)
beside the existing IncludeRootCertificate. When True, which is what every
existing build does, nothing changes: the SignedData carries the signer
certificate and, subject to IncludeRootCertificate, the rest of the chain.
Set it False and the OPTIONAL certificates field of RFC 5652 is omitted
altogether, leaving the SignerInfo's sid as the only thing that names the
signer.
The reason to want that is SIZE. A certificate can be several kilobytes
and dwarf a short message, and a verifier that already holds it gains
nothing from a second copy.
It is NOT a way to hide who signed. The sid identifies the signer just as
well as the certificate does - by issuer and serial, or by subject key
identifier - and certificates are normally public, so anyone who can look
one up learns the same name from either form. Omitting the certificate
moves the lookup, it does not remove the identity.
What it costs is that a verifier which does not already hold the signer
certificate cannot get it from the message. It has to look it up. If it
cannot, verification fails with CertificateNotFound - it does not quietly
succeed - so the failure is visible and nameable rather than silent.
BEHAVIOUR CHANGE: none. The default is True and matches what the component
did before.
46. CHANGED - AllowCMSv3 is now published on TstMPSignedData
The property already existed on the CMS base component, in a protected
section marked "To be published", but it had never been surfaced - so a
caller outside the unit could not reach it and every SignerInfo this
component produced identified its signer by issuerAndSerialNumber.
It is now published beside IncludeRootCertificate and IncludeCertificates.
Set it True and a SignerInfo names the signer by subjectKeyIdentifier
(CMS v3) wherever the certificate carries that extension, falling back to
issuerAndSerialNumber where it does not.
The identifier is then a bare key hash instead of the issuing authority's
full distinguished name and a serial number: about sixty bytes smaller per
signer, and it does not restate where the certificate came from.
Note for the verifying side, because this is easy to get wrong and fails
in a way that looks like a bad signature: a SignerInfo is resolved against
the certificate STORE, not against the certificate set carried in the
message. Certificates that arrive in a message are put in the store by
ImportFromCMS, which needs BOTH CollectedStoreName and CollectedIndexName
set on the key manager - an unset name resolves to nil and the certificate
is discarded silently, after which verification reports that the signer
certificate cannot be checked. For subjectKeyIdentifier signers the
collected index should be an index over subject key identifiers.
BEHAVIOUR CHANGE: none by default. AllowCMSv3 is False unless set.
47. DOCUMENTED - S/MIME message wrapping is a core component, not a demo
PKIX.txt's feature matrix put full S/MIME message wrapping in the
"Missing / not implemented" column, as "demo-level, not a core library
API", and pointed the reader at the Indy demo under Demos. Both halves
were wrong.
StreamSec.Mail.SMIMEBroker (TstSMIMEBroker) is a core unit and a palette
component - RegisterComponents on 'StreamSec Tools'. It descends from the
CMS broker and adds Encode/Decode overloads taking TsmEmail messages,
which is the RFC 8551 wrapping and unwrapping: multipart/signed both
PRODUCED and VERIFIED, or opaque application/pkcs7-mime, chosen by
SignedFormat. It supersedes the Indy demo broker the matrix named.
MAIL.txt documents it as a core component; only PKIX.txt's matrix said
otherwise, and it no longer does. The row's Missing column now names what
is genuinely absent instead: ESS signed receipts (RFC 2634).
NO CODE CHANGED.
48. ADDED - StreamSec.Pdf.Canvas, a page-composition surface for the PDF family
StreamSec.Pdf.Model reads a PDF and appends to one, and StreamSec.Pdf.Signer
signs one. Neither COMPOSES one. The gap was real rather than theoretical: a
licensee who bought the PAdES signer had nothing in the library to sign, and
had to bring a third-party generator to produce the document in the first
place.
tPdfCanvas fills it, deliberately narrowly. It draws text and rules on one
or more pages and saves the file, using the fourteen standard PDF fonts -
the Helvetica family here - through WinAnsiEncoding, with the real AFM width
tables compiled in so that TextWidth is exact and an amount column right-
aligns on the glyph rather than on an estimate. No embedded fonts, no
images, no vector graphics. It is the surface a business document needs and
not a drawing library.
Page size is settable, in points, at construction or before anything is
drawn - A4 remains what the parameterless constructor gives - and a side
outside the 3 .. 14400 points of ISO 32000 Annex C.2 is refused. So is a
size change after the first drawing operation, because the coordinate flip
and the MediaBox are fixed once content exists.
Content streams are written UNCOMPRESSED and the cross-reference table is
the classic kind. That is a deliberate cost: it makes a generated document
greppable, so a test can assert that a particular string was printed at a
particular place, and it makes a defect in the output legible to a person
with a text editor rather than only to a PDF parser.
A CHARACTER WinAnsiEncoding CANNOT CARRY IS REFUSED BY DEFAULT. TextOut,
TextWidth and FitText raise ePdfCanvas naming the position and the code
point, rather than emitting the '?' that a naive encoder produces. On a
document that will be signed, filed and read back years later, a '?' where a
name should be is a defect that stops announcing itself the moment the file
is closed.
That is a default and not a law. Unrenderable may be set to puSubstitute per
instance, for a caller that must produce a document unattended and for whom
a mangled name beats no document at all. Substitution is then COUNTED, in
Substitutions, and a caller that opts in is expected to read it: the
objection to '?' was never the character but that nothing recorded the loss.
CanRender answers the same question without raising, for a caller that
wants to check before committing to a document.
The unit is a member of the runtime package.
--------------------------------------------------------------------------------
CIPHERS, KEMS AND ENCODINGS: HCTR2, A FASTER ML-KEM, AES-NI KEY-SCHEDULE
ALIGNMENT, AND HexToBytes
================================================================================
49. ADDED - HCTR2, length-preserving encryption for where there is no room
for a nonce or a tag
Two new units:
stPolyval tPolyval - POLYVAL, RFC 8452 section 3
stHCTR2 tHCTR2Encryption - HCTR2, ia.cr/2021/1441
HCTR2 is a tweakable super-pseudorandom permutation. It has three
properties together that no registered CMS content-encryption algorithm
has:
- The ciphertext is exactly as long as the plaintext. CBC pads and
GCM expands; where the ciphertext has to be the same size as the
plaintext, neither can be used at all.
- It is a WIDE block. Changing one bit of the ciphertext changes
essentially every byte of the recovered plaintext, however long the
message. A stream cipher of the same length changes exactly the one
bit, and that difference is the point: an adversary who can XOR a
known mask into a stream-ciphered value at one place and test for it
at another has a confirmation oracle. Measured on the test harness,
one flipped ciphertext bit changed at worst 251 of 256 plaintext
bytes over 256 trials.
- It takes a tweak of any length, at no cost on the wire, which binds
a ciphertext to its context.
The message must be at least one block; any length at or above that is
accepted, block aligned or not. Key sizes are 16, 24 and 32 bytes.
IT IS NOT AN AEAD AND MUST NOT BE USED AS ONE. There is no tag, so a
wrong key or a corrupted ciphertext yields random-looking plaintext
rather than an error. Code that needs to know whether what it decrypted
is genuine must arrange that for itself.
POLYVAL is exposed on its own because it is also what AES-GCM-SIV uses.
It is built on the library's existing GHASH core through the conversion
RFC 8452 states - byte-reverse the operands, multiply the hash key by x
in GHASH's field - so it inherits every arm that core already has:
PCLMULQDQ or PMULL where the processor offers it, the constant-time
software multiply where it does not.
Four OIDs are allocated, one per instantiation rather than one for the
mode, so that an AlgorithmIdentifier says which key a recipient needs:
id-hctr2 1.3.6.1.4.1.13085.2.4
aes128-HCTR2 1.3.6.1.4.1.13085.2.4.1
aes192-HCTR2 1.3.6.1.4.1.13085.2.4.2
aes256-HCTR2 1.3.6.1.4.1.13085.2.4.3
These are StreamSec OIDs. No standards body has assigned one for HCTR2.
Verified against the vectors Google publishes for it - 200 HCTR2-AES128,
350 HCTR2-AES256, 45 POLYVAL and 50 XCTR - on Win32, Win64 and Linux64,
plus the worked examples in RFC 8452 appendix A and section 8. AES-192
has no published HCTR2 vector in that set and is covered by a round trip
only.
BEHAVIOUR CHANGE: an OID under 1.3.6.1.4.1.13085.2 that has no name of
its own now reports as streamsec-cipher rather than as streamsec. That
arc holds the Twofish and Blowfish identifiers, so those two change
what GetObjectName returns for them.
50. FIXED - stTweakableEncryption did not compile except on 32-bit x86
Its RightShift helper has three arms - x86 assembler, x64 assembler, and
a portable one for everything else - and the portable arm called a
ByteSwap overload for Int64 that does not exist in the library. Any
target taking that arm failed to compile with "E2003 Undeclared
identifier: 'ByteSwap'". The arm is now written in portable Pascal.
The unit is in no package, so nothing had ever compiled it for a target
that takes that arm, which is why this went unseen. Note that its
tCMCEncryption is still not exercised by any test and does not currently
round trip; the fix above is to the shared helper only.
51. BEHAVIOUR CHANGE - ML-KEM is up to ten times faster, uses AVX2 where the
machine has it, and a Delphi Linux64 build that links it needs one more
object
What ML-KEM computes is unchanged: for the same inputs every key,
ciphertext and shared secret is identical, bit for bit. What changed is
how quickly it gets there, in two layers.
ON EVERY TARGET. The number-theoretic transform and its inverse reduce
with Montgomery and Barrett arithmetic rather than a remainder per
product; the matrix A-hat and the noise polynomials draw their SHAKE
output a block at a time; and each key object computes its expanded
public data - A-hat, t-hat and H(ek) - once, on first use, and keeps it.
A key made by KEMKeyGen starts out with it. So every encapsulation or
decapsulation after the first with the same key object skips that work,
which is most of an encapsulation.
WITH AVX2. The transforms, polynomial multiplication and addition, and a
four-way Keccak that expands A-hat and samples noise four polynomials at
a time have AVX2 code. It is used on 64-bit Windows with Delphi 11
Alexandria or later (earlier Win64 compilers do not know the AVX
instructions), on Delphi Linux64 from 10.3 Rio on,
and under Free Pascal on x86-64 Linux, macOS and BSD.
AVX2 is not part of the x86-64 baseline, so it is not assumed. When the
unit initializes it asks the processor whether it has AVX and AVX2, and
the operating system whether it saves the 256-bit register state, and on
any machine where either answer is no it runs the Pascal code. Both give
the same results. tKEM.Avx2Available reports the answer;
tKEM.SetUseAvx2(False) selects the Pascal code on a machine where it is
yes, for comparing the two. Define ST4_NO_AVX2 - or ST4_NO_ASM, which
removes all of the library's assembler - to compile the AVX2 code out.
Measured on one machine, ML-KEM-768, microseconds per operation, before
-> after (the faster of two interleaved runs, each the fastest of 21
timed batches, one core):
Win64 Win32 Linux64
key generation 69.1 -> 20.4 158.0 -> 97.5 116.3 -> 30.2
encapsulate, same key 68.0 -> 9.2 153.9 -> 46.2 118.2 -> 12.9
decapsulate, same key 84.0 -> 15.7 186.9 -> 72.3 147.4 -> 24.9
import ek, encapsulate 69.8 -> 19.8 156.3 -> 111.9 120.6 -> 33.7
import dk, decapsulate 87.2 -> 27.5 200.2 -> 147.8 153.3 -> 48.2
keygen, decapsulate 155.9 -> 36.5 347.4 -> 170.2 266.0 -> 55.8
Win32 has no AVX2 code, so its column is the first layer alone. The last
three rows are the shape of a hybrid TLS 1.3 key exchange: a server
imports the client's key and encapsulates once, a client generates a key
and decapsulates once. ML-KEM-512 and ML-KEM-1024 show the same pattern;
the largest gain measured was 10.7 times, encapsulation with ML-KEM-1024
on Linux64.
Checked against OpenSSL 3.5 on Win32, Win64 and Linux64, 150 checks
each: keys regenerated from each other's seeds and compared byte for
byte, encapsulation in both directions, and implicit rejection of a
tampered ciphertext. For fixed inputs the output equals that of release
4.1.3.357, on all fourteen Windows compilers and all six Linux64 ones.
WHAT YOU HAVE TO DO - DELPHI LINUX64 ONLY. That compiler has no inline
assembler, so the AVX2 code reaches Linux64 the way hardware AES does
(entry 11 of the 4.1.3.357 notes): stMLKEMAvx2Func.pas carries it, and
Free Pascal assembles it into stMLKEMAvx2Func.o, which ships beside the
sources and beside stAESNIFunc.o. If DCC_ObjPath or -O already names that
directory, as hardware AES requires, there is nothing to do. Otherwise a
Linux64 link that includes StreamSec.DSI.MLC fails with "cannot open
stMLKEMAvx2Func.o" until the directory is added - or define ST4_NO_AVX2,
which needs no object and keeps the Pascal code with the first layer's
gains.
52. FIXED - ML-KEM built with Free Pascal disagreed with other
implementations on a share of encapsulations and decapsulations
tKEM.DivQ, the division by q behind ciphertext compression, returned a
wrong quotient under Free Pascal for one of the 3329 coefficient values
at 10-bit compression and two at 11-bit compression. Free Pascal
evaluates an unsigned 32-bit expression containing a signed constant in
64 bits, and the shift that followed kept bits a 32-bit evaluation
discards. Delphi evaluates the same expression in 32 bits, so no Delphi
build on any platform was affected.
One coefficient off by one does not stop the other side decrypting, but
decapsulation re-encrypts and compares, so such a ciphertext is rejected
- implicitly, with a pseudorandom shared secret rather than an error -
and a handshake fails. Counted over all inputs, that happened to 14% of
operations with ML-KEM-512, 21% with ML-KEM-768 and 46% with ML-KEM-1024,
encapsulation and decapsulation alike. Key generation does not compress
and was not affected. Two Free Pascal builds agreed with each other,
since both erred the same way.
The difference is now stored before it is shifted, which gives the same
quotient under both compilers. With Free Pascal 3.2.2 on Linux x86-64 the
OpenSSL checks of entry 51 pass 150 of 150; the previous build failed 8
of 60.
53. CHANGED - composite ML-KEM decapsulation is about twice as fast with a
key that is used more than once
StreamSec.DSI.CompositeKEM. The composite shared secret is a hash over,
among other inputs, the public key of the traditional component. For the
ECDH and X25519/X448 combinations every decapsulation derived that public
key again from the private scalar - a full scalar multiplication, about
as costly as the Diffie-Hellman step it follows. A private key object now
derives it on first use and keeps it. A key made by KEMKeyGen starts out
with it, since key generation has just computed that point, and
GetEncodedPublicKey and PublicKey use the kept value too.
Nothing that is computed differs. For the same key and ciphertext every
shared secret, and the public key both of those methods return, is
identical, bit for bit, to what release 4.1.3.357 computes. Checked
against the draft's test vectors, and for all thirteen supported
combinations - the three SSH hybrids and tampered ciphertexts included -
against the 4.1.3.357 unit, on every Win32 and Win64 compiler from XE6 to
13 and every Linux64 compiler from 10.3 Rio to 13.
Measured, microseconds per operation, before -> after (the fastest of
four interleaved runs, each the median of 11 timed batches, one core):
Win64 Linux64
MLKEM768-P256 decapsulate 1176 -> 603 4451 -> 2079
MLKEM768-X25519 decapsulate 100 -> 57 845 -> 422
MLKEM768-P384 decapsulate 2086 -> 1056 10098 -> 5530
MLKEM1024-X448 decapsulate 546 -> 281 4366 -> 2052
MLKEM768-P256 generate key 1185 -> 617 4038 -> 2269
"Decapsulate" is a key object used again. A key imported and used once
costs what it did, since its public key is derived once either way. For
the RSA combinations there was little to save: their public key is a
short DER encoding, not a scalar multiplication.
Keeping the value adds nothing that needs synchronising. Threads making
the first use of one key at the same moment may each derive it; one copy
is kept and the others are released. It is public data, so keeping it
changes nothing about what the timing of a decapsulation can reveal.
54. CHANGED - the Win64 AES-NI assembler no longer needs its round-key
schedule aligned
Release 4.1.3.357 fixed an access violation in AES-NI on 64-bit Windows
(entry 10 of its notes) by restoring the 16-byte alignment its assembler
required: an eight-byte padding field in stAES.tRijndael_ECB, and a check
when stAESNI initializes that refused to register the implementation at
all if a later change to an ancestor class moved the schedule again.
That worked, and it left the library carrying an invariant no compiler
checks. The offset of a field is emergent from the size of every ancestor
class, so a field added to or removed from tCipher, tCipherMAC or
tBlockCipher - an edit that need have nothing to do with AES - moves it,
and {$ALIGN 16} cannot prevent that: it caps alignment rather than
setting a floor. The requirement existed only because the Win64 arm
addressed round keys as memory operands, which no other arm of the unit
does.
It no longer does either. The Win64 arm loads the schedule through movdqu,
as the Win32, FPC/System V and ARM arms already did, and both the padding
field and the initialization check are gone. No arm of stAESNI now cares
where the schedule sits, so the class of failure that produced the 356
regression cannot recur.
IT COSTS NOTHING, WHICH IS WHY IT WAS DONE RATHER THAN LEFT ALONE. Only
CBC-encrypt and OFB reach the two routines that changed; every other mode
runs through the four-block path, which already loaded round keys with
movdqu. Measured over 100 interleaved rounds, against a rebuild of the
identical source as a control, the two forms cannot be told apart: peak
throughput within 0.04%, per-round medians within 0.3%, and the new form
ahead in about half the rounds.
Nothing here is visible to your code. No API changed, no ciphertext
changed, and no throughput changed. tRijndael_ECB is eight bytes smaller
on Win64.
55. FIXED - HexToBytes wrote one octet past the end of its result on an odd
number of hex digits, and through a nil pointer on a single one
HexToBytes (stDERUtils.pas) sized its output
SetLength(Result,Length(aHexStr) shr 1)
- half the digit count, rounded DOWN - and then, after the pair loop, wrote
one more octet for a trailing odd digit:
if K = 1 then begin Result[J] := B; ... end;
For an all-hex string of odd length 2m+1 the array held m octets and that
tail wrote Result[m], one past the end. For a single digit the array was
nil and Result[0] wrote through a nil pointer. Range checking is off for
the whole library (ver.inc), so neither reported anything: the one-digit
case is an access violation, and the longer odd cases silently corrupt
whatever the memory manager placed after the block. HexToOS and the
UnicodeString overload of HexToBytes had the identical shape and are fixed
with it.
The fix rounds the allocation up - (Length + 1) shr 1 - so the trailing
octet has somewhere to go. Every even-length input, which is every correct
one, is byte-for-byte unchanged; only the previously-corrupting odd inputs
change, and they now return the same value a correct decoder always should.
This is reachable from untrusted input. A hex nonce, tag or serial arriving
from the wire and decoded before its length is checked - one consumer
decodes a peer-supplied session nonce exactly this way - turns a one-
character value into a nil write in the receiving process. Any caller that
hex-decodes before validating length is exposed; there are around fifty
callers of HexToBytes in the tree.
--------------------------------------------------------------------------------
SNIF, SNIP AND SSH: RESPONSE ECHO, FRAME PADDING, A CLIENT ON A GIVEN ENGINE,
BOUNDED WAITS, AND CHANNEL MESSAGES DURING A GLOBAL REQUEST
================================================================================
56. CHANGED - a Snif response no longer echoes arguments the caller sent
TsnifClassServer returned EVERY argument of a call in the response,
whichever way the parameter was declared. It now returns only those a
callee can actually change - var and out. A by-value or const parameter
cannot carry anything back to the caller, so sending it was work done for
no reader.
Streams and callback interfaces are unaffected: those are returned as
before, because for them the echoed value is protocol machinery rather
than a copy of the argument.
TWO REASONS, AND THE SECOND IS THE IMPORTANT ONE.
It is smaller. A response drops the bytes of every input argument. On a
directory lookup measured here that was 81 bytes of a 11,302-byte answer,
and the saving grows with the arguments.
And it removes a length correlation. Because the answer carried the
question, an answer GREW WITH ITS QUESTION: a call passing a 60-character
string came back 54 bytes larger than the same call passing six. Anything
counting bytes between the two ends - a proxy, a load balancer, a network
observer - could therefore read the length of an argument it could not
decrypt, in BOTH directions. Padding the request alone would not have
closed that, because the response reproduced it.
BEHAVIOUR CHANGE, and here is who it can affect: code that declared a
parameter by value or const, MODIFIED it in the server implementation, and
relied on the client seeing that change. That never worked as an interface
contract - the client writes a returned argument into its own copy, and for
a by-value parameter the caller's variable is not that copy - but a caller
reading the value back out of a TsnicClassClient argument array would have
observed it. Declare such a parameter var or out, which is what it always
should have been. The client tolerates an absent argument (it copies one
back only if it finds one), so nothing needs to change in step.
Verified against all three consumers of the transport: the library battery
(1541 checks), a consuming application's battery (806) and the web server's
own administration client end to end over a real socket (39).
57. ADDED - snip frames can be padded to a fixed size
TsnipBaseOctetConnection gained three properties, inherited by every snip
transport - TLS, SSH and the in-memory connection alike, because all three
share one framing:
PadRequestsTo: Integer (default 0, off)
PadResponsesTo: Integer (default 0, off)
RequirePadding: Boolean (default False)
With a size set, every outbound frame of that kind is zero-padded up to
the next multiple of it. TsnipTLSServer and TsnipTLSClient publish the
same three and pass them to each connection they make.
WHAT IT IS FOR. A snip frame is otherwise exactly as long as what it
carries, so anything counting octets between two endpoints - a proxy, a
load balancer, a network observer - reads the size of a request it cannot
decrypt. From that it can usually tell which method was called, how long
an argument was, and whether the answer was a hit or a miss. Padding makes
every request the same size as every other request, and every response the
same as every other response.
PADDING IS KEYED ON THE KIND, NOT THE DIRECTION, so both ends are given
the SAME two numbers: you pad whichever kind you send, and may require
whichever you receive. Connect, accept and close frames are never padded -
they are identified by their position in a connection whatever their
length, so padding them would buy nothing and cost a frame per connection.
A frame larger than its size is padded up to the next multiple rather than
refused. Refusing would make the failure depend on the content, which is
the very thing being hidden.
NOTHING NEEDS TO NEGOTIATE. The padding sits after the end-of-message
octet and the frame header's length covers it, so a reader consumes it and
the decoder never looks at it: a padded peer and an unpadded one still
interoperate in both directions. That is also why RequirePadding exists -
an unpadded peer is otherwise accepted in silence, and the property is
lost without anyone noticing. Leave it off until both ends pad.
BEHAVIOUR CHANGE: none. All three default to off, and off adds no octets
and makes no check.
58. ADDED - a snip/TLS client that takes the TLS engine it is given, so many
clients can share one
TsnipTLSClient creates a TsmSimpleTLSInternalServer in its constructor and
owns it for life; its TLSServer setter has always been inert, and assigning
an engine to it did nothing at all - silently, which is the worst way for a
property to refuse. That is right for a component dropped on a form and
wrong for anything opening connections in a loop, because the engine is
expensive to build and tear down: measured on one machine, an engine costs
several times what the handshake it serves costs.
TsnipAdvancedTLSClient is the counterpart the Mobile line has had all
along, and it follows that line exactly. Assign it an engine and it uses
that one, shared with as many other clients as you like; assign nothing and
it uses the process-wide GlobalServer; it creates no engine of its own and
frees none it did not make, and a freed engine nils the reference rather
than leaving it dangling. TsnipTLSClient is unchanged in name, in published
properties and in behaviour - it and the new tier now share an ancestor,
TsnipCustomTLSClient, which is where the work moved.
Both tiers gained two events, OnConfigureLayer and OnTransportReady, fired
from the protected virtuals of the same names. Before this, a consumer that
wanted to set anything per connection - a resumption ticket, extra
application protocols, a group preference - or to read what a completed
handshake negotiated had to descend from the component to reach a virtual.
The event argument list matches the Mobile line's, so one handler binds to
either family.
The new component is registered and carries a palette icon. It is in every
package that carries the snip framework: not XE4 or XE5, which have never
had it.
59. FIXED - three waits in the snip TLS transport had no bound, and a peer
that went quiet could park a thread for ever
A snip connection is meant to sit quiet between calls, so the transport
waited for the next frame with no deadline. That is right for an idle
session and wrong in three places where something is genuinely expected:
during the TLS handshake, during the connect exchange that follows it, and
while a caller waits for the answer to a request it has already sent. In
each of those a peer that accepted the connection and then said nothing -
silent, wedged, stopped in a debugger, or refusing the traffic without
saying so - held the calling thread permanently.
A WAIT NOW HAS THREE ANSWERS, NOT TWO, and that is the load-bearing part.
TsnipWaitOutcome = (swoData,swoTimeout,swoClosed) says which of the three
happened, because a bound that expired is not the same event as a peer
that went away: the connection is still up, and a caller told otherwise
would throw away a good session and reconnect. EsnipTimeout is therefore a
leaf of EsnipError and deliberately NOT of EsnipClosed. The new protected
virtual is WaitForFrame(aMSec); WaitForData keeps its exact signature and
meaning and is now a wrapper over it.
THE HANDSHAKE IS BOUNDED BY DEFAULT, AND THIS IS A BEHAVIOUR CHANGE.
TsnipCustomTLSClient.HandshakeTimeout is new and defaults to 20000 ms,
covering the WHOLE handshake rather than one round. Like every bound in
this entry it is a CEILING, NOT A DELAY: a server that answers in
milliseconds is still answered in milliseconds, and the bound is reached
only when nothing arrives. An application whose server legitimately
takes longer than that - heavily loaded, a slow
signature path, a lossy link, or a server stopped in a debugger - now gets
EsnipTimeout where it previously succeeded eventually. SETTING IT TO 0
RESTORES THE OLD BEHAVIOUR EXACTLY, including the original exception class
and message. Note that an existing .dfm carries no HandshakeTimeout line,
so a streamed component takes the new default; the old behaviour cannot be
inherited by accident and must be asked for.
THE SERVER BOUNDS THE CONNECT EXCHANGE. TsnipTLSServer.ConnectTimeout is
new and defaults to 15000 ms, stamped onto every accepted connection. A
client that completes TLS and then does not send its connect frame is
dropped instead of holding a serving thread. Normal clients send it at
once; this reaches only a peer that is stalled or is not really a client.
BOUNDING AN ORDINARY ANSWER IS AVAILABLE AND OFF. ReadTimeout is new on
the client, the server and the connection, and defaults to 0 - wait for
ever - because a long-poll or server-callback deployment is exactly what
this transport exists for and must not be reaped by an upgrade. Assign it
where every exchange is a request and an answer.
AND Stop NO LONGER WAITS OUT ITS WHOLE DrainTimeout. TsnipTLSServer.Stop
paid the full ten seconds whenever any idle connection existed, and leaked
one serving thread per idle session, because the serving loop could not
re-read its active flag - the wait it sat in never returned while the
client was quiet. It now returns about a poll interval after being asked,
and the threads actually exit. DrainTimeout's default is unchanged. This
is faster on purpose, but it IS a timing change: anything that measured a
ten-second shutdown, or counted threads after Stop, will see the
difference.
TWO COMPILE-TIME BREAKS, both loud rather than silent. The protected
virtual Refill gained a milliseconds parameter, because the two ends park
in different places and neither could be bounded without the caller saying
for how long; only a descendant declared outside the unit is affected, and
there is none. TsnipServerTLSOctetConnection.WaitData returns the outcome
instead of a Boolean and takes a bound; pass 0 and compare against swoData
for the old meaning. Its only caller is the serving loop in this same
change.
KNOWN, AND NOT ADDRESSED HERE: on Windows a peer that resets the
connection reaches a parked caller as EstSocketError rather than as
anything in the snip hierarchy, because the socket layer raises on a reset
instead of reporting end-of-stream. A handler written as "on EsnipClosed"
- or even "on EsnipError" - does not catch it. That behaviour is
unchanged by this entry and predates it.
60. FIXED - an SSH client discarded channel data, EOF and CLOSE that arrived
while it waited for the reply to a remote port-forwarding request
StreamSec.SSH.ClientChannel. The remote-forwarding components
(TstSSHForwardingClientSocket) send tcpip-forward from Open and
cancel-tcpip-forward from Close through
tSSHClientChannelBroker.GlobalRequest, which read the reply off the SSH
connection itself. Every message that arrived ahead of the reply was
taken off the connection as well, answered with SSH_MSG_UNIMPLEMENTED
and discarded. On a connection that is already forwarding, those are
the messages the server goes on sending while it handles the request,
and that can take a while: this library's server answers tcpip-forward
once its listener is running, and cancel-tcpip-forward once its accept
loop notices, which can take up to a second.
- CHANNEL_DATA was lost, so a forwarded stream reached the other end
with pieces missing, and nothing reported it.
- CHANNEL_EOF and CHANNEL_CLOSE for a forwarded connection that had just
ended were lost, so the client never closed its side: the connection
to the forward target, the thread serving it and the channel stayed
open until the SSH connection was closed. When the server was this
library's with gSSHForwardHalfClose set, it waits for the client's EOF
before it closes, so it also kept its accepted socket and a thread for
as long.
The same applied to any other channel open on the connection at the
time, and to requests sent with GlobalRequest directly.
The reply is now read by the broker's read thread, like every other
message, and whatever arrives before it reaches its channel.
GlobalRequest returns the same result and response data as before.
Requests from several threads are sent one at a time, since a reply
does not say which request it answers. While a request waits, other
threads can go on sending on the connection; before, they waited with
it.
ONE DIFFERENCE IN HOW LONG IT WAITS. While a reply was pending, a server
that sent nothing at all for about five seconds had the SSH connection
disconnected, and GlobalRequest raised eSSHOutgoingDisconnect. It now
waits for as long as the connection is up, and raises
eSSHClientChannelError if the connection's read thread stops first.
WHO WAS AFFECTED. Code that opens or cancels a remote forward, or calls
GlobalRequest, on an SSH client connection that is carrying traffic at
that moment. A connection that never sends a global request is not
affected, and neither are the SSH server components.
Checked on Win32, Win64 and Linux64 with a client and a server from this
library in one process: a stream forwarded while spare forwards were
opened and cancelled, and forwarded connections closed, and half-closed,
immediately before a request. With the unit as released in 4.1.3.357 the
stream arrived with pieces missing and none of those connections closed,
on every run; with this version every octet arrived, in order, and every
connection closed, on both sides.
--------------------------------------------------------------------------------
PLATFORMS AND COMPILERS: THE SUPPORT FLOORS, macOS ON XE3 THROUGH XE7, A POSIX
SOCKET WAIT PAST 1024 DESCRIPTORS, AND NO_GUI
================================================================================
61. CHANGED - Linux64 is supported from 10.3 Rio, and iOS and Android from
10.4 Sydney
Delphi has had a Linux64 target since 10.2 Tokyo, and iOS and Android
targets since XE4 and XE5. But 10.2 Tokyo's Linux64 compiler, and every
iOS and Android compiler up to and including 10.3 Rio, is a NEXTGEN
compiler: its RTL declares no AnsiString, AnsiChar, PAnsiChar or
WideString, strings of bytes work differently, and objects are
reference-counted. This library does not compile with those compilers,
and they are not supported. Compiled one unit at a time with 10.2
Tokyo's Linux64 compiler, 137 of the 287 units of the runtime package
compile, and 10.3 Rio's Android compiler stops at the same lines.
Linux64 is supported from 10.3 Rio and iOS and Android from 10.4 Sydney,
the release in which Embarcadero retired the NEXTGEN compilers. Win32,
Win64 and macOS are unaffected.
The component palette follows the same floors: no IDE before 10.3 Rio
offers a component for Linux64, and no IDE before 10.4 Sydney offers one
for iOS or Android. Every other IDE, target and component is offered
exactly as before. Checked by reading the platform attribute of every
component class with each of the fourteen compilers, before and after:
from 10.4 Sydney on every value is unchanged, and below it the only
entries removed are Linux64 before 10.3 Rio and iOS and Android.
Two declarations that only a NEXTGEN compiler rejects are written
differently, with the same result on every supported compiler.
stSecUtils.tDualSecretKey.CreateForPFX stages the PKCS#12 password in a
UnicodeString rather than a WideString, the same UTF-16 buffer for this
purpose: both halves of the derived key were checked byte for byte over
an empty password, ASCII, Latin-1, Cyrillic, a surrogate pair, an
embedded NUL and a 64-character password, and are identical in every
case, the empty password included. stOIDs registers its two
single-character OID roots, '1' and '2', from literals that name their
type, and every OID resolves to the name it did before, roots and deep
arcs alike. The runtime packages of all fourteen compilers were rebuilt
on Win32 and Win64, and the AES and OID suites pass on both.
62. FIXED - the library did not compile for macOS on XE3 through XE7
Two declarations, neither of them about macOS, were the whole of the
difference; every release from XE8 onwards had built all along.
stEntropySource opens /dev/random with the POSIX open call, which the RTL
of XE3 through XE7 declares with a mandatory third parameter, the
creation mode - "E2035 Not enough actual parameters". The call passes a
mode of 0 on every compiler; without O_CREAT the value is never read.
stSocket.Posix waited with select() and cleared and tested its sets with
FD_ZERO, _FD_SET and FD_ISSET, names the RTL has only had since XE5; XE3
and XE4 export the same helpers as __FD_ZERO, __FD_SET and __FD_ISSET -
"E2003 Undeclared identifier: 'FD_ZERO'". The unit now waits with poll()
instead, on every compiler and every POSIX platform, and uses none of
those helpers. That change fixes a defect of its own, which every
compiler had: see entry 63.
Checked by building the macOS unit set with each of XE3, XE4, XE5, XE6
and XE7, and linking a program that uses every unit of it: all 132 units
compile and link, where 85 had compiled before the first error stopped
the build. The Windows packages of all fourteen compilers, and the macOS
and Linux sets of the releases that already built, were rebuilt as well
and are unchanged.
63. FIXED - a socket wait on Linux, macOS, iOS and Android wrote past its
descriptor set, and returned without waiting, for a descriptor of 1024
or more
stSocket.Posix. tPosixSocket.WaitForData and WaitForWrite, the waits
behind every stSocket connection on those platforms, waited with
select(). A select() descriptor set has room for descriptors 0 to 1023
only, and adding a higher one writes past the end of the set, which
nothing reports. Each socket holds three descriptors - the socket
itself and the pipe that Send and Wake write to - so a process whose
open-file limit had been raised above 1024 reached that range after a
few hundred sockets. From there a wait returned at once instead of
waiting, or the process failed with an access violation, either in the
wait or later, wherever the overwritten memory was next used.
The waits are now built on poll(), which has no such limit. Below
descriptor 1024 WaitForData, WaitForWrite and Wake behave exactly as
before: the same timeouts, the same readiness for data and for a peer
that has closed, and a Wake still ends a wait that is already blocked
and, when none is, the next one.
WHO WAS AFFECTED. Every component that connects through stSocket on
those platforms: the TLS, HTTP, snip, SSH, mail and OCSP clients, the
SSH and OCSP servers, and the plain-text redirect of TsmAsyncTLSServer.
A process limited to 1024 open files, the usual soft limit for a
service on Linux, never reaches the range. Windows is unaffected: its
socket layer is a separate implementation whose descriptor sets are
bounded.
Checked on Linux64 with sockets held on descriptors from 1100 to 65000.
Release 4.1.3.357 fails the wait and Wake checks there, with waits that
return in 0 ms and with access violations; this version passes every
one of them, as both versions do below 1024.
64. FIXED - StreamSec.Mobile.CertConfig did not compile with NO_GUI defined
A project that defines NO_GUI - a service, a console program, a Linux
target without FireMonkey - could not compile the unit at all. The
compiler stopped in TsmCustomCertConfig.PerformSetup with "E2029
Identifier expected but 'BEGIN' found": NO_GUI took out the method's
local variables, which only its dialogs use, but left the var keyword
in front of them. The keyword now goes with them. A build without NO_GUI
compiles the same code as before.
Checked by compiling the unit with NO_GUI on Win32, Win64 and Linux64,
where it failed on all three before, and without NO_GUI on Win32 and
Win64; and by building the runtime packages of all fourteen compilers,
XE3 through 13 Florence.