Feature notes
Release notes (CHANGES)
================================================================================
CHANGES - StreamSec Tools
(StreamSec Security Library for Embarcadero Delphi)
================================================================================
Grouped by subject. 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.5.362, which was
released on 2026-10-26. What that release itself brought is in
CHANGES_4.1.5.362.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.
RFCs cited here are at https://www.rfc-editor.org/rfc/rfcNNNN.txt, where NNNN
is the RFC's number.
--------------------------------------------------------------------------------
MAIL: WHAT AN IMAP CLIENT SEES OF A MAILBOX
================================================================================
What a regular mail client needs of TsmIMAPServer beyond signing in and
selecting a mailbox: the BODY[section] forms of FETCH that clients use to list
and read messages, a mailbox that tells an open session about new mail, an
EXPUNGE that removes what is flagged, an INBOX for an account that has never
been sent anything, \Recent flags that EXAMINE and STATUS leave alone, and a
mailbox whose UIDs and files stay what they are while other sessions - POP3
ones among them - use it too. Each of the eight entries below was in every
release from 4.1.2.355, the first with the mail suite, to 4.1.5.362.
1. FIXED - IMAP FETCH answered BODY[] and BODY[HEADER] and refused every other
BODY[section] form - HEADER.FIELDS, HEADER.FIELDS.NOT, TEXT, MIME, part
numbers and partial fetches - with BAD, so a mail client could select a
mailbox and count its messages but not list or open them
StreamSec.Mail.IMAPEngine (TsmIMAPServer).
RFC 3501 sec.6.4.5 defines BODY[<section>]<<partial>>, and clients use it
for nearly everything they show. Thunderbird opens a folder with
UID FETCH 1:* (UID RFC822.SIZE FLAGS BODY.PEEK[HEADER.FIELDS
(From To Cc Bcc Subject Date Message-ID ...)])
and reads a message part by part with BODY.PEEK[1], BODY.PEEK[1.MIME] and
partial fetches. The engine knew BODY[], BODY.PEEK[], BODY[HEADER] and
BODY.PEEK[HEADER] by name and answered a command naming any other item
with "BAD unsupported FETCH item".
THE STEP THAT FAILED is the item check in tImapSession.NormalizeFetchItems,
which compared each item with a fixed list of names. Nothing was wrong with
the mailbox, the store or the sign-in, and the way to tell this defect from
another is that SELECT, STATUS, FETCH of UID, FLAGS, RFC822.SIZE, ENVELOPE,
BODYSTRUCTURE and BODY.PEEK[] all worked: a client that lists messages with
ENVELOPE alone never met it.
The item list is now parsed by the grammar of RFC 3501 sec.6.4.5 and 9:
part numbers (1, 2.1, ...), HEADER, HEADER.FIELDS (list), HEADER.FIELDS.NOT
(list), TEXT and MIME in the combinations it allows, and <origin.count>.
- The octets are the stored ones, taken from tMimeEntity, the MIME parser
the engine already uses for BODYSTRUCTURE. A part's content excludes the
CRLF before the next boundary, which belongs to the boundary.
- HEADER.FIELDS and HEADER.FIELDS.NOT match field names without regard to
case, carry each field with its continuation lines, and end with the
blank line, which "is included in all header fetches, except in the case
of a message which has no body and no blank line" (sec.6.4.5) - and in
that case none is added.
- HEADER, HEADER.FIELDS and TEXT after a part number require that part to
be a MESSAGE/RFC822, and then name the encapsulated message's header or
body; MIME names a part's own header.
- A part the message does not have is answered NIL, and the command still
completes OK. A partial fetch is truncated at the end of the text, and
one starting beyond it is the empty string. Part numbers, origins and
lengths run to 4294967295, as sec.9 has it; the bound is on the value,
so an origin may carry leading zeros. A length is nz-number,
"digit-nz *DIGIT", and must begin with a nonzero digit (sec.9).
- One message has one parsing budget for a section, however deep its
encapsulation: a walk through MESSAGE/RFC822 parts shares
cMailMaxNestingDepth and cMailMaxPartCount across the levels, and frees
each level before it parses the next. A section beyond that budget, or
more than cMailMaxNestingDepth + 1 part numbers, is answered NIL.
- The response names the section that was requested - part numbers as
sent, BODY[4294967295] NIL - in upper case, and gives only the origin of
a partial, as sec.7.4.2 has it: BODY[HEADER.FIELDS (FROM SUBJECT)]<0>.
- A HEADER.FIELDS name is an IMAP astring (sec.9) and may be any RFC 5322
field name. One an IMAP atom cannot carry - X*Foo, or a name with a
parenthesis or a bracket in it - is accepted quoted, and named quoted in
the response. This includes every character the FETCH item splitter
or section parser treats specially: both brackets, quotes, backslashes
and parentheses.
- BODY[...] without .PEEK sets \Seen, as before.
- A malformed section - HEADER.FIELDS without its list, MIME without a part
number, a part number 0, a partial without its length, anything after
TEXT, a number above 4294967295 - is BAD before a single untagged line is
sent, as before.
NOT CHANGED: BINARY and BINARY.PEEK (RFC 3516) are not advertised and are
refused by name. A field name sent as a literal, which the astring grammar
also allows, is refused with BAD: the literal does not travel in the
command line, and answering without it would name a list the client did
not ask for. A quoted name carries any name a header field can have.
2. FIXED, BEHAVIOUR CHANGE - IMAP RFC822.TEXT returned the whole message,
header included, where RFC 3501 defines it as the body alone
StreamSec.Mail.IMAPEngine (TsmIMAPServer).
RFC 3501 sec.6.4.5: RFC822.TEXT is "Functionally equivalent to BODY[TEXT]".
THE STEP THAT FAILED is tImapSession.EmitFetch, which answered it with the
same octets as RFC822, so a client that reads a message's text this way
showed the header as its first lines. It now returns the octets after the
blank line that ends the header, and still sets \Seen.
ALSO FIXED: RFC822.HEADER and BODY[HEADER] of a message stored with bare LF
line ends. They took the header from tMaildirView.ReadHead, which ends a
header only at CRLF CRLF, so they returned the whole message. They now end
at the first blank line, with either line end, and RFC822.HEADER returns
the same octets as BODY.PEEK[HEADER] and still sets no \Seen.
BEHAVIOUR CHANGE for code that relied on getting the header there: fetch
RFC822 or BODY[] for the whole message.
3. FIXED - an IMAP session never learned of mail that arrived after it selected
the mailbox: NOOP, CHECK, IDLE and DONE did not look at the mailbox again,
so a client saw new mail only by selecting the mailbox anew or by
reconnecting
StreamSec.Mail.IMAPEngine, StreamSec.Mail.IMAPServer,
StreamSec.Mail.IMAPTransport, StreamSec.Mail.Maildir (TsmIMAPServer,
TsmMailStore).
RFC 3501 sec.6.1.2 says NOOP "can be used as a periodic poll for new
messages", and RFC 2177 that while IDLE is active "the server is now free
to send untagged EXISTS, EXPUNGE, and other messages at any time". The
engine re-read the mailbox only after the transport had called
tImapSession.Nudge, and nothing in the library called it. A client polling
with NOOP never saw a new message; a client in IDLE - Thunderbird and phone
clients park a connection that way - heard nothing until it selected the
mailbox again or reconnected.
THE STEP THAT FAILED is tImapSession.ReportChanges, which rescanned only
when that nudge had been given. Delivery was not involved: the message was
in the maildir, a fresh SELECT showed it, and POP3, which takes a fresh view
per session, never had the problem.
What a session does now:
- NOOP, CHECK, the start of IDLE, DONE and EXPUNGE rescan the mailbox.
Every message that another session expunged in the meantime is reported
as EXPUNGE, highest number first, and then EXISTS and RECENT give the new
totals, so the client's message numbers never silently shift. A rescan
never runs inside FETCH, STORE or SEARCH, where RFC 3501 sec.7.4.1
forbids EXPUNGE.
- A rescan keeps the messages in UID order, which is the order IMAP
numbers them in (sec.2.3.1.2): a message that arrives with a file name
that sorts before the others - written by another program, or by a clock
that was behind - is given the next UID and comes last, and no message
the client has already numbered changes its number.
- While a session is in IDLE on the cleartext port (StartTLS, 143), its
connection thread calls the session about once a second
(cMailConnectionReadRoundMs, 1000 ms), through the new iImapIdleHandler.
The session rescans when the generation of the selected mailbox has
moved, and otherwise every cImapIdleRescanSeconds (30). A delivery,
APPEND, EXPUNGE or COPY into that mailbox through the same store instance
moves the generation, and the client hears of it at the next round. A
change made through another store instance or another process is noticed
by the timed rescan, within 30 seconds. Delivery to other mailboxes causes
no rescan; a mailbox that shares one of the cMailGenerationSlots (256)
hash slots only costs a needless one. These three values were chosen, not
measured.
- Flag changes alone are never pushed during IDLE, whoever made them: the
client reads them with its next FETCH of FLAGS.
- \Recent stays on a message for the rest of the session once reported
(RFC 3501 sec.2.3.2); a rescan used to keep it only on the arrivals it
moved itself.
NEW: iImapIdleHandler (StreamSec.Mail.IMAPTransport), which a connection
handler implements to be called while its peer is silent - the existing
handler interfaces are unchanged; tImapServerSession.IdleRound and
cImapIdleRescanSeconds (StreamSec.Mail.IMAPServer); tMaildir.Generation,
GenerationSlot and MailboxGeneration (StreamSec.Mail.Maildir).
NOT CHANGED: the implicit-TLS attachment (993, on a TsmAsyncTLSServer) has
no idle round, so a client idling there learns of new mail at its next
NOOP or at DONE, which RFC 2177 advises it to send at least every 29
minutes.
A rescan that fails on a file, stream or I/O error is logged and leaves the
session as it was: NOOP and CHECK finish, the snapshot stays, and the next
command works. The command parser resets its pending command in a finally
block. A process-state exception is not contained here (entry 20).
A rescan also refuses a mailbox whose directory has been renamed or
deleted, and never creates new/ or cur/, so the old name does not come back
in LIST and cannot be opened without CREATE. Opening a resolved address's
INBOX and delivery still create their directories (entry 5). A session that
has the mailbox selected when another session renames or deletes it, in an
idle round too, gets
"* BYE selected mailbox was renamed or deleted, have to disconnect" and the
connection closes; when the store has become unavailable the text is
"* BYE mailbox service is shutting down".
4. FIXED - IMAP EXPUNGE and CLOSE did not remove a message another session had
flagged \Deleted, and UID EXPUNGE of a set that named no message in the
mailbox removed every message flagged \Deleted
StreamSec.Mail.IMAPEngine, StreamSec.Mail.IMAPServer (TsmIMAPServer).
RFC 3501 sec.6.4.3: EXPUNGE "permanently removes all messages that have the
\Deleted flag set from the currently selected mailbox". THE STEP THAT
FAILED is tImapServerSession.Expunge, which took what to remove from the
open view's deletion marks, and only this session's own STORE commands set
those; a flag another session or client set is stored in the message's file
name, which this session had not read again.
UID EXPUNGE (RFC 4315 sec.2.1) is the opposite case, and A SECOND STEP
FAILED, in tImapSession.CmdExpunge: it removes only the messages it names,
and the engine hands the policy their sequence numbers - an empty list
meaning plain EXPUNGE. A UID set that named no message in the mailbox
resolved to an empty list, so "UID EXPUNGE 999" with no message 999 removed
every flagged message in the mailbox.
Now EXPUNGE, UID EXPUNGE and CLOSE rescan the mailbox first and rebuild the
marks from the stored flags, and a UID EXPUNGE whose set names no message
removes nothing and completes OK. A message another session un-deleted
between the rescan and the removal is kept, and the command answers OK: only
a message still present and still \Deleted is a failure (entry 7). POP3 is
not affected: there DELE marks, and QUIT removes exactly what was marked,
whatever flags the message has by then (RFC 1939 sec.6).
5. FIXED - an account that had never been sent anything could not open its
own INBOX: IMAP SELECT, EXAMINE and STATUS answered "NO no such folder",
and POP3 refused the maildrop after the password had been accepted
StreamSec.Mail.Maildir (TsmMailStore).
THE STEP THAT FAILED is tMaildir.OpenFolder: a mailbox's directory was
created by its first delivery, and until then OpenFolder answered "no such
folder". POP3 told the client "the maildrop is not available; it may be
locked by another session" - after accepting its password - and logged the
real reason. INBOX now exists from the moment the mailbox does: a
read-write or exclusive open (SELECT, POP3) of the INBOX of an address the
store resolves - a configured mailbox or an account - creates its
directories as the first delivery would. A read-only open (STATUS, and
EXAMINE, which RFC 3501 sec.6.3.2 calls "identical to SELECT") creates them
for an INBOX that has neither new/ nor cur/, also when the account directory
already exists because a client has created another folder. It does not
repair an INBOX that has exactly one of the two: that open answers
"NO cannot open that mailbox".
NOT CHANGED: an address the store does not resolve still has no mailbox to
open, and every folder other than INBOX is still made by CREATE.
6. FIXED - IMAP EXAMINE and STATUS took the \Recent flag from new mail, so
the session that selected the mailbox next did not see it as recent; and
the UIDs a read-only session gave messages were not recorded, so they
could be given out again to other messages
StreamSec.Mail.Maildir (TsmMailStore, TsmIMAPServer).
RFC 3501 sec.6.3.2: "No changes to the permanent state of the mailbox,
including per-user state, are permitted; in particular, EXAMINE MUST NOT
cause messages to lose the \Recent flag." Sec.6.3.10 says the same of
STATUS. A read-only view of a maildir - what EXAMINE and STATUS open -
moved new mail out of new/ as a read-write view does, and in maildir that
move IS the message's \Recent: the next session to select the mailbox
found it in cur/ and did not report it. STATUS is the command clients send
to every folder to count new mail, so a client that polled with it took
\Recent from all of them.
The same view gave UIDs to the messages it found unnumbered and did not
record them, because a read-only view wrote nothing. The next read of the
mailbox numbered them again, and when the set of unnumbered messages had
changed in between, in another order: a message that arrives with a name
sorting first, as in entry 3, took the UID already reported for another
message. That is one UID naming two messages under one UIDVALIDITY, which
sec.2.3.1.1 forbids (entry 8).
THE STEP THAT FAILED is tMaildirView.Refresh, which in a read-only view
moved the arrivals as a read-write one does and then skipped writing the
index.
A read-only view now leaves new/ alone - an arrival is \Recent to it, and
still \Recent for the next session that selects the mailbox - and writes
the UID index as any other view does: numbering is the store's, not a
change to a message. A message that another process moves out of new/
while the view reads the directory is counted once. Every view now saves
the index first, and only then does a read-write view move arrivals to
cur/, carrying the flags their names in new/ hold: 4.1.5.362 moved them
first and discarded those. If saving the index fails, the open or refresh
is refused, and no arrival has lost its \Recent. A failed refresh keeps the
previous snapshot and numbering; it never publishes unrecorded UIDs that a
later scan could give to another message in the same session.
NOT CHANGED: APPEND and COPY open a read-write view of their destination,
and that view still moves the arrivals it finds there out of new/, so they
are not \Recent for the next session.
7. FIXED - a message that another session had re-flagged could not be read
by a session that had the mailbox open, and a POP3 session that deleted it
left it in the mailbox, where it came back under a new UID
StreamSec.Mail.Maildir, StreamSec.Mail.IMAPServer, StreamSec.Mail.POP3Server
(TsmMailStore, TsmIMAPServer, TsmPOP3Server).
Maildir keeps a message's flags in its file name, so setting or clearing
one renames the file. An open view used each file name as it had last
read it. Once another session had changed a flag, FETCH of the message's
content found no file: BODY[], BODY[HEADER] and RFC822 were each answered
as an empty message. A POP3 maildrop is read once, at sign-in, and its QUIT
deleted the old name - which deleted nothing, while the index dropped the
message, so it stayed in the mailbox and was numbered again as if it had
just arrived.
THE STEP THAT FAILED is tMaildirView.FileOf, and the delete in
tMaildirView.Expunge, which built the path from the name the view had
last read.
A view now finds a message's file by its base name, which a flag change
does not alter, in new/ and then in cur/, and Expunge deletes it by the same
lookup. A read takes no lock, neither the store's nor .ss-index.lock, and a
flag change takes the store's operation lock and, for its rename, the short
commit gate, never .ss-index.lock, so neither fails because another process
is scanning the mailbox. A read that loses the file to a
rename looks again, up to cMailStoreFlagAttempts (3, chosen, not measured);
a message still moving after that is an error, not an empty message. A read
also checks, before and after, that the selected mailbox is still the same
one. A message that is truly gone is answered NIL for a BODY[section],
where 4.1.5.362 sent an empty BODY[] or BODY[HEADER], and as an empty
string for RFC822, RFC822.HEADER and RFC822.TEXT.
ALSO FIXED, Windows: a reader opened the message file denying writes, so a
FETCH or RETR made another session's STORE or EXPUNGE of that message fail
with a sharing violation. Message files are now opened sharing read, write
and delete. An expunge renames the file to <name>.tmp, which no lookup or
scan takes for a message, and deletes it; a failed delete renames it back.
Other platforms delete the file directly. Each is retried up to
cMailStoreFlagAttempts when the old name has vanished.
A delete counts as removed only after the file is gone: 4.1.5.362 counted a
failed delete as done. Sharing and permission failures keep the message,
deletion mark and index row. IMAP sends no EXPUNGE for a retained message.
EXPUNGE and UID EXPUNGE answer NO if any message selected for removal is
still present and still \Deleted, while reporting each successful removal.
CLOSE also answers NO on failure and deselects the mailbox, suppressing
EXPUNGE responses as RFC 3501 sec.6.4.2 requires. Sec.6.4.3 gives EXPUNGE's
failure result as "NO - expunge failure: can't expunge (e.g., permission
denied)". POP3 QUIT returns -ERR if UPDATE could not remove every
DELE-marked message. RFC 1939 sec.6 lists the failure response as "-ERR some
deleted messages not removed". Some marked messages may have been removed
before a failure: "In no case may the server remove any messages not marked
as deleted." The lock is released whether UPDATE succeeds or fails.
If the index cannot be saved after a physical removal, EXPUNGE reports what
was removed, answers NO, and leaves the selected snapshot aligned with the
remaining files.
8. FIXED - a mailbox view that had not read the mailbox again wrote its own
UID index over the one on disk when it expunged or appended, so UIDs
other sessions had given out were lost, UIDNEXT went back, and a UID
could name a second message
StreamSec.Mail.Maildir, StreamSec.Mail.IMAPServer, StreamSec.Mail.POP3Server
(TsmMailStore, TsmIMAPServer, TsmPOP3Server).
The UID index of a mailbox is shared by every session that opens it. A
view rewrote the whole index from its own list when it expunged or
appended, and its list is the mailbox as that view last read it. A POP3
maildrop is read once, at sign-in, so its QUIT wrote back an index
without the messages IMAP sessions had numbered since, and with the
UIDNEXT of the moment POP3 signed in. The next read numbered those
messages again from there: a message took a lower UID than the one it had
been given - the UID of a message IMAP had expunged, among them. RFC 3501
sec.2.3.1.1: a UID with its UIDVALIDITY "MUST NOT refer to any other
message in the mailbox or any subsequent mailbox with the same name
forever", and UIDs are "assigned in a strictly ascending fashion". APPEND
and COPY could do the same in a narrower window: the view they open
numbered the new message from its own UIDNEXT, which a session that
numbered an arrival in the meantime had already given out.
THE STEP THAT FAILED is tMaildirView.Expunge and tMaildirView.Append,
which wrote the view's own list with tMaildir.SaveIndex.
Both now apply their change to the index on disk - the expunged messages
leave it, the appended one joins it under the UID a session has already
given it or the next one - with UIDNEXT never lower than either knows,
through the new protected tMaildir.UpdateIndex. A valid disk index with
a different UIDVALIDITY always wins. A missing or invalid disk index also
refuses mutation: only a fresh open may recover it under a new epoch.
A stale Append fails and removes its published file, and a stale Expunge
fails before deleting a message, even when no deletion was marked. Neither
replaces the disk epoch, reuses its UIDs or lowers its UIDNEXT. When a
selected IMAP session's disk index is missing or invalid, its rescan is
refused, it keeps its old numbering and EXPUNGE answers NO; POP3 QUIT
answers -ERR, also without a DELE mark. When the disk index holds a
different valid UIDVALIDITY the IMAP session ends with BYE, as in entry 3.
RFC 3501 sec.2.3.1.1: "The combination of mailbox name, UIDVALIDITY, and UID
must refer to a single immutable message on that server forever."
A RESCAN NO LONGER DROPS A MESSAGE IT MISSED. 4.1.5.362 rewrote the index
from the scan of cur/, so a file a rename moved past the scan lost its UID.
Now every message the view or the index knows and the scan did not see is
looked up again by base name, and only a message missed by that second look
as well is absent. Its row stays as a tombstone, remembered per mailbox on
the store instance; the next Refresh of that mailbox, by any view of that
store, that misses it again prunes the row. So one miss keeps a UID, and any
other row the view does not hold stays in the index. A message this session
has never been shown and that is numbered below what it has shown stays out
of its view until a new SELECT, so no number the client holds changes.
UIDVALIDITY, UIDNEXT and every indexed UID are parsed as nonzero decimal
unsigned 32-bit values, through 4294967295. A missing, malformed,
duplicate or out-of-range epoch or next-UID header, an invalid UID, a
UID at or above UIDNEXT, a repeated UID, or a repeated message name
invalidates the whole index. Duplicate rows are never silently merged.
No malformed number falls back to 1. A usable epoch header still raises
the counter before recovery, even when later index content is corrupt.
The counter and name-history parsers use the same unsigned range.
Persisted numbers and Win32 UID/pointer conversions retain the high bit.
UIDNEXT 4294967295 remains a valid exhausted index: existing messages can
be read or expunged, but assigning another UID refuses the operation
rather than wrapping UIDNEXT to zero or reusing a UID.
The store-root .ss-uidvalidity-counter file gives out each new epoch before
its index can be published; 4.1.5.362 took the current Unix second, so
mailboxes opened in one second shared an epoch. Under a cross-process lock,
the next value is the greater of the current Unix second and the counter
plus one. A temporary file is written, flushed and atomically renamed over
the counter, whatever FlushToDisk says, and on POSIX the directory is
flushed too; a crash leaves the old or new counter, without an unlink gap.
The name history is written the same way. The file stays small regardless
of how many epochs have been given out. It keeps the high-water value
through folder deletion and recreation, process exit and a clock moving
back, so same-second index loss cannot reuse an epoch. RFC 3501 sec.2.3.1.1
requires that "the unique identifier validity value MUST be greater than the
one used in the earlier session."
If the counter is missing or invalid, recovery retains every readable
FIRST and LAST value, even among malformed or duplicate rows, and scans
every index under the store root and the name-history records.
A process high-water mark for each canonical store-root path retains
every epoch given out or observed in that root, including loaded indexes
and open views. Windows resolves directory aliases, dot segments and
case to the same root. EVERY mint exceeds its own root's mark, including
when the counter parses as valid. The mark raises only LAST, never
FIRST; another root cannot change this store's epoch classification.
Losing an index and counter under a live view therefore cannot reuse
that view's epoch or silently give its UID to another message - with one
exception off Windows: there the root is keyed by its path as given, and
symbolic links are not resolved, so a store opened through two different
paths keeps two marks, and losing both files can then reissue an epoch a
view opened through the other path still holds. Open a store through one
path only.
An index written by an earlier release keeps its epoch and its UIDs, but
that epoch is unproven, since it came from the clock. Missing or damaged
counter recovery preserves uniqueness proven by remembered valid counter
ranges or U records in .ss-uidnames-history. FIRST is reconstructed from the
certified interval above unproven evidence. A bare index header raises the
allocation floor but does not by itself prove uniqueness, and neither does
a certified interval alone. L records and repeated live-index epochs
contradict uniqueness: the recovery scan counts an epoch repeated anywhere
under the store root, and the check made for one mailbox reads the history
and the indexes of its own account, INBOX and folders, one directory level.
Earlier certified values below the recovered interval keep their individual
proof; matching legacy or duplicate evidence defeats it. Thus a higher
legacy epoch does not erase an earlier U record's sound provenance. Entry 17
describes when a returning mailbox needs a fresh value after provenance is
lost. A scan retains whether evidence was unproven or contradicted
uniqueness even if a later read fails and that evidence is removed before
retry. Retaining its numeric allocation floor alone cannot certify it. A
higher observed epoch preserves FIRST when it has uniqueness proof; an
unproven observed header cannot extend a certified interval.
The first mint for each store root in each process scans the same disk
evidence even with a valid counter. This protects an older restored
counter against surviving indexes and name history at that first mint.
Later mints use this root's small counter and process floor; they do not
scan the whole store unless counter recovery is required.
Keep .ss-uidvalidity-counter and .ss-uidnames-history with the store. After
a process's first scan, restoring only the counter can reuse an epoch
subsequently issued by another process if this process has not observed
that epoch, even while its index and the other process's live view survive.
Such a restore requires stopping all users of the store and restarting them.
Another process's live views are also invisible when every disk record
of their epochs is lost. Deleting or rolling back all index and history
evidence after process exit has the same limit. A legacy epoch lost
before this process first observes it is likewise unavailable.
An index replaced with an unrelated mailbox incarnation using the same
certified numeric epoch cannot be distinguished from the original
incarnation if no conflicting history or duplicate live index remains.
At 4294967295, minting refuses recovery rather than wrapping and reusing
an epoch. Refresh, Append and Expunge retain the store-root
.ss-index.lock gate through index publication, preventing a delayed
process from publishing an older epoch over a newer one. A process guard
also serializes retrieval across stores because POSIX record locks
exclude processes rather than threads. The separate .ss-rename.lock
coordinates folder names and rollback cleanup even after an index-lock
refusal. Contention fails closed for retry. Delivery takes no retrieval
lock.
COPY now answers NO if any source read or destination Append fails, and
supplies no COPYUID for a failed command. It records each published
Maildir base name and removes those files on failure, independently of
destination UIDs, flag renames, folder renames or index loss, replacement
and recovery. RENAME remains legal while APPEND or COPY is in progress.
Cleanup searches the account's INBOX and Maildir++ folders for its own
published base names and temporary files, including after repeated or
parent-folder renames.
RENAME and cleanup share a store-root .ss-rename.lock gate, with a process
guard as well, so the search cannot race another cooperating RENAME.
Ordinary sharing contention waits for the rename to finish; other I/O
errors fail explicitly. This gate is separate from the index gate so an
index-lock failure does not prevent removal of a publication.
The new iMailboxView.RemoveAppended accepts only that view's own
publications - iMailboxView therefore has a new GUID, and a mailbox store
of your own that implements it must add the method. It preserves the
current disk index and its UIDNEXT; rows
for removed files remain as tombstones, as above. A failed
Append removes its own publication (entry 14). A physical rollback
failure is logged and still answers NO. RFC 3501 sec.6.4.7: "If the COPY
command is unsuccessful for any reason, server implementations MUST
restore the destination mailbox
to its state before the COPY attempt."
--------------------------------------------------------------------------------
MAIL: WHAT THE SMTP SERVER ACCEPTS, AND WHAT IT WRITES INTO A MAILBOX
================================================================================
The submission port and what authenticates a session there, the postmaster
address, and the Delivered-To field of a locally delivered copy. Each of the
four entries below was in every release from 4.1.2.355 to 4.1.5.362.
9. FIXED, BEHAVIOUR CHANGE - the submission port of TsmSMTPServer took MAIL
FROM from a session that had not authenticated, so anybody could deliver
to the server's own mailboxes through it without the checks the inbound
port makes
StreamSec.Mail.SMTPServer (TsmSMTPServer).
RFC 6409 sec.4.3: "The MSA MUST, by default, issue an error response to
the MAIL command if the session has not been authenticated using
[SMTP-AUTH], unless it has already independently established
authentication or authorization (such as being within a protected
subnetwork)." The submission role - Submission, conventionally 587, and
the implicit-TLS attachment on a TsmAsyncTLSServer, 465 - offered AUTH and
did not require it. The only refusal of an unauthenticated MAIL FROM was
RequireAuth, which applies to every port of the server and is documented
to stay off on a server that also receives inbound mail, so a server
answering 25 and 587 had no way to say it.
Relaying stayed closed - a remote recipient still needed authentication -
but mail for a LOCAL mailbox was taken from anybody, and the inbound checks
did not apply there: VerifyInbound's SPF, DKIM and DMARC judge mail that
arrives as an MX. A message from a domain whose DMARC policy is p=reject,
refused "550 5.7.1" on port 25, was delivered when sent to port 587.
THE STEP THAT FAILED is tSmtpServerSession.CheckSender, which never asked
whether a submission session had authenticated.
A submission session that has not authenticated is now refused at MAIL
FROM with "530 authentication required", unless its address is in
RelayNetworks - the "protected subnetwork" the RFC names. Authenticated
means SMTP AUTH, or a client certificate bound to this transaction's
reverse path (RelayForClientCertificate; see entry 12). The inbound port is
unchanged, and so is RequireAuth, which still extends the refusal to every
port.
BEHAVIOUR CHANGE: a sender that submitted without authenticating - a script
on another host mailing local users, say - is now refused. Give it an
account, or list its address in RelayNetworks.
10. FIXED, BEHAVIOUR CHANGE - mail to postmaster@<domain> was refused unless
PostmasterMailbox was set or a mailbox of that name existed, and RCPT
TO:<Postmaster> with no domain was refused on the inbound port, though
RFC 5321 requires both to be accepted
StreamSec.Mail.SMTPServer (TsmSMTPServer).
RFC 5321 sec.4.5.1: "The requirement to accept mail for postmaster implies
that RCPT commands that specify a mailbox for postmaster at any of the
domains for which the SMTP server provides mail service, as well as the
special case of "RCPT TO:<Postmaster>" (with no domain specification),
MUST be supported." Postmaster was special only when PostmasterMailbox
named a mailbox. Without one, postmaster@<domain> was an ordinary local
part, refused "550 no such user here" under RequireKnownMailbox (the
default) when no mailbox of that name existed; and the bare <Postmaster>,
having no domain, was not local at all and drew "550 relay not permitted".
THE STEP THAT FAILED is TsmCustomSMTPServer.RouteRecipient, whose postmaster
rule ran only with PostmasterMailbox set and an address in a local domain.
Both spellings, in any case, are now accepted wherever the message has
somewhere to go. OnResolveMailbox, when assigned, still answers first, as
it does for every address; then the message goes to PostmasterMailbox when
it is set, as before; else to the mailbox postmaster@<domain> resolves to;
and otherwise to the mailbox named by the new constant
cSmtpPostmasterMailbox, 'postmaster' - the mailbox an account
postmaster@<domain> is given by a TsmMailStore with Users, so that account
reads what arrived before it existed. With no local store
(LocalDeliveryMode sldNone or sldEvent) there is nowhere to put the message
but the application's hands, so postmaster is accepted only while an
OnMessage or OnLocalDeliver handler is assigned to take it. Without one,
both spellings are refused at RCPT with "550 postmaster delivery is not
configured". This delivery-owner check also applies when OnResolveMailbox
answers local with an empty mailbox and when PostmasterMailbox is set. Bare
<Postmaster> is local or refused on authenticated submission too: a relay
grant cannot provide its missing domain. RFC 5321 sec.4.1.2 requires that
"all quoted forms MUST be treated as equivalent" when comparing local
parts. The local part is decoded once, including quoted-pair escapes,
before the postmaster comparison; quoted bare and qualified spellings use
the same delivery-owner rule on both ports. The canonical local part
'postmaster' is used by store aliases, OnResolveMailbox, recipient
callbacks and delivery, including Delivered-To. OnMessage and
OnLocalDeliver receive a canonical envelope copy with the transaction's
identity, authentication, transport and message parameters preserved.
For example, postmaster@mx.example=admin also receives mail addressed to
"postmaster"@mx.example or "post\master"@mx.example. Other local addresses
retain their existing routing rules.
BEHAVIOUR CHANGE: with no store and no handler, postmaster@<domain> is now
refused; through 4.1.5.362 the rule for an address in a local domain
accepted it with nowhere to put it, and it was lost. A bare <Postmaster> on
an authenticated submission session no longer passes the relay gate. The
application's callbacks now see the canonical local part where they saw the
client's spelling.
11. FIXED - each locally delivered copy of a message named the FIRST
recipient of the transaction in its Delivered-To field, so the copies of
the other recipients named somebody else - a Bcc recipient included
StreamSec.Mail.SMTPServer, StreamSec.Mail.SMTPDelivery (TsmSMTPServer,
tSmtpLocalAgent, tSmtpMaildirStore).
For local delivery the maildir store puts Return-Path and Delivered-To in
front of the message. It took the recipient from the envelope it was
handed, and the server (TsmCustomSMTPServer.DeliverLocal) and the queue's
local agent (tSmtpLocalAgent) both handed it the whole transaction's. The
copy in bob's mailbox of a message to alice and bob said "Delivered-To:
<alice@...>", which told bob that alice received it even when she was a
Bcc recipient.
THE STEP THAT FAILED is tSmtpMaildirStore.Deliver, which took the first
recipient of the envelope whatever mailbox it was writing.
Both callers now hand the store a one-recipient envelope. The store itself,
given several, names the first that resolves to the mailbox it is writing,
and writes no Delivered-To at all when none does, rather than name somebody
else.
12. FIXED - with RelayForClientCertificate on, a client certificate that
authenticated one transaction kept the session authenticated for every
later transaction on the connection, so after one message from the
address it names, its holder could relay mail from any address
StreamSec.Mail.SMTPServer, StreamSec.Mail.SMTPEngine (TsmSMTPServer).
RelayForClientCertificate lets a peer that presented a verified client
certificate relay, and only from the address the certificate names: "THE
RULE IS EXACT-ADDRESS AND NOTHING ELSE" and "AN UNMATCHED CERTIFICATE
AUTHORIZES NOTHING", says the binding's own documentation. The binding was
made at MAIL FROM by marking the envelope authenticated - the mark SMTP
AUTH sets, which is kept across RSET and across the end of a message, as
SMTP AUTH's must be. So after a MAIL FROM naming the certificate's address,
a RSET and a MAIL FROM:<anyone@...> on the same connection were
authenticated too, and the relay gate carried the mail.
The same binding had two more faults, in sessions that use SMTP AUTH:
- In a session that had authenticated with SMTP AUTH and also presented a
certificate, a MAIL FROM naming the certificate's address replaced the
authenticated user with that address - in the Received stamp, the
spool and any bounce - and the replacement stayed for the session's
later transactions, whatever their reverse path. The account that had
authenticated was no longer named on its own mail.
- After a certificate had authenticated a transaction, SMTP AUTH answered
"503 already authenticated" for the rest of the connection.
WHO IS AFFECTED: a server with RelayForClientCertificate set, which is off
by default, and only a peer holding a certificate the server's trust
configuration admits that names an address - one of the server's own
certificate users, who could then send under any sender address. A peer
without such a certificate gains nothing. For a session that also used
SMTP AUTH the relay decision was not affected, only the identity recorded.
THE STEP THAT FAILED is tSmtpServerSession.CheckSender, which set the
envelope's authentication for a matching certificate - the same mark, and
the same user field, as SMTP AUTH sets - and never withdrew it.
A certificate now authenticates one transaction. The envelope marks that
authentication as the transaction's - the new
tSmtpEnvelope.AuthForTransaction - and the engine's reset of a
transaction withdraws it: RSET, EHLO or HELO, the end of a message, and the
start of the next MAIL FROM. A RCPT that raises keeps the transaction, and
so keeps this identity; any other command that raises resets the
transaction and withdraws it. SMTP AUTH may follow, and its identity is the
session's for good. In a session authenticated with SMTP AUTH a certificate
naming the reverse path no longer replaces the user. The relay gate and the
submission rule of entry 9 both read the result: after a RSET, a session
without SMTP AUTH and outside RelayNetworks gets 530 at a MAIL FROM on the
submission port for an address the certificate does not name.
NEW: tSmtpEnvelope.AuthForTransaction (StreamSec.Mail.SMTPEngine).
--------------------------------------------------------------------------------
MAIL: ACCOUNTS
================================================================================
The account store's provisioning surface.
13. NEW - TsmMailUsers.IsEnabled reads back what SetEnabled set
StreamSec.Mail.Users.
SetEnabled turns an account's sign-in off and on, keeping its verifier,
but nothing read the state back, so a tool that provisions accounts could
not show it. IsEnabled answers True when the account exists and SetEnabled
permits sign-in, and False when it is disabled or does not exist. It does
not test temporary lockout: IsLocked reports that.
--------------------------------------------------------------------------------
MAIL: IMAP COMMANDS AND THE MAILDIR STORE
================================================================================
What IMAP commands answer when the store refuses them, and what the store
keeps. The failures of entries 14, 15 and 16 were each in every release from
4.1.2.355 to 4.1.5.362.
14. FIXED - an unsuccessful IMAP APPEND left its message in the destination
when the UID index could not be saved, and no tagged completion was sent
StreamSec.Mail.Maildir, StreamSec.Mail.IMAPServer (TsmMailStore,
TsmIMAPServer).
THE STEP THAT FAILED was tMaildirView.Append, which published the message
file and then saved the UID index with no way back. When the save raised,
the file stayed in the destination and the exception reached the transport,
which closed the connection with no response to the command.
APPEND publishes a message file before recording its UID. A failed index
save now removes that publication by its stable Maildir base name and
leaves the view's snapshot unpublished. IMAP completes the command with
NO and no APPENDUID, and the next command remains usable. Each Append
inside COPY has the same cleanup rule; entry 8 covers rollback of the
command's earlier successful appends. A destination RENAME between
publication and refusal is followed by searching the account's folders
under the separate folder-name gate, rather than treating the obsolete
destination path as proof that the publication is gone. If the removal
itself fails, the command still answers NO and OnLog has the reason. The
removal runs only while the store is Available: a store that has failed or
been deactivated writes nothing more, so the file then stays.
RFC 3501 sec.6.3.11 requires that the "mailbox MUST be restored to its
state before the APPEND attempt; no partial appending is permitted."
15. FIXED, BEHAVIOUR CHANGE - IMAP message and UID sets refused values above
2147483647, selecting a real high-bit UID could raise ERangeError, and a
sequence number above the message count answered OK
StreamSec.Mail.IMAPEngine.
RFC 3501 sec.9 defines nz-number as a "Non-zero unsigned 32-bit integer"
with "(0 < n < 4,294,967,296)"; seq-number and uniqueid use nz-number.
Its grammar is "digit-nz *DIGIT", so leading-zero bounds are invalid.
For message sequence numbers it says: "The server should respond with a
tagged BAD response to a command that uses a message sequence number
greater than the number of messages in the selected mailbox." It adds:
"This includes "*" if the selected mailbox is empty."
RFC 3501 sec.6.4.8: "A non-existent unique identifier is ignored without
any error message generated."
THE STEP THAT FAILED was ImapParseSet parsing set endpoints as signed
Integer, and tImapSession.ResolveSet resolving a UID set by allocating an
array through its highest UID, clamped to MaxInt. Valid unsigned endpoints
were refused, and a real high-bit UID made the array length overflow before
tagged completion. SEARCH's UID and sequence-set keys go through the same
resolution. Sequence sets were then clipped to the mailbox count instead of
rejecting bad bounds.
Set endpoints and UID comparisons retain the full Cardinal range.
Resolution tests actual mailbox items against parsed intervals instead
of expanding the UID number space. A reverse range has the same members
as its forward spelling; '*' resolves to the highest actual UID, or
UIDNEXT in an empty mailbox. A message sequence bound above the message
count, including '*' in an empty mailbox, returns tagged BAD before any
selected item is used. Leading-zero numeric bounds return BAD in both
sequence and UID sets. Nonmatching UID sets still complete without an
error. Internal selected-item indices are bounded by the message count.
BEHAVIOUR CHANGE: a client that sends a sequence number above the message
count, or '*' in an empty mailbox, or a bound with leading zeros got OK
through 4.1.5.362 and now gets tagged BAD, and each BAD counts towards the
session's protocol-error limit (Errors on the IMAP limits).
Tested on Win32 and Win64 with FETCH, STORE, COPY, SEARCH and UID EXPUNGE.
16. FIXED - RENAME answered OK after moving a parent but leaving a child
behind when its destination name collided or its move failed
StreamSec.Mail.Maildir, StreamSec.Mail.IMAPServer.
RFC 3501 sec.6.3.5: "If the name has inferior hierarchical names, then
the inferior hierarchical names MUST also be renamed." It also says:
"Any error in renaming will return a tagged NO response."
THE STEP THAT FAILED was tMaildir.RenameFolder moving the parent before
checking every descendant destination, then ignoring the result of
each child's RenameFile call. An existing B.Child could leave A.Child
behind after RENAME A B had answered OK.
RenameFolder collects the complete subtree and checks all destination
paths before moving anything, including file collisions. Every forward
move must succeed. A refusal attempts every completed move in reverse
order and returns failure, so the IMAP policy answers NO. If those
rollback moves all succeed, every directory has its original name.
A second failed move during rollback can leave names split between the
source and destination subtrees: all-or-nothing restoration of names
depends on rollback succeeding. Every rollback move is checked, and all
failed current-to-original path pairs are reported in eMailRenameError
after the remaining reverse moves and lock cleanup. The IMAP policy logs
those paths and sends a generic tagged NO. Names stay where the last
successful move left them; the error does not promise restoration.
Once the store is no longer Available no rollback move is attempted: a
store that has failed or been deactivated writes nothing more.
An ordinary failed rename preserves the source epochs and index bytes.
If a known destination-name collision requires a fresh epoch, that epoch
can remain even when names are restored, as entry 17 says.
The folder-name gate covers preflight, provenance, epoch checks and moves.
CREATE and DELETE take the same gate so cooperating hierarchy changes
cannot race the subtree snapshot.
NEW: eMailRenameError (StreamSec.Mail.Maildir).
17. FIXED, BEHAVIOUR CHANGE - a mailbox name used again after DELETE or
RENAME could make a client's cached UID name a different message
StreamSec.Mail.Maildir.
THE STEP THAT FAILED was tMaildir.LoadIndex giving a mailbox the current
Unix second as its UIDVALIDITY at its first open, with tMaildir.RenameFolder
and tMaildir.DeleteFolder keeping no record of what a name had been.
Mailboxes first opened in the same second shared an epoch; a client polling
STATUS across folders never opened before does that to many at once. After
a DELETE or a RENAME away, a new or renamed mailbox under the old name could
carry the same UIDVALIDITY. The same name, UIDVALIDITY and UID then named a
different message, and the client's cache showed the wrong mail. Present in
every release from 4.1.2.355 to 4.1.5.362.
RFC 3501 sec.2.3.1.1 item 3 says: "If the mailbox is deleted and a new
mailbox with the same name is created at a later date, the server must
either keep track of unique identifiers from the previous instance of
the mailbox, or it must assign a new UIDVALIDITY value to the new
instance of the mailbox."
RFC 9051 sec.2.3.1.1 item 3 says: "If the mailbox is deleted/renamed and a
new mailbox with the same name is created at a later date, the server
must either keep track of unique identifiers from the previous instance
of the mailbox or assign a new UIDVALIDITY value to the new instance of
the mailbox."
RFC 3501 item 4 says: "The combination of mailbox name, UIDVALIDITY, and
UID must refer to a single immutable message on that server forever."
RFC 9051 item 4 says: "The combination of mailbox name, UIDVALIDITY, and
UID must refer to a single, immutable (or expunged) message on that server
forever."
RFC 3501 sec.6.3.5 (RENAME) says: "The value of the highest-used unique
identifier of the old mailbox name MUST be preserved so that a new
mailbox created with the same name will not reuse the identifiers of
the former incarnation, UNLESS the new incarnation has a different
unique identifier validity value."
RFC 9051 sec.6.3.6 (RENAME) says: "The value of the highest-used unique
identifier of the old mailbox name MUST be preserved so that a new
mailbox created with the same name will not reuse the identifiers of
the former incarnation, unless the new incarnation has a different
unique identifier validity value."
These rules protect an earlier lifetime under a name. Neither requires
the mailbox being renamed to receive a new UIDVALIDITY. A successful
RENAME keeps each mailbox's UIDVALIDITY and message UIDs, including its
children, as 4.1.5.362 did, except for unknown target history or a known
collision with a target name's earlier UIDVALIDITY. Legacy mailboxes could
share a second-based epoch; if the earlier target had that epoch, its UID 1
could otherwise identify the incoming mailbox's different message.
That mailbox alone receives a fresh counter value; its message UIDs
and contents are kept. History is keyed by name and epoch. A -> B -> A
keeps its unique epoch: equal history then identifies the same mailbox
incarnation, including after closing and reopening the store, provided
its history is known. Unknown history, or a matching legacy epoch whose
uniqueness is unproven, requires a fresh value.
BEHAVIOUR CHANGE. Every epoch in a store written by 4.1.5.362 is such a
legacy epoch, and observing it never certifies it. The first rename-away
records it as legacy, so A -> B -> A of that mailbox now returns under a
fresh UIDVALIDITY where 4.1.5.362 kept the old one. The client discards its
cache for that mailbox once; UIDs and contents are kept.
The store-root .ss-uidvalidity-counter file records FIRST, the start of its
certified unique interval, and LAST, its allocation floor. Until uniqueness
is established, FIRST is zero; the first mint starts above existing numeric
evidence. The process keeps allocation floors and trusted intervals per
store root (entry 8 says how a root is identified). A higher remembered
floor raises only LAST on mint and cannot reset FIRST. Separate roots cannot
invalidate one another's provenance.
If the counter disappears or is damaged, remembered valid ranges and
surviving U name-history records reconstruct FIRST above unproven or
legacy evidence. Certified epochs below that interval remain provable
individually. A matching L record defeats such proof, and so does the same
epoch in a second index of the account, INBOX and its folders; the recovery
and first-mint scan, which reads every index in the store, also rejects an
epoch it finds twice. Intact history therefore keeps A -> B -> A unchanged
after counter loss, including in a fresh process; creating mailboxes in
another root cannot change that result.
Provenance genuinely cannot be recovered when a fresh process has lost
the counter before any U record survives for the mailbox. A numeric
ss-uidlist header alone cannot distinguish a uniquely minted epoch from
a shared legacy second. The first rename-away then records L. A later
return to that name with the matching unproven epoch gets a fresh value.
The same process can still preserve its remembered valid range. UNKNOWN
target history and conflicting legacy or duplicate evidence get a fresh
value in every case.
The store-root .ss-uidnames-history file records name lifetimes and
whether each epoch was unique (U) or legacy (L). Records precede DELETE, a
rename away, and a rollback away from a destination name. All historical
epochs are retained. It grows on DELETE and rename-away attempts, not
with every minted epoch, and is committed by temporary-file write and
atomic replacement while the store's cross-process .ss-rename.lock and
.ss-index.lock are held. RENAME consults each target through
OnCompareFolderName; CREATE consults its name's history before the new
index obtains a fresh counter value. A CREATE that makes a new mailbox
always receives a fresh epoch, also after a recorded DELETE or rename-away,
and commits an empty index before returning, where 4.1.5.362 wrote no index
until the first open. That distinguishes a known first identity from
recovery of a lost legacy index.
If an existing mailbox's index is missing, corrupt or unreadable, its
prior identities cannot be established. A recovered ss-uidlist retains
that fact in a HISTORY UNKNOWN trailer, which later index saves keep.
Recovery alone does not grow .ss-uidnames-history. DELETE or rename-away
records UNKNOWN there before vacating the name; a rollback also records
it before vacating a destination with no index. These records survive
restart and later known lifetimes. RENAME onto that name receives a
fresh UIDVALIDITY even if its incoming epoch has matching unique
provenance. CREATE onto it also gets a fresh counter value. This is the
second branch of item 3 quoted above. Failure to retain UNKNOWN refuses
recovery or destructive work before publishing an index or vacating the
name.
An existing unreadable or malformed index refuses RENAME and DELETE,
retaining UNKNOWN before refusal. A usable epoch header in such an index
still raises the counter. Only an index proven absent can await recovery
after RENAME. A genuine collision's replacement epoch is minted and saved
before any directory moves, so a failed move can leave that fresh epoch at
the source. An ordinary failed rename keeps its original epoch and index
bytes.
RESIDUAL LIMIT. A mailbox instance deleted under 4.1.5.362 or earlier left
no name history, and cannot be detected if its legacy UIDVALIDITY equals the
incoming renamed mailbox's. The store cannot reconstruct that missing
history. Replacing an index with an unrelated incarnation carrying an
already certified epoch is also indistinguishable when no conflicting
history or duplicate live epoch survives. The administrative restore limits
in entry 8 apply.
18. FIXED, BEHAVIOUR CHANGE - failed APPEND and COPY told clients to CREATE
destinations that already existed
StreamSec.Mail.IMAPEngine, StreamSec.Mail.IMAPServer,
StreamSec.Mail.Maildir, StreamSec.Mail.POP3Server (access adapter).
RFC 3501 sec.7.1, TRYCREATE: "An APPEND or COPY attempt is failing
because the target mailbox does not exist (as opposed to some other
reason)." It continues: "This is a hint to the client that the operation
can succeed if the mailbox is first created by the CREATE command."
THE STEP THAT FAILED was tImapSession.CmdAppend and CmdCopy prefixing every
refused APPEND or COPY with [TRYCREATE], including existing-mailbox
open/save failures and storage-policy refusals. The response gave an
incorrect recovery instruction even though its NO status correctly refused
the command. Present in every release from 4.1.2.355 to 4.1.5.362.
OpenFolder now reports missing destination separately from its reason.
The IMAP policy carries that status to APPEND and COPY, and the engine
emits [TRYCREATE] only for that case. Other refusals are plain NO with
their reason. The POP3 adapter ignores the extra open result.
BEHAVIOUR CHANGE. The text a client sees for a failed open is now fixed, for
SELECT, EXAMINE, STATUS, APPEND and COPY: "no such mailbox" for a missing
folder, otherwise "cannot open that mailbox". The store's own reason, which
4.1.5.362 sent to the client, goes to OnLog instead. A mailbox another
session renames or deletes during STATUS or APPEND answers NO "the mailbox
was renamed or deleted", and during COPY NO "the destination mailbox was
renamed or deleted"; the session stays. Losing COPY's source is the loss of
the session's own selection and ends the session with BYE.
iMailboxAccess.OpenFolder has a new out aMissing, and
iImapServerPolicy.AppendMessage and CopyMessages a new out aTryCreate;
custom implementations must supply the explicit missing-target result. The
GUIDs are now, with the other members entries 20 and 21 change:
iMailboxAccess {94FAAA5E-565E-4FA2-B477-1F56DD91800A}
iImapServerPolicy {A5F34816-8136-4B9A-834B-B04E585D79E4}
APPEND, COPY and UID COPY to a missing folder keep NO [TRYCREATE]; APPEND
and COPY to an existing folder return plain NO with the policy's reason,
and existing-folder open failures also return plain NO.
19. FIXED - RENAME INBOX was refused instead of moving its messages to a
new mailbox and leaving INBOX empty
StreamSec.Mail.Maildir, StreamSec.Mail.IMAPServer,
StreamSec.Mail.IMAPEngine.
RFC 3501 sec.6.3.5: "Renaming INBOX is permitted, and has special
behavior. It moves all messages in INBOX to a new mailbox with the
given name, leaving INBOX empty. If the server implementation supports
inferior hierarchical names of INBOX, these are unaffected by a rename
of INBOX."
RFC 9051 sec.6.3.6: "Renaming INBOX is permitted and does not result in
a tagged BAD response, and it has special behavior: It moves all
messages in INBOX to a new mailbox with the given name, leaving INBOX
empty. If the server implementation supports inferior hierarchical
names of INBOX, these are unaffected by a rename of INBOX. (Note that
some servers disallow renaming INBOX by returning a tagged NO response,
so clients need to be able to handle the failure of such RENAME
commands.)"
RFC 3501 sec.6.3.5 also says: "The value of the highest-used unique
identifier of the old mailbox name MUST be preserved so that a new
mailbox created with the same name will not reuse the identifiers of
the former incarnation, UNLESS the new incarnation has a different
unique identifier validity value."
THE STEP THAT FAILED was tMaildir.RenameFolder refusing either INBOX
argument before any move. INBOX was usable for SELECT, STATUS, APPEND
and POP3, but a client could not rename its contents to another folder.
The session policy also released its selected view before calling
RenameFolder, so a refused RENAME of the selected INBOX still cost the
issuing session its view of the mailbox. Present in every release from
4.1.2.355 to 4.1.5.362.
RENAME INBOX, in any ASCII case, now creates the absent destination and
moves each message file with its complete flag suffix and original octets.
INBOX remains present and empty, retaining its UIDVALIDITY and UIDNEXT
high-water mark. The destination receives a fresh counter UIDVALIDITY.
Message UIDs are retained within that new epoch. INBOX's inferior
names and their Maildir++ directories are untouched. The INBOX of an
account that has never had a delivery or an open, so that nothing of it is
on disk yet, can also be renamed. An empty source name is not INBOX:
RENAME "" x answers NO "RENAME needs a nonempty source mailbox".
An existing destination returns plain NO, as ordinary RENAME does;
no response code was added. The move holds INBOX's exclusive POP3
maildrop handle, so a held mbmExclusive maildrop, in this process or
another, causes NO before any message moves. The issuing session with INBOX
selected reports every actual removal as an untagged EXPUNGE, highest
sequence number first, before RENAME's tagged completion. This also applies
to a partial move that returns NO. Its selected view advances with these
reports, so the next NOOP does not repeat them. One exception: if that
rescan fails, for instance because INBOX's index cannot be written, the
command still answers as the move went, and the issuing session is told of
the removals only at its next NOOP or other rescan. Other selected INBOX
sessions retain their snapshots and learn of removals at their next
permitted rescan. Delivery still takes no mailbox lock: arrivals after the
move's snapshot can remain in INBOX.
RFC 3501/9051 sec.5.2: "A server MUST send mailbox size updates
automatically if a mailbox size change is observed during the
processing of a command." RFC 3501 sec.7.4.1 prohibits EXPUNGE "when no
command is in progress, nor while responding to a FETCH, STORE, or
SEARCH command." RFC 3501/9051 sec.5.5 permits EXPUNGE for "commands
other than FETCH, STORE, and SEARCH"; RENAME is permitted.
FAILURE AND CRASH GUARANTEE. Both complete UID maps are committed
before the first message move. The Windows index commit atomically
replaces the old index without an unlink gap; a failed publication
leaves its old UIDVALIDITY and UIDNEXT recoverable. Each subsequent
message move is one atomic rename, never copy then delete. A failed
move returns NO without rolling earlier moves back: those messages
remain at the destination and the remainder stay in INBOX. Every
message is present exactly once. A process crash between moves leaves
the same recoverable split. Rows for absent files stay in each index as
tombstones, as entry 8 describes, preserving both UIDNEXT floors and
allocated epochs. No post-move index save is needed.
Before the first message move, failure leaves all messages in INBOX;
removal of any empty, unprepared target uses only empty-directory
removals. If filesystem permissions also refuse cleanup, that empty
target remains unavailable until the filesystem problem is repaired.
After target index publication, an empty or partially filled target
can remain on failure and cannot be overwritten by another RENAME.
These guarantees require the filesystem to retain committed message,
index, counter and history metadata; they do not recover filesystem loss
or rollback. FlushToDisk retains its configured durability policy.
The declaration of iMailboxAccess.RenameFolder describes the contract.
20. NEW, BEHAVIOUR CHANGE - TsmMailStore.OnCompareFolderName lets the
application decide which folder names identify the same mailbox;
deactivating a store ends the sessions on it; a process-state exception
fails every store and ends the process
StreamSec.Mail.Maildir (TsmMailStore, tMaildir, iMailboxAccess),
StreamSec.Mail.IMAPEngine, StreamSec.Mail.POP3Engine,
StreamSec.Mail.SMTPEngine, StreamSec.Mail.IMAPServer,
StreamSec.Mail.POP3Server, StreamSec.Mail.SMTPServer,
StreamSec.Mail.Retrieval, StreamSec.Mail.Transport,
StreamSec.Mail.SMTPSpool,
StreamSec.Mobile.AsyncTLSServer, stWorkerFatal.
In 4.1.5.362 RENAME's search for child folders and LIST's prefix filter
ignored ASCII case while the folder paths did not, so on POSIX renaming A
also moved a.Child. A case-sensitive application can now distinguish A from
a: renaming A then leaves a.Child in place. Assign OnCompareFolderName to
decide equality. Its tMailCompareFolderNameEvent receives Sender, the two
names and aSame preloaded with the validated default. The default maps
ASCII A-Z to a-z explicitly, independently of locale, then compares the
lower-case names. It ignores ASCII case on case-sensitive filesystems too
and does not perform Unicode folding or normalization. Windows ASCII
folding agrees, but filesystem-specific case-sensitivity settings still
govern physical path collisions. INBOX keeps its RFC comparison rule.
Two name rules apply. A name that becomes a new path, such as a client's
CREATE or a RENAME target, must pass MailSafeSegment and MailFolderToDir:
letters, digits, '.', '_' and '-', 64 characters per segment
(cMailMaxSegment), 255 per mapped folder, no empty segment, no leading or
trailing dot and no Windows device basename, with or without an extension.
A name compared with what is on disk passes MailComparisonNameValid: at
most 254 units (cMailComparisonNameLimit; UTF-16 units on Windows, UTF-8
octets on Linux and Android, Unicode characters on Darwin), never NUL or
'/', and on Windows no control character, none of < > : " \ | ? * and no
trailing dot or space. So a directory such as .Aux or .Con.Sub, or one
another mail program left in the account, does not break the account's
folder operations; clients still cannot CREATE such a name. An invalid
full-name pair raises non-fatal eMailStoreError before any handler is
called. LIST prefix fragments are compared literally and need not be valid
complete names.
The handler must define a consistent equivalence over time: reflexive,
symmetric, transitive and stable for the life of the store's data.
Violating that contract makes the store's behaviour undefined. The store
does not prefer an exact spelling among application-equivalent names or
compensate for changes in the handler's answers.
RFC 3501 sec.5.1 reserves INBOX as the case-insensitive primary mailbox.
INBOX remains case-insensitive regardless of the handler and cannot alias
an ordinary name. INBOX.Child is an ordinary folder name; it does not
inherit INBOX's special comparison rule.
The decision covers RENAME descendants, existing and planned destination
collisions, LIST's existing prefix filter, subscription deduplication,
and every equivalent name's UIDVALIDITY provenance and UNKNOWN history.
CREATE, OPEN, DELETE and the RENAME source also resolve equivalent
names under the default or application comparison. DELETE removes only
its named folder: Maildir++ children are sibling directories and survive.
Prefix filtering compares literal prefixes of equal length; the existing
'*'/'%' stripping behaviour is unchanged. Physical path safety and
filesystem collision checks still apply.
BEHAVIOUR CHANGE, POSIX: folder names were exact paths in 4.1.5.362; the
default comparison now ignores ASCII case. When two directories on disk,
such as .Work and .work, compare equal, every operation on that name raises
eMailStoreError "ambiguous mailbox folder name" and answers NO, until they
are merged or OnCompareFolderName tells them apart.
BEHAVIOUR CHANGE: a whole mailbox directory name, such as an account's local
part or a Mailboxes entry, is checked by MailSafeSegment, which now also
refuses a trailing dot and a device basename with an extension (aux.team,
con.x). 4.1.5.362 refused only the bare device name. An account with such a
local part gets no mailbox. Folder names were already refused in these
cases, because each dot-separated segment is checked on its own. A mapped
folder name over 255 characters is now refused as well.
IMAP uses the same decision for selected-folder DELETE/RENAME,
SUBSCRIBE/UNSUBSCRIBE and the LSUB intersection. iMailboxAccess has the new
GUID {94FAAA5E-565E-4FA2-B477-1F56DD91800A} and adds SameFolderName and
Available; custom implementations must supply both.
A handler exception propagates and cancels the operation. All required
comparisons precede the first mutation, or mutations are undone. This
includes CREATE, DELETE, ordinary and INBOX RENAME, OPEN, SELECT, EXAMINE,
STATUS, LIST/LSUB, subscriptions, APPEND/COPY target resolution and
name-history lookups. The server logs the exception's class and message.
On a non-fatal exception IMAP returns a tagged NO with a generic reason;
POP3 returns a generic -ERR where it opens a folder. The handler's text
stays out of protocol replies, and the session remains usable. This rule
includes eMailStoreUnavailable raised by a handler using another store.
Disconnection depends on the session's own retained store being failed or
retired, not the exception class. iMailboxAccess.Available reports that
state without running application callbacks or accessing mailbox data.
BEHAVIOUR CHANGE: process-state exceptions are fatal to the process. The
set is EAccessViolation, EPrivilege, EStackOverflow, EExternalException and
EInvalidPointer, including descendants (stWorkerFatal.WorkerFatalException;
MailStoreFatalException answers the same). EIntError and EMathError
descendants remain non-fatal. This covers one raised by the comparison
handler; the entry on fatal handling on mail threads gives the other places.
4.1.5.362 had no such path.
Fatal handling is process-wide. It stops new commits at once, then attempts
to log the fatal class, message and exception address through every attached
server ("fatal mailbox store: ..."), then permanently latches every activated
TsmMailStore Failed. A blocked logger cannot prevent that latch.
Later store and view operations raise eMailStoreUnavailable, with no
further mail-data writes. Delivery and APPEND recheck Failed immediately
before publishing a message. Their commit rename, UID index, counter and
name-history writes share a gate with the permanent latch, so an in-flight
write is refused once the latch wins. SMTP reports temporary failure so
the sender can retry. Reactivation cannot recover the component.
Every mail component's sessions get a fixed farewell, "* BYE mailbox store
failed", "-ERR mailbox store failed" or "421 mailbox store failed", with no
folder comparison or mailbox reads, and attached IMAP/POP3 servers and SMTP
local delivery stop their listeners. Fatal shutdown closes accepting sockets
and sets an attached TsmAsyncTLSServer's Active to False without joining the
failed request worker.
Every fatal comparison hands handling to a coordinator and unwinds,
so the faulting thread releases its locks while the coordinator stops
the service. This includes mailbox-aware OnConnectionNudge callbacks
holding the TLS gate needed by farewell and reactor teardown workers.
The original exception and address remain available to fatal observers.
SMTP closes with a generic 421 only for its own unavailable store; a
handler exception from another store cancels with a generic 451.
Listener and worker objects remain alive until process termination.
A shared implicit TLS server has one deactivation owner, even when
several mail protocols request shutdown concurrently.
Healthy stop handlers finish before notification; a blocked stop is
abandoned at its deadline, rather than reported as complete.
TsmMailStore.OnFatalError is a published tMailFatalErrorEvent (Sender,
E: Exception). On Windows and POSIX, fatal handling attempts logging,
permanently marks the stores failed, requests bounded service shutdown,
then invokes every store's event on a notification worker. E is valid only
during the callback.
While mandatory fatal shutdown is pending, TsmMailStore rejects
destruction with eMailStoreUnavailable before any component cleanup.
A caller's finally block therefore cannot free coordinator state or wait
on shutdown while retaining a lock needed by farewell workers.
The handler is for an orderly stop of what the application owns,
including its Windows service; it does not permit continuation. Do not
free library components or join request threads from the callback.
The process WILL end after the handler returns, whether or not a handler
is assigned. An exception raised by the handler is offered to server
loggers and cannot prevent process termination.
Each Windows and POSIX logging, service-shutdown and event phase has a
one-second deadline (cWorkerFatalPhaseTimeout). Independent service
observers start independently, so a stuck logger or session cannot suppress
the other observers. Session broadcasts precede implicit-TLS stop attempts,
with a shared 650 ms channel-closure wait after dispatch
(cMailChannelCloseTimeoutMs), at most 16 close workers
(cMailChannelCloseWorkers) and a 750 ms shutdown-request deadline that
includes listener-stop completion (cMailShutdownRequestTimeoutMs). Fatal
shutdown does not join request workers; normal component destruction still
does. Hung work is abandoned when its deadline expires. The failed-state
latch uses the short commit gate, bounded by the one-second fatal step; a
stuck gate ends the process without further notification. It takes no
session or full-publication lock. A separate five-second watchdog
(cWorkerFatalWatchdogTimeout) is armed before any fatal-path lock or
application callback. If a phase cannot finish, the next phase proceeds; the
hard deadline still ends the process even if orchestration itself cannot
proceed.
Windows uses TerminateProcess(GetCurrentProcess, 70), not Delphi Halt or
ExitProcess: it ends blocked threads without RTL finalization, component
destruction or DLL detach callbacks that could touch corrupted state or
wait on its locks. POSIX uses _exit(70), with the same bounded phases and
an independent watchdog. Exit code 70 (cWorkerFatalExitCode) is nonzero and
is the status the TLS worker boundaries of entry 24 use.
These deadlines, the worker count and the exit status are chosen, not
measured. Short deadlines can cut off farewells and reporting; long
deadlines leave a damaged process running.
OnCompareFolderName is per store and runs on the requesting thread. It runs
under one process-wide recursive operation lock, which replaces the
per-store lock of 4.1.5.362, so a handler that consults another store cannot
invert the lock order, and a slow handler holds up every store in the
process.
BEHAVIOUR CHANGE: deactivating or freeing TsmMailStore invalidates retained
Access references and views. In 4.1.5.362 Active := False only dropped the
component's reference, and live sessions went on using the old store.
Any operation needing the comparison or store then raises a store error;
it cannot fall back to default comparison or keep using the retired store.
A view outliving its own store is disconnected even after that component
has been freed. The session logs its own store's error and disconnects:
IMAP sends an untagged BYE,
POP3 sends -ERR, and the connection closes. Such retained operations
should occur only during shutdown.
Tested on Win32 and Win64. The POSIX and mobile compilers (XE3, 10.3, 10.4,
Delphi 13) compile these units; the tests have not been run on POSIX.
21. FIXED, BEHAVIOUR CHANGE - IMAP STORE and FETCH's implicit \Seen reported
flags that were not stored and left out flags a peer had stored
StreamSec.Mail.Maildir, StreamSec.Mail.IMAPServer,
StreamSec.Mail.IMAPEngine (TsmMailStore, TsmIMAPServer).
RFC 3501 sec.6.4.6: "Normally, STORE will return the updated value of
the data with an untagged FETCH response." Its flag operations return
the resulting flags even when applying them changes nothing on disk.
The same section says: "Regardless of whether or not the ".SILENT"
suffix was used, the server SHOULD send an untagged FETCH response if a
change to a message's flags from an external source is observed."
RFC 3501 sec.6.4.8 and RFC 9051 sec.6.4.9: "A non-existent unique
identifier is ignored without any error message generated." UID STORE
therefore completes OK for missing UIDs while storing the surviving
messages, including when the selection still remembers an expunged UID.
For sequence-number STORE, RFC 2180 sec.4.2.1: "If the ".SILENT" suffix
is used, and the STORE completed successfully for all the non-expunged
messages, the server SHOULD return a tagged OK."
RFC 2180 sec.4.2.2: "If the ".SILENT" suffix is not used, and only
expunged messages are referenced, the server SHOULD return only a
tagged NO."
RFC 2180 sec.4.2.3: "If the ".SILENT" suffix is not used, and a mixture
of expunged and non-expunged messages are referenced, the server MAY set
the flags and return a FETCH response for the non-expunged messages
along with a tagged NO."
The same section advises: "After receiving a tagged NO STORE response,
the client SHOULD issue a NOOP command so that it will be informed of
any pending EXPUNGE responses."
RFC 5530 sec.3 defines EXPUNGEISSUED: "Someone else has issued an
EXPUNGE for the same mailbox. The client may want to issue NOOP soon.
[RFC2180] discusses this subject in depth." RFC 9051 sec.7.1 retains
the definition: "Someone else has issued an EXPUNGE for the same
mailbox. The client may want to issue NOOP soon. [IMAP-MULTIACCESS]
discusses this subject in depth."
RFC 3501 sec.6.4.6 defines STORE failure as
"NO - store error: can't store that data". Sec.5.5 says: "This is not a
problem for FETCH, STORE, or SEARCH commands because servers are
prohibited from sending EXPUNGE responses while any of those commands
are in progress." Sec.7.4.1: "An EXPUNGE response MUST NOT be sent when
no command is in progress, nor while responding to a FETCH, STORE, or
SEARCH command."
THE STEP THAT FAILED was tMaildirView.SetFlags computing the new flags from
the session snapshot and publishing them there without checking whether the
message-file rename succeeded. If another session had expunged the message
or changed its flags, which renames the file, or the filesystem refused the
rename, CmdStore still sent FETCH (FLAGS ...) and tagged OK: the flags were
not stored, the reported flags left out what the other session had stored,
and a refused \Deleted stayed marked in the session, so a later EXPUNGE acted
on it. The implicit \Seen of FETCH took the same path. A successful flag
change also dropped any letter in the file's Maildir info that the library
does not know. Every release with the mail suite, 4.1.2.355 through
4.1.5.362, has this.
STORE now resolves the message's current file name through PathOf and
applies +FLAGS or -FLAGS to that name's flags. FLAGS replaces them.
Unknown info letters are kept (MailMergeInfo).
A successful rename or no-op updates the snapshot to the resulting
stored flags. A non-silent command emits FETCH (FLAGS ...) for every
message stored successfully, changed or not; UID STORE includes its UID.
Under .SILENT, FETCH is sent when the pre-STORE on-disk flags differed
from the session's snapshot, reporting the resulting flags after the
operation. A failed write also reports an observed external change,
using only the persisted flags it read, before the tagged NO. A missing
message never gets FETCH.
If a peer renames the message after lookup or before the flag rename,
STORE resolves its exact base name again in new/ and cur/ and retries
against its current flags. A missing saved filename alone is never an
expunge: mfrMissing requires the base name to be absent from both
directories. Up to three total attempts (cMailStoreFlagAttempts = 3)
handle competing renames. This bound is chosen, not measured; fewer
attempts can cause avoidable STORE errors, while
more can hold a request busy longer. Exhaustion is a store error,
with observed peer flags retained, rather than false EXPUNGEISSUED or
a skipped update under .SILENT or UID STORE. A selection whose mailbox was
renamed or replaced elsewhere ends with "* BYE selected mailbox was renamed
or deleted, have to disconnect" rather than a false success.
A referenced message already expunged by another session is skipped.
Non-silent sequence-number STORE still processes surviving messages,
reports their resulting flags, and finishes NO [EXPUNGEISSUED]. Its
.SILENT form finishes OK if every non-expunged message was stored
successfully, including when every target is gone. UID STORE ignores
missing UIDs and completes OK when every surviving target succeeds,
with or without .SILENT. Neither form emits EXPUNGE; the snapshot keeps
its sequence numbers until the next permitted rescan, such as NOOP.
RFC 3501 permits EXPUNGE during UID commands; this server also defers it
for UID STORE.
Other rename failures are logged and finish tagged NO, including with
.SILENT. If peer flags were observed, the snapshot retains those flags
and FETCH reports them before NO, so NOOP cannot silently consume the
change. Without an external change, a refused write emits no FETCH.
Successful stores to other messages remain applied and are reported
under the rules above. A filesystem failure is not EXPUNGEISSUED.
POP3 DELE still marks in memory and commits the marks only at QUIT.
BEHAVIOUR CHANGE: a client now gets tagged NO where 4.1.5.362 answered OK:
NO [EXPUNGEISSUED] from a non-silent sequence-number STORE that names an
expunged message, and NO for a refused rename.
SetFlags returns tMailFlagResult: mfrUnchanged, mfrChanged, mfrMissing
or mfrFailed. Its optional final aExternalChanged: PBoolean reports
observed external flags for changed, unchanged and failed writes.
The flag and the observed snapshot survive a refused rename. The view
returns the first three outcomes; filesystem errors raise eMailStoreError,
which the server policy logs and translates to
mfrFailed. iMailboxView has new GUID
{BF42CE71-9C04-482B-9575-A331F1487E98}; iImapServerPolicy has new GUID
{A5F34816-8136-4B9A-834B-B04E585D79E4}. Custom implementations must return
the per-message outcome.
FETCH of BODY[...], RFC822 or RFC822.TEXT reports the current flags when
its implicit \Seen observes flags persisted by another session. This
includes an unchanged result when the peer already stored \Seen, and
observed peer flags retained after a refused \Seen write. The reported
flags come from the refreshed snapshot, never the unapplied request.
This applies to FETCH and UID FETCH, with or without an explicit FLAGS
item. Missing messages do not cause an extra flag report.
RFC 3501 sec.5.2: "A server SHOULD send message flag updates automatically"
when it observes external changes. Section 6.4.5: "The \Seen flag is
implicitly set"; changed flags "SHOULD be included as part of the FETCH
responses." FLAGS describes "The flags that are set for this message."
RFC822 is equivalent to BODY[] and RFC822.TEXT to BODY[TEXT].
--------------------------------------------------------------------------------
TLS SERVER CERTIFICATE REPLACEMENT AND FILE RELOAD
================================================================================
These changes preserve signed certificate data, publish complete TLS serving
identities together, and let applications follow local PFX publications.
22. FIXED, BEHAVIOUR CHANGE - PKIX issuer and CA queries preserve signatures
StreamSec.DSI.PkixCert.
THE STEP THAT FAILED was IsAllegedIssuer reading a missing authority-key-
identifier through an accessor that created it in the queried certificate's
to-be-signed part. IsCA similarly created missing basic constraints. Filing
an in-process generated certificate through AddCertificate or
ReplaceTLSServerCertificate could alter its signed bytes and leave a broken
signature. These queries now inspect existing extensions and issuer names.
For mutable certificates (not ReadOnly, or Modified), absent AKI now permits
issuer-name matching; absent basic constraints preserves the keyCertSign
answer. IsAllegedIssuer(nil) returns False instead of failing. ReadOnly,
unmodified certificates decoded from files did not suffer this mutation.
Issuer matching considers every authorityCertIssuer directory name.
23. FIXED, BEHAVIOUR CHANGE - TLS replacement publishes complete engine caches
StreamSec.Mobile.StreamSecII, StreamSec.Mobile.TlsInternalServer,
StreamSec.Mobile.AsyncTLSServer.
THE STEP THAT FAILED was replacing an earlier serving slot before a later
slot had finished preparing its chain. An exception could leave one engine
serving a mixture of identities. This shipped in 4.0.1.345 through
4.1.5.362. Preparation now completes before that engine publishes any slot.
Async replacement fans out shard by shard under each engine's TLSLock; a
later shard failure can leave earlier shards serving the new identity. This
guarantee covers serving-cache rows only. Key/certificate/CA/CRL filing and
key-pair/cipher-suite options can change before replacement and remain
changed if a later step refuses. Import and replacement are separate calls.
Concurrent writers can leave a lasting mixture across shards; use one
writer per target or serialize all writers externally.
ReplaceTLSServerCertificate now raises for a nil certificate or key, an
unsupported public-key algorithm, or a leaf that fills no row
TLSSetupServer would populate. Callers must handle these refusals.
THE STEP THAT FAILED for an EC leaf was treating keyAgreement as an
alternative to digitalSignature. A leaf allowing both, or omitting
keyUsage, could miss ECDHE/TLS 1.3 slots after replacement even though
TLSSetupServer selected it. This shipped in 4.0.1.345 through 4.1.5.362.
Replacement now uses the same signing-slot placement as initial setup.
Existing name/algorithm replacement rules remain in effect; selected
sessions retain their certificate/key references.
24. FIXED, BEHAVIOUR CHANGE - OCSP warming follows publication and joins
StreamSec.Mobile.StreamSecII, StreamSec.Mobile.TlsInternalServer,
stWorkerFatal.
THE STEP THAT FAILED was warming OCSP after committing a new certificate but
allowing an ordinary warm-up exception to report the whole swap as failed.
Start/stop also raced, and component destruction freed stores before joining
a worker that used them. These defects shipped in 4.1.1.350 through
4.1.5.362. Warm-up now starts after publication, contains and reports
ordinary worker errors, serializes warm-up requests, and joins before store
destruction. Each worker exits after its queued passes; publication does not
join an earlier fetch. Warming uses the assigned Ocsp component with its
descendant state, TrustedCertificates, linked stores and hooks, without
copying RootCerts. Changing or detaching Ocsp, including destruction
notification, waits for the in-flight fetch. Its Timeout bounds each read,
not the total exchange; slow-drip peers and custom descendants can extend
the wait without a finite total bound. Custom descendants must detach Ocsp
before their destructor frees state used by CheckCertificate. Configure
OnWorkerError for logging; Sender is the TLS component. Ordinary
post-publication scheduling failures are contained without calling
application events. The five process-state classes raised while scheduling
instead propagate on the publishing caller, without worker reporting or
automatic exit. The cache is already committed. If the caller is the
reloader worker, its own outer worker boundary handles the fault.
Process-state faults reaching the OCSP warm-up worker boundary now log,
notify OnWorkerFatal and terminate the process with exit code 70. The
classes are EAccessViolation, EPrivilege, EStackOverflow, EExternalException
and EInvalidPointer. Arithmetic errors, Ctrl-C and EOutOfMemory are
excluded. This boundary covers the warm-up worker only. Handshake staple
fetches swallow exceptions as before and call no worker event.
AddCertificate, ValidateMyCert and destructor wrappers retain ordinary
caller behavior. The NEW unit stWorkerFatal adds tWorkerFatalEvent,
WorkerFatalException, EndProcessAfterWorkerFatal, cWorkerFatalExitCode,
cWorkerFatalPhaseTimeout and cWorkerFatalWatchdogTimeout for the bounded
worker-fault sequence. OnWorkerError also observes its fatal LOG phase.
OnWorkerError and OnWorkerFatal are new events on TsmStreamSecII and
TsmCustomTLSInternalServer, republished on TsmTLSInternalServer and
TsmSimpleTLSInternalServer; both default to nil. The TsmStreamSecII
extension surface adds protected IsStapleWarmupWorker, virtual
WarmupTLSServerStaples and virtual ExportTLSServerCertificateChain.
TTLSCertArray now uses the public tTLSCertRow dynamic row type;
pTLSCertArray points to that array. InternalAddTLSServerCert has the extra
optional preparation argument used by per-engine publication. Each observer
has a chosen, not measured, 1000 ms deadline; a chosen, not measured, 5000
ms watchdog bounds stalled dispatch. Short deadlines can truncate reporting;
long deadlines leave a damaged process running.
25. NEW - PFX followers replace certificates on registered TLS components
StreamSec.Mobile.CertificateReload, StreamSec.Mobile.TlsInternalServer,
StreamSec.Mobile.AsyncTLSServer, CertificateReload.txt.
New public API includes tCertificateReloader, tCertificateReloadFile,
tCertificateReloadLogKind, tCertificateReloadLogEvent, eCertificateReload,
eCertificateReloadRead. Log kinds are crlkAccepted, crlkRejected,
crlkRecovered, crlkWarning and crlkDebug. The cCertificateReload* limits are
listed by name in CertificateReload.txt. The reloader has AddTarget
overloads, AddFile, ValidateSnapshot (protected), CheckOnce, Start, Stop,
HostNames, PollIntervalMs, Running, LogCallback and FatalCallback; file
state exposes Path, CurrentCertificate and AcceptedFingerprint.
TsmAsyncTLSServer.AddLocalCertificate files chain CAs using each shard's
startup trust and duplicate-key-identifier defaults. The protected
StoreReloadCertificate and StoreReloadCRL methods on both TLS components
retain startup filing semantics under each engine's setup lock and
TLSLock. TsmAsyncTLSServer adds protected EngineGeneration so CheckOnce
detects a recreated bank without opening an unchanged PFX on idle polls.
Every certificate bag's variable-size IF/DL key operands are bounded
before verification or filing, including CAs outside the leaf chain.
TsmCustomTLSInternalServer.ImportFromPFX(const aContent: TBytes; aPassword:
iSecretKey) imports closed snapshot bytes.
tCertificateReloader follows independent RSA/ECDSA PFX paths and passwords
with application-supplied host names. Initial provisioning remains
ImportFromPFX plus TLSSetupServer. Runtime internal-server import consumes
the validated snapshot bytes before ReplaceTLSServerCertificate. Async
targets file the private key on every shard before the leaf, then call
ReplaceTLSServerCertificate. This is the reloader's internal key-store path;
applications need not call the protected StorePrivateKey surface. Key-first
filing puts the leaf in MyCerts. All parsed bags reach startup store
methods, including CAs outside the leaf chain and each engine's startup
trust rule. CRL bags: see entry 27. Parsing and PKCS#12 KDF/decryption
finish before engine mutation locks.
Polls inspect metadata without opening the PFX. Windows lists the parent
directory for file identity, size and write/change times; this requires
FILE_LIST_DIRECTORY permission. Watched paths must be regular files; Windows
reparse points are refused. Existing 8.3 paths resolve to long names.
Reliable detection requires local NTFS; FAT/exFAT, ReFS and network shares
are outside this metadata contract. On NTFS, identity detects replacement
with preserved size and last-write time. POSIX stat supplies device/inode
and subsecond write/change times. A file differs from accepted content until
every target has applied it. Each check-up may make one exclusive-read
attempt while it differs; sharing/lock conflicts defer at debug level until
the next check-up. Other open/lock errors warn once per distinct reason.
Publisher replacement can fail during the exclusive read and should retry.
Bytes-only failures are memoized and cause no reopen until metadata changes.
Accepted, unchanged files cause no read. Persistent metadata failures warn
once until recovery. Snapshots close before parsing. POSIX locking is
advisory; rename and noncooperating native opens are not excluded. Only
regular files are read.
MAC, leaf/key, chain and TLS usage checks precede replacement. The target
can use issuers already in its store, as startup import does. A missing
configured DNS name is applied with a warning naming it. Leaf validity
follows startup import and the process validity-enclosure policy. Failed
targets retry each poll; successful targets are not reapplied. Recovery is
logged only when every target serves the accepted identity. Start after a
prior run clears per-target apply state, so recreated async shards receive
unchanged watched content again. Chain and revocation checking retain the
startup engine policy and fetch behavior. TsmAsyncQUICServer is not a reload
target.
Chosen, not measured defaults: poll 5 s, expiry warning 14 days, bounded
Stop 10 s. Short polling adds metadata I/O; long polling delays adoption.
Short Stop may return while work is still in progress; long Stop delays
shutdown. Stop records its warning through LogCallback when its callback
lock can be taken immediately, otherwise through a native diagnostic. POSIX
diagnostics write directly to descriptor 2. Fatal logging uses that
diagnostic immediately if the logger lock is busy. LogCallback calls never
overlap; FatalCallback can overlap a stuck logger so notification remains
bounded. Retain dependencies until the worker finishes. Only process-state
faults reaching the polling worker use the same bounded exit-70 mechanism as
OCSP. Synchronous CheckOnce retains caller behavior.
Chosen, not measured validation limits: 4 MiB snapshot, 32 certificates, 64
bags, ASN.1 depth 32 and 65536 nodes, 1000000 KDF iterations and 2000000
aggregate work, 64 MiB scrypt memory, 1024 derived bytes, 8192 key bits,
2048 group words. Smaller limits reject files; larger limits increase
memory, parsing, cryptographic work and shutdown delay. The operational note
gives every named constant and its tradeoff.
--------------------------------------------------------------------------------
TLS: CERTIFICATE CHECKS, FATAL ALERTS AND THE CLOSE CONTRACT
================================================================================
26. FIXED, BEHAVIOUR CHANGE, NEW - TLS clients check every server
certificate's identity and usage and never complete a refused session;
a fatal alert ends a session on both roles, and close_notify is
tracked per direction
StreamSec.Mobile.TlsLayer, StreamSec.Mobile.TlsClass, StreamSec.Mobile.Tls,
StreamSec.Mobile.TlsInternalServer, StreamSec.Mobile.StreamSecII,
StreamSec.Mobile.AsyncTLSServer, StreamSec.Mail.Transport,
StreamSec.Snip.TLSOctetConnection, StreamSec.Mobile.TLSClient,
StreamSec.Snip.TLSClient, StreamSec.Http.Client, StreamSec.Mobile.HTTPS,
StreamSec.Mobile.AsyncTLSReactor (and its IOCP and Poll backends),
StreamSec.Mobile.TlsChainProbe (a comment only); TLS.txt,
AsyncTLSServer.txt.
THE STEP THAT FAILED was the TLS 1.3 client's certificate validation: it
never ran the server-certificate extended-key-usage (EKU) and key-usage
check that the TLS 1.2 path runs. A TLS 1.3 client therefore accepted a
certificate from a trusted CA whose EKU did not allow server authentication
or whose keyUsage did not allow digitalSignature. When the EKU listed
serverAuth or the Netscape server OID, it also accepted a certificate whose
Netscape certificate type did not allow SSL server. Releases 4.1.0.348
through 4.1.5.362 carried this TLS 1.3 defect.
TLS 1.2 skipped the usage check when the engine already knew the certificate
([crcTrusted]), in releases 4.0.1.313 through 4.1.5.362. 4.0.1.313 is the
first StreamSec Tools 4 release tag carrying StreamSec.Mobile.TlsLayer; the
4.0 beta tags 0.276 through 0.312 do not. A server certificate the
application trusted explicitly always received [crcTrusted], so its usage
was never checked, even on the first handshake.
A certificate that failed the check was removed from the engine's store when
the alert handler returned normally, so a later connection checked it again.
When the handler raised instead - the TsmCustomTLSInternalServer default
when no OnTLSOutgoingAlert handler is assigned - the removal was skipped,
and a later connection on the same engine accepted the certificate without
the check. TsmTLSClient, TsmHTTPSClient and the mail clients keep one engine
for all their connections and assign no alert handler. The same applied when
the engine already held the certificate for another reason.
Both versions now run the same usage check on every server certificate,
including one already known to the engine or trusted explicitly. If the
certificate has an EKU it must allow server authentication. Only when the
EKU lists serverAuth or the Netscape server OID must the Netscape
certificate type allow SSL server. TLS 1.2 retains its key-exchange usage
rules; TLS 1.3 requires digitalSignature when keyUsage is present (RFC 8446
section 4.4.2.2). Both versions stop after the first fatal certificate
alert: only the first failing check reaches the alert handler, LastAlertCode
and the wire (BEHAVIOUR CHANGE for TLS 1.2, which used to run every check,
call the handler for each failure, write an alert record for each into
Response and leave the last code in LastAlertCode).
BEHAVIOUR CHANGE: a certificate that fails these checks is no longer removed
from the engine's store. A leaf the client refuses now stays in
CollectedCertificates, and an application that saves that store saves it
too.
Both versions now apply one identity rule. A certificate is likely meant for
several purposes and several locations, so when at least one of
DNSNameToCheck, IPToCheck and URIToCheck is set, the certificate must match
at least one of the configured values; one that matches none is refused with
one fatal certificate_unknown alert. TLS 1.3 used to check DNSNameToCheck
only, and TLS 1.2 checked each configured value on its own. These checks run
regardless of whether the engine already knows the certificate.
BEHAVIOUR CHANGE, TLS 1.2: a certificate that matches none of the configured
names is now refused with a FATAL certificate_unknown alert that ends the
handshake. Through 4.1.5.362 each mismatch was a warning: only the
TsmCustomTLSInternalServer default, which raises, stopped the handshake, and
an application with an alert handler that only logged connected to a server
whose certificate did not match the configured name. These checks date from
in-house RPC use, where the certificate chain alone identified the peer;
client-side HTTPS needs the name check to fail closed. An application that
wants no identity check leaves DNSNameToCheck, IPToCheck and URIToCheck
empty. URIToCheck is matched against URI subjectAltNames and then the
subject CN only, never against dNSName subjectAltNames: an application that
puts a host name in URIToCheck as its only configured name is now refused on
both versions whenever the certificate names the host only in a dNSName
subjectAltName. A host name belongs in DNSNameToCheck.
ALERT DOWNGRADE stays: an outgoing alert handler that sets Fatal := False on
a certificate alert (bad_certificate, unsupported_certificate,
certificate_unknown, certificate_expired, certificate_revoked) still sends
it as a warning. It is for testing only - do not use it in production. A
downgraded identity (name, IP, URI) or usage alert lets the handshake go on
with the certificate the client refused, which then counts as accepted. A
downgraded chain-validation alert leaves no certificate accepted: TLS 1.3
then ends the handshake with unexpected_message at CertificateVerify; TLS
1.2 (EC)DHE suites go on with a ServerKeyExchange whose signature is not
checked, and static RSA ends with internal_error at ClientKeyExchange. On
TLS 1.2 the handshake goes on only with a peer that honours the warning
level, such as this library's server when its OnTLSIncomingAlert handler
does not raise on a warning (TsmCustomTLSInternalServer's default handler
raises on every alert except close_notify). On TLS 1.3 a downgraded alert is
a warning-level error alert, which RFC 8446 section 6 forbids ("All the
alerts listed in Section 6.2 MUST be sent with AlertLevel=fatal and MUST be
treated as error alerts when received regardless of the AlertLevel in the
message"), so a conforming TLS 1.3 peer, this library included, closes the
connection on receipt: the downgrade changes only what this side sends. On a
server session a downgraded alert leaves no client certificate
(ClientCertificate nil). The alert events now say so.
BEHAVIOUR CHANGE, TLS 1.3: a received error alert now ends the session
whatever its level, as RFC 8446 section 6 requires. Through 4.1.5.362 a
warning-level error alert from the peer left the session open. The only
other closure alert, user_canceled, is reported to the incoming alert event
with Fatal = False and the session goes on: the consumer decides, and closes
if it does not want to go on. TLS 1.2 is unchanged: the alert's own level
decides.
BEHAVIOUR CHANGE in both versions: callers can now receive a certificate
alert for an explicitly trusted or already known server certificate whose
EKU or keyUsage does not allow server authentication. TLS 1.3 also refuses a
certificate whose EKU, conditional Netscape certificate type or keyUsage
fails these rules, where releases 4.1.0.348 through 4.1.5.362 accepted it.
TLS 1.3 connections now fail when the certificate matches none of the
configured DNSNameToCheck, IPToCheck and URIToCheck values.
BEHAVIOUR CHANGE, TLS 1.2: rejecting a server certificate for EKU,
conditional Netscape certificate type or key usage no longer clears the
session's ServerCertificate, so it stays readable after the handshake fails
(an alert handler already saw it). In 4.1.5.362 only TLS 1.2 cleared it,
only for a certificate new to the engine, and only when the outgoing alert
handler returned normally. A bare TsmStreamSecII without an assigned handler
returns normally; TsmCustomTLSInternalServer's default raises and left the
certificate set. TLS 1.3 had no usage check and no such clear. A TLS 1.2
chain-validation failure still leaves ServerCertificate nil on a first
handshake: no validated certificate was returned to keep. An empty or
unparseable renegotiation Certificate, or a failure before that message, can
leave the previous certificate readable.
NEW: ServerCertificateAccepted on the content layer, and
GetServerCertAccepted on TAbstractTLSSocket, say whether the client accepted
the server's certificate in the current handshake. Code that tested
ServerCertificate for nil to learn that tests this property instead. It is
also False after a name, IP or URI mismatch, after a rejection under a
raising handler, after a TLS 1.2 ServerKeyExchange key-type rejection and
after a TLS 1.3 CertificateVerify scheme rejection for an EdDSA or ML-DSA
key, where ServerCertificate stays set. Only an identity or usage alert the
handler downgrades (testing only) lets a failed check count as accepted. The
flag is False when a client handshake starts and while the certificate
checks run. A resumed session sends no certificate: on a TLS 1.3 PSK
resumption and on a TLS 1.2 session-ID resumption the flag is False and
ServerCertificate nil, with Encrypted and IsResumedSession True. During a
failed TLS 1.2 renegotiation Encrypted still describes the earlier
handshake; read Active and LastAlertCode as well.
A SECOND STEP FAILED: Connect on a TLS 1.3 client session whose handshake
had already been refused. Connect kept that handshake's keys, transcript and
server certificate and started nothing new, so a server holding the refused
certificate's key could send CertificateVerify and Finished, and the session
became Encrypted with the certificate the client had refused. It took an
application that called Connect again on the refused session, for example
TLSConnect with the same UserData after a raising alert handler had left the
session registered. In releases 4.1.0.348 through 4.1.5.362 a TLS 1.3 client
kept the certificate after refusing it for a host-name mismatch, so those
releases carried this defect.
Connect now refuses a client session that ended with a fatal alert, this
side's Close or the peer's close_notify, also when an earlier Connect raised
before any handshake state was kept: it returns -1, writes nothing, leaves
Active as it is and keeps LastAlertCode, a recorded close_notify (code 0)
included; it sets unexpected_message only when no alert at all was recorded.
No alert record is sent and no alert handler is called, because the
connection is already closed. Accept on a client session returns -1 and
writes nothing before it touches the session, and leaves LastAlertCode as it
is. The TLS 1.3 client takes the server's flight in the order of RFC 8446
section 2 - EncryptedExtensions first, then CertificateRequest, Certificate,
CertificateVerify and Finished, each once - and processes a
CertificateVerify only after a server certificate it accepted in the same
handshake; a PSK-resumed handshake takes no Certificate, CertificateRequest
or CertificateVerify, and after the handshake only NewSessionTicket and
KeyUpdate are taken. The TLS 1.3 server takes EndOfEarlyData only once,
before the client's Finished and after accepted 0-RTT, and refuses any other
message type in the client's flight. Any of these out of place ends the
handshake with unexpected_message (RFC 8446 section 4); a KeyUpdate received
before the handshake completes ends it the same way on both roles (section
4.6.3).
BEHAVIOUR CHANGE: Connect on a client session that ended returns -1 and
writes nothing, on both versions; a raising alert handler no longer raises
on that call. Connect while a client handshake is in progress, including a
TLS 1.2 renegotiation before its ChangeCipherSpec, returns -1 and leaves
that handshake alone; it used to end it with unexpected_message or, on TLS
1.3 after the ServerHello, discard part of its state. Connect on an
established TLS 1.3 session now does nothing (it used to discard buffered
handshake state). Starting a renegotiation on an established, idle TLS 1.2
session is unchanged. A first Connect that raised without ending the session
now leaves no handshake state, so it can be retried on the same session; one
that raised on a fatal alert cannot. A TLS 1.3 handshake message out of
place (above), on either role, now ends the session; it used to be processed
or ignored.
A THIRD STEP FAILED: completing a TLS 1.2 handshake after its Finished check
had failed. When the peer's Finished did not verify, the client (and the
server) sent a fatal decrypt_error, and, when the alert handler returned
normally, still marked the handshake done: the session reported Encrypted,
OnHandshakeDone fired, and a server called Accept again, which re-activated
the session. Releases 4.0.1.313 through 4.1.5.362 carried this. A fatal
alert now ends Finished processing on both sides (RFC 5246 section 7.2.2),
and a TLS 1.3 client that sends a fatal alert while building its flight
sends no Finished. A TLS 1.3 server that sends a fatal alert while writing
its ServerHello or HelloRetryRequest or while building its flight (no usable
certificate, a failed signature) stops there too: it computes no Finished
and installs no application keys, which on QUIC used to reach the transport.
A fatal alert while the TLS 1.3 server sends its NewSessionTickets stores no
further ticket and fires no OnHandshakeDone.
TLS 1.2 SESSION IDS: a client stored a resumable session when the server's
ChangeCipherSpec arrived, before it verified the server's Finished, and no
fatal alert ever removed a stored session. RFC 5246 section 7.2.2: "any
connection terminated with a fatal alert MUST NOT be resumed".
TsmStreamSecII now stores the session when the handshake completes, on both
roles, once per SessionID (a resumed TLS 1.2 client used to add a second
copy). When a connection ends with a fatal alert the engine forgets the
stored sessions that connection itself stored or resumed - after a
renegotiation the earlier session too - and only those: never one matched by
a session ID the peer chose, which a TLS 1.2 client takes from the
unauthenticated ServerHello. The layer does this itself, so it also holds
for a session taken out of the engine and driven directly
(TAbstractTLSSocket, TsmAsyncTLSServer, the mail transport). Releases
4.0.1.313 through 4.1.5.362 carried this.
ALSO FIXED, session cache: TsmStreamSecII handed a resuming handshake a
pointer to the stored session and released its lock before the handshake
read it, so a stored session that expired, or that another connection's
fatal alert forgot, could be freed while a concurrent resumption still read
its master secret (releases 4.0.1.313 through 4.1.5.362, through expiry).
The handshake now gets a copy taken under the lock and frees it after use.
NEW: TCustomTLSSession.Origin is set on such a copy and names the stored
session; a handshake frees a session an OnRenegotiate handler hands out only
when Origin is set.
BEHAVIOUR CHANGE: a TLS 1.2 client whose offered session the server resumes
now reports IsResumedSession True, as a TLS 1.2 server and a TLS 1.3 client
already did. This holds for a session offered from the engine's own session
cache (TsmStreamSecII); a session an application's OnRenegotiate handler
supplies itself is not marked.
A FOURTH STEP FAILED: EncodeData checked only that a write key existed. A
TLS 1.3 client whose handshake was still running, or had been refused,
encrypted application data under its handshake key; a TLS 1.2 endpoint
encrypted it after its own Finished, before the peer's, on the first
handshake; and any session went on encrypting after a fatal alert (TLS 1.3
from 4.1.0.348, TLS 1.2 from 4.0.1.313, through 4.1.5.362). RFC 8446 section
6.2: "Whenever an implementation encounters a fatal error condition, it
SHOULD send an appropriate fatal alert and MUST close the connection without
sending or receiving any additional data." RFC 8446 section 2: "Application
Data MUST NOT be sent prior to sending the Finished message, except as
specified in Section 2.3."
THE CLOSE CONTRACT, documented on the new Closed property: a session that
sent or received a fatal error alert is Closed for good. The call that
produced or read the alert returns its normal result unless an alert handler
raised, and the alert record it sent is the last thing in its Response, also
when a handler raised. The consumer writes those bytes, writes nothing else
- it discards any data it still had queued for the peer - and closes the
transport. From then on DecodeData discards its input and returns -1, and
EncodeData, Close, KeyUpdate, Connect and Accept return -1; none of them
writes a byte or calls an alert event. EncodeData also returns -1, writing
nothing, before the first handshake completes (RFC 5246 section 7.3:
"Application data MUST NOT be sent prior to the completion of the first
handshake"); a TLS 1.2 renegotiation does not stop it. The TLS 1.3 server's
0.5-RTT window (after its Finished, before the client's) is the one
exception; client 0-RTT data goes through EarlyData with the ClientHello,
never through EncodeData. An alert an OnOutgoingAlert handler downgrades to
a warning (testing only) closes nothing.
THE CLOSE_NOTIFY STATE MACHINE: close_notify is not an error and goes out at
warning level. Like ChangeCipherSpec in TLS 1.2 it is tracked per direction,
by one handler used by Close and by the received alert, and Active becomes
False only once both directions are closed, in either order. After this
side's Close (CloseNotifySent) it sends nothing more - EncodeData, KeyUpdate
and Connect return -1, a second Close returns 0 - and still reads every
record of the peer: data, alerts, a TLS 1.3 KeyUpdate or NewSessionTicket; a
new handshake from the peer (a TLS 1.2 HelloRequest) is ignored. After the
peer's close_notify (CloseNotifyReceived), at either level, nothing more is
read (RFC 8446 section 6.1: "Any data received after a closure alert has
been received MUST be ignored"); data that came before it in the same input
is still delivered. TLS 1.3 may still send data and then its own
close_notify (section 6.1: "Either party MAY initiate a close of its write
side of the connection"); TLS 1.2 only answers with its own close_notify,
and EncodeData returns -1 (RFC 5246 section 7.2.1: "The other party MUST
respond with a close_notify alert of its own and close down the connection
immediately, discarding any pending writes"). Neither direction sets Closed.
BEHAVIOUR CHANGE: after a fatal alert, and before the first handshake
completes, EncodeData returns -1 and writes nothing where it used to
encrypt; Close writes no close_notify after a fatal alert; DecodeData on a
Closed session discards its input; Accept on a Closed server session returns
-1 instead of restarting it, and so does Accept on a server session after
either side's close_notify; it used to re-activate the session and handle a
new ClientHello.
BEHAVIOUR CHANGE, close_notify: this side's Close sends close_notify at
warning level on both versions; it used to go out at fatal level, which
under RFC 5246 section 7.2 ("Alert messages with a level of fatal result in
the immediate termination of the connection" and "the session identifier
MUST be invalidated") ends the session for a TLS 1.2 peer. The
OnOutgoingAlert event now reports it with Fatal = False, and OnIncomingAlert
likewise reports a received close_notify with Fatal = False at either level.
A received close_notify at either level now ends reading; a warning-level
one from another TLS stack used to let the records after it through, and one
at fatal level (from this library) set Active False at once. Active now
stays True until both close_notify alerts are processed, so
TsmStreamSecII.TLSDecodeData keeps a session after the peer's close_notify
and TLSClose can answer it. A consumer learns of the peer's close from
CloseNotifyReceived, not from Active. TsmAsyncTLSServer first hands its
session every byte that came before the close_notify, also when the session
has paused receiving, then answers: at once on TLS 1.2, on TLS 1.3 when the
session closes or the idle deadline expires (IdleTimeout, or 30 seconds when
IdleTimeout is 0). A FIN that follows the close_notify, or a FIN alone, ends
the connection at once, without this side's close_notify, unless the session
implements the new iAppSessionShutdown (below): then the connection stays
open for sending until the session closes or that deadline expires. The mail
transport returns that data first, answers at once on TLS 1.2 and, on TLS
1.3, after the reply to that data; a close_notify that came with the last
read of STARTTLS is answered by the first read after it. TAbstractTLSSocket,
also when the close_notify came with the last handshake read, and the snip
TLS octet connection answer and disconnect; after a warning-level
close_notify (the level other TLS stacks use) they used to stay connected
until the TCP connection closed, because they watched only Active.
TsmCustomTLSClient, the snip TLS client and tHttpTransport end their
handshake on the peer's close_notify instead of reading on until a timeout;
after the handshake they still learn of the peer's close only from the
transport. This side's close_notify sent before the handshake completed (the
acme-tls/1 validation handshake, or Close mid-handshake) ends the session at
once: there is nothing left to half-close. TLSClose still releases a session
after sending this side's close_notify, so the peer's records after it are
not read through the UserData and SessionID calls; to read them, drive the
content layer directly. After this side's Close, DecodeData now reads every
record of the peer; it used to stop after the first and dispatch nothing, so
the peer's close_notify went unreported and a TLS 1.3 KeyUpdate left the
session unable to read.
NEW: Closed, CloseNotifySent and CloseNotifyReceived on the content layer.
NEW: iAppSessionShutdown, an optional companion to iAppSession that
TsmAsyncTLSServer finds with Supports, as it finds iAppSessionDrain.
ReceiveClosed says nothing more will be delivered: after the peer's
close_notify, or a FIN without one, it comes once every octet before it
reached DataReceived (after a TLS 1.2 close_notify the server answers and
closes as soon as ReceiveClosed returns, and a Send from it is dropped, RFC
5246 section 7.2.1); on a fatal alert or teardown it comes with SendClosed,
and data still parked for a paused session is discarded. SendClosed says
this side can send nothing more (its close_notify went out, a fatal alert,
or the connection is going away). Each comes at most once, and both before
iAppSession.Closed, which is still the last call. For a session that
implements it the server keeps the connection open for sending after a FIN,
so a reply to a request the peer sent before half-closing still goes out,
followed by this side's close_notify; the session's Close(True) ends it, or
the idle deadline (30 seconds when IdleTimeout is 0, kept armed across
completed sends), which asks the session and the application again and
closes only if they do not answer nvKeepAlive; after the peer's close a
keep-alive with aRearmMs 0 is asked again every 30 seconds instead of
leaving deadline scope. iAppSession and sessions that do not implement the
new interface are unchanged. The HTTP/1.1 session implements it: once the
peer has finished, it closes after the last response it can answer, or at
once when no response is leaving (a partial request still buffered can never
complete). BEHAVIOUR CHANGE for HTTP/1.1: a client that half-closes after
its request gets the response, where the FIN used to end the connection at
once.
NEW, test builds only: TTLS_ContentLayer.TestHandshakeMessage, which hands
one plaintext handshake message to the handshake layer, exists only in
builds that define STREAMSEC_TLS_TEST_HOOKS; the packages do not.
ALSO FIXED: reading ServerCertificate or ClientCertificate before Connect or
Accept raised an access violation; both now return nil. TAbstractTLSSocket's
GetServerCertDNSName, GetServerCertIP and GetServerCertURI kept the first
non-empty answer for every later connection on the same socket object; they
are cleared when a new connection starts. A stored TLS 1.2 session left its
master secret in freed memory; every session object, stored or handed out
for a resumption, now wipes it when it is freed.
Client-certificate checks were already right in both versions: a certificate
without EKU is accepted, otherwise clientAuth is required. They are
unchanged.
--------------------------------------------------------------------------------
PKCS#12: CRL BAGS
================================================================================
27. FIXED, BEHAVIOUR CHANGE - X.509 CRL bags reach PKCS#12 consumers
StreamSec.DSI.Pkcs12, StreamSec.Mobile.TlsInternalServer,
StreamSec.Mobile.CertificateReload; AsyncTLSServer.txt,
CertificateReload.txt.
THE STEP THAT FAILED was selecting the x509CRL bag value as a plain
OCTET STRING. AsX509Crl returned nil instead of the enclosed
CertificateList. This mapping shipped from 4.0 PREVIEW 0.282 through
4.1.5.362. tPFX.CopyTo passed nil to StoreCRL, so no PFX CRL ever reached
a store: TLS ImportFromPFX (file and bytes), TsmAsyncTLSServer startup and
tCertificateReloader filed keys and certificates without the CRL, and the
file imports also skipped every certificate bag after the CRL bag.
iSafeContents.ImposeCRL, tPFX.StoreCRL and TLS ExportToPFX - whenever
MyCerts or RootCerts held a CRL for the exported certificate or its
issuers, for example after AddCRL - raised EAccessViolation and wrote no
file.
The mapping now decodes the OCTET STRING's content as a CertificateList,
with the same explicit wrapping used for X.509 certificate bags. The
writers emit that OCTET STRING with the CRL's DER. ExportToPFX writes each
distinct CRL once. Certificate and key mappings are unchanged. There is no
interface change. The mainstream exporters checked (Windows
PFXExportCertStoreEx, OpenSSL pkcs12) do not write CRL bags; files that
carry them come from other producers.
BEHAVIOUR CHANGE, PFX imports:
- CRL bags are filed with the startup CRL rules (MyCerts, then RootCerts,
then CollectedCertificates), and revocation checks now see them. The
stores apply the AddCRL rules, so expired, not-yet-valid and
unknown-issuer CRLs are filed as AddCRL would file them.
- tPFX.CopyTo offers every bag whatever an earlier Store call returned,
and files CRL bags after all certificate bags. A refused certificate or
CRL no longer drops the bags after it (with LocalExplicitTrustByDefault
at its default False the CA bag is refused, and the CRL after it used to
be skipped). CopyTo still returns False when any bag was refused.
- A CRL bag that does not hold a DER CertificateList makes the whole
import raise eASN1DataError, where 4.1.5.362 accepted the file without
the CRL. That reaches TLS ImportFromPFX, TsmAsyncTLSServer startup,
tCertificateReloader (the attempt is rejected),
TstCustomCertificateManager.ImportFromPFXFile (raises) and the ACME
storage's LoadLeafFromPFX (returns False, so the renewal manager obtains
a new certificate).
- A PFX whose own CRL revokes its serving leaf cannot start a server: TLS
setup finds no usable certificate and TLSSetupServer or
TsmAsyncTLSServer activation raises. tCertificateReloader now refuses
such a file before touching any target ("PFX CRL revokes the leaf
certificate", or a certificate in its chain) when an issuer in the same
PFX signed that CRL, and keeps serving the current identity. Before
this change the CRL was ignored and both paths served the leaf.
AsyncTLSServer.txt and CertificateReload.txt describe the filing above.
--------------------------------------------------------------------------------
PKIX: CERTIFICATE IDENTITY CHECKS
================================================================================
28. FIXED, BEHAVIOUR CHANGE - CheckDNSName, CheckIP and CheckURI find the
name wherever the certificate is meant to carry it
StreamSec.DSI.PkixCert; StreamSec.Mobile.TlsClass (URIToCheck comment).
The rule: a certificate is likely to serve several purposes in several
places, so a check passes when the name occurs in at least one place
that the check looks at. CheckDNSName looks at every dNSName entry of
the subjectAltName and every commonName attribute of the subject;
CheckIP at every iPAddress entry; CheckURI at every
uniformResourceIdentifier entry. Releases 4.0.1.313 through 4.1.5.362
carried each defect below.
THE STEP THAT FAILED, CheckDNSName: with no dNSName entry it fell back
to the subject CN, and a subject without a CN passed whatever name was
asked for. A match only counted on the first CN value. With dNSName
entries present the CN was never consulted. Now the name must occur in
a dNSName entry or in any CN attribute, and nothing matches a
certificate that has neither.
THE STEP THAT FAILED, CheckIP: an IPv6 address matched only when written
with all eight groups: "::" was not expanded and the last group became
one octet instead of two. Malformed text was read as zeros, and IPv4
parts with leading zeros were accepted. The text is now converted to the
4 or 16 octets of RFC 5280 section 4.2.1.6 and compared exactly (RFC
9525 section 6.4): IPv4 as four decimal parts 0-255 without leading
zeros, IPv6 in any RFC 4291 section 2.2 form, including "::", an
embedded IPv4 tail and the text RFC 5952 section 4 recommends, with
surrounding [ ] and an RFC 4007 zone index ("%...") removed. Any other
text matches nothing. An IPv4-mapped IPv6 address does not match an IPv4
entry.
THE STEP THAT FAILED, CheckURI: the host taken from the URI to check was
compared with the certificate's URI written out in full, so a URI entry
in the subjectAltName never matched, and only the CN fallback could
pass. Now both URIs are parsed as RFC 3986 section 3 describes, and the
scheme (case-insensitive) and the host must match, as RFC 9525 sections
6.5 and 7.2 require; userinfo, port, path, query and fragment are
ignored. A URI without a scheme or a host matches nothing. There is no
CN fallback for URIs (RFC 9525 section 2: "The Common Name RDN MUST NOT
be used to identify a service").
BEHAVIOUR CHANGE: DNSNameToCheck and CheckDNSName no longer strip a
scheme, a port or a path from the name: pass a bare host name.
URIToCheck and CheckURI take a full URI with scheme and host. A
certificate without a CN or a dNSName entry no longer passes a DNS name
check, a URI check no longer passes on the CN, and a CN that names a
host the dNSName entries do not list now passes for that host.
--------------------------------------------------------------------------------
TLS: ONE CERTIFICATE RELOADER FOR STARTTLS AND IMPLICIT TLS
================================================================================
29. BEHAVIOUR CHANGE, NEW - The reloader applies a PFX to every kind of
target in one sequence, and a superseded leaf is no longer served
StreamSec.Mobile.CertificateReload, StreamSec.Mobile.StreamSecII,
StreamSec.Mobile.TlsInternalServer, StreamSec.Mobile.AsyncTLSServer;
CertificateReload.txt, AsyncTLSServer.txt.
One tCertificateReloader follows a PFX file for every registered target:
a STARTTLS engine (TsmCustomTLSInternalServer) and the TsmAsyncTLSServer
instances that serve the same protocols with implicit TLS, such as SMTP
submission on 465, IMAP on 993 and POP3 on 995. Each change is read once,
with an exclusive open, and parsed once. Every target then gets the same
sequence: the private key is stored through the target's iKeyAndCertStore,
the leaf is added (with its key present it is filed in MyCerts), every
certificate and CRL bag of the file is filed under the target's setup lock
and TLSLock, ReplaceTLSServerCertificate publishes the new serving rows,
and key pairs are validated again. An async target does each step on
every shard. The reloader no longer calls ImportFromPFX on an
internal-server target, which replaces the path that entry 25 describes;
ImportFromPFX itself is unchanged.
BEHAVIOUR CHANGE: applying a replacement retires every leaf that the
target may serve from that file: the one it served before, and one that a
failed apply published to some shards. A leaf that another watched file
still holds is kept. A retired leaf is removed from the target's serving
cache, on every shard of an async target, including rows for host names
and key algorithms that only it covered: before, the old leaf stayed
selectable for those until the process restarted, after its file had been
replaced. A handshake for such a name now gets what the target serves for
a name it has no row for. PublicKeyAlgorithms no longer counts a retired
leaf, so a key type that only retired leaves covered is no longer
advertised, and TLSSetupServer does not serve a retired leaf again, so an
in-process restart of a target does not bring it back. The stores keep a
retired leaf until the process restarts; it is only no longer offered.
StoreCertificate, ImportFromPFX and ReplaceTLSServerCertificate make a
retired leaf servable again; AddCertificate and LoadMyCertsFromFile do
not.
BEHAVIOUR CHANGE: AddFile with aCurrentContent and no aCurrentCert now
derives the current leaf from the content, so the first replacement
retires the leaf the targets were started from. The seed is best effort:
content that is not one decodable PFX identity seeds nothing and is
logged as a warning, and the first check applies or rejects the file as
usual, so a seed never stops the application. Before, nothing was
retired until the first applied leaf was superseded.
BEHAVIOUR CHANGE: a TsmAsyncTLSServer holds a bank lock while activation
builds its shards and Deactivate frees them, and while the new form of
ReplaceTLSServerCertificate or a reload walks them. A Deactivate on
another thread now waits for a walk to finish instead of freeing a shard
under it, and a reload into a server that is no longer active is refused.
Do not call ReplaceTLSServerCertificate from a session callback, which
Deactivate waits for.
NEW: ReplaceTLSServerCertificate(aCert,aPriv,aRetired), aRetired an array
of iCertificate, on TsmStreamSecII, TsmCustomTLSInternalServer and
TsmAsyncTLSServer retires every leaf in aRetired and then publishes aCert
as the two-argument form does; nil entries, and aCert itself, are
skipped. TsmStreamSecII.IsRetiredServerCert, UnretireServerCert and
RetireServerCert read, clear and set the retirement; RetireServerCert is
for an application that sets an engine up again in the same process with
a leaf an earlier run served. The two-argument form is unchanged. Protected
ValidateReloadPublicKeyPairs on TsmCustomTLSInternalServer and
TsmAsyncTLSServer validates key pairs under the same locks as the other
reload-only methods, and protected LockBank and UnlockBank on
TsmAsyncTLSServer hold the bank lock.
Three comments were wrong and now describe the code: BeforeImportTLSCert
fires when a peer's Certificate message is imported, not for the
component's own PFX imports; the TsmAsyncTLSServer import comment now
says that tPFX.CopyTo offers every bag before it reports a refusal; and
the reloader's bag-filing comment now says that the private key, unlike
the certificate and CRL bags, goes through the unlocked
iKeyAndCertStore, because the key ring locks itself.
--------------------------------------------------------------------------------
PKIX: SIGNED-OBJECT THUMBPRINT
================================================================================
30. FIXED - tSigned.GetTBSThumbprint always returns a fresh digest array
StreamSec.DSI.PkixSigned.
THE STEP THAT FAILED was writing the to-be-signed digest: DoneBytes wrote
into the function's Result array without first giving it a new instance.
A managed Result is not automatically initialized, so the digest could be
written into an array the caller still shared with another variable, for
example a cached thumbprint. Result is now set to a new zero-filled array
of the digest's size before the digest is written. When the signature's
hash algorithm is not supported, Result is now empty: it used to return,
and on a read-only object cache, whatever the uninitialized Result held.
--------------------------------------------------------------------------------
ASN.1: COPIED STRUCTURES
================================================================================
31. FIXED - A copied Name keeps its values when the copy is read or
expanded before it is saved
stASN1Base.
THE STEP THAT FAILED was selecting a CHOICE alternative while decoding a
copy. CopyStreamedContents copies a structure by decoding the source's
encoding lazily into an editable destination. When that destination was
read or expanded before it was saved, each CHOICE it decoded selected
its alternative as an edit: the encoded value was dropped and the CHOICE
became an empty default alternative. A certificate's issuer is such a
copy - tCertificate.BeforeSign copies the issuing certificate's subject
into it - so ExpandFull on a newly signed certificate turned every
issuer value into an empty TeletexString (an empty PrintableString or
IA5String for the country and the e-mail address). Reading CommonName
from a copied Name returned an empty string and emptied the other
values. A copy saved without being touched first was not affected, nor
were certificates loaded from DER or names built in code. The defect is
present in 4.0.1.345 and 4.1.5.362.
A CHOICE whose encoding has not been read yet now records the
alternative its encoding holds without treating that as an edit, and so
does the value of an AttributeTypeAndValue, whose alternative follows
from the attribute type. Selecting a different alternative from code is
still an edit.
A copy is for reading and saving as it is: a copied Name is not meant to
be modified. A name that has to differ from its source is built from
scratch. The declaration of CopyStreamedContents now says so.
--------------------------------------------------------------------------------
PKIX: CERTIFICATE GENERATOR KEY PAIR
================================================================================
32. FIXED - TstBaseCertificateGenerator fills in the subject public key
when it generates the key pair itself
StreamSec.DSI.PkixCertGenerator.
THE STEP THAT FAILED was imposing the subject public key. The built-in
key generation returns the private half of the new key pair, and
ImposeSubjectPublicKeyItem cast that to a public-key interface to fill
in subjectPublicKeyInfo. The default DSI key objects implement only one
half, so the cast raised EIntfCastError "Interface not supported" and no
certificate was issued: with no key-pair handler, the generator issued
nothing for any key algorithm. Applications that supplied the key in
BeforeGenerateKeyPair, as a public key or as an object implementing both
halves, were not affected. The defect dates from 4.0 beta 0.292.
The built-in key generation now keeps the public half in the new
SubjectPublicKey property of TstBasePKIXObjectGenerator, and the
subjectPublicKeyInfo is filled in from it; for Ed25519 and Ed448 it now
also makes that public key. Execute clears SubjectPublicKey before the
key pair is generated. A BeforeGenerateKeyPair or AfterGenerateKeyPair
handler that supplies a private key whose object does not implement the
public-key interface - a token or HSM key - assigns SubjectPublicKey
with it. A software RSA private key still works without it, because the
public half is derived from the private key. Any other key without its
public half now gets eCertificateGenerator "The subject key does not
carry its public half: assign SubjectPublicKey together with the private
key" instead of EIntfCastError.
Tested on Win32, Win64 and Linux64 with RSA-2048, P-256, Ed25519 and
ML-DSA-44.
--------------------------------------------------------------------------------
TLS: CCADB ROOT SET LICENCE
================================================================================
33. FIXED - The CCADB root set ships with the text of its licence,
CDLA-Permissive-2.0, and names the CCADB as its source
StreamSec.Mobile.CCADBRoots, LICENSE-CDLA-Permissive-2.0.txt (new),
PRODUCTINFO.txt, the release SBOM (not in the archive: PRODUCTINFO.txt
section 10 says where to get it).
THE STEP THAT FAILED was stating the licence of the root set. The
certificates compiled into StreamSec.Mobile.CCADBRoots are taken from
the Common CA Database (CCADB), whose Data Usage Terms name the Community
Data License Agreement - Permissive, Version 2.0 as the licence of its
data. Section 2.1 of that agreement makes sharing the data conditional on
making the agreement's text available with it. The release and the trial
archives carried neither the text nor a reference to it, and the release
SBOM gave the root set's licence as MPL-2.0. No release from 4.1.2.355,
the first with the unit, to 4.1.5.362 carried the text.
LICENSE-CDLA-Permissive-2.0.txt now ships in the release and in the
trial archives. It holds the agreement's text and the addresses of the
agreement, its FAQ, the export and the CCADB's Data Usage Terms, which
state that attribution to the CCADB is required when the data is
redistributed or used in derived works and restrict the use of its name
and trademarks to endorse or promote products derived from the data. It
also says which binaries carry the certificates. A runtime package built
from the supplied StrSecIV<nnn>.dpk, as in the trials, does, whether or
not the application that loads it uses TsmCCADBTrustAnchors, because the
unit is in that package. A package you build yourself does only if it
contains the unit (not measured). A statically linked executable that
never refers to StreamSec.Mobile.CCADB or StreamSec.Mobile.CCADBRoots does
not. The unit's header and PRODUCTINFO.txt refer to that file, and the SBOM
component for the root set names CDLA-Permissive-2.0. What the sources ask,
and when, is for you to read in them. No code changed.
--------------------------------------------------------------------------------
PKIX: EC KEYS ON A PKCS#11 TOKEN
================================================================================
34. FIXED - The certificate manager finds an EC private key held on a
PKCS#11 token
StreamSec.DSI.DiscreteLog, StreamSec.DSI.PKTypes,
StreamSec.DSI.Pkcs11ExtKey.
TWO STEPS FAILED, both in TstCustomCertificateManager.GetSignPrivateKey for
a key whose scalar stays on the device. Filing the private key failed:
the public-key index asks a key for its public point, and
tDLPrivateKey.PublicKey computed the point from the scalar, so the key was
never filed under the certificate's public key. Validating it would have
failed next: tDLPrivateKey.Validate required a scalar and never asked the
external key. GetSignPrivateKey returned nil for the matching certificate,
so an EC CA or signing key on a token could not be used through
tKeyStoragePkcs11, although the certificate was found. RSA keys on a token
were not affected, and neither was signing with a key from
NewPkcs11DLPrivateKey called directly. The defect is present in every
release with tKeyStoragePkcs11, 4.1.3.356 to 4.1.5.362.
tExternalDLPrivateKey has a new virtual method GetPublicKey, which returns
nil unless a subclass overrides it, and tDLPrivateKey.PublicKey returns its
result for an external key. NewPkcs11DLPrivateKey keeps the point of the
public key it is given. tDLPrivateKey.Validate, for an external key, checks
the public key and its parameters and then returns what the external key's
Validate says; for tPkcs11DLPrivateKey that compares the point on the
device. A subclass of tExternalDLPrivateKey that does not override
GetPublicKey and Validate is still refused.
--------------------------------------------------------------------------------
MAIL: TWO WAYS TO EXHAUST A SERVER THROUGH IMAP
================================================================================
35. FIXED, BEHAVIOUR CHANGE - IMAP allocated a literal's whole announced size
before authentication and kept a command's literals without limit
StreamSec.Mail.IMAPEngine (tImapSession, tImapLimits).
THE STEP THAT FAILED was tImapSession.HandleLine believing a literal's
announced size. As soon as a line ended in {n} it allocated all n octets,
before one of them had arrived and before the command was parsed, and it
kept every completed literal of the command in memory, with no limit on how
many. tImapLimits.LiteralBytes bounded one literal at a time, by default at
32 MiB. None of this looked at the session's state. Every release with the
mail suite, 4.1.2.355 through 4.1.5.362, has this.
NO AUTHENTICATION WAS NEEDED. Any peer that could connect could do this
before signing in: on a port offering STARTTLS before starting TLS, in
cleartext, and on an implicit TLS port after the TLS handshake. One line of
text held 32 MiB for as long as the connection stayed open, and connections
add up. A peer that went on to send the octets could grow what one command
retained without limit. The effect was on availability: the server process's
memory. The octets were only stored until the command ended, so this
disclosed nothing, bypassed no sign-in and touched no mailbox.
Now nothing is allocated when a literal is announced. Its buffer grows with
the octets received, geometrically, and never beyond the announced size; a
buffer that grows wipes the old block, because a literal may be a password.
The bounds are:
- tImapLimits.LiteralBytes is the literal octets one command may carry IN
ALL, summed over its literals, so also the largest APPEND. The default is
still cImapMaxLiteral, 32 MiB, and 0 still means no limit.
- Before authentication the sum is limited to cImapUnauthLiteralBytes, 4096,
whatever LiteralBytes says.
- A command may carry cImapMaxLiteralsPerCommand, 16, literals, always, also
with LiteralBytes 0. A zero-length literal counts.
4096 and 16 are chosen, not measured. A smaller 4096 may refuse a LOGIN
password sent as a literal; a larger one lets an unauthenticated peer retain
more per connection. A smaller 16 may refuse a command with many literals; a
larger one retains more while a command is incomplete.
BEHAVIOUR CHANGE: an authenticated command whose literals together exceed
LiteralBytes is refused where each used to pass on its own. A command before
authentication whose literals exceed 4096 octets, such as a LOGIN, and any
command with more than 16 literals, are refused. The refusal is tagged,
"<tag> BAD literal too large" or "<tag> BAD too many literals", where
4.1.5.362 sent an untagged BAD; the refusal of a non-synchronising literal is
tagged as well. Each still counts towards tImapLimits.Errors.
36. FIXED, BEHAVIOUR CHANGE - IMAP gave each encapsulated message a new MIME
budget, and the bounds that replace the shipped 16 and 1000
StreamSec.Mail.IMAPEngine, StreamSec.Mail.Message (tMimeEntity).
THE STEP THAT FAILED was tImapSession.EmitBodyStructure parsing each
message/rfc822 part with tMimeEntity.Parse, which starts again at depth 0
with no parts counted. So cMailMaxNestingDepth and cMailMaxPartCount never
applied across encapsulation. The walk recursed once per level and each
level kept copies of everything below it until the recursion unwound. A
level costs about 32 octets, so memory and work grew with the square of the
message size and stack depth with its size. Every release with the mail
suite, 4.1.2.355 through 4.1.5.362, has this. Only FETCH BODY and
BODYSTRUCTURE took this walk in those releases.
WHO COULD DO THIS. The command needs a signed-in session on the mailbox, but
the message does not: whoever can deliver mail to the mailbox can place one,
with no credentials on an inbound SMTP port that takes mail for it, and the
owner's mail client then fetches BODYSTRUCTURE by itself. The message stays,
so each such FETCH does it again. The effect was on availability: the server
process's memory, CPU and stack. The walk disclosed nothing and changed
nothing. An exception from the walk reached the transport, so the client lost
its connection with no reply, each time it asked for that message's
structure.
Now one depth count and one part total cover a whole message: its
encapsulated messages and their siblings, for BODY, BODYSTRUCTURE and the
sections of entry 1. An ancestor's stored octets are released before the
walk descends. A structure item over budget answers tagged NO "mailbox
operation failed" and is logged, with no partial "* n FETCH (" line; complete
untagged responses before it stay, and the session goes on. A section over
budget answers NIL (entry 1).
BEHAVIOUR CHANGE, THE BOUNDS ARE RAISED: cMailMaxNestingDepth from 16 to 100
and cMailMaxPartCount from 1000 to 10000. One budget for a whole message
means ordinary mail needs more of it than a single parse did. A message
forwarded as an attachment costs two levels, so 16 would stop at about 8,
and a digest of 300 list messages of two parts each is about 1200 entities.
The new values are the defaults of Dovecot's message parser (2.3.11,
CVE-2020-12100); they are chosen, not measured. Smaller refuses such mail;
larger raises the stack depth, allocations and work one message can cost.
tMimeEntity.Parse and TsmEmail use the same constants, so they now accept
100 levels and 10000 parts where they raised eMailMessageError at 16 and
1000. Parse alone does not descend into an encapsulated message.
NEW on tMimeEntity: ParseWithBudget, which carries a depth and a part total
into another parse, NestingDepth and DiscardBodyStorage.
A chain of 20 forwards and the digest above are served; 60 forwards and a
part count spread over sibling messages are refused.
--------------------------------------------------------------------------------
MAIL: WHEN A COMMAND OR A CALLBACK RAISES
================================================================================
37. FIXED, BEHAVIOUR CHANGE - a raising mailbox call dropped the connection with
no reply
StreamSec.Mail.IMAPEngine, StreamSec.Mail.POP3Engine,
StreamSec.Mail.SMTPEngine, StreamSec.Mail.IMAPServer,
StreamSec.Mail.POP3Server, StreamSec.Mail.SMTPServer.
THE STEP THAT FAILED was command dispatch: tImapSession.DispatchCommand,
tPop3Session.ProcessBuffer and tSmtpSession.ProcessBuffer caught nothing, so
an exception from a store or a policy call reached the transport, which
logged it and closed. The client lost its connection, with no reply, over a
failure that concerned one command. Every release with the mail suite,
4.1.2.355 through 4.1.5.362, has this.
An exception is now logged and answered, and its text stays out of the reply:
- IMAP discards the command's incomplete response, keeps complete untagged
responses already produced, answers tagged NO "mailbox operation failed"
and goes on. A failed IDLE or AUTHENTICATE leaves no IDLE or SASL exchange
behind. A response already on the wire, as with STARTTLS, cannot be
replaced, so that session closes.
- POP3 replaces the buffered reply with "-ERR mailbox operation failed", so
multi-line framing holds for pipelined commands. If the failure changed the
session's state the reply is "-ERR mailbox operation failed, closing
connection" and the session closes.
- SMTP answers "451 mailbox operation failed". A RCPT that raises keeps MAIL
and the recipients already accepted (entry 12); any other command resets
the transaction. Inside an unfinished DATA, or a DATA that raises once in
the data state, the answer is "421 temporary failure receiving message,
closing", because a body line must never become a command. An exception on
the terminating dot answers 451 and the session stays.
- When the session's own store is no longer available the answer is "* BYE
mailbox service is shutting down", "-ERR mailbox service is shutting down"
or "421 mailbox service is shutting down", and the session closes.
- The process-state classes of entry 20 take the fatal path of entry 38. An
engine used without a store callback raises them to its owner.
BEHAVIOUR CHANGE: a client that used to see the connection drop now gets the
reply above and can go on.
NEW: OnException and OnStoreUnavailable on tImapSession, tPop3Session and
tSmtpSession, through which a server logs and classifies the failure;
tImapSession.IdleFailed, for an idle-round failure (entry 3);
eMailSelectionUnavailable, a descendant of eMailStoreUnavailable, which ends
the session whose own selection went away with the BYE of entry 21.
38. NEW, BEHAVIOUR CHANGE - fatal handling on mail threads: a process-state
exception there, or in a mail session's own code, ends the process
StreamSec.Mail.Transport, StreamSec.Mail.Retrieval,
StreamSec.Mail.IMAPServer, StreamSec.Mail.POP3Server,
StreamSec.Mail.SMTPServer, StreamSec.Mail.SMTPSpool,
StreamSec.Mail.Maildir, stWorkerFatal.
In 4.1.5.362 tMailConnectionThread.Execute logged any exception, an access
violation included, and the server went on in a process that exception may
have damaged.
BEHAVIOUR CHANGE: the process-state classes of entry 20 now end the process,
with exit code 70 and the bounded sequence entry 20 describes, in these
places:
- on a mail thread, each of which calls MarkWorkerThread: tMailAcceptDaemon,
tMailConnectionThread, the mail shutdown and channel close workers, and
tSmtpSpoolWorker, including a raising delivery agent;
- in a mail session's code on any thread, which includes a reactor thread of
a TsmAsyncTLSServer serving an implicit TLS session: a mailbox operation or
policy call of an IMAP, POP3 or SMTP session, and the retrieval servers'
OnSessionOpened, OnSessionClosed and OnAuthenticate handlers.
An OnLog handler alone depends on the thread. On a marked thread a process-
state exception from it is fatal. On any other thread, such as the
application's main thread during SetActive, an exception from it is
contained, whatever its class.
The rest of the async server is not covered: its reactor, listener, reaper
and redirect threads on their own account behave as before. The TLS worker
boundaries of entries 24 and 25 are unchanged. An ordinary exception from the
work of an accept, connection or spool thread goes to the owning component's
OnLog; at a shutdown or channel close worker it is dropped. None goes to
stderr.
There is one latch in the process, shared with those TLS worker boundaries.
A mail store that faults while another owner holds it stops committing at
once and leaves reporting and the exit to that owner. Without a registered
coordinator, or when the coordinator does not take the failure over, a worker
exception of these classes ends the process at once with code 70.
StreamSec.Mail.Maildir registers itself as the coordinator.
NEW in stWorkerFatal, beyond entry 24: tWorkerFatalHandler,
tWorkerThreadLogEvent, ClaimWorkerFatal, ReleaseWorkerFatal,
EndWorkerFatalProcess, WorkerFatalTickMs, SetWorkerFatalHandler,
HandleWorkerThreadException, MarkWorkerThread and HandleCallbackException.
NEW elsewhere: TsmMailStore.ReportFatalError and FailurePending;
tMailListener.ThreadLog; cMailFatalExitCode, cMailFatalPhaseTimeout and
cMailFatalWatchdogTimeout, aliases of the stWorkerFatal constants.
--------------------------------------------------------------------------------
MAIL: COMPONENT LIFETIME
================================================================================
39. FIXED, BEHAVIOUR CHANGE, NEW - freeing a mail component left its sessions
on a shared TsmAsyncTLSServer reaching the freed component
StreamSec.Mail.Retrieval, StreamSec.Mail.IMAPServer,
StreamSec.Mail.POP3Server, StreamSec.Mail.SMTPServer,
StreamSec.Mail.Transport, StreamSec.Mobile.AsyncTLSServer.
THE STEP THAT FAILED was the destructors of TsmCustomIMAPServer,
TsmCustomPOP3Server and TsmCustomSMTPServer. They unbound the protocol and
detached its adapter, which stops new sessions, and did nothing about live
ones. A session on an attached TsmAsyncTLSServer kept its reference, so when
the application freed the mail component and kept the async server up, the
session's next data or close reached freed memory. Every release with the
mail suite, 4.1.2.355 through 4.1.5.362, has this.
A destructor now stops the component's own listeners and then closes its
sessions on the shared server. A farewell ("* BYE server shutting down",
"-ERR server shutting down", "421 service closing transmission channel") and
a graceful close run on worker threads, not on the calling thread, unless no
worker thread can be started at all. The
component is freed only when the last session has unregistered, which is the
last thing a session's destructor does. A session that registers during the
wait is closed and waited for too. The destructor never changes the shared
server's Active: HTTP/2, Snip, ACME and anything else on it stay up. Setting
a mail component's Active to False still leaves its sessions on the shared
server alone.
BEHAVIOUR CHANGE: the destructor waits. On the main thread it runs
CheckSynchronize while waiting, every cMailDrainPollMs (10 ms), so a session
callback that synchronizes with the main thread can finish; on another thread
it sleeps. After cMailDrainAbortMs (10000 ms) sessions still registered are
aborted, so a peer that stopped reading cannot hold it; a slow but live
client past that point sees a reset. A session callback that never returns
holds the destructor for ever, because freeing under it would be a
use-after-free. Every cMailDestroyDrainMs (5000 ms) the component then logs
through OnLog "<n> ms passed and a session on the shared TLS server still
holds this component".
These values are chosen, not measured. A shorter abort resets slow clients; a
longer one lets a stopped peer hold the teardown longer. A shorter report
fills the log during a slow close; a longer one shows a stall later.
NEW: iAppTransportAbort, an optional companion to iAppTransport that
TsmAsyncTLSServer's connection implements and a session finds with Supports.
Abort discards queued output and has the reactor tear the connection down on
one of its own threads, without asking the session or OnConnectionNudge. It
never takes the connection's gate and never waits for a session callback, so
it is safe from any thread; a callback running on the connection finishes
first. On a reactor backend without an out-of-band wake the close stays
requested until the connection's next completion. Also NEW:
iMailChannelAbort, tMailDrainReportEvent and tMailServiceShutdown.
40. FIXED, BEHAVIOUR CHANGE - setting Active on a mail server in the Object
Inspector tried to start it inside the IDE
StreamSec.Mail.Retrieval, StreamSec.Mail.SMTPServer,
StreamSec.Mail.IMAPServer, StreamSec.Mail.POP3Server.
THE STEP THAT FAILED was SetActive on TsmCustomMailRetrievalServer and
TsmCustomSMTPServer, which parked the value only while csLoading was set. At
design time it went on to start the listeners in the IDE's process, or to
raise there. Every release with the mail suite, 4.1.2.355 through 4.1.5.362,
has this.
BEHAVIOUR CHANGE: at design time the value is now only kept and streamed, and
Loaded starts the server at run time only, as TsmAsyncTLSServer does. A form
saved with Active True starts when the application loads it, and no longer
when the IDE opens it. TsmCustomSMTPServer also learns at design time of an
async server on another form or data module being freed.
41. NEW - BoundPort reports the port a listener actually got
StreamSec.Mobile.AsyncTLSServer, StreamSec.Mail.Transport,
StreamSec.Mail.IMAPServer, StreamSec.Mail.POP3Server,
StreamSec.Mail.SMTPServer.
TsmAsyncTLSServer.BoundPort is the port the TLS listener is bound to while
Active, otherwise 0. tMailListenerOptions.BoundPort (TsmSMTPServer's Inbound
and Submission, the retrieval servers' Plain) is the port bound while InUse,
otherwise 0. Both are public and read-only, not published. With 0 configured
they give the port the system assigned; BindPort and Port keep the configured
value, so a stop and start asks for a new port and the setting streams out as
it was set. The mail components' "listening" log lines now show the bound
port.
--------------------------------------------------------------------------------
MAIL: WHAT THE STORE AND THE SPOOL DO ON DISK
================================================================================
42. FIXED, BEHAVIOUR CHANGE - a failed flush still answered 250 or OK, and
Darwin did not flush the device cache
StreamSec.Mail.Maildir, StreamSec.Mail.SMTPSpool.
THE STEP THAT FAILED was FlushStream in the Maildir store and
tSmtpSpool.WriteWholeFile, which ignored the result of FlushFileBuffers and
of fsync. With FlushToDisk on, a failed flush still answered 250 or OK, with
the message not durable. On Darwin fsync does not flush the device cache.
Every release with the mail suite, 4.1.2.355 through 4.1.5.362, has this.
BEHAVIOUR CHANGE: a failed flush now raises, "cannot flush message data" or
"cannot flush spool file", so SMTP answers 451 and APPEND answers NO. NEW:
MailFlushHandle (StreamSec.Mail.Maildir) returns True on success: Windows
FlushFileBuffers, POSIX fsync, and on Darwin fcntl F_FULLFSYNC, falling back
to fsync where the file system does not support it. On POSIX the directory
is flushed for the store's metadata files (entry 8), not when a message is
published.
43. FIXED, BEHAVIOUR CHANGE - the POP3 maildrop lock did not exclude a second
session in the same POSIX process, and was broken by age
StreamSec.Mail.Maildir.
THE STEP THAT FAILED was tMaildir.OpenFolder taking the lock with a
TFileStream opened fmShareExclusive and deleting a lock file older than
cMailLockStaleSeconds (1800 s). On POSIX that open is a record lock, which
does not conflict within a process, so a second maildrop open in one process
succeeded, and closing any descriptor of the file dropped the process's lock.
Two POP3 sessions of one account in one server could hold the maildrop
together. On POSIX the age check also unlinked the lock file of a holder
still connected after 30 minutes, so another session, from any process, then
got the maildrop. Windows was exposed to neither: the share mode excludes
other handles and refuses the delete. Every release with the mail suite,
4.1.2.355 through 4.1.5.362, has this.
A process-wide registry, keyed by device and inode on POSIX, is now checked
before any open, and a second open gets "the mailbox is locked by another
session". The lock is the open handle: the system releases it when its holder
dies, so nothing has to be broken.
BEHAVIOUR CHANGE: no lock is broken by age, and closing a maildrop no longer
deletes ss-pop3.lock. The file stays on disk and its presence means nothing.
cMailLockStaleSeconds is still declared and has no effect. The POSIX
compilers build this; the tests have not been run on POSIX.
44. FIXED - DELETE of a folder holding a directory link deleted what the link
pointed at
StreamSec.Mail.Maildir.
THE STEP THAT FAILED was tMaildir.DeleteFolder removing the folder with
TDirectory.Delete(path,True), whose walk descends into any entry with the
directory attribute. With a junction inside the folder and the Delphi 13 RTL,
the files in the junction's target were deleted. Clients cannot create such a
link through the mail protocols; someone with access to the store's disk has
to have placed it. Every release with the mail suite, 4.1.2.355 through
4.1.5.362, makes this call.
tMaildir.DeleteTree now reads each entry's own attributes without following
links and removes a directory link itself, never its target.
45. BEHAVIOUR CHANGE - the SMTP spool attempts nothing while its shared mail
store is deactivated, and a fatal failure freezes the queue
StreamSec.Mail.SMTPSpool, StreamSec.Mail.SMTPServer, StreamSec.Mail.Maildir.
BEHAVIOUR CHANGE: with local delivery through a TsmMailStore (sldMaildir) and
that store deactivated, delivery workers now attempt nothing, remote
deliveries included, and look again every cSmtpSpoolStoreWaitMs (1000 ms,
chosen, not measured). Queue writes raise eSmtpSpoolError "the spool has
failed". The messages stay queued. The spool keeps the store it was started
with, so it goes on waiting until the SMTP server is stopped and started
again with the store active. 4.1.5.362 kept attempting.
After the fatal path of entries 20 and 38 the queue files of a server with
sldMaildir local delivery stay exactly as they were at the latch; a server
with another LocalDeliveryMode keeps writing its queue until the process
exits. Queue writes share the store's commit gate, and Start raises the same
error. A remote delivery in progress at that moment may
complete with no acknowledgement in the queue, so the next run can send that
message again. Before a message's relay copy is spooled, the session checks
the store once more. An ordinary Stop still records the outcome of a delivery
in flight, and releases one claimed but not started.
NEW: tSmtpSpool.StoreGate and RequestStop(aFreezeWrites);
tMaildir.BeginCommit and EndCommit are public. tSmtpSpool.Start raises "Stop
must finish before Start" while a previous Stop has workers left.
StreamSec.Mail.SMTPSpool now uses StreamSec.Mail.Maildir.
46. FIXED, BEHAVIOUR CHANGE - an import of PFX bytes sets PublicKeyAlgorithms
and narrows the local cipher list, as an import of a file does
StreamSec.Mobile.TlsInternalServer, AsyncTLSServer.txt.
THE STEP THAT FAILED was ValidatePublicKeyPairs at the end of
TsmCustomTLSInternalServer.ImportFromPFX(const aContent: TBytes; ...), on an
engine that held no own certificate yet. That import files the leaf through
AddCertificate, which does not record that own certificates are loaded, so
the validation scanned nothing: PublicKeyAlgorithms stayed empty and Options
kept what the leaf cannot serve. With only an RSA leaf SignatureECDSA stayed
allowed; a TLS 1.2 client offering ECDHE-ECDSA first, which is OpenSSL's
default order, had that suite selected and received a fatal
handshake_failure, "Unable to find a server certificate appropriate for the
selected cipher suite". With only an EC leaf the same happened to a client
offering ECDHE-RSA first. TLS 1.3 was not affected.
That overload arrived with entry 25, after 4.1.5.362: no release has it. The
import of a file, which is what releases have, was not affected.
BEHAVIOUR CHANGE, against entry 25: the import of bytes now leaves the same
PublicKeyAlgorithms and Options as the import of the same PFX from a file.
The server's own TLS 1.2 cipher list and the KeyAgreement* options follow
the leaves held, and KeyAgreementRSA set to prAllowed afterwards stays
allowed only with a leaf whose keyUsage has keyEncipherment. Since entry 62
the leaves held no longer narrow the Signature* options, which are the peer
policy: the signatures and client certificates accepted from the peer.
AsyncTLSServer.txt now states that a recorded ImportFromPFX is replayed
before OnConfigureEngine, so a trust setting made in the handler does not
apply to it, and which two orders file a CA from the file. The code of that
order is not changed.
47. FIXED, BEHAVIOUR CHANGE - a client that resets before it has read the banner
gives its connection slot back at once and leaves no thread spinning
StreamSec.Mail.Transport, MAIL.txt.
THE STEP THAT FAILED was tMailChannel.Receive, on a socket that a failed
send had already closed. A send that fails with a real error closes the
socket (tWinSocket.Send, tPosixSocket.Send), and WaitForData on a closed
socket answers False at once. Receive took that False for an empty round
and answered -1 with aTimedOut True, so tMailConnectionThread went round
again with no wait at all until its idle limit ended the session.
A client gets there by resetting before the greeting has gone out, the
greeting's send being what finds the reset, or by resetting after sending a
command, while the reply is going out. A reset the thread was already
waiting for was reported correctly, and so was every FIN.
SYMPTOM, on the plain ports (25, 587, 110, 143): each such connection kept
its slot for the idle limit of its protocol (300 s SMTP, 600 s POP3, 1,800
s IMAP), with whatever the session held, and its thread used a whole CPU
core all that time. Measured on Win64, 32 logical processors, with the
default limits: 750 clients resetting from different addresses within 5 s
stopped all four ports answering and took 31 of the 32 for as long as it
was watched (120 s). In an earlier run 270 such clients on 25 and 587
stopped those ports for about 5 minutes and 70 on POP3 stopped it for about
10. The implicit-TLS ports run on the async server and were not affected.
Affected: every release with the mail family, 4.1.2.355 to 4.1.5.362, on
every platform; the code at those tags is the same.
BEHAVIOUR CHANGE: for a socket that is no longer open tMailChannel.Receive
now answers 0 with aTimedOut False, as it does for an orderly close, where
it answered -1 with aTimedOut True. The session ends and the slot is free
at once. With the same 750 clients all four ports answered at the first
probe, the CPU was back at 0.00 cores within 10 s, and the thread count was
back where it started. A Wake on a live socket still answers -1, and data
that came before a FIN is still delivered first.
48. FIXED, BEHAVIOUR CHANGE - on the plain ports a session that has neither
authenticated nor opened a transaction no longer holds its slot for the
protocol's whole idle limit once the port is filling; on IMAP it never does
StreamSec.Mail.Transport, StreamSec.Mail.SMTPTransport,
StreamSec.Mail.POP3Transport, StreamSec.Mail.IMAPTransport,
StreamSec.Mail.SMTPServer, StreamSec.Mail.POP3Server,
StreamSec.Mail.IMAPServer, MAIL.txt.
THE STEP THAT FAILED was the idle test in
tMailConnectionThread.RunConversation. It had one limit for every state of a
session, so a peer that connected and said nothing was held as long as a
signed-in user: 300 s on SMTP, 600 s on POP3, 1,800 s on IMAP. Saying NOOP
inside that limit extended it, up to the whole-session limit.
SYMPTOM, with the default limits: 32 addresses at 8 connections each fill
port 25 or 587 (256 slots) for 5 minutes, 16 addresses at 8 fill 143 (128)
for 30 minutes, and 22 at 3 fill 110 (64) for 10 minutes. Measured on Win64
with 300 silent connections per port from different addresses: 256, 256, 128
and 64 of them were still held after 123 s, and a new client on any of the
four ports was refused until they closed.
Affected: every release with the mail family, 4.1.2.355 to 4.1.5.362, on
every platform; the code at those tags is the same.
BEHAVIOUR CHANGE. tMailListenerOptions has three new published properties.
A session is in its PREAMBLE until it has authenticated or, on SMTP, has had
MAIL accepted with the transaction not yet over; RSET or the end of a message
puts an unauthenticated SMTP session back in it.
SMTP POP3 IMAP
PreambleIdleSeconds 30 30 60 silence
PreambleSessionSeconds 120 120 180 from the accept
PreamblePressurePercent 50 50 0 of MaxConnections
These limits apply only while the share of MaxConnections in use is at least
PreamblePressurePercent; 0 means at any load. At the limit the session ends
the way the idle limit ends it: 421 on SMTP, a close on POP3 and IMAP. Every
session that has reached the limit at that moment goes, so a port can fall
below the percentage by more than one. 0 in either of the first two turns
that limit off. A TLS upgrade in progress no longer runs on to the session
limit: PreambleSessionSeconds bounds the upgrade at any load.
IdleTimeoutSeconds and SessionTimeoutSeconds keep their values and their
meaning, and apply unchanged to a session past its preamble.
WHY THE PROTOCOLS DIFFER. RFC 9051 sec.5.4 has its 30-minute minimum for a
timer "that applies to sessions after authentication" and places no
restriction on a timer before it, so IMAP applies its short limits at any
load. RFC 3501 sec.5.4, which RFC 9051 obsoletes, does not make that
distinction. RFC 5321 sec.4.5.3.2.7 asks an SMTP server for "at least 5
minutes while it is awaiting the next command" and names no state, and
RFC 1939 sec.3 asks for "at least 10 minutes' duration" of an inactivity
autologout timer and names none either. So SMTP and POP3 keep those minutes
while the port has room. Past the percentage they do not: RFC 5321 sec.3.8
confines its limits on closing to "normal operational circumstances" and
sec.7.8 has servers "permitted to detect such attacks", but RFC 1939 has no
such text. Set PreamblePressurePercent to 100 to shed only on a full port, or
both limits to 0 to keep the floors at any load.
A peer that has had MAIL accepted, or has authenticated, still holds its slot
for the idle limit. The numbers above are chosen, not measured; MAIL.txt
section 11 says what each costs when wrong and where to change it.
49. FIXED, BEHAVIOUR CHANGE - the implicit-TLS mail ports have limits per
address and in total, and their sessions keep the idle and session limits
of the protocol's own port
StreamSec.Mobile.AsyncTLSServer, StreamSec.Mobile.AsyncTLSFilter,
StreamSec.Mail.Transport, StreamSec.Mail.SMTPServer,
StreamSec.Mail.POP3Server, StreamSec.Mail.IMAPServer, AsyncTLSServer.txt,
MAIL.txt.
THE STEPS THAT FAILED were two. TsmAsyncTLSServer.StartPeerTransport admitted
a connection against MaxConcurrentHandshakes (256) and MaxLiveSessions (8192)
alone, with nothing per address. And a mail session on the async server set
no deadline of its own, so with IdleTimeout at its default of 0 nothing ended
one after the handshake: the limits on Inbound, Submission and Plain reached
only those listeners' own connections.
SYMPTOM. Measured on Win64 with the default limits: 270 silent connections
from ONE address took every handshake slot, and a client from another address
was refused on 465, 993 and 995 until HandshakeTimeout had reaped them, 15 s
later. That one address, reopening what was reaped, kept the port from
answering 5 probes in 40. A peer that completed the handshake and then said
nothing, or said NOOP, was held until it left, and 8192 such sessions were
allowed. On the plain ports the same address got 8 connections.
Affected: every release with the mail family, 4.1.2.355 to 4.1.5.362, on
every platform; the code at those tags is the same.
BEHAVIOUR CHANGE, on a mail session on an implicit-TLS port (465 goes by
Submission, 995 and 993 by Plain):
- IdleTimeoutSeconds and SessionTimeoutSeconds apply as on that listener:
idle 300, 600 and 1,800 s, session 1,800, 1,800 and 86,400 s by default, in
place of no limit. A server IdleTimeout that is set and shorter still wins,
and OnConnectionNudge still has the last word.
- The preamble limits of entry 48 apply, the percentage being of the fuller
of MaxLiveSessions and MaxConcurrentHandshakes.
- At a limit SMTP says 421 and POP3 and IMAP close, nothing expunged.
- The whole-session and short limits reach OnConnectionNudge as
nrRequestStalled, a reason no connection raised before.
NEW, and off until set, so no other use of the async server changes:
- TsmAsyncTLSServer.MaxConnectionsPerPeer, default 0. A connection over it is
closed at the accept, before a handshake token is taken, and reported to
OnPeerRefused with the new prTooManyConnections. tPeerRefusal grew by that
member at its end.
- iAppTransportDeadlines on the transport: SetIdleLimit replaces IdleTimeout
for one connection, SetSessionBudget raises nrRequestStalled once whatever
traffic there is meanwhile, LoadPercent says how full the server is, and
ServerIdleMs reads IdleTimeout.
MEASURED on Win64 with these caps set from the listeners' and the default
limits: 270 silent connections from one address left 8, 8 and 3 held on 465,
993 and 995 and a client from another address was answered at once on each;
40 of 40 probes were answered while that address kept reopening. 300 silent
connections per port from different addresses, on all seven ports, opened
over about 18 s, still refused new clients while they lasted. By 39 s they
were all gone from the implicit ports, by 73 s from 143, and by 50 s from 25,
587 and 110 down to 127, 124 and 30 held, under half of each, which stay for
the floor; every port was answering again by 121 s, where before this entry
and entry 48 all of them on the four plain ports were still held.
These server properties are the application's to set. A mail server that sets
none has the idle and session limits above, and still no per-address limit:
MAIL.txt section 10 shows the assignments that give an implicit-TLS port the
caps of its protocol's listener. With 8 per address, 32 addresses still fill
256 handshake slots until HandshakeTimeout, 15 s, and can do it again;
neither cap can tell many addresses from many clients.
50. FIXED, BEHAVIOUR CHANGE - IMAP IDLE on the implicit-TLS port pushes EXISTS,
EXPUNGE and RECENT as it does on the STARTTLS port
StreamSec.Mail.IMAPServer, StreamSec.Mail.Transport,
StreamSec.Mobile.AsyncTLSServer, AsyncTLSServer.txt, MAIL.txt.
THE STEP THAT FAILED was the idle round, which did not exist for this
session. tImapServerSession.IdleRound rescans the selected mailbox while a
client sits in IDLE, and its only caller was the connection thread's read
loop on the listener. tImapAsyncSession, which serves 993 on
TsmAsyncTLSServer, has no such thread and nothing else called it, so MAIL.txt
listed push on that port as not done.
SYMPTOM: a client idling on 993 saw no new mail until it ended IDLE or sent
its next command. RFC 2177 lets a client re-issue IDLE as rarely as every 29
minutes, and that was how late it could hear. A mailbox deleted by another
session, or the store going away, did not reach the idling client either: on
the listener each of those ends the session with BYE. The same client on 143
after STARTTLS is told within a second.
Affected: every release with the mail family, 4.1.2.355 to 4.1.5.362, on
every platform, where IDLE pushed on neither port. Entry 3 gave the listener
its round and rescans at the start of IDLE and at DONE, and left this session
without a round.
BEHAVIOUR CHANGE, on an IMAP session on the implicit-TLS port, from IDLE to
DONE only:
- The session runs the same round as the listener, about once a second
(cMailConnectionReadRoundMs), on a reactor thread by
iAppTransportWork.SetWorkDeadline. No thread per session is added, and a
session outside IDLE sets no deadline.
- The round is the listener's: a rescan when the selected mailbox's
generation has moved, or after cImapIdleRescanSeconds, 30 s, for changes
made through another store instance or process. Delivery to another mailbox
causes none. A flag-only change is still not pushed.
- A mailbox deleted, or the store going away, ends the session with BYE and a
close. A round that raises is logged and closes the connection.
- What a round sends does not count as the client's traffic. A client that
reads its pushes and says nothing ends at IdleTimeoutSeconds, as on the
listener. The async server re-arms its idle deadline on each completed
send, so the session asks for nrIdle through the new
iAppTransportDeadlines.ExpireIdleLimit. OnConnectionNudge still has the
last word; after nvKeepAlive it is asked again one limit later.
- tImapAsyncSession now implements iAppSessionWork, so on a connection
without TLS compression its input arrives in pieces of at most 16 KiB. The
engine takes input in pieces of any size.
A rescan runs on a reactor thread, as every command on that port does, and
other connections on that thread wait while it runs (MAIL.txt section 14,
item 7). A reactor backend that runs no application work has no round; its
sessions hear of changes at DONE or their next command, as before. The
shipped backends all run it.
iAppTransportDeadlines has a new method and a new GUID. An application that
only calls the interface recompiles unchanged. Entry 49 introduced it, so no
release has the old form.
MEASURED on a mail server built on these units, Win64: on 993 and on 143
after STARTTLS, a delivery reached the idling client 0.5 to 1.0 s after it
was stored, and another session's EXPUNGE was pushed on both. In a
TsmIMAPServer on the async server, 200 sessions in IDLE with nothing arriving
took 3 to 4 % of one core over 32 s, every session's timed rescan included,
on Win32 and Win64.
51. FIXED, BEHAVIOUR CHANGE - a run of wrong passwords locks out the address it
came from, not the account
StreamSec.Mail.Users, StreamSec.Mail.Retrieval, StreamSec.Mail.IMAPServer,
StreamSec.Mail.POP3Server, StreamSec.Mail.SMTPServer, MAIL.txt.
THE STEP THAT FAILED: TsmMailUsers.VerifyEx kept one failure count per
account. Ten wrong passwords from anywhere refused the RIGHT password from
everywhere, on IMAP, POP3 and SMTP, on every port, for LockoutSeconds. All
anybody needed to shut a user out for as long as they cared to keep trying
was the mailbox address.
Affected: every release with the mail family, 4.1.2.355 to 4.1.5.362, on
every platform.
BEHAVIOUR CHANGE:
- Failures are counted per account AND source address, in a table on the
component. The count that locks, MaxFailures (10), and the time it locks
for, LockoutSeconds (900), are as they were. A locked-out address is
refused the right password too; another address signs in. A right password
clears its own address's count and nobody else's.
- One source is one IPv4 address, or one /64 of IPv6: RFC 4291 sec.2.5.4
gives a global unicast address a 64-bit interface identifier, so one host
may hold every address of its /64. A v4-mapped address is the IPv4 address.
The new function MailUserSourceKey says what counts as one source.
- The table is bounded: MaxFailureEntries, new, default 16,384 entries,
cMailUserFailureEntries, chosen, not measured. Only an account that exists
gets an entry. When it is full the oldest entry not locked out goes first,
then the oldest locked out. What goes is that address's count, so a full
table gives an address its guesses back sooner and never refuses a sign-in.
- The table is in memory, so a restart ends every lockout. The count used to
be written to the account file at each failure; it is no longer, so a wrong
password causes no disk write. The file's Failures and LastFailure fields
are still read and written, and lock nobody.
- New overloads Verify, VerifyEx and IsLocked take the source. Verify and
VerifyEx with no source still compile and count as one source of their own,
so an application that calls them gets the old behaviour among those calls.
IsLocked with no source now answers whether ANY source is locked out, and
Unlock clears every source.
- TsmCustomMailRetrievalServer.DoAuthenticate, a protected method, takes the
source. The log line of a refused sign-in on IMAP and POP3 names the
address.
WHAT THIS LEAVES, stated so nobody assumes otherwise: guessing spread over
many addresses. Each may make MaxFailures guesses at an account, then one per
LockoutSeconds. Nothing counts across addresses, because a limit across
addresses is what let a stranger lock an account out. See MAIL.txt section 7.
An address shared by several clients is one source: a NAT gateway's users
share a lockout.
52. FIXED, BEHAVIOUR CHANGE - with DNS not answering, VerifyInbound defers a
message instead of accepting it
StreamSec.Mail.MessageAuth, MAIL.txt.
THE STEP THAT FAILED: tSmtpMessageAuthenticator.Decide took a DMARC record
that could not be retrieved for no policy at all, because
FailClosedOnTempError defaulted to False. With this server's DNS unreachable,
a forged sender of a p=reject domain was accepted at end-of-data and
delivered, stamped spf=temperror and dmarc=temperror. Anybody able to
interrupt the server's DNS could pass the check. The other way round, an SPF
temperror under a retrievable p=reject refused a message for good that a
definite SPF answer might have passed.
Affected: every release with the mail family, 4.1.2.355 to 4.1.5.362, on
every platform, with VerifyInbound on. TsmSMTPServer has it off by default.
BEHAVIOUR CHANGE. FailClosedOnTempError now defaults to True:
- A DNS failure on the DMARC record, at the From domain or its organizational
domain, is 451 4.4.3, after DATA. It was 451 4.7.5 where the property had
been set by hand.
- p=reject or p=quarantine with a DMARC fail and an SPF temperror is 451
4.4.3. p=reject was 550; p=quarantine was delivered.
- RFC 7489 sec.6.6.3 leaves DNS errors at the DMARC record to the receiver
and names the case: "they could result in the message being temporarily
rejected". RFC 7208 sec.8.6 on temperror: "the software SHOULD use an SMTP
reply code of 451" "and, if supported, the 4.4.3 enhanced status code". Not
changed:
- A permanent answer that no record exists: DMARC does not apply and the
message is delivered.
- An SPF temperror with no DMARC refusal at stake (no record, p=none, a pass
through DKIM): delivered and stamped spf=temperror. No SPF result alone
refuses a message here, so a definite answer could change nothing.
- EnforceDmarc False with no RequirePublishedPolicy: no DMARC answer decides
anything, and nothing is deferred on it.
- A DKIM key that could not be retrieved stays 451 4.7.5.
A sender holds a deferred message and retries, so a DNS outage longer than
its retry time turns into its bounce. FailClosedOnTempError := False on
TsmSMTPServer.Authenticator, or OnMailAuth, gives the old answer back. The
default of tDmarcEvaluator.FailClosedOnTempError itself stays False.
--------------------------------------------------------------------------------
TLS: CLIENT CERTIFICATEVERIFY KEY EXTRACTION
================================================================================
53. FIXED - a TLS 1.2 server could access-violate before verifying an ECDSA
client's CertificateVerify signature
StreamSec.Mobile.Tls, StreamSec.Mobile.TlsLayer.
With an accepted ECDSA client certificate, HandleClientCertVer queried the
certificate's SubjectPublicKeyInfo directly for iECPublicKey and ignored
the failed query. That object delegates iDLPublicKey, not iECPublicKey, so
the decoder received a nil key. Its signature-length pre-check then read
Params.GroupOrder through that nil interface, before signature verification.
No valid client signature was needed. An application catching exceptions
per connection could close it; otherwise the exception escaped that path.
The released 4.1.5.362 code has this defect.
The server now extracts iDLPublicKey first and queries that key for
iECPublicKey, checking both queries. The extracted named curve already has
its group order; missing curve expansion was not the cause. The same
correction applies to the DSA branch's iFFPublicKey query. The RSA branch
also checks its interface query before calling the decoder.
CertificateVerify decoders now reject missing key material and truncated
signature headers or bodies before dereferencing or hashing. The RSA
length bound includes the two TLS 1.2 signature-algorithm octets. The DSA
and ECDSA ServerKeyExchange decoders also refuse missing keys or domain
parameters. A valid signature is still verified cryptographically; a bad
CertificateVerify signature produces fatal decrypt_error, without an access
violation. TLS 1.0/1.1 share the corrected extraction and decoders. TLS 1.3
already extracts through iDLPublicKey and does not use this decoder.
TESTED with Delphi 13 on Win32 and Win64, using independent Node/OpenSSL
signatures for P-256, P-384, P-521 and DSA, plus invalid signatures,
truncated lengths and missing keys or parameters. Over a native-socket TLS
1.2 client authentication an accepted P-256 client authenticates; changed
signature bytes and a declared signature longer than its body each get
decrypt_error, with no exception. DSA was tested at the extraction and
decoder level.
--------------------------------------------------------------------------------
TLS AND PKIX: SIGNATURE ALGORITHMS AND PRIVATE-KEY FORMATS
================================================================================
54. NEW, BEHAVIOUR CHANGE - opt-in experimental composite ML-DSA authentication
in TLS 1.3
StreamSec.Mobile.Tls, Tls13Handshake, TlsLayer, StreamSecII and
TlsInternalServer.
SignatureCompositeMLDSA now enables the implemented composite profiles for
TLS 1.3. The TLS draft still has no assigned SignatureScheme values: FE30
through FE3F are a StreamSec PRIVATE-USE mapping of the sixteen implemented
LAMPS profiles, not IANA assignments. The option remains prNotAllowed by
default. Both peers must explicitly opt in and agree to that mapping. No
public composite TLS interoperability is implied.
Thirteen profiles can sign CertificateVerify. The three RSA-PKCS1 composite
profiles are certificate-signature-only and are excluded from that message
and its offer. signature_algorithms_cert carries the separate certificate-
signature policy. Explicit TLS 1.2 offers carry no PQ or experimental
signature schemes; this is not a TLS 1.2 extension (RFC 9851 section 2).
The server cache and key ring now retain composite identities loaded from
PFX, including replacement, and choose an eligible identity against the peer
offer. The client selects an identity and scheme against CertificateRequest.
Schemes must match the actual public key and parameter set; a certificate
signature is not the CertificateVerify algorithm.
BEHAVIOUR CHANGE: an unmapped certificate-signature algorithm is no longer
treated as advertised. A sender must find a certificate signature allowed by
the peer certificate-signature list, or by its signature_algorithms list
when the separate extension is absent. Unknown and unoffered schemes,
certificate-only profiles in CertificateVerify, wrong keys and damaged
signatures remain errors.
Malformed, empty or duplicate signature-list extensions are rejected.
Verification retains an owned copy of the actual transmitted offer, so a
callback cannot broaden it during the handshake. A HelloRetryRequest retains
the first ClientHello signature lists.
55. FIXED, BEHAVIOUR CHANGE - TLS 1.3 distinguishes an RSA-PSS key from an
ordinary RSA key using a PSS signature
StreamSec.Mobile.Tls13Handshake, TlsLayer and StreamSecII.
The rsa_pss_pss_sha256/384/512 schemes (0809, 080A, 080B) are selected for
an id-RSASSA-PSS SubjectPublicKeyInfo, separately from rsa_pss_rsae_* for
rsaEncryption. Previously the restricted key had no complete selection and
verification path. Both client and server authentication now match the key
family and public and private parameter restrictions before signing or
accepting CertificateVerify.
A fixed hash or MGF restriction must permit the selected TLS scheme, and the
TLS salt length must satisfy the key minimum. An unconstrained PSS key is
not silently constrained to the factory default. Candidate selection
continues to a compatible offered hash instead of stopping at an
incompatible first choice. The signature is still verified
cryptographically; a right algorithm name is not proof of a right signature.
Certificate-signature selection uses the issuer key family when
distinguishing the PSS schemes. Ordinary RSA certificates signed using PSS
retain their ordinary RSA subject-key identity. Unsupported restrictions and
a mismatched scheme are refused rather than converted to rsae or PKCS1 v1.5.
For certificate signatures, present issuer PSS parameters must match the
certificate signature parameters exactly (RFC 9846 section 4.2.3). This is
separate from the minimum-salt rule for CertificateVerify.
56. FIXED, BEHAVIOUR CHANGE - PKCS #8 generic signing extraction and RSA-PSS
identity survive export
StreamSec.DSI.Pkcs8 and StreamSec.DSI.Pkcs8Format.
ExtractSignPrivateKey omitted the existing typed ML-DSA and composite ML-DSA
extractors, so a decoded private key could be available through its typed
interface and absent through the generic signing API. The generic path now
returns both. Pure ML-DSA extraction also sets the pure signing mode rather
than inheriting the provider factory hash default.
RSA-PSS extraction read the salt length but did not put it on the signing
key. It now retains the salt, hash and MGF restrictions and signature-only
usage. Imported RSA keys retain an independent immutable AlgorithmIdentifier
snapshot for export, including absent versus explicitly encoded PSS
parameters; source-object release or later mutation cannot change it.
The PKCS #8 formatter serializes the current private-key material with that
original algorithm. Legacy usage attributes and conflicting mutable
preferences cannot weaken intrinsic PSS restrictions. Ordinary RSA using a
PSS signing preference remains rsaEncryption, including a signing-only
ordinary RSA key; it is not reclassified as an intrinsically PSS-restricted
key.
BEHAVIOUR CHANGE: incompatible preferences are refused, rather than exported
as a different algorithm or weaker constraints. The existing ASN.1 data
interfaces remain reachable through the metadata view.
57. FIXED - PFX StorePrivateKeyEx writes RSA-PSS keys without dropping their
algorithm or parameters
StreamSec.DSI.Pkcs12.
The convenience writer handled rsaEncryption but had no id-RSASSA-PSS
branch. It now writes that signing key in its encrypted PKCS #8 safe bag,
with the original hash, MGF and salt parameters or their absence, through
both PBES2 and compatibility encryption. Current private-key integers are
written, not a stale copy of the imported key material.
Conflicting PSS preferences and an attempt to label an intrinsic PSS key as
rsaEncryption are refused. Integrity and password processing are unchanged.
Independent OpenSSL decryption, public-key comparison and verification with
the recovered key cover the exported container.
58. NEW - read-only observation of the peer CertificateVerify algorithm
StreamSec.Mobile.TlsClass and TlsLayer.
TCustomTLS_ContentLayer.PeerCertificateVerifyScheme is the Word observed in
a complete parsed peer CertificateVerify. Read
PeerCertificateVerifySchemeAvailable first: an unavailable zero is not an
algorithm selection. Availability records the message, not successful
verification, certificate authentication or handshake completion.
TLS 1.3 records the peer message in either role. TLS 1.2 records the
explicit hash/signature pair when the server receives the client
CertificateVerify; the server ServerKeyExchange is a different message. TLS
1.0/1.1 implicit algorithms, PSK-only handshakes and resumed handshakes with
no CertificateVerify remain unavailable.
A complete but rejected scheme or signature stays observable after a fatal
error. Truncated vectors do not set availability. A new handshake clears the
old observation; KeyUpdate and connection close retain it. No value is
inferred from the certificate issuer signature or the cipher-suite hash.
Documentation: the CHM builder now balances nested class, interface, object
and record bodies while indexing the containing class. A private nested
update helper no longer truncates the TsmStreamSecII API pages or exposes
its methods as unit routines. Forward declarations still resolve to their
full class.
59. FIXED, BEHAVIOUR CHANGE - nonclassical peer-signature policy no longer
depends on the local certificate family
StreamSec.Mobile.TlsInternalServer.
HandleCipherSuitesChange turned SignatureEdDSA and SignatureMLDSA off when
PublicKeyAlgorithms contained no local signing certificate of that family.
Those options also supplied the peer verification list and
CertificateRequest, so an EdDSA server rejected an otherwise valid ML-DSA
client, and the reverse, although matching-family handshakes worked.
Explicit EdDSA, ML-DSA and composite peer acceptance is now retained
independently of the local identity. Local signing still requires an
eligible certificate and matching private key and peer offer. Explicit
prNotAllowed remains a refusal; no verification, EKU, name, trust or
required-client-certificate check is bypassed. Defaults are unchanged.
BEHAVIOUR CHANGE: enabling one of these peer algorithms now permits that
peer family without loading a local identity of the same family.
Applications no longer need a layer callback merely to restore the
configured peer acceptance list. Entry 62 does the same for RSA, DSA and
ECDSA, and says what server choices that removes from these options.
Server startup now checks cached local identities independently of peer
acceptance when own certificates were configured or rejected. An all-revoked
or unmatched own identity cannot start certificate-authenticated service
merely because a peer algorithm remains allowed. Fresh and key-only dynamic
certificate callbacks, explicit anonymous configurations, client engines and
real enabled PSK ticket state retain their setup paths. An own-store
rejection is retained for a readable startup diagnostic and cleared by
ClearCertificates.
--------------------------------------------------------------------------------
TLS: MISSING CLIENT CERTIFICATES AND INDY ACCEPT THREADING
================================================================================
60. FIXED - TLS 1.2 reports handshake_failure for an empty required client
Certificate, preserving the rejection when an alert handler raises
StreamSec.Mobile.TlsLayer.
HandleClientCert emitted bad_certificate inside its validation try/except
block. The internal server's default outgoing-alert handler raises an
exception; that exception was caught and reported again as internal_error.
This was shared TLS code, with behavior depending on the alert handler:
a non-raising handler, such as the async server's, avoided the conversion.
The first fatal record could still contain bad_certificate because closing
the TLS write side suppresses subsequent records; the exception and last
alert code could therefore disagree with the pending response bytes.
Policy alerts are now emitted outside the validation exception handler.
An empty required Certificate produces fatal handshake_failure, as RFC 5246
sec.7.4.6 specifies; a rejected nonempty certificate retains bad_certificate.
TLS 1.3 retains certificate_required. Optional empty client certificates
continue without client authentication.
TESTED with Delphi 13 on Win32 and Win64: both TLS versions cover default,
logging and raising alert handlers, optional empty certificates and a valid
client identity.
The pre-fix TLS 1.2 case reproduces bad_certificate on the wire with an
internal_error exception from the default handler; a raising user callback
is invoked twice. The fixed case sends one handshake_failure and preserves
that error in the exception.
61. FIXED, BEHAVIOUR CHANGE - the Indy TLS adapter defers the server handshake
until the accepted connection performs encrypted I/O
smTLSId10D<nn>IOHandler.pas in each Demos folder from Delphi XE3 through
Delphi 13, one unit per version.
AfterAccept used to call StartSSL in Indy's listener thread, serializing
handshakes and letting a stalled peer block new connections. It now arms
implicit TLS without exchanging records. The first encrypted read or write
performs the handshake, normally in the connection thread, and handshake
errors reach the connection's OnException handler. A failed handshake also
raises before encrypted I/O can access the TLS socket released by Close.
OnConnect can now run before TLS authentication. If it needs the client
certificate or negotiated TLS details before doing I/O, call the accepted
IOHandler's StartSSL explicitly there. Setting PassThrough to False again
does not force this, because implicit TLS has already armed that flag.
Avoid I/O in listener callbacks such as OnContextCreated: the thread doing
the first encrypted I/O owns the handshake. STARTTLS from passthrough mode
and outbound client handshakes retain their immediate behavior.
TESTED: the adapters build with their native compilers, Win32 and Win64,
for every demo version from XE3 through Delphi 13. On the wire, with XE3,
Delphi 11, Delphi 12 and Delphi 13 builds on Win32 and Win64: TLS 1.2 and
TLS 1.3, idle and malformed clients, read-first and write-first protocols,
explicit StartSSL, STARTTLS and plain passthrough.
--------------------------------------------------------------------------------
TLS: TLS 1.2 CLIENT CERTIFICATE REQUESTS
================================================================================
62. FIXED, BEHAVIOUR CHANGE - TLS 1.2 client authentication selects a usable
identity and signature against the actual CertificateRequest
StreamSec.Mobile.Tls, TlsConst, TlsLayer, X509Comp, StreamSecII and
TlsInternalServer.
A mixed request containing RSA and ECDSA previously rejected an available
RSA identity because every advertised certificate type had to be supported.
Requests now select a matching certificate and private key from the offered
alternatives. Validity, revocation, digitalSignature, clientAuth, issuer
names, configured algorithm/hash policy and matching private-key possession
are checked before a chain is sent. The restrictions of a certificate
whose subject public key is id-RSASSA-PSS, including its PSS parameters,
cannot be overridden by an rsaEncryption certificate for the same key or by
mutable signing preferences; the private key does not record them. An
empty authority-name list leaves the issuer unconstrained; it does not
relax the remaining checks. Ineligible
candidates are skipped so another configured identity can be selected.
Standard ECC certificate types are 64, 65 and 66; the previous 5, 6 and 7
values are no longer emitted or treated as their substitutes. The request's
exact signature pairs are retained separately from known hash/family sets.
CertificateVerify uses the chosen offered hash and correct TLS 1.2 framing
for RSA, DSA and ECDSA; an unsupported or forbidden offer cannot become an
unoffered SHA-256 or SHA-1 fallback. Certificate issuer-signature constraints
are checked separately, including RSA-PSS versus PKCS1 issuer signatures.
A self-signed client leaf remains subject to those constraints.
No usable identity produces one empty Certificate and no CertificateVerify;
required authentication continues to fail. Request/key/message state is
cleared before another request, and a full new handshake no longer offers
an old session identifier after cached resumption was declined. Optional
empty certificates do not retain a prior CertificateVerify requirement.
Servers bind received client types and exact nonempty CertificateVerify
framing/pairs to the request actually sent, before accepting authentication.
Cached and dynamic requests accept configured peer signing families
independently of the server's own certificate family. Simple components
preserve explicit RSA/DSA/ECDSA refusals instead of silently re-enabling them
on option changes. Legacy server cipher lists still require usable local
credentials; default DSA and deprecated agreement settings remain off.
Empty classical request policies produce no malformed cached template.
The signature options therefore no longer restrict what a server signs
with. Turning every signature scheme off does not make an RSA certificate
key-transport only, and no signature option can forbid the server's
PKCS#1 v1.5 signatures while allowing RSA-PSS. Key transport only follows
from the certificate: an RSA leaf without digitalSignature in its keyUsage
is not used for the signing suites. Signing only with RSA-PSS also follows
from the certificate: one whose subject public key is id-RSASSA-PSS. The
private key does not record the difference; the certificate carries it.
New API: TInternalCertificateRequest.supported_sign_schemes retains ordered
wire pairs; TLS12_EncodeCertificateVerify overloads take an explicit hash;
ExportClientChainToTLS checks signing candidates through a callback supplied
with the complete local issuer path. The path is cycle-safe and bounded at
32 certificates. Wire root omission remains governed by
IncludeRootInTLSChain.
Existing encoder entry points and explicitly configured fixed-agreement
paths remain; this does not add TLS 1.2 PQ or new subject-key families.
TESTED with Delphi 13 on Win32 and Win64: public sessions on the wire, the
decoder and encoder, the selector and its cache, and strict interop with
OpenSSL. Tests were written and failed before the respective corrections.
Both positive controls and rejection-stage evidence are kept. Legacy TLS
1.0/1.1 mTLS controls use explicitly lowered test-only policy.
--------------------------------------------------------------------------------
TLS: PEER CERTIFICATE DIAGNOSTICS
================================================================================
63. ADDED, FIXED - Per-handshake peer certificate evidence and chain-import
verdict
StreamSec.Mobile.TlsClass and TlsLayer.
TCustomTLS_ContentLayer now exposes PeerCertificateList as an independent
copy of the raw uint24-length-prefixed DER entries received from the peer,
before certificate import or validation. Order, duplicates and unrelated
entries are preserved. TLS 1.3 certificate context and entry extensions are
removed by the existing normalizer; this list is not a constructed path.
PeerCertificateValidationAttempted, PeerCertificateChainAccepted and
PeerCertificateStatus report the chain-import step. Later hostname, EKU and
proof-of-possession checks remain separate. An empty status without an
attempted import must not be interpreted as successful authentication.
Starting a new handshake clears all four diagnostics, so renegotiation and
PSK-only resumption cannot display an earlier handshake's certificates or
trust verdict. Completed evidence survives Close and TLS 1.3 KeyUpdate.
These accessors do not change authentication or trust policy.
TESTED with Delphi 13 on Win32 and Win64, with the library alone, including
real TLS 1.2/1.3 handshakes, rejected-chain versus wrong-name verdicts,
exact normalized bytes, copy isolation and bounds, same-layer renegotiation,
PSK resumption with accepted 0-RTT, Close and KeyUpdate. The lifecycle
checks failed before the reset fix. No application source or OS trust store
is required.
--------------------------------------------------------------------------------
TLS: SESSION RESUMPTION AND CIPHER TRANSITIONS
================================================================================
64. FIXED - TLS 1.2 abbreviated handshakes and cipher transitions
A client accepting a cached session no longer waits for a new Certificate
or ServerKeyExchange before the server's CCS and Finished. A declined
session still requires the full authenticated server flight. Both peers
bind resumption to the cached version, cipher suite and compression method;
resumed-session flags describe the current handshake.
Legacy renegotiation CCS records are authenticated with the old connection
keys before installing the new read keys. A second incoming CCS cannot
reinstall those keys. TLS 1.3 retains its dummy-CCS handling.
TESTED: 180 public-API checks on each of Win32 and Win64 cover fresh and
same-layer resumption, full fallback, negotiated-parameter changes, missing
flights, altered Finished and CCS records, and bidirectional application
data. TLS 1.3 full-handshake controls also pass. The expanded suite recorded
172 passes and eight failures per architecture before the CCS corrections;
both matrices now pass. Server tuple and duplicate-installation guards
also received independent source review.
--------------------------------------------------------------------------------
TLS: DEFAULT CLIENT CIPHER CACHE
================================================================================
65. FIXED - Recompute the local cipher list when every preference is a default
StreamSec.Mobile.TlsInternalServer.
The temporary options object introduced by Change 62 could retain an empty
derived cipher list when Assign copied only default-valued preferences.
Switching an already initialized component to client mode could then replace
its valid cipher cache with nil, emitting a TLS 1.2 ClientHello with no
suites.
The temporary object now explicitly computes its final list after local-key
filtering. Explicit peer refusals and server credential limits remain intact;
no prohibited algorithm or deprecated protocol is enabled. This corrects an
unreleased regression in Change 62, not a released version of the library.
TESTED: actual public TLS 1.2 ClientHello records on Win32 and Win64, with
both initialization orders and explicit ECDSA refusals. The valid
loaded-before-role order failed before this correction.
--------------------------------------------------------------------------------
PKIX: AUTHENTICATED CRL REPLACEMENT AND REMEMBERED GENERATIONS
================================================================================
66. FIXED, BEHAVIOUR CHANGE - Reject authenticated CRL rollback before replacing
a held issuer list or its persistent cache
StreamSec.DSI.PkixCRL, StreamSec.DSI.PkixKeyFilter,
StreamSec.Mobile.X509Comp, PKIX.txt.
A valid signature and a current nextUpdate do not establish that a CRL is
newer than one already held. The DSI filter now authenticates the issuer
before comparing the loaded generation, the signed cache file at the
destination and every other signed list of the same issuer and scope in
the cache directory. A lower number, a backwards thisUpdate, removal of a
known number, or different signed TBS contents at an equal number is
rejected. Exact signed-content retransmission remains idempotent. An
authenticated list in the cache directory, expired or not, remains an
ordering floor for LoadCRL through a normal process restart, under
rpSoftFail and rpHardFail alike, whatever its file name and whatever file
name the later LoadCRL uses; a list in a file FileFilter does not select
is a floor while that file can be read (see below). A startup scan keeps
the same order (see below).
New shared functions CRLHaveSameScope and CRLMayReplace compare issuer Name,
exact issuingDistributionPoint and full/delta class. Callers authenticate
both lists under the intended issuing key first. Verifier capacity covers
nonnegative 160-bit magnitudes without Int64 truncation; a required leading
sign octet can make their DER INTEGER contents 21 octets long. A number of
2^159-1, encoded in exactly 20 content octets, is accepted. This capacity
bound is not a strict 20-DER-content-octet issuer-profile check. Initially
unnumbered lists retain a time/content ordering path.
LoadCRL now accepts an optional expected-issuer certificate. Existing
one-argument calls still compile and work, with this limit: without the
expected issuer LoadCRL accepts a list of any CA the certificate manager
trusts. A genuine list of another trusted CA, substituted on the network
path for the one requested at a cache file name that has no file yet, is
cached under that name, and the requested CA's lists are then refused
there until that file is removed; the error names the file. Passing the
expected issuer, the CA the list was requested from, prevents this.
Verification, generation checks, atomic cache replacement and loaded-list
replacement share the filter's write lock. RemoveCRL uses that lock too.
A stale-list fetch callback must return the same authenticated
issuer/scope and respect the stale argument's own floor, including on a
cold directory scan. What it returns is read only after its signature has
been checked; a reply that does not authenticate, or anything that raises
while a reply is judged or applied, leaves the stale list as if nothing
had come back. LoadCRL persists the selected fresh replacement rather
than the stale argument passed to the callback.
BEHAVIOUR CHANGE - a cache file belongs to one issuer and scope. LoadCRL
caches a list as Directory plus the file name of its argument, so the
caller names the cache file: one cache file name per issuer and scope
(issuer Name, issuingDistributionPoint, full or delta). When that file
holds a list authenticated under a CA the certificate manager trusts, but
of another issuer or another scope than the list being loaded, LoadCRL now
raises eDSIPkix naming the file, which stays as it was. Earlier releases
did not read that file: the list overwrote it,
or, while the filter held a list it had loaded under that name, was
silently not loaded. Overwriting the file would take the floor of the
list it holds with it: another trusted CA's genuine list substituted on
the network path under that name and loaded without the expected issuer,
or an application that downloads every CA's list under one name, would
leave the first CA without a floor on disk, so that after a restart an
older list of that CA would be accepted, with or without the expected
issuer. An application that uses one name for several CAs, or for lists
of several scopes of one CA, now gets the refusal from the second list
on; give each issuer and scope a name of its own.
The expected issuer binds the issuer and not the scope, so a list of the
same issuer but of another scope - full or delta, or another
issuingDistributionPoint - is refused there with or without it: a CA's
genuine list of one scope, substituted on the network path for its list
of another scope, does not take that scope's place under its cache file
name, and the lists of that name go on loading.
The first list of an issuer that a cache file name holds sets the scope
of that name: a list of another scope substituted under a name nothing
was cached under yet blocks the lists meant for that name, and those
lists are refused until it is removed. To clear a name, RemoveCRL its
list, save the filter so that the CRLS section of a filter file
(FilterFileName) no longer lists it, and delete the file. RemoveCRL now
finds a list by its file name, given alone or with a path, whichever of
LoadCRL, a filter file or a directory scan loaded it: a list a startup scan
had loaded was held under its full path, and RemoveCRL with the file name
alone answered False and left it in the set.
This also keeps a CA's full list where a narrower list of the CA under
that name would stand for it: HasFreshCRLFor, which the OCSP responder
asks before it answers "good", counts any fresh list of the CA, a delta
list or a partition included. A cache file that holds no CRL, or a list
that authenticates under no trusted CA, is replaced. A name
with the extension .lock, or holding .tmp-{, in any letter case, is
refused: those are the lease and staging files of the cache directory,
and a trailing dot or space that Windows drops from a file name does not
make one of them another name. A list an earlier release cached under
such a name is no floor; load it once under a cache file name.
The floor does not depend on the in-memory set or the file name. Under
rpHardFail a directory scan at startup leaves an expired list out of
revocation use, and RemoveCRL drops a list from the set, but neither takes
that list out of the floor, for a load under any file name.
LoadCRL reads every regular file in Directory, whatever its name
and whether it matches FileFilter or not, except the .lock lease files and
the staging files of a replacement in progress, and compares the
candidate with each one that holds an authenticated list of its issuer
and scope; only those have their signature checked, and a file that is
no such list stops nothing. A file that does not start with the header
the DER reader takes for a list - the outer tag of a list is not covered
by its signature, and may also be written in the high-tag-number form -
is read no further than the octets of that header, which in that form
end only at an octet without the high bit or at the end of the file. On
Linux and macOS a FIFO or a device is not read, also should one take the
place of a file while LoadCRL opens it. A file FileFilter selects that
cannot be read at that moment - another program holding it open
exclusively, access denied - the cache file being loaded under, whether
FileFilter selects it or not, when it cannot be read, and a Directory that
cannot be listed make LoadCRL raise eDSIPkix naming them, with the cache
file as it was; retry once they can be read. Any other file that cannot be
read at that moment is no floor, so that a file of another program in
Directory, such as a log it
holds open, does not stop the load. That includes a list cached under a
name FileFilter does not select: while another program holds it open
exclusively, as another process's startup does when it reads the CRLS
section of a filter file, a lower list loaded under another name is
accepted. Cache under names FileFilter selects. Give the filter a
Directory of its own, holding the CRL cache only: left blank, Directory
is the current directory. Stage downloads outside Directory: a file
written there is a cache file.
LoadCRL reads every file it compares while sharing reading, writing and
deletion with other programs. On Windows a replacement of a cache file
still fails while any other program has the file open, even one that
shares deletion: another process's LoadCRL reading the directory, or its
startup scan. LoadCRL then raises eDSIPkix naming the file, with the
previous content kept, instead of the operating system's error; retry.
A startup scan (PopulateKeyList) keeps the same order. It used to take
the lists it found one by one in directory order and apply the revocation
policy to each on its own: under rpHardFail a higher list that had expired
was left out, and a lower list of the same issuer and scope under another
file name, still fresh, was loaded and gave that CA fresh coverage, so
that HasFreshCRLFor returned True and the OCSP responder answered "good"
for a certificate revoked only in the higher list. The scan now
first reads and authenticates every list FileFilter selects, expired ones
included, verifying each signature once, and then loads only the lists
that no higher authenticated list of the same issuer and scope among them
outranks, in the order LoadCRL applies, under every RevocationPolicy. Where
one list outranks another, the file names and the order the directory
lists them in play no part. So under rpHardFail the lower list in that
example gives no fresh coverage, and that CA has none until LoadCRL
installs a newer list: HasFreshCRLFor returns False and the OCSP responder
does not answer "good". The revocations of the lower list are applied, as
in earlier releases, and those of the higher list, which the policy leaves
out, are not: IsKeyAllowed refuses a certificate the lower list revokes
and does not refuse one only the higher list revokes. Under rpSoftFail the
higher list is loaded, stale, and its revocations are applied. A list that
another outranks is not offered to OnFetchFreshCRL either. Of lists neither
of which outranks the other - such
as identical lists under two names, two lists of one number with
different signed contents, a numbered list and a later unnumbered one, or
a higher number with an earlier thisUpdate - the first by file name is
loaded. With one list per issuer and scope in Directory, which one cache
file name for each gives, nothing changes; a single expired list is treated
by the policy as before.
A list that verifies under the certificate held for its issuer Name but
cannot be ranked outranks nothing and is applied after the others. That
is a list whose alleged issuer that certificate is not - the certificate
lacks the cRLSign key usage, or the list's authority key identifier gives
no key identifier matching it - which has its revocations applied and,
unlike in earlier releases, gives no fresh coverage, and a list whose
issuingDistributionPoint or delta CRL indicator value does not decode,
which is loaded, with its revocations and its coverage, when the filter
holds no list of its CA that does decode.
BEHAVIOUR CHANGE - beside a list of its CA that does decode, a list of the
second kind whose value does not decode at its outermost level stays out of
a scan and of a filter file, which do not apply its revocations, where
earlier releases applied those of both. LoadCRL raises a decoding error for
such a list, with the filter and the cache file as they were, except when
the value's outermost length runs past its end: then it accepts the list,
applies it and holds it beside the other. A value that decodes at its
outermost level and not further in is of another scope than that list: the
list carrying it is applied and held beside it, by a scan and by LoadCRL,
as in earlier releases.
BEHAVIOUR CHANGE - LoadCRL refuses a list of the first kind, which earlier
releases loaded and counted as fresh coverage, with an error that says
that certificate is not its alleged issuer and not that its signature is
invalid, also when aExpectedIssuer is passed.
A list whose CRL number cannot be read as an integer, is negative or is
above 160 bits is no generation: the scan leaves it out, its
revocations are not applied and it gives no coverage, and LoadCRL refuses
it. Earlier releases did not read the number.
The order reads the number and those two extensions only: any other CRL
extension, such as Authority Information Access, Freshest CRL, the CA
version and next publication extensions a Microsoft CA writes or a private
one, plays no part in it, and a list carrying one is ranked like any other.
A list that outranks others and then cannot be applied - rpHardFail refuses
it because it has expired, also when the OnFetchFreshCRL handler it is
offered to raises, or one of its entries does not decode - gives that CA
no fresh coverage and does not take the revocations of the lists it
outranks with it: those are applied, also without fresh coverage, from
their files, which are read and verified again for this, and they are not
offered to the handler. Under rpHardFail a list among them that has expired
stays out, its revocations not applied.
In this scan a file that cannot be read at that moment is passed over, as
in earlier releases, and a file FileFilter does not select is not read.
The CRLS section of a filter file (FilterFileName) follows the same order:
a listed list that another listed list outranks is not loaded (a filter
file of an earlier release can list both). BEHAVIOUR CHANGE - a listed list
that a list in Directory outranks gives way when the filter is enabled, its
revocations not applied, where earlier releases applied those of a list
under a name FileFilter selects. When that higher list cannot be applied -
under rpHardFail because it has expired - the listed list has its
revocations applied and gives no fresh coverage, as in the scan. A filter
file stays strict: a listed file is read whatever its name, and one that is
missing, cannot be read or does not authenticate makes enabling the filter
raise, as does, under rpHardFail, a listed list that has expired, as in
earlier releases. BEHAVIOUR CHANGE - so now do any two listed lists of one
issuer and scope neither of which outranks the other and which are not
identical - two of one number with different signed contents, a numbered
one and a later unnumbered one, or a higher number with an earlier
thisUpdate - and a listed list whose CRL number cannot be read as an
integer, is negative or is above 160 bits. Earlier releases loaded them.
A listed list that verifies under the certificate held for its issuer Name
and cannot be ranked, of either kind above, does not stop the enabling, not
even when it has expired under rpHardFail: the list the filter file checked
against its thumbprint is treated as the scan treats such a list, also
under a name FileFilter does not select, so that a filter file written by
an earlier release does not stop the start. This has a limit: a list that
is applied without being held - a list of the first kind above, or a listed
list whose higher list in Directory cannot be applied - leaves the CRLS
section at the next save, and its revocations are then applied at a start
only when FileFilter selects its name.
Two LoadCRL calls for lists of one issuer under two names at the same
moment do not see each other's list.
A filter file records a cache file's thumbprint at the save, and LoadCRL
replaces that file at once. Save the filter after each LoadCRL: if the
process ends between the two, or another process's LoadCRL replaces a
listed file in a shared Directory, the thumbprint no longer matches and
enabling the filter raises, as for any listed file that has changed, until
that name is out of the CRLS section.
Four older defects of the DSI filter are corrected with this change.
FIXED - the revocations of a list a filter file lists were lost at the next
start when FileFilter does not select its name. Every release up to and
including 4.1.5.362. The step that reads a filter file applied the
revocations of the lists in its CRLS section, and the step after it cleared
them again; the Entry sections of the file give none back. The directory
scan that follows applied again the lists FileFilter selects and did not
read the others, which stayed held: HasFreshCRLFor went on answering True
for that CA while IsKeyAllowed accepted a certificate the list revokes, and
the OCSP responder, which asks both, answered "good". A list LoadCRL loaded
while the filter was disabled lost its revocations the same way when a
filter file was read before the filter was enabled. Lists under a name
FileFilter selects, the default *.crl included, were not affected.
Enabling the filter now applies the revocations of every list it goes on
holding, whatever its name. Under rpHardFail a list held at that moment that
has expired is held no longer and keeps no other list out. BEHAVIOUR CHANGE
- a list held at that moment that does not verify under the certificate
then held for its issuer Name is held no longer and gives no fresh coverage,
where earlier releases went on claiming it. See above for a list applied
without being held.
FIXED - turning the filter off and on again lost the revocations of the
lists a directory scan had loaded. Every release up to and including
4.1.5.362. Enabled := False cleared the revocations and left those lists
held; on Enabled := True the scan passed over a list already held under
its path, so its revocations were not applied again, while HasFreshCRLFor
went on answering True for that CA. IsKeyAllowed then accepted a revoked
certificate and the OCSP responder, which asks both, answered "good".
Nothing about the lists or their files entered into it: a filter enabled
only once was not affected, and neither were lists loaded by LoadCRL under
a name FileFilter selects, which the scan applied again. Disabling the
filter now forgets the lists it holds and enabling it scans Directory as
the first enabling did. BEHAVIOUR CHANGE - a list cached under a name
FileFilter does not select, or listed by a filter file under such a name,
is not read by that scan: after off and on it gives no fresh coverage,
where earlier releases went on claiming it with its revocations gone.
FIXED, BEHAVIOUR CHANGE - under rpSoftFail an OnFetchFreshCRL handler that
raises, a failed download, lost the revocations of the expired list it had
been offered. Releases 4.1.1.349, which added the event, up to and
including 4.1.5.362. The call to the handler was not guarded, so the step
that records the entries of the list did not run: in a startup scan the
list was left out with no error, and LoadCRL and the reading of a filter
file raised the handler's exception. Under rpSoftFail a handler that raises
now counts as one that declined: the expired list is loaded, its
revocations are applied and it gives no fresh coverage. LoadCRL no longer
raises that exception and caches the expired list, and a filter file
listing it no longer stops the enabling. A handler that returns nil was
never affected. Under rpHardFail the exception goes on to the caller of
LoadCRL, as before.
FIXED - the DSI filter misread entries of an indirect CRL. Every release up
to and including 4.1.5.362. An entry without a certificateIssuer extension
was recorded under the list's own issuer, where RFC 5280 section 5.3.3 gives
it the certificate issuer of the entry before it, and a certificateIssuer
holding more than one GeneralName was recorded under all of them together,
which no certificate matches. So a certificate of the other issuer named
that way was accepted, and a certificate of the list's own issuer with that
serial number was refused. Other lists were not affected. For a list with
the indirectCRL flag the filter now reads an entry as
iCertificateList.IsRevoked does (entry 98): by the directoryName values in
its certificateIssuer, or those of the entry before it, and the first entry
by the list's issuer. A list without that flag is read as before.
The filter records every entry of a list as a revocation, one whose reason
is removeFromCRL in a delta list included, unlike the store of entry 98: it
errs on the refusing side.
The Mobile store already rejected lower native CRL numbers. Its full issuer
path now authenticates known-issuer signatures before advancing a floor and
uses the shared number/time/content comparison before any legacy integer
conversion. Forged queued lists cannot become authenticated floors when an
issuer is later known. Unknown-issuer deferred import and the legacy scoped
and delta paths remain; this is not a redesign of those profiles. Callers
must continue to inspect the AddCRL status, not just its returned index.
Compatibility: optional nextUpdate and the existing soft-fail, hard-fail and
ignore policies retain their meanings, but for the order of a startup scan
and a handler that raises under rpSoftFail, described above. Atomic
replacement keeps the previous
complete cache on validation or pre-rename write failure. Windows flushes the
staged file and uses a write-through replacement; the POSIX path uses atomic
same-filesystem rename, without a power-loss durability claim. Revocation
callbacks can observe stricter information before a save fails; the durable
floor guarantee concerns successfully committed bytes. The revocations of a
list are applied in memory before LoadCRL looks at the directory for the
last time and saves: when that raises, because a callback or another
program has changed a file meanwhile, they stay applied and the cache file
stays as it was. Generic startup-hook replacements are memory-only unless
committed through LoadCRL: a filter file saved while one is held names the
list its file still holds. A handler that commits a newer list through
LoadCRL during a startup scan keeps it: the scan checks the order again
before it holds the list it was working on. First contact cannot establish
the issuer's newest list, and rollback/deletion of all local trusted state
is outside this network-replay protection.
TESTED with Delphi 13 on Win32, Win64 and Linux64, with public signed
test lists: large numbers, forged and otherwise trusted wrong issuers,
equal-number conflicts, expired floors, callback substitutions, exact
replay and reconstruction after restart; on Windows, a cache file held
open so that its replacement fails, the previous bytes and freshness
evidence kept. Another trusted CA's list loaded with and without the
expected issuer under a CA's cache file name, refused with the file and
the floor kept through a restart; the same list at a name nothing was
cached under yet, the CA's own lists then refused naming the file and
taken once it is removed, and refused before anything is cached when the
expected issuer is passed; one name for two CAs; a delta list followed by
the full list under one name, refused, and taken once the delta list is
removed and its file deleted; an unauthenticated cache file; the CA's
full list substituted under the name of its delta list and of its
partition, and those lists loaded again under their names after it, also
after a restart; lower lists under other file names against an expired
floor under rpHardFail, against a floor under a name outside FileFilter
and against a cache file whose entry RemoveCRL had dropped; on Windows, a
floor another reader holds open exclusively, and a file of another
program held open in Directory, also with Directory left blank; on Linux,
a FIFO in Directory; a partition and a delta list of a CA loaded with the
expected issuer under the name of its expired full list, before and after
a restart under rpHardFail; a partition followed by the full list under
one name, refused; the lease and staging names, in either letter case
and, on Windows, with a trailing dot or space; on Linux, a FIFO renamed
over a name in Directory during the load; on Windows, a replacement that
another reader blocks, also one sharing deletion, with a filter file
saved before it, then the same load without the reader; a list in
Directory whose outer tag is written in the high-tag-number form, in two
and in three octets. At startup, a lower fresh list and a higher expired
list under two names, in both name orders, under rpHardFail and
rpSoftFail; a higher fresh list in their place; three generations;
identical lists under two names; two lists of one number with different
signed contents, in both name orders, also one of them expired; an
expired delta list beside a
full list and another CA's list beside a list; an outranked expired list
with OnFetchFreshCRL assigned; on Windows, a filter file listing the
lower list with a higher expired list in Directory, and one listing a
lower and a higher list in either order; a higher list that does not
verify, and one signed with another key under the CA's Name, beside a
lower list in both name orders; a filter enabled under one key and
enabled again under another key of the CA's Name, and, on Windows, a
filter file read under the first key; a list of a CA without the cRLSign
key usage, a list whose authority key identifier gives no key identifier,
and lists whose issuingDistributionPoint or delta indicator value does
not decode, alone and beside other lists; lists whose CRL number is not
an integer or is negative, alone and beside a list of their CA; lists
carrying Authority Information Access, Freshest CRL, the extensions a
Microsoft CA writes or private extensions, on the higher list, the lower
list or both, in both name orders and, on Windows, listed in a filter
file; a higher list with an entry that does not decode, beside lower
lists fresh and expired, under rpHardFail and rpSoftFail; an
OnFetchFreshCRL handler that raises, under both, and under rpSoftFail one
that first deletes the file of the list it is offered, replaces it or,
on Windows, holds it open; on
Windows, a filter file read under one certificate and the filter enabled
under another certificate of its key without the cRLSign key usage;
clearing a cache name with RemoveCRL by file name and by path and, on
Windows, after a restart with a filter file; under rpHardFail a fresh list
a higher expired one outranks, alone in revoking a certificate, with and
without a handler that raises, three generations and a delta list, and, on
Windows, the same listed in a filter file; a handler that raises under
rpSoftFail and rpHardFail at a startup scan and at LoadCRL and, on Windows,
under rpSoftFail while a filter file is read; replies that nobody signed,
whose authority key identifier does not decode, that are no list at all,
or that the CA signed with an entry that does not decode; the filter
turned off and on after a scan, after LoadCRL and with a replacement held;
indirect lists whose entries inherit
their certificate issuer or name it among several GeneralNames, and the
same entries without the indirectCRL flag; a handler that loads a newer
list during a scan; on Windows, a filter file saved while a replacement was
held, one read while a replacement is taken, one listing a list that is no
alleged issuer's or whose issuingDistributionPoint or delta indicator value
does not decode, under names FileFilter selects and under others, alone and
beside a list of its CA, and listed pairs of each kind that makes enabling
raise; a list of no alleged issuer below a good list of its CA; values of
the issuingDistributionPoint that decode at their outermost level only,
at a startup scan and at LoadCRL; under rpHardFail a list held that has
expired above a fresh list, after a change of the policy and after the list
expired while the filter was disabled; a filter enabled under another key
of the CA's Name with only the first key's list held; on Windows, a listed
list that a higher fresh list in Directory outranks, or a higher list that
cannot be applied; a listed list that cannot be ranked whose file a handler
overwrites during the enabling; two filter files read in turn; and a save
and a further start after a list applied without being held. All of it
against the same tests built from the units before this change.
Additional shared-cache hardening: LoadCRL now holds an OS-backed exclusive
transaction lease from the durable-floor read through application callbacks
and atomic replacement, and rechecks the current signed disk floor after a
callback. Independent managers and processes sharing a cache cannot overwrite
a newer committed generation from an old snapshot. A competing writer fails
immediately and can retry; crash/handle closure releases the lease. The .lock
sidecar is intentionally retained. AcquireCRLCacheLock exposes the same lease
for applications that need a longer-lived cache owner through a separate
directory sentinel. Two-manager callback interleaving, retry/replay/restart
and process crash-release are tested. The lease serializes publication; it
does not broadcast in-memory updates between independent filter instances
or defeat local state rollback.
--------------------------------------------------------------------------------
CMS: ENVELOPED MESSAGE CLEANUP
================================================================================
67. FIXED - Reclaim loaded EnvelopedData graphs on Clear and destruction
StreamSec.DSI.PkixCms.
TstCustomMPEnvelopedData.Clear now chains inherited cleanup, releases its
loaded envelope and cached CBC/AEAD content-encryption parameter interfaces,
then requests the same pair of GC sweeps as SignedData.Clear. The base
destructor dispatches this cleanup as well. Failed recipient/key lookup,
truncated CMS and random input are reclaimed consistently with successful
decryption. Sweep deferral still batches collection until its outermost end;
stGC's manual collection contract is unchanged.
TESTED with Delphi 13 on Win32 and Win64: real AES-256-CBC EnvelopedData
and AES-256-GCM AuthEnvelopedData decrypt Booleans and exact plaintext,
refusal outcomes, repeated Clear and destruction at 20/60 calls, live
external certificate/envelope children, and nested sweep deferral. The
cleanup batches show zero retained or peak GC growth. The same test against
the pre-fix unit fails on each target.
One certificate-reload retention case remains. It is separate and outside
the supported one-certificate-per-instance contract. No certificate reload
or collector change is included.
--------------------------------------------------------------------------------
TLS: AN OWN CERTIFICATE ADDED BY AddCertificate
================================================================================
68. FIXED, BEHAVIOUR CHANGE - a server whose own certificate came in through
AddCertificate answers TLS 1.2 clients again
StreamSec.Mobile.TlsInternalServer.
THE STEP THAT FAILED was TsmCustomTLSInternalServer.TLSSetupServer, which
since entry 62 limits the server's own TLS 1.2 cipher list to the key
families in PublicKeyAlgorithms. AddCertificate filed an own certificate in
MyCerts without recording that own certificates were loaded, so
ValidatePublicKeyPairs left PublicKeyAlgorithms empty, and TLSSetupServer
took every RSA, ECDSA and DSS suite out of the list and set KeyAgreementRSA
to prNotAllowed. The server answered every TLS 1.2 ClientHello with a fatal
handshake_failure alert and served TLS 1.3 only. TsmAsyncTLSServer.
AddCertificate and AddLocalCertificate file through this method, so a
TsmAsyncTLSServer given its identity that way was affected as well. The same
held for an own certificate that reached the MyCerts store below the engine,
with a MyCertList over it, and for a private key stored after its
certificate: nothing paired them before setup. ClearCertificates left the
record set after it had emptied MyCerts.
Which releases: none. Entry 62 came after 4.1.5.362. In 4.1.5.362 and
earlier, AddCertificate also left the record unset, but TLSSetupServer did
not narrow anything on it; only a later re-run of the narrowing, which a
change to Options makes on a component whose Loaded has run, applied the
empty PublicKeyAlgorithms, and in those releases that narrowing also turned
the Signature* options off. That released path was found by reading the
source and has not been reproduced.
Now the record is MyCerts itself: ValidatePublicKeyPairs counts the own
certificates whenever it runs. AddCertificate pairs keys and certificates
as soon as it files an own certificate, under the setup lock and then the
engine lock, the order every other path takes them. Assigning MyCertList at
run time pairs too. ClearCertificates empties PublicKeyAlgorithms.
TLSSetupServer pairs once more before it builds the cipher list, so a key
stored after its certificate is counted. The Signature* options stay peer
policy, as entry 62 made them: an RSA-only server with SignatureECDSA
allowed still advertises ecdsa_sign in its CertificateRequest and accepts
an ECDSA client certificate.
BEHAVIOUR CHANGE: AddCertificate of an own certificate now updates
PublicKeyAlgorithms, the local cipher list and the KeyAgreement* options at
once rather than at the next TLSSetupServer, and TLSSetupServer recomputes
PublicKeyAlgorithms from MyCerts and the keys held. After ClearCertificates,
TLSSetupServer treats an engine with no own certificate as a fresh one, as
ClearCertificates already did for a rejected certificate: it no longer
refuses to start because of a certificate that was cleared.
TESTED with Delphi 13 on Win32, Win64 and Linux64, against certificates and
TLS 1.2 ClientHello records made by OpenSSL: RSA and P-256 leaves through
AddCertificate, through a MyCertList with the key stored before and after,
ClearCertificates followed by a leaf of the other family, client
authentication with an ECDSA certificate on an RSA-only server, and the
import of a PFX file and of PFX bytes as controls.
--------------------------------------------------------------------------------
MAIL: THE IDLE LIMIT BEFORE SIGN-IN ON THE IMPLICIT-TLS PORTS
================================================================================
69. FIXED, BEHAVIOUR CHANGE - on 465 and 995 with room on the port, a session
that had not signed in was held until the whole-session limit, not the
idle limit
StreamSec.Mobile.AsyncTLSServer, StreamSec.Mail.Transport,
AsyncTLSServer.txt, MAIL.txt.
THE STEP THAT FAILED was tTLSConnection.DoNudge answering a session budget.
Since entry 49 a mail session on an implicit-TLS port that has not left its
preamble sets a budget for the preamble's whole-session limit and, once that
is reached with the port not under pressure, asks again every
cMailPreambleRecheckMs (5,000 ms). Each of those reached DoNudge as
nrRequestStalled with aRearmMs set to the idle limit, so the session's
nvKeepAlive re-armed the idle deadline from that moment. A preamble idle
limit longer than 5 s, as the defaults are (30 s), was then never reached,
and tMailImplicitClock.Expired, asked by the budget, did not test the idle
limit itself.
SYMPTOM. On 465 (Submission) and 995 (Plain), with PreamblePressurePercent
at its default of 50 and the port below it, a session that said nothing
after its banner was held until SessionTimeoutSeconds, 1,800 s by default,
not until IdleTimeoutSeconds, 300 s and 600 s. Reproduced with the limits
shortened on Win32, Win64 and Linux64: held past 16 s against an idle limit
of 7 s. By reading, the same
holds for an SMTP session back in its preamble after a message. A session
past its preamble, IMAP on 993 (its preamble applies at any load) and a
port under pressure were not affected.
Which releases: none. Entry 49 came after 4.1.5.362.
Now nrRequestStalled reaches iAppSessionNudge.Nudged and OnConnectionNudge
with aRearmMs set to what is left of the idle deadline already running, 0
when none is, so nvKeepAlive with aRearmMs left alone leaves the idle
deadline where it was, as iAppTransportDeadlines already said. And Expired
ends a session in its preamble that the peer has left silent for the whole
idle limit, whichever deadline asks. Such a session on 465 or 995 ends at
the idle limit, and SMTP says 421 there.
BEHAVIOUR CHANGE: an OnConnectionNudge handler sees, for nrRequestStalled,
the time left on the idle deadline in aRearmMs where it saw the idle limit.
No session in the library other than the mail sessions sets a budget, so
no other reason and no other protocol is affected.
TESTED with Delphi 13 on Win32, Win64 and Linux64: tMailImplicitClock on a
clock it is handed, at the default limits, and the real SMTP, POP3 and IMAP
servers on a TsmAsyncTLSServer with a TLS client, a silent session and a
signed-in one on each, against the same tests built with the step above
undone.
--------------------------------------------------------------------------------
ASYNC SERVER: WHAT COUNTS AS ONE PEER ADDRESS
================================================================================
70. FIXED, BEHAVIOUR CHANGE - MaxConnectionsPerPeer counts an IPv6 peer by its
/64 and an IPv4-mapped IPv6 peer as its IPv4 address
StreamSec.Mobile.AsyncTLSServer, stSocketAddress, StreamSec.Mail.Users,
AsyncTLSServer.txt, MAIL.txt.
THE STEP THAT FAILED was TsmAsyncTLSServer.TakePeerSlot, which counted live
connections per address TEXT, as StartPeerTransport received it. RFC 4291
sec.2.5.4 gives a global unicast IPv6 address a 64-bit interface identifier,
so one host may hold every address of its /64: rotating through them, it
was a new peer at each connection and never reached the limit. And
::ffff:192.0.2.1 and 192.0.2.1, one IPv4 peer reported two ways, had a
limit each.
SYMPTOM, found by reading. The listeners TsmAsyncTLSServer ships with, on
Windows and POSIX, accept IPv4 only and report a dotted quad, so through
them neither case arose and the count there does not change. A descendant
that hands StartPeerTransport connections it accepted over IPv6 got no
per-address limit against such a host. Entry 49 is where the limit came in,
so every user of the async server is concerned: the web server, HTTP/2,
Snip and the implicit-TLS mail ports. HTTP/3 runs on TsmAsyncQUICServer,
which has no such count.
Which releases: none. Entry 49 came after 4.1.5.362.
Now TakePeerSlot keys the address with the new PeerSourceKey, and the
connection gives its slot back by that same key on every path: a refusal
by Admit, a failure while the connection is set up, and the close. An IPv4
address is itself, an IPv4-mapped IPv6 address is its IPv4 address, and any
other IPv6 address counts by its first cPeerSourceIPv6PrefixBits bits, 64,
a port, brackets, a zone and upper-case hexadecimal making no difference.
The 64 is chosen, not measured: everybody behind one IPv6 /64 shares one
limit, as everybody behind one IPv4 NAT does.
NEW: PeerSourceKey and cPeerSourceIPv6PrefixBits in
StreamSec.Mobile.AsyncTLSServer; TsmAsyncTLSServer.PeerConnections, the
live count of the source an address belongs to; TakePeerSlot and
ReleasePeerSlot are protected, TakePeerSlot handing back the key it used;
stSocketAddress.SourceAddressKey and SourceOctetsKey, the key for any
prefix length from 1 to 128. MailUserSourceKey, the key of the sign-in
lockout, is now written by SourceOctetsKey and gives the keys it gave.
BEHAVIOUR CHANGE, for an application whose own code reaches
StartPeerTransport with IPv6 or IPv4-mapped addresses: connections from
one /64, or from an IPv4 address in either form, share one
MaxConnectionsPerPeer. OnPeerRefused still hears the address as reported.
TESTED with Delphi 13 on Win32, Win64 and Linux64: the key for addresses
in one /64 and in neighbouring ones, mapped and plain IPv4, ports, brackets,
zones and case, other prefix lengths and bad ones; the slot table through a
descendant; and the real listener over 127.0.0.1, refusing over the limit
and giving the slot back when the peer closes before its handshake, when
the handshake budget reaps it, when Admit refuses it and when its session
closes it, against the same tests built with the key undone. IPv6 loopback
is ::1 alone, and the listener accepts IPv4, so no /64 went over the wire.
--------------------------------------------------------------------------------
MAIL: SUBMISSION SENDER IDENTITY
================================================================================
71. FIXED, NEW, BEHAVIOUR CHANGE - an authenticated account may give MAIL FROM
only its own address
StreamSec.Mail.SMTPServer, MAIL.txt.
THE STEP THAT FAILED: MAIL FROM after a successful SMTP AUTH on
TsmSMTPServer. The reverse path was not compared with the account that
authenticated, so any account holder could submit mail with any envelope
sender - another account on the same server, or an address in a domain the
server has nothing to do with - and the server relayed it, and signed it
when SignOutbound is on. The AUTH= parameter of MAIL was already ignored and
lent no identity.
Affected: every release with the mail family, 4.1.2.355 to 4.1.5.362, on
every platform.
BEHAVIOUR CHANGE: on a session that authenticated with SMTP AUTH, MAIL FROM
is accepted for the identity it authenticated as (the account name, or the
aAuthorizedAs an OnAuthenticate handler set), compared without regard to
case; for the null path; and for an address a client certificate on the same
connection asserts. Anything else is answered 550 5.7.1 and the session goes
on; RFC 6409 sec.6.1 lets an MSA refuse a MAIL FROM not authorized with the
authentication used. The rule runs before the spam filter and OnCheckSender,
so neither can widen it. Sessions without SMTP AUTH are not affected: an
inbound MX peer, a RelayNetworks peer and a client certificate on its own
behave as before.
NEW: the event OnCheckSenderIdentity (tSmtpCheckSenderIdentityEvent: Sender,
aEnvelope, aAccount, aPath, var aAllow) lets an application allow further
addresses for an account, such as an alias it owns. It is asked only for a
path the rule above refuses. A handler that raises allows nothing; the
client gets 451.
The header From is not checked. See MAIL.txt section 3.2.
Tested on Win32, Win64 and Linux64.
--------------------------------------------------------------------------------
MAIL: IMAP FOLDER NAMES
================================================================================
72. NEW, BEHAVIOUR CHANGE - IMAP folder names with a space and in modified
UTF-7
StreamSec.Mail.Maildir, StreamSec.Mail.IMAPEngine, MAIL.txt.
Until now CREATE, RENAME, SELECT, APPEND and the other mailbox commands
refused a folder name with a space, such as "Sent Items", and every name in
the modified UTF-7 of RFC 3501 sec.5.1.3, which is how an IMAP client spells
any name outside US-ASCII: the store's allowlist took letters, digits, dot,
underscore and hyphen only, and the client was told "cannot create that
mailbox".
NEW: a folder segment may also hold an interior space and modified UTF-7.
The name is decoded to check it and stored under its own spelling as the
Maildir++ directory - '.Sent Items', '.&AMQ-rende' - as Dovecot and Courier
store theirs, so LIST returns exactly what the client created. A name is
accepted only as the one canonical spelling of what it decodes to: no
padding bits, no null shift, and no run that encodes printable US-ASCII, so
an encoded dot, slash or backslash is refused. The decoded text may hold no
control character, lone surrogate, U+FFFE, U+FFFF or bidirectional
control. Account directories and local parts keep the old allowlist. The
new functions MailSafeFolderSegment, MailEncodeFolderName and
MailDecodeFolderName are the allowlist and the conversion.
NEW: spaces around a folder name and around each of its segments are
trimmed, as more likely a keyboard error than a chosen name: CREATE
" Work . Sent " makes 'Work.Sent', and SELECT "Work.Sent " opens it.
Interior spaces are kept. This holds for the mailbox names of every IMAP
command (not the patterns of LIST and LSUB) and for the store's own
functions alike, through the new function MailTrimFolderName. Only the
space U+0020 is trimmed; a tab or another control is refused. A segment
left empty is refused, and the store refuses a name of spaces alone rather
than take it for INBOX. A trimmed spelling is the name it trims to: RENAME
"Work " "Work" is a rename onto itself and refused.
BEHAVIOUR CHANGE: the IMAP server trimmed the whole name only, and took off
a tab or another control character at either end along with the spaces.
Now only spaces are trimmed, so a name ending in a tab is refused rather
than created without it.
BEHAVIOUR CHANGE: the default folder comparison, the answer
OnCompareFolderName's aSame arrives holding, no longer ignores ASCII case
inside a modified UTF-7 run, where letter case is part of the encoded value:
'&AOQ-' (a with diaeresis) and '&AoQ-' (U+0284) are two folders. Only names
with an '&' in them are affected. On Windows, where the two would be one
directory, CREATE of the second is refused.
See MAIL.txt section 7.1.
Tested on Win32, Win64 and Linux64.
--------------------------------------------------------------------------------
MAIL: IMAP SEARCH
================================================================================
73. FIXED, NEW - IMAP SEARCH looks in the named field, and takes OR, NOT and
parenthesised lists
StreamSec.Mail.IMAPEngine, MAIL.txt.
THE STEP THAT FAILED: evaluating the SEARCH keys FROM, TO, CC, BCC, SUBJECT
and HEADER in TsmIMAPServer. A message matched when its whole header block
held '<KEY>:' somewhere and the string somewhere else, so 'TO:' was found
inside 'Reply-To:' and 'In-Reply-To:', SEARCH FROM alice found every message
sent TO alice, and SEARCH SUBJECT x found a message with x in any field. A
folded field did not match across its fold, an empty string matched
nothing, and BODY searched the header as well. The answer could hold
messages that do not match, which a client then shows or acts on as
matches. A string sent as a literal left no placeholder in the command, so
a key after it was read as its value.
Affected: every release with the mail family, 4.1.2.355 to 4.1.5.362, on
every platform.
Now FROM, TO, CC, BCC and SUBJECT match the string, without regard to case,
in the unfolded value of that header field only, and HEADER in the value of
the field it names (RFC 3501 sec.6.4.4, RFC 9051 sec.6.4.4); an empty
string matches every message that has the field. BODY is the body alone,
TEXT the header and body. A SEARCH whose string arrives as a literal is
answered NO "SEARCH takes quoted strings, not literals".
NEW: OR, NOT and parenthesised lists, nested. The command is parsed whole
before any message is read: a malformed tree is BAD, and an unknown key
anywhere in it, also inside NOT, is NO. Nesting deeper than the new
constant cImapMaxSearchDepth (100) is NO [LIMIT]. A '\"' inside a quoted
string in any parenthesised argument no longer ends the string. A
sequence-set or UID key is held as the ranges it was written as, never
as a list of the messages it selects, so the memory a SEARCH needs
follows the length of its command line, not the number of messages in
the mailbox (entry 95).
See MAIL.txt sections 6.3 and 6.4.
Tested on Win32, Win64 and Linux64.
--------------------------------------------------------------------------------
MAIL: IMAP MOVE
================================================================================
74. NEW, BEHAVIOUR CHANGE - IMAP MOVE and UID MOVE (RFC 6851)
StreamSec.Mail.IMAPEngine, StreamSec.Mail.IMAPServer,
StreamSec.Mail.Maildir, MAIL.txt.
NEW: TsmIMAPServer answers MOVE and UID MOVE (RFC 6851) and names MOVE in
CAPABILITY. Until now a client had to COPY, STORE +FLAGS \Deleted and
EXPUNGE, and a failure between those steps left the message in both
mailboxes or marked \Deleted for another client to see.
The store moves each message by one rename of its file into the target's
cur/ directory, under a fresh base name and with its flags, so at every
instant, a crash included, the message is in exactly one of the two
mailboxes. Its UID in the target is reserved in the target's index before
the first rename; a reserved UID that is not used is never handed out.
\Deleted is never set on the way, and messages the set does not name keep
whatever flags they carry.
The answer is an untagged OK [COPYUID <uidvalidity> <source UIDs> <target
UIDs>], then an untagged EXPUNGE for each moved message, highest number
first, then the tagged OK (RFC 6851 sec.3.3 and 4.3, RFC 4315 sec.3). A
message that could not move stays where it was and the command answers NO,
after the COPYUID and EXPUNGEs of those that did. A store fault part way
through, such as a keyword table or index of the target that cannot be
written, stops the move at that message and is answered the same way, with
the fault in the server log. A missing target is NO [TRYCREATE] and an
EXAMINE selection NO; in both nothing moves.
BEHAVIOUR CHANGE for custom implementations of the interfaces:
iMailboxView has the new method MoveTo and the new GUID
{A39E1789-A39C-4130-8441-CE0CC527981D}; iImapServerPolicy has the new
method MoveMessages and the new GUID
{C330C64D-A464-4131-9299-1A826B57E4EE}.
See MAIL.txt section 6.3.
Tested on Win32, Win64 and Linux64.
--------------------------------------------------------------------------------
MAIL: IMAP SPECIAL-USE
================================================================================
75. NEW, BEHAVIOUR CHANGE - IMAP special-use mailboxes (RFC 6154)
StreamSec.Mail.IMAPEngine, StreamSec.Mail.IMAPServer, MAIL.txt.
NEW: TsmIMAPServer advertises SPECIAL-USE and CREATE-SPECIAL-USE, and
LIST gives a folder the attributes \Sent, \Drafts, \Trash, \Junk or
\Archive (RFC 6154 sec.2), so a client finds the folders it files sent,
draft, deleted, junk and archived mail into without asking its user.
The new published property TsmIMAPServer.SpecialUse is the mapping: one
'<attribute>=<folder>' per line, the folder by its full IMAP name,
compared as the store compares folder names. Its default, the new
constant cImapDefaultSpecialUse, maps Sent, Sent Items and Sent Messages
to \Sent; Drafts to \Drafts; Trash, Deleted Items and Deleted Messages
to \Trash; Junk, Spam, Junk E-mail and Junk Email to \Junk; and Archive
to \Archive. A line with another attribute or no folder maps nothing.
CREATE <name> (USE (<attributes>)) creates the folder when the mapping
already gives that name every use asked for, and is otherwise NO
[USEATTR] with nothing created (RFC 6154 sec.3). The new constant
cImapSpecialUses lists the five uses a folder can carry.
BEHAVIOUR CHANGE: LIST answers '* LIST (\Sent) ...' and the like where it
answered '* LIST () ...'; LSUB is unchanged. CREATE with anything after
the name other than (USE (...)) is BAD, where the rest of the line was
ignored. iImapServerPolicy has the new method SpecialUse and the new GUID
{D469B5E5-9509-4D02-8A3A-2154FA9D74BD}.
See MAIL.txt section 6.3.
Tested on Win32, Win64 and Linux64.
--------------------------------------------------------------------------------
MAIL: IMAP KEYWORDS
================================================================================
76. NEW, BEHAVIOUR CHANGE - IMAP keywords, $Junk and $NotJunk among them
StreamSec.Mail.IMAPEngine, StreamSec.Mail.IMAPServer,
StreamSec.Mail.Maildir, MAIL.txt.
NEW: TsmIMAPServer stores IMAP keywords. $Junk and $NotJunk, the keywords
of the IMAP keyword registry (RFC 5788) a client sets when its user marks
a message as junk or not junk, were refused with NO "unsupported flag",
like every keyword. Now STORE, APPEND, COPY and MOVE take keywords; SELECT
lists the folder's keywords in FLAGS and PERMANENTFLAGS, with \* while
the folder can take a new one (RFC 3501 sec.7.1); a STORE that defines one
answers an untagged FLAGS; SEARCH KEYWORD and UNKEYWORD test them. A
keyword matches without regard to case and keeps its first spelling.
The store keeps them in the Maildir, as lower-case letters 'a' to 'z' of
the message's info suffix, named by a keyword table per folder,
ss-keywords, beside the folder's index, in the format of Dovecot's
dovecot-keywords. Another session and a restart see them. COPY, MOVE and
RENAME INBOX carry keywords by name into the target's table.
Limits, new constants: cMailMaxKeywords (26) keywords per folder, fixed by
the letters of the format, past which a STORE needing a new keyword is NO
[LIMIT]; cMailMaxKeywordLength (64), chosen, not measured. The new
function MailKeywordIsValid says what a keyword may be, and the new
exception eMailKeywordLimit is raised for a full table.
BEHAVIOUR CHANGE: STORE FLAGS (...) without a keyword now also clears the
message's keywords (RFC 3501 sec.6.4.6). tMailItem has the new field
Keywords. iMailboxView has the new methods Keywords, SetFlagsKeywords and
AppendKeywords and the new GUID {D7A588E2-EC8B-4BDE-8C67-11F37AAEA50C}.
iImapServerPolicy.SetFlags and AppendMessage take a new const aKeywords,
and the new method MailboxKeywords answers the keywords and the room
left; its new GUID is {0CC1868F-BF1A-4277-B502-594DAB0AE271}. The new
functions ImapTextToFlagsKeywords and ImapFlagsKeywordsToText are the
flag lists with keywords.
See MAIL.txt sections 6.3 and 7.1.
Tested on Win32, Win64 and Linux64.
--------------------------------------------------------------------------------
MAIL: QUOTAS
================================================================================
77. NEW, BEHAVIOUR CHANGE - Mailbox quotas: IMAP QUOTA (RFC 9208) and the
SMTP refusals
StreamSec.Mail.Maildir, StreamSec.Mail.IMAPEngine,
StreamSec.Mail.IMAPServer, StreamSec.Mail.SMTPDelivery,
StreamSec.Mail.SMTPServer, MAIL.txt.
NEW: a mailbox can have a storage limit. The new published property
TsmMailStore.Quota is the limit of every mailbox in octets, 0 (the
default) for none, and the new event OnMailboxQuota sets it for one
mailbox, named by its directory. The new tMaildir.MailboxQuota and
AccountQuota answer a mailbox's usage and limit; the usage is the octets
of the files in new/ and cur/ of INBOX and every folder.
The usage is counted once, at the first question about a mailbox, and
then kept: a delivery, APPEND and COPY add to it, EXPUNGE takes from it,
and DELETE of a folder has it counted again. It is held in memory only,
per store root and process, so a crash leaves nothing on disk that can
disagree with the files, and after a restart each mailbox is counted when
first asked about. Files another program adds or removes are seen at the
next count, at most cMailQuotaRecountSeconds (300, new, chosen, not
measured) after the last one, or at once after the new
tMaildir.RecountUsage.
IMAP: TsmIMAPServer advertises QUOTA and QUOTA=RES-STORAGE (RFC 9208).
Each account has one quota root, "", over INBOX and every folder.
GETQUOTAROOT and GETQUOTA answer its STORAGE in units of 1024 octets; with
no limit the resource list is empty. STATUS takes DELETED-STORAGE
(sec.4.1.4). An APPEND or COPY whose messages do not fit the room left is
NO [OVERQUOTA] (sec.4.3.1) and stores nothing. MOVE is not refused: it
adds nothing to the one root, so a user at the limit can still move mail
to Trash. SETQUOTA is NO, and QUOTASET is not advertised.
SMTP: RCPT TO to a local mailbox at or over its limit is 452 4.2.2, so the
sender retries (RFC 3463 sec.3.3, X.2.2); a SIZE= declared at MAIL FROM
that does not fit the room left is 552 5.2.2 at that RCPT (RFC 1870
sec.6.4), and the other recipients are still accepted. At the end of DATA
every local mailbox the message is for is checked again, and the message
is delivered to none if one refuses it: 452 4.2.2 for a mailbox that has
reached its limit since RCPT, 552 5.2.2 for a message whose copies, at
the size they are stored, do not fit the room a mailbox has left (entry
91). A recipient OnResolveMailbox resolves to a mailbox, an alias,
counts against that mailbox. The new interface iSmtpMailboxQuota is how
a mailbox store takes part; tSmtpMaildirStore implements it.
BEHAVIOUR CHANGE: CAPABILITY lists QUOTA QUOTA=RES-STORAGE, and GETQUOTA,
GETQUOTAROOT and SETQUOTA are answered where they were BAD. With Quota 0
nothing is refused. iImapServerPolicy has the new methods QuotaRoots and
QuotaResources and the new GUID {6E1B3D94-27A8-4C5F-B0D3-9F48A7E2C165};
tImapStatusItem has the new member isiDeletedStorage and
tImapStatusCounts the new field DeletedStorage. New types
tImapQuotaResource and tMailQuotaEvent; new constant cImapQuotaRoot.
See MAIL.txt sections 3.5, 6.3, 7.1 and 11.
Tested on Win32, Win64 and Linux64.
--------------------------------------------------------------------------------
MAIL: WHEN AN SMTP SESSION LEAVES ITS PREAMBLE
================================================================================
78. FIXED, BEHAVIOUR CHANGE - MAIL alone no longer takes an SMTP session out
of its preamble, and a session back in it after a message has its
preamble limits from then
StreamSec.Mail.SMTPServer, StreamSec.Mail.Transport, MAIL.txt.
THE STEP THAT FAILED was tSmtpServerSession.PastPreamble, which said a
session had left its preamble once MAIL was accepted. MAIL costs a peer
nothing, the null path included, and names nothing the server has agreed
to take. And the preamble's own whole limit (PreambleSessionSeconds) ran
from the accept even for a session that came back to its preamble at the
end of a message.
SYMPTOM, found by reading and reproduced with the limits shortened on
Win32, Win64 and Linux64. On port 25 under pressure, a session that said
MAIL FROM:<> and then NOOP once in a while held its slot for the whole
idle and session limits, 300 s and 1,800 s by default, instead of the
preamble's 30 s and 120 s: a few addresses could still keep every slot,
which is what entry 48 set out to stop. And under pressure an MTA that had
been connected longer than PreambleSessionSeconds, delivering mail, was
answered 421 before its next MAIL. By reading, the second holds on 465 as
well, for a session that sends without signing in.
Which releases: none. Entries 48 and 49 came after 4.1.5.362.
Now an SMTP session leaves its preamble when it has authenticated, or when
a RCPT has been accepted in an open transaction; DATA and BDAT come after
one, so a message being sent is past it too. MAIL alone, or with RCPTs
that were all refused, is still the preamble. When a session comes back
to its preamble - the end of a message, RSET - both preamble limits run
from that moment, on the listeners and on the implicit-TLS port. The
whole-session limit (SessionTimeoutSeconds) still runs from the accept.
NEW: tMailImplicitClock.PreambleEntered; tMailPreambleClock.Restart and
OpenedAt.
BEHAVIOUR CHANGE: under pressure, or on a port whose PreamblePressurePercent
is 0, a session with MAIL accepted and no RCPT is held to the preamble
limits, and given 421 when one runs out. The listener asks
iMailSessionPhase.PastPreamble after every read, and a session whose
answer goes back to False gets its preamble limits afresh.
TESTED with Delphi 13 on Win32, Win64 and Linux64: the real inbound
listener over loopback, under pressure and at any load, with MAIL FROM:<>
silent and saying NOOP, a refused RCPT, an accepted one, a message after
the preamble's whole limit followed by MAIL, by silence and by NOOP, and
RSET; and tMailImplicitClock on a clock it is handed; against the same
tests built with the step above undone.
--------------------------------------------------------------------------------
MAIL: SIGN-IN ATTEMPTS IN PARALLEL
================================================================================
79. FIXED, BEHAVIOUR CHANGE - sign-in attempts in parallel from one source
get no more guesses than MaxFailures
StreamSec.Mail.Users, MAIL.txt.
THE STEP THAT FAILED was TsmMailUsers.VerifyEx, which tested the lockout
under its lock, ran the Argon2id derivation outside it, and counted the
failure after. Every attempt that reached the test before the others had
been counted found the count below MaxFailures.
SYMPTOM. Connections from one source guessing at one account at the same
moment each made a guess: 16 at once with MaxFailures 3 made 16 guesses,
and 16 more each time the lockout ran out, where MAIL.txt promised one per
LockoutSeconds. Reproduced on Win32, Win64 and Linux64. The limits on
connections per address on each port bound how many run at once.
Which releases: every release with the mail family, 4.1.2.355 to
4.1.5.362, on every platform. Until entry 51 the count was per account,
and the same step let parallel attempts past it.
Now an attempt is reserved under the lock, before its derivation, and
counts against MaxFailures until it is over; it is given back on every
path: a right password, a wrong one, an account changed or deleted
meanwhile, and a derivation that raises. While the failures and the
attempts in flight reach MaxFailures, another attempt from that source is
refused as locked out, after a decoy derivation as before. After a lockout
runs out, the source has one attempt at a time. With lockout off nothing
is reserved.
The IPv6 prefix that is one source, 64, is now the named constant
cMailUserSourcePrefixBits; it is chosen, not measured, and its trade-off is
in MAIL.txt's limits table. MAIL.txt now also says what the failure table
does when every entry in it is locked out: the oldest lockout goes, and
its source has MaxFailures guesses again.
NEW: the constant cMailUserSourcePrefixBits, which was private.
BEHAVIOUR CHANGE: a right password in flight counts too, so more than
MaxFailures sign-ins to one account from one source at the same moment
see the excess refused as locked out, and retry.
TESTED with Delphi 13 on Win32, Win64 and Linux64: TsmMailUsers with
threads started together, wrong passwords from one source, from one IPv6
/64 and from one IPv4 address in both forms, before and after a lockout
runs out and with room left; right passwords, an unknown account, an
account deleted while its attempt ran, lockout off, and other sources and
accounts meanwhile; against the same tests built with the step above
undone.
--------------------------------------------------------------------------------
MAIL: AN SPF TEMPERROR THAT COULD NOT HAVE MATTERED
================================================================================
80. FIXED, BEHAVIOUR CHANGE - an SPF temperror defers a DMARC refusal only
when the SPF domain is aligned with From:
StreamSec.Mail.MessageAuth, MAIL.txt.
THE STEP THAT FAILED was tSmtpMessageAuthenticator deciding to defer: under
a DMARC p=reject or p=quarantine, with EnforceDmarc and
FailClosedOnTempError on, it answered 451 to any SPF temperror. Only an SPF
pass for a domain aligned with From: satisfies DMARC (RFC 7489 sec.3.1.2
and sec.4.2), so for any other domain no SPF answer could have changed the
outcome; and the SPF domain, the MAIL FROM domain or the HELO name, is the
sender's to choose.
SYMPTOM, found by reading and reproduced on Win32, Win64 and Linux64. A
forger of a p=reject domain that gave MAIL FROM in a domain of its own,
whose SPF lookup it kept from answering, turned the 550 into a 451: the
message waited at the sender instead of being refused, for as long as the
lookup did not answer.
Which releases: none. Entry 52 came after 4.1.5.362.
Now the deferral needs the SPF domain to be aligned with the From: domain
under relaxed alignment - the same name or the same organizational domain
- whatever aspf= says; otherwise the DMARC answer stands, 550 for p=reject
and quarantine for p=quarantine. A DMARC record that could not be retrieved
still defers, whatever SPF said.
BEHAVIOUR CHANGE: a message whose unaligned SPF domain gives a temperror,
under a p=reject or p=quarantine it does not otherwise satisfy, is refused
or quarantined where it was deferred.
TESTED with Delphi 13 on Win32, Win64 and Linux64: the authenticator on
scripted DNS, with unaligned and aligned SPF domains that do not answer,
by name, by organizational domain, for a bounce by its HELO name, across
one public suffix and under aspf=s, and the answers that did not change;
against the same tests built with the step above undone.
--------------------------------------------------------------------------------
MAIL: POP3 CITATIONS
================================================================================
81. FIXED (documentation only) - the POP3 units cited RFC 1939 sec.8 for the
autologout timer and for what a dropped session deletes
StreamSec.Mail.POP3Server, StreamSec.Mail.POP3Engine,
StreamSec.Mail.POP3Transport.
RFC 1939 sec.8 is "Scaling and Operational Considerations". The ten-minute
floor of the autologout timer, and that when it expires "the session does
NOT enter the UPDATE state", are in sec.3; that a session ending other than
by QUIT removes no messages is in sec.6. The comments now say so. No
behaviour changes.
Which releases: 4.1.2.355 to 4.1.5.362 carry the wrong citations.
--------------------------------------------------------------------------------
MAIL: WHEN DNS DOES NOT ANSWER, THE MESSAGE SAYS SO
================================================================================
82. FIXED, NEW, BEHAVIOUR CHANGE - a DMARC record that does not answer no
longer defers an exact DKIM d= match; every check DNS did not answer is
stamped on the message
StreamSec.Mail.MessageAuth, StreamSec.Mail.Dmarc, StreamSec.Mail.Spf,
StreamSec.Mail.SpamFilter, StreamSec.Mail.SpamChecks,
StreamSec.Mail.SMTPServer, MAIL.txt.
THE STEP THAT FAILED was tDmarcEvaluator.Evaluate meeting a DMARC record
that could not be retrieved: with FailClosedOnTempError on, it asked for a
451 4.4.3 without looking at the signatures, so a message with a verified
DKIM signature whose d= is the From domain itself waited at the sender.
RFC 7489 sec.6.6.2 step 5: "If one or more of the Authenticated
Identifiers align with the RFC5322.From domain, the message is considered
to pass the DMARC mechanism check." An identical name aligns under
adkim=r and adkim=s alike, so no record could have changed the answer.
AND A CHECK THAT WENT ON WITHOUT ITS DNS ANSWER - SPF, a DKIM key, the
DMARC record, reverse DNS, a blocklist or an allowlist - left the
delivered message saying nothing of it, beyond spf= or dmarc= temperror
in Authentication-Results; the spam checks left no trace at all. A
blocklist that did not answer let a listed address through unscored and
unmarked. And with no DNS server configured, reverse DNS scored the peer
as having no PTR record.
Which releases: the 451 on an exact d= match, none: entry 52 came after
4.1.5.362. The unmarked checks: 4.1.2.355 to 4.1.5.362, on every
platform, with VerifyInbound on or a SpamFilter assigned.
Now:
- A DMARC record that could not be retrieved, at the From domain or at
its organizational domain, with a verified DKIM signature whose d=
equals the From domain - without regard to case or a trailing dot - is
a DMARC pass, and the message is delivered. Authentication-Results says
dmarc=pass with the comment "exact header.d match, policy record not
retrieved". A d= that is a subdomain or the parent of the From domain
is still 451 4.4.3: whether it aligns is the record's adkim=, which is
what could not be fetched. RFC 7489 sec.6.6.3 leaves the rest to the
receiver: "Handling of DNS errors when querying for the DMARC policy
record is left to the discretion of the Mail Receiver."
- Every check that went on without its DNS answer - a timeout, SERVFAIL,
no reachable server, a blocklist that refused the query; never a
definite answer that no record exists - adds one X-DNS-Warning field
to the message, naming this host, the check, the DNS name and what the
message was judged without:
X-DNS-Warning: mx.example.net;
check=dkim; dns=sf._domainkey.other.example;
relaxed="signature not verified, judged without it"
The checks are spf, dkim, dmarc and the spam checks' own names. The
field is added whatever let the message through - FailClosedOnTempError
False and OnMailAuth included - and on top of the other stamps. An
X-DNS-Warning that arrives with a message naming this host is removed
first, on every message the checks ran on; one naming another host is
kept (entry 85).
- tSmtpAuthReport.Relaxed lists the checks; tSpfEvaluator.TempErrorName
and tDmarcVerdict.TempErrorName name what did not answer;
SmtpStampDnsWarnings stamps a message from such a list.
- tSpamFinding has DnsName and DnsRelaxed. tSpamReverseDnsCheck and
tSpamDnsblCheck fill them and return a finding worth no points where
they returned none, and take a resolver with no server for one that
did not answer. iSpamCheck has a new GUID.
- A DMARC temperror in Authentication-Results no longer carries
"(p=none)": no policy was read.
BEHAVIOUR CHANGE: such an exact-match message is delivered where it was
deferred; a delivered message carries an X-DNS-Warning for each check DNS
did not answer; an incoming X-DNS-Warning naming this host is removed;
with no DNS server configured, reverse DNS no longer scores
NoReversePoints; a host reading tSpamOutcome.Findings sees a finding worth
no points for each such check; an iSpamCheck implementation must be
recompiled.
TESTED with Delphi 13 on Win32, Win64 and Linux64: a loopback listener on
scripted DNS with the shipped spam checks and an Ed25519 signature: the
exact d= match delivered, a subdomain and a parent d= deferred; one
warning for each check above, for SPF two includes down, at the
organizational domain, with FailClosedOnTempError off and with no DNS
server at all under OnMailAuth; none for definite answers; a planted
field removed with warnings and without; against the same tests built
from the units before this change.
--------------------------------------------------------------------------------
MAIL: AN EMPTY IMAP MAILBOX NAME
================================================================================
83. FIXED, BEHAVIOUR CHANGE - an empty IMAP mailbox name is refused, not
taken for INBOX
StreamSec.Mail.IMAPEngine, MAIL.txt.
THE STEP THAT FAILED was the IMAP server passing an empty mailbox name on
to the store, whose OpenFolder takes '' for the maildir root, which is
INBOX. So SELECT "", EXAMINE "" and STATUS "" answered for INBOX, APPEND ""
put the message in INBOX, and COPY 1 "" and MOVE 1 "" copied or moved
messages into it. A name of spaces alone is trimmed to the same empty
name. RFC 3501 gives the empty string a meaning as a mailbox name only in
LIST and LSUB, sec.6.3.8: "An empty ("" string) mailbox name argument is
a special request to return the hierarchy delimiter and the root name of
the name given in the reference."
Which releases: 4.1.2.355 to 4.1.5.362, on every platform. Those trimmed
every white-space character, so a name of tabs alone was empty too.
Now SELECT, EXAMINE, STATUS, APPEND, CREATE, DELETE, RENAME (either name),
COPY, UID COPY, MOVE, UID MOVE, SUBSCRIBE, UNSUBSCRIBE and GETQUOTAROOT
answer a mailbox name that is empty, or empty once trimmed, with a tagged
NO "a mailbox name cannot be empty", and do nothing else. CREATE "." is
the empty name too: CREATE drops a trailing hierarchy delimiter (RFC 3501
sec.6.3.3). A SELECT or EXAMINE refused this way still deselects the
mailbox that was selected, as every failed SELECT does (sec.6.3.1).
RENAME "" x keeps its text, "RENAME needs a nonempty source mailbox".
RFC 3501 defines no response code for an empty name, and none of RFC
5530's fits - its NONEXISTENT is for an operation that "attempts to
delete something that does not exist" - so the NO carries none.
LIST and LSUB are unchanged: an empty reference and an empty pattern are
legal there, and LIST "" "" still answers the hierarchy delimiter and the
root. GETQUOTA and SETQUOTA take a quota root, not a mailbox, and are
unchanged. The store's own functions keep their meaning for a library
caller: OpenFolder with '' opens INBOX.
BEHAVIOUR CHANGE: a client that sent an empty name, or one of spaces, gets
NO where it got INBOX. CREATE "" and DELETE "" were refused before, with
another text.
TESTED with Delphi 13 on Win32, Win64 and Linux64, in-process IMAP
sessions over a store: every command above with "" and with " ",
refused, with INBOX's message count unchanged by APPEND, COPY and MOVE and
no mailbox selected after SELECT; LIST "" "", LSUB "" "", LIST "" "*" and
LIST "" "%" as before; against the same tests built from the units before
this change, where SELECT "" opened INBOX and APPEND "" wrote to it.
--------------------------------------------------------------------------------
MAIL: IMAP CREATE OF A MAILBOX THAT EXISTS
================================================================================
84. FIXED, NEW, BEHAVIOUR CHANGE - IMAP CREATE of a mailbox that exists
answers NO [ALREADYEXISTS]
StreamSec.Mail.Maildir (iMailboxAccess, tMaildir),
StreamSec.Mail.IMAPServer, StreamSec.Mail.IMAPEngine, MAIL.txt.
THE STEP THAT FAILED was the IMAP server's CREATE asking the store's
CreateFolder, which answers True whenever the folder exists afterwards,
whether or not that call made it. So CREATE of a mailbox that already
existed answered OK, and of two sessions creating one name at once both
were told they had. RFC 3501 sec.6.3.3: "An OK response is returned only
if a new mailbox with that name has been created. It is an error to
attempt to create INBOX or a mailbox with a name that refers to an extant
mailbox. Any error in creation will return a tagged NO response." RFC
5530 sec.3 defines the response code for it:
ALREADYEXISTS
The operation attempts to create something that already exists,
such as when the CREATE or RENAME directories attempt to create
a mailbox and there is already one of that name.
Which releases: 4.1.2.355 to 4.1.5.362, on every platform. CREATE INBOX
was refused there, with a plain NO "INBOX already exists".
Now CREATE of a name that refers to an existing mailbox answers NO
[ALREADYEXISTS] and leaves that mailbox as it was: INBOX in any case,
with spaces around it or with a trailing delimiter, NO "[ALREADYEXISTS]
INBOX already exists"; any other, NO "[ALREADYEXISTS] that mailbox
already exists". That holds for a name that compares equal to an
existing one (OnCompareFolderName), a spelling that trims to it, a name
with the trailing hierarchy delimiter, and a CREATE with a USE list
(RFC 6154 sec.3). A child does not create its parent: Maildir++ keeps
'A.B' as a directory of its own, so CREATE "A" after CREATE "A.B"
answers OK, as before. APPEND, COPY and MOVE to a missing mailbox still
answer NO [TRYCREATE], and the CREATE a client sends on it still makes
the mailbox.
NEW: iMailboxAccess.CreateNewFolder(aAddress, aFolder, out aExisted) is
True only when that call made the folder; False with aExisted True for
one that exists, INBOX included; False with aExisted False for a name
the store refuses. tMaildir decides it under the folder-name lock that
every store object over one root shares, in the step that creates, so of
calls racing for one name - from two sessions, two store objects or two
processes - exactly one is True. A directory left without its tmp, new
or cur by a creation cut short is completed and counts as made.
CreateFolder keeps its meaning. iImapServerPolicy.CreateFolder's
declaration now says that a mailbox that exists is False with aWhy
starting "[ALREADYEXISTS] "; the interface itself is unchanged.
BEHAVIOUR CHANGE: a client that sent CREATE for a mailbox it had, or
that lost a race for one, gets NO [ALREADYEXISTS] where it got OK.
iMailboxAccess has the new GUID {3EB0BC59-F70F-451A-A928-72CFC3F32D60},
replacing the one entries 18 and 20 give; a custom implementation must
supply CreateNewFolder.
TESTED with Delphi 13 on Win32, Win64 and Linux64, in-process IMAP
sessions over a store: CREATE of an existing name, of a trimmed,
case-folded and trailing-delimiter spelling of it, of five spellings of
INBOX and with a USE list, each NO [ALREADYEXISTS], the mailbox's
messages, UIDNEXT and UIDVALIDITY unchanged; the parent after a child
OK, then NO [ALREADYEXISTS]; a deleted mailbox created again; APPEND,
COPY and MOVE answering TRYCREATE and succeeding after CREATE; two
sessions racing CREATE for one name, 25 rounds, one OK each round; two
store objects over one root racing CreateNewFolder, 25 rounds, one True
each round; against the same tests built from the units before this
change, where every second CREATE answered OK.
--------------------------------------------------------------------------------
MAIL: DEFER ONLY WHAT AN ANSWER COULD STILL CHANGE
================================================================================
85. FIXED, BEHAVIOUR CHANGE - a DNS answer that did not come defers a message
only if it could still change the DMARC verdict; an X-DNS-Warning naming
another host is kept
StreamSec.Mail.MessageAuth, StreamSec.Mail.Dmarc,
StreamSec.Mail.SMTPServer, MAIL.txt.
THE RULE. A message waits at the sender only if the DNS answer that did
not come could still change the DMARC verdict; a verdict that is already
settled is acted on. RFC 7489 sec.6.6.2: "If neither passes and one or
both of them fail due to a temporary error, the Receiver evaluating the
message is unable to conclude that the DMARC mechanism had a permanent
failure; they therefore cannot apply the advertised DMARC policy."
THE STEPS THAT FAILED:
- tDmarcEvaluator.Evaluate, meeting a DMARC record that could not be
retrieved, passed an exact DKIM d= match (entry 82) but not an SPF pass
for the From domain itself. RFC 7489 sec.3.1.2 aligns that in both
modes: "In relaxed mode, the [SPF]-authenticated domain and
RFC5322.From domain must have the same Organizational Domain. In strict
mode, only an exact DNS domain match is considered to produce
Identifier Alignment."
- tSmtpMessageAuthenticator, deferring on an SPF temperror under a known
p=reject or p=quarantine (entry 80), took relaxed alignment whatever
the record's aspf= said. Under aspf=s an SPF domain that is a subdomain
or the parent of the From domain cannot satisfy the record, whatever SPF
answers.
- Under the same known refusal, once another signature had verified, a
DKIM signature whose key could not be retrieved was left out: its d=
was never looked at, though the key could have made the message pass.
- SmtpStampDnsWarnings removed every X-DNS-Warning that came with a
message, whatever host it named.
SYMPTOM, found by reading and reproduced on Win32, Win64 and Linux64.
Mail whose own SPF passed for the From domain waited at the sender with
451 4.4.3 for as long as that domain's DMARC record did not answer. Under
aspf=s a forger that gave MAIL FROM in a subdomain of the domain, whose
SPF lookup did not answer, turned the 550 into a 451. Mail signed by a
mailing list or a provider and by the From domain itself was refused 550,
or quarantined, while the From domain's key did not answer. And a
diagnostic another server had added was lost.
Which releases: the SPF match, aspf= and X-DNS-Warning, none: entries 52,
80 and 82 came after 4.1.5.362. The unfetchable key: 4.1.2.355 to
4.1.5.362, on every platform, with VerifyInbound on and
FailClosedOnTempError set to True; it defaulted to False there, and with
False the refusal still stands.
Now:
- A DMARC record that could not be retrieved, at the From domain or at
its organizational domain, with an SPF pass whose domain - the MAIL FROM
domain, or the HELO name for a bounce - equals the From domain without
regard to case or a trailing dot, is a DMARC pass, and the message is
delivered. Authentication-Results says dmarc=pass with the comment
"exact smtp.mailfrom match, policy record not retrieved"; the
X-DNS-Warning for the record says "DMARC pass on an SPF domain equal to
From:, without the policy record". A subdomain or the parent is still
451 4.4.3.
- The SPF-temperror deferral of entry 80 takes the record's own aspf=:
the same name under aspf=s, the same organizational domain under aspf=r.
- Under a retrieved p=reject or p=quarantine with nothing aligned passing,
a signature whose key could not be retrieved and whose d= - read from
the signature, which needs no key - is aligned with From: under the
record's adkim= defers the message with 451 4.4.3, the reply of entries
52 and 80, with EnforceDmarc and FailClosedOnTempError on, and OnMailAuth
has the last word as before. One whose d= is not aligned leaves the
refusal standing. Only the first MaxSignatures signatures are verified,
so one past them is never fetched and defers nothing. With no signature
verified at all, a key that could not be retrieved is still 451 4.7.5,
before DMARC is looked at.
- An X-DNS-Warning that comes with a message is removed only when it
names this host: its first token - after white space and comments, a
token or a quoted string - equal to the server name without regard to
case. That is what RFC 8601 sec.5 has a receiver remove of an
Authentication-Results field: an instance "that claims, by virtue of its
authentication service identifier, to have been added within its trust
boundary". Every other X-DNS-Warning stays byte for byte where it was:
it is a diagnostic, a sender gains nothing by planting one, and mail
clients do not show it.
- tDmarcVerdict has SpfUndecided and DkimUndecidedDomain: on a DMARC fail
under a retrieved record, the aligned identifier whose answer did not
come.
BEHAVIOUR CHANGE: such an SPF match is delivered where it was deferred;
under aspf=s an SPF domain aligned only by organizational domain is
refused or quarantined where it was deferred; a message with an aligned
signature whose key did not answer is deferred where it was refused or
quarantined; an incoming X-DNS-Warning naming another host is delivered
with the message; the 451 text for a key names its d=.
TESTED with Delphi 13 on Win32, Win64 and Linux64: the authenticator on
scripted DNS with Ed25519 signatures, and a loopback listener: the exact
SPF domain by name, by case, for a bounce and at the organizational
domain delivered, a subdomain, a parent, a fail and an unrelated domain
deferred; aspf=s and aspf=r with exact, subdomain, parent and sibling SPF
domains; keys that do not answer for an exact, a subdomain, an unrelated
and a public-suffix d=, under adkim=r and adkim=s, p=reject, p=quarantine,
p=none and pct=50, beside an aligned DKIM or SPF pass, with
FailClosedOnTempError and EnforceDmarc off, and as the eighth and the
ninth signature; incoming fields naming another host and this one, in any
case, behind a comment and a version, quoted, and mixed, with a warning of
ours and without; against the same tests built from the units before this
change.
--------------------------------------------------------------------------------
MAIL: WHAT CLAIMS TO COME FROM THIS SERVER, AND A KEY THAT DOES NOT ANSWER
================================================================================
86. FIXED, NEW, BEHAVIOUR CHANGE - a field that claims to come from this
server is removed however it is written, the message says so and scores
for it; a DKIM key that does not answer defers only if it could still
change the outcome
StreamSec.Mail.MessageAuth, StreamSec.Mail.SpamFilter,
StreamSec.Mail.SMTPServer, MAIL.txt.
THE STEPS THAT FAILED:
- tSmtpMessageAuthenticator.StampMessage removed an incoming
Authentication-Results as this host's only when everything before its
first ';' was the server name. RFC 8601 sec.2.2 lets comments surround
the authserv-id and a version follow it:
authres-payload = [CFWS] authserv-id
[ CFWS authres-version ]
( no-result / 1*resinfo ) [CFWS] CRLF
authserv-id = value
and RFC 2045 defines "value := token / quoted-string". RFC 8601 sec.5:
an MTA "MUST delete any discovered instance of this header field that
claims, by virtue of its authentication service identifier, to have
been added within its trust boundary but that did not come directly
from another trusted MTA."
- SmtpStampDnsWarnings read the first token of an X-DNS-Warning that way
(entry 85), but took the name with a trailing dot for another host.
- Nothing on the message said that a field had been removed, and the
spam score did not count it.
- tSmtpMessageAuthenticator, with no DKIM signature verified and a key
that could not be retrieved, answered 451 4.7.5 before DMARC was looked
at: whatever the signature's d=, whatever the policy, and with
FailClosedOnTempError False too.
SYMPTOM, found by reading and reproduced on Win32, Win64 and Linux64. A
sender that put "Authentication-Results: mx.example.net 1; dkim=pass
header.d=bank.example" on a message to mx.example.net, or wrote the name
behind a comment, quoted or with a trailing dot, had it delivered beside
this host's own results, for any reader that trusts them. A forger of a
p=reject domain that added a signature of a domain of its own, whose key
lookup it kept from answering, turned the 550 into a 451 for as long as
it liked. And mail whose only signature's key did not answer waited at
the sender where nothing could have refused it: no DMARC record and
RejectBrokenSignature False, p=none, or FailClosedOnTempError False.
Which releases: Authentication-Results and the DKIM key, 4.1.2.355 to
4.1.5.362, on every platform, with VerifyInbound on. X-DNS-Warning, none:
entry 82 came after 4.1.5.362.
Now:
- An incoming Authentication-Results, X-DNS-Warning or X-Stripped-Fields
NAMES THIS HOST when its first token is the server name: after white
space, folding and comments, a token or a quoted string, so that a
version or a comment after it is not part of it, compared without
regard to case or a trailing dot. One that does is removed, on every
message the checks ran on - an Authentication-Results while
StripInboundResults is on, the default. Every other field stays byte
for byte where it was: "mx.example.net.org" and "(mx.example.net)
relay.example" name other hosts. The message below this host's own
fields is now byte for byte as it came, where removing a field rewrote
the whole header section.
- NEW: a message that lost any of them carries one field, above every
other of this host's:
X-Stripped-Fields: mx.example.net;
authentication-results=2; x-dns-warning=1;
reason="claimed to come from this host"
naming this host and each field name removed with how many. Nothing of
the removed fields is copied: they are the sender's text. An incoming
X-Stripped-Fields naming this host is a forgery of it and is removed
and counted; one naming another host is kept.
- NEW: removing any of them adds tSpamFilter.ForgedStampPoints to the spam
score, once per message, as the finding forged-stamp in X-Spam-Status and
in the verdict of the end-of-data stage. The default,
cSpamForgedStampPoints, is 40: on a scale whose file threshold is 80 it is
one strong signal, reaching a tag threshold of 40 alone and never filing
alone. A message this host stamped that comes back to it carries a genuine
field of ours and scores the same; 0 keeps the finding, worth nothing.
TsmSMTPServer removes the fields after DKIM verification and before the
spam stage and hands the count over in tSpamContext.ForgedStamps.
- NEW for a host with its own pipeline: tSmtpStrippedFields,
SmtpAuthServId, SmtpFieldNamesHost, SmtpStripForgedFields,
SmtpStrippedFieldsNote, and StampMessage and SmtpStampDnsWarnings
overloads that take the count. The SmtpStampDnsWarnings of entry 82
writes the note for what it removes itself.
- A DKIM key that could not be retrieved, with no signature verified,
defers the message only when the key could still change what happens
to it, the rule of entry 85: its d= is aligned with From: under the
record's adkim= and the record asks for p=reject or p=quarantine, 451
4.4.3 as in entry 85; or RejectBrokenSignature or
RejectAnyBrokenSignature could turn on it, 451 4.7.5 as before - unless
the message is refused whatever the key says: another signature that
failed under RejectAnyBrokenSignature, a DMARC p=reject with nothing
aligned still waiting for DNS, or RequirePublishedPolicy with no
record. Otherwise the signature is judged without: the message is
delivered, quarantined or refused on the rest, with the X-DNS-Warning
for the key (entry 82). FailClosedOnTempError False defers on neither,
and OnMailAuth has the last word, as in entries 52, 80 and 85. "Every
signature failed" counts only the signatures whose key came.
BEHAVIOUR CHANGE: an Authentication-Results naming this host in any of
those forms, and an X-DNS-Warning naming it with a trailing dot, is
removed where it was delivered; a message that lost one carries
X-Stripped-Fields and scores 40 more, so a filter with a TagScore of 40
or less tags it on that alone. Of a message with no signature verified
and a key that did not answer: under p=reject with no aligned d=, refused
550 where it was deferred; under p=reject or p=quarantine with an aligned
d= and RejectBrokenSignature False, deferred 451 4.4.3 where 4.7.5; with
RejectBrokenSignature False and nothing else waiting, or with
FailClosedOnTempError False, delivered, quarantined or refused on the
rest where it was deferred - refused 550 5.7.20 when every other
signature failed; under RejectAnyBrokenSignature with another signature
failed, or RequirePublishedPolicy with no record, refused where it was
deferred. tSpamContext has ForgedStamps, appended; iSpamCheck and
tSpamFinding are unchanged.
TESTED with Delphi 13 on Win32, Win64 and Linux64: a loopback listener on
scripted DNS with a spam filter tagging at 40: Authentication-Results
naming this host exactly, with a version, behind a comment, quoted, with
a trailing dot, in upper case, folded, all at once and with no result,
each removed, noted, scored and tagged; four naming other hosts, some
beginning with this host's name, kept byte for byte with nothing noted;
X-DNS-Warning with a trailing dot and with a version; a planted note
naming this host and one naming another; all of them mixed and scored
once; StripInboundResults off. And the authenticator with Ed25519
signatures whose keys do not answer, aligned and not, under p=reject,
p=quarantine, p=none and no record, beside a signature that failed and
an aligned SPF pass, with RejectBrokenSignature,
RejectAnyBrokenSignature, RequirePublishedPolicy and
FailClosedOnTempError on and off, and over the wire with OnMailAuth;
against the same tests built from the units before this change.
--------------------------------------------------------------------------------
MAIL: AN Authentication-Results THIS SERVER CANNOT READ, AND WHATEVER IS ON
================================================================================
87. FIXED, BEHAVIOUR CHANGE - an Authentication-Results bearing a version
this server does not support is removed whoever it names; what claims
to come from this server is removed whatever is switched on
StreamSec.Mail.MessageAuth, StreamSec.Mail.SMTPServer, MAIL.txt.
THE RULE. RFC 8601 sec.5: "An MTA SHOULD remove any instance of this
header field bearing a version (express or implied) that it does not
support. However, an MTA MUST remove such a header field if the SMTP
connection [SMTP] relaying the message is not from a trusted internal
MTA." This server has no trusted internal MTA. The version is RFC 8601
sec.2.2's "authres-version = 1*DIGIT [CFWS]" after the authserv-id: "this
specification is version "1", and the absence of a version implies this
version of the specification".
THE STEPS THAT FAILED:
- tSmtpMessageAuthenticator.StampMessage removed an incoming
Authentication-Results only when it named this host; one bearing
another version was delivered whoever it named.
- TsmSMTPServer removed an incoming Authentication-Results naming this
host only with VerifyInbound on: with the spam filter alone, or with
neither, it was delivered. With neither, an X-DNS-Warning or
X-Stripped-Fields naming this host was delivered too.
SYMPTOM, found by reading and reproduced on Win32, Win64 and Linux64.
"Authentication-Results: relay.example 2; dkim=pass" reached the mailbox,
for a reader that does not check the version to take as a pass. And with
VerifyInbound off, "Authentication-Results: mx.example.net; dkim=pass"
reached the mailboxes of mx.example.net as if it had written it.
Which releases: the version, and an Authentication-Results naming this
host with VerifyInbound off, 4.1.2.355 to 4.1.5.362, on every platform.
X-DNS-Warning and X-Stripped-Fields, none: entries 82 and 86 came after
4.1.5.362.
Now:
- An incoming Authentication-Results bearing a version other than 1 -
"01" is 1, and none means 1 - is removed whoever it names, on every
message, with StripInboundResults on or off. A run of digits after the
authserv-id and its comments is the version when white space, a
comment, the ';' or the end of the field follows it. Nothing else
about the field is read.
- Every field of entry 86 that names this host, and every field above,
is removed on every message the server takes in, whatever is switched
on: VerifyInbound or not, a SpamFilter or not, on every port.
- StripInboundResults False is kept as the application's explicit
opt-out, the only one: its word that an Authentication-Results in this
host's name may be genuine, written by a filter of its own in front of
this server, the "trusted MTA" of RFC 8601 sec.5. The server now reads
it whether or not VerifyInbound is on. It keeps only such a field, with
version 1.
- The X-Stripped-Fields note of entry 86 has one group per reason, a
line of counts closed by its reason:
X-Stripped-Fields: mx.example.net;
authentication-results=2; x-dns-warning=1;
reason="claimed to come from this host";
authentication-results=1;
reason="version not supported"
A reason nothing was removed for is left out, so a message that lost
only fields naming this host carries the field of entry 86 unchanged.
A field is counted once: one naming this host is counted under the
first reason whatever its version, unless StripInboundResults is off.
Nothing of the removed fields is copied, as before.
- A field removed for its version is NOT SCORED: it is no claim in this
host's name, and a host that writes a newer version is not a spammer
for it. tSpamContext.ForgedStamps counts the fields naming this host
alone, and the forged-stamp points of entry 86 go only with them.
- NEW for a host with its own pipeline: SmtpAuthResultsVersion,
SmtpAuthResultsVersionSupported, SmtpStrippedForged,
cSmtpAuthResultsVersion, cSmtpStrippedClaimed, cSmtpStrippedVersion,
and tSmtpStrippedFields.UnsupportedVersion, appended;
SmtpStrippedTotal counts it. SmtpStripForgedFields and StampMessage
remove such fields.
BEHAVIOUR CHANGE: an incoming Authentication-Results with a version other
than 1 is removed where it was delivered; with VerifyInbound off, a field
naming this host is removed and noted where it was delivered, and scored
when a SpamFilter is on; a message that lost a field for its version
carries X-Stripped-Fields. A host that zeroes tSmtpStrippedFields field by
field must zero the new one too.
TESTED with Delphi 13 on Win32, Win64 and Linux64: a loopback listener on
scripted DNS with a spam filter tagging at 40: versions 2, 17 behind
comments and folded, and 0 after a quoted authserv-id, removed, noted and
not scored; 1, 01 and none kept byte for byte; version 2 naming this host
removed as a forgery and scored; both reasons on one message;
StripInboundResults off keeping a field of ours with version 1 and
removing one with version 3; VerifyInbound off with the filter alone and
with nothing at all, with every kind of field and with none; and the
authenticator's own vectors; against the same tests built from the units
before this change.
--------------------------------------------------------------------------------
MAIL: THE SPAM VERDICT OF ONE MESSAGE
================================================================================
88. FIXED, BEHAVIOUR CHANGE - the spam verdict is TagScore and FileScore
applied to the score of one transaction summed over its stages; one
message's points no longer reach the next one's
StreamSec.Mail.SpamFilter, StreamSec.Mail.SMTPServer, MAIL.txt.
THE STEPS THAT FAILED:
- TsmSMTPServer added every stage's outcome to one running total for the
whole connection and never started it again: the second message on a
connection was stamped with the first one's points and findings added
to its own, and so was a message after a transaction abandoned with
RSET. A second EHLO counted the greeting twice.
- tSpamFilter.Evaluate judged each stage's own points against TagScore and
FileScore, and tSpamFilter.Merge kept the harder of the stages'
verdicts, which TsmSMTPServer stamped: points spread over the stages
crossed no threshold however high the sum, and one stage over a
threshold tagged a message whose sum stayed under it.
SYMPTOM, found by reading and reproduced on Win32, Win64 and Linux64.
With TagScore 40, a sender that sent one message scoring 40 and then
another on the same connection had the second tagged
"X-Spam-Status: Yes, score=45" for 5 points of its own. And 15 points at
connect, 10 at RCPT and 15 at the end of data were stamped
"X-Spam-Status: No, score=40".
Which releases: 4.1.2.355 to 4.1.5.362, on every platform, with a
SpamFilter assigned and enabled.
Now:
- A message's score is the connection's own stages - connect and the
latest EHLO - plus this transaction's: MAIL FROM, every RCPT and the end
of data. It starts again at every MAIL FROM, after every message,
accepted or not, and at every EHLO; RSET is followed by the MAIL FROM
that starts the next one.
- The verdict X-Spam-Status says is TagScore and FileScore applied to that
sum, together with the hardest verdict a check asked for.
- A stage's own verdict still answers that stage on the wire, as before:
a check's refusal at connect is 554, a deferral or refusal at EHLO,
MAIL, RCPT or the end of data is answered there, and a recipient
refused leaves the others.
- NEW: tSpamFilter.Conclude, the verdict of a whole message from a Merge
of its stages; Merge is unchanged.
BEHAVIOUR CHANGE: a message is tagged, or given the verdict svFile, when its
summed score reaches the threshold, where it was not, and is not when only
one stage's points did - its stamp says Yes either way, and only a forgery
is filed into a Junk folder (entry 90); a second message on a connection, or
one after RSET, is scored on its own transaction; a second EHLO's points
replace the first one's.
TESTED with Delphi 13 on Win32, Win64 and Linux64: a loopback listener
with a check scoring each stage: two messages on one connection, the
second untagged and keeping the connection's points; a transaction
abandoned with RSET; EHLO twice; points spread over connect, RCPT and
the end of data crossing TagScore and FileScore; one stage over TagScore
with the sum under it; a check's refusal at connect, deferral at MAIL,
refusal at RCPT beside an accepted recipient, and deferral at the end of
data; and Conclude on its own; against the same tests built from the
units before this change.
--------------------------------------------------------------------------------
MAIL: THE STAMP OF A DELIVERED MESSAGE SAYS NO OR YES
================================================================================
89. BEHAVIOUR CHANGE, NEW - the X-Spam-Status of a delivered message says
"No" or "Yes"; a deferral or refusal a check asked for is logged where it
is answered
StreamSec.Mail.SpamFilter, StreamSec.Mail.SMTPServer, MAIL.txt.
WHAT IT DID: TsmSMTPServer stamped the verdict of the whole transaction,
and that verdict kept the hardest one any stage asked for. A message
delivered to one recipient while a check refused or deferred another at
RCPT was stamped "X-Spam-Status: Refused" or "Deferred", and so was one
whose deferral or refusal at connect, EHLO, MAIL or RCPT the application
accepted in OnCheckConnection, OnCheckHelo, OnCheckSender or OnCheckRelay.
With TagScore 40 a message scoring 40, delivered to alice after bob was
refused at RCPT, said "Refused, score=40" where it was tagged. Nothing in
the server's log said a recipient had been refused or deferred by the
filter.
Which releases: 4.1.2.355 to 4.1.5.362, on every platform, with a
SpamFilter assigned and enabled.
Now:
- The X-Spam-Status of a message the server delivers or spools says "Yes"
when its summed score reached TagScore or FileScore, or a check asked to
tag or file it, and "No" otherwise. A message whose verdict is svFile says
"Yes", as before. The score, X-Spam-Score and the list of findings are
stamped as before, the finding of a check that asked to defer or refuse
included.
- A deferral or refusal the filter asks for at connect, EHLO, MAIL or
RCPT is logged through OnLog where it is answered, naming the stage and
what it was about:
<bob@example.net> from 192.0.2.1 refused by the spam filter at RCPT:
550 <the check's text>
and when the application accepts it all the same:
<bob@example.net> from 192.0.2.1 accepted by the application over the
spam filter's deferral at RCPT
The end of data logs its own refusal with the message's id, as before.
- NEW: tSpamFilter.StampVerdict, the verdict the stamp says, svAccept,
svTag or svFile. tSpamFilter.ResultsHeader and StampMessage use it.
- Unchanged: what is answered on the wire at every stage, and
tSpamFilter.Conclude, Merge and Evaluate, whose Verdict still says
svDefer or svRefuse with its Code and Text. SpamVerdictToStr still
names all five verdicts.
BEHAVIOUR CHANGE: an X-Spam-Status that said "Refused" or "Deferred" on a
delivered message now says "No" or "Yes"; a filter rule keyed on those
words no longer matches. The server logs a line for each deferral or
refusal the filter asked for before the end of data, and for each the
application overrode.
TESTED with Delphi 13 on Win32, Win64 and Linux64: a loopback listener
with a check scoring each stage: one recipient refused at RCPT beside an
accepted one, the delivered copy saying No and the refusal logged for the
recipient; the same with the score over TagScore saying Yes, and a
deferral at RCPT with the score over FileScore saying Yes; a deferral at
RCPT the application accepted in OnCheckRelay, and one at connect accepted
in OnCheckConnection, both logged with the override and stamped on the
score; the tag and file cases of entry 88 unchanged; and StampVerdict on a
refused total; against the same tests built from the units before this
change.
--------------------------------------------------------------------------------
MAIL: A FORGERY THE RECIPIENT CAN SEE
================================================================================
90. FIXED, NEW, BEHAVIOUR CHANGE - a field that claims to come from this
server is kept renamed X-Forged-; the copy delivered here of a message
that had one says so in its Subject and is filed into Junk
StreamSec.Mail.MessageAuth, StreamSec.Mail.SpamFilter,
StreamSec.Mail.SMTPServer, StreamSec.Mail.SMTPDelivery,
StreamSec.Mail.Maildir, MAIL.txt.
THE RULE. A message whose forged fields are removed is never delivered
without a visible sign that it was tampered with. RFC 8601 sec.5 asks for
removal and allows less: an MTA "MUST delete any discovered instance of this
header field that claims, by virtue of its authentication service
identifier, to have been added within its trust boundary but that did not
come directly from another trusted MTA. For example, an MTA for example.com
receiving a message MUST delete or otherwise obscure any instance of this
header field bearing an authentication service identifier indicating that
the header field was added within example.com prior to adding its own header
fields."
THE STEPS THAT FAILED:
- TsmSMTPServer removed an Authentication-Results, X-DNS-Warning or
X-Stripped-Fields naming this host (entries 86 and 87), said so only in
X-Stripped-Fields, which mail clients do not show, and scored it 40
points, which reach a tag threshold and file nothing.
SYMPTOM, found by reading. A message to mx.example.net carrying
"Authentication-Results: mx.example.net; dkim=pass header.d=bank.example"
reached the inbox with its Subject as the sender wrote it and nothing a
reader sees saying anything was wrong with it; what it had claimed was
gone, so the recipient could not see that either.
Which releases: the defect - an Authentication-Results naming this host
taken out of the message with nothing a reader sees saying so - is in
4.1.2.355 to 4.1.5.362, with VerifyInbound on. The rest is in no release:
the X-Stripped-Fields note, the score and the removal of a forged
X-DNS-Warning or X-Stripped-Fields came with entries 86 and 87, after
4.1.5.362, and the renaming, the Subject mark and the filing are new here.
Now:
- RENAMED, NOT DROPPED. A field naming this host is kept as evidence,
cSmtpForgedFieldPrefix "X-Forged-" in front of the name it arrived
with and every other octet as it came, folding and all, in its place:
X-Forged-Authentication-Results: mx.example.net; dkim=pass
header.d=bank.example
X-Forged-X-DNS-Warning: mx.example.net; check=spf; dns=a.example
Under that name it is no longer an Authentication-Results field, or an
X-DNS-Warning: no filter or client reads it as one, which is what the
passage above asks of "delete or otherwise obscure", and one prefix
for every kind is one rule that finds them all. An incoming field
already named X-Forged- is not this server's to police and stays as
it came. An Authentication-Results bearing a version not supported
(entry 87) is no claim in this host's name: it is still removed, and
gets none of what follows. StripInboundResults False still keeps an
Authentication-Results in this host's name as it is.
- THE NOTE SAYS RENAMED. X-Stripped-Fields keeps its name - the fields
were stripped of their standing as this host's, of their name or
altogether - and the group of the fields naming this host says to
what:
X-Stripped-Fields: mx.example.net;
authentication-results=2; x-dns-warning=1;
renamed="X-Forged-"; reason="claimed to come from this host";
authentication-results=1;
reason="version not supported"
The counts are as before, under the names the fields arrived with.
- THE SUBJECT, of the copy delivered to a local mailbox: NEW
TsmSMTPServer.ForgedSubjectPrefix, default cSmtpForgedSubjectPrefix
"[Suspect] ", goes in front of it once. A Subject that already begins with
it, in any case - a message that came back through here - is left. A
folded Subject, or one of RFC 2047 encoded words, gets it before the first
word with a space, never inside an encoded word: "Subject:
=?UTF-8?Q?...?=" becomes "Subject: [Suspect] =?UTF-8?Q?...?="; a value
that begins on a continuation line gets "[Suspect]", the fold separating
it; a message with no Subject gets "Subject: [Suspect]". A prefix of its
own is given a trailing space if it has none. Empty, or nothing printable,
turns it off; in a form, where an empty string is not stored, a single
space does. CHANGING THE SUBJECT BREAKS A DKIM SIGNATURE THAT COVERS IT
for anyone who verifies after this server, which has verified it on the
message as it arrived; renaming a field a signature covers does too, as
removing it did, which RFC 8601 sec.5 calls "desirable".
- STAMPED YES: the forged-stamp finding of entry 86 now asks for svFile
itself, so X-Spam-Status says Yes (tSpamFilter.StampVerdict, entry 89)
whatever the thresholds and the points, which stay as they were and still
count in X-Spam-Score. That verdict is not what files the message; the
forgery is, below.
- NEW, FILED: TsmSMTPServer files such a message, for the forgery on it and
whatever its spam verdict, with a SpamFilter or without one, into
JunkFolder, default cSmtpJunkFolder "Junk", the name the IMAP server's
default special-use mapping gives \Junk first, OF EACH LOCAL MAILBOX THAT
HAS THAT FOLDER. ONLY A FORGERY IS FILED: a message whose verdict is
svFile from FileScore or a check, with no forgery on it, is stamped
X-Spam-Status Yes and goes to the INBOX, as before; filing it is a host's
own pipeline's to do. That is the per-account switch: a mailbox read over
IMAP has a Junk folder, which its client, its user or the application
made, and one collected over POP3 has none and gets the message in its
INBOX, its Subject and its stamp saying what it is. The server never
creates the folder. The built-in store files (LocalDeliveryMode
sldMaildir, or Store); a message delivered through OnLocalDeliver is not
filed, as before. An empty JunkFolder files nothing.
- WHAT GOES ONWARD IS NOT MARKED. Local is the one definition the
server already uses at RCPT and at the end of data: a recipient it
routes to one of its mailboxes. The copy for every other recipient -
relayed for a RelayNetworks peer, or submitted by an authenticated
client - has the fields renamed and the note, keeps its Subject, is
filed nowhere, and the server logs that a forgery was on it. A
transaction with recipients of both kinds delivers the marked copy
here and queues the other.
- NEW for a host with its own pipeline: SmtpPrefixSubject and
SmtpSubjectPrefixText in StreamSec.Mail.MessageAuth;
iSmtpMailboxFiling in StreamSec.Mail.SMTPDelivery, implemented by
tSmtpMaildirStore; tMaildir.DeliverToFolder in StreamSec.Mail.Maildir,
which writes into a folder that exists and answers False, writing
nothing, for one that does not. SmtpStripForgedFields, StampMessage
and SmtpStampDnsWarnings rename where they removed.
BEHAVIOUR CHANGE: a field naming this host is delivered renamed X-Forged-
where it was removed, and the note says renamed=; the local copy of a
message that had one has its Subject marked and is filed into a Junk
folder the mailbox has, and is stamped X-Spam-Status Yes. A deployment
that wants no filing sets JunkFolder empty. Where FileScore is reached
with no forgery, the message still goes to the INBOX. tSpamContext,
tSpamFinding, iSpamCheck and iSmtpMailboxStore are unchanged.
TESTED with Delphi 13 on Win32, Win64 and Linux64: a loopback listener on
scripted DNS: the Subject marked, not marked twice in another case, made for
a message with none, marked before a folded value and before encoded words
with and without a space after the colon, with a prefix of its own given no
space, and left with an empty prefix; Authentication-Results folded and in
upper case and an X-DNS-Warning renamed in place byte for byte, the note
saying renamed; an incoming X-Forged- field left as it came; a version not
supported removed with no mark and no filing; filed into the Junk folder of
a mailbox that has one and to the INBOX of one that has none, with no
thresholds, with no points, with no SpamFilter, and not with JunkFolder
empty; a message over FileScore with no forgery, and one a check asked
svFile for with no forgery, each delivered to the INBOX of a mailbox that
has a Junk folder, stamped Yes, not filed and with its Subject as it came;
FileScore reached together with a forgery, filed into that Junk folder with
the Subject prefix; a transaction for a local and a relayed recipient, and
one relayed alone, the relayed copy renamed and noted with its Subject
unchanged, and the log; every earlier vector of entries 82 and 85 to 88 with
the fields found renamed; against the same tests built from the units before
this change, which lack the new properties and do not build.
--------------------------------------------------------------------------------
MAIL: A QUOTA CHECKED AT THE SIZE THAT IS STORED
================================================================================
91. FIXED, NEW, BEHAVIOUR CHANGE - a message is checked against a mailbox's
quota at the size it is stored, the Return-Path and Delivered-To the
store adds included
StreamSec.Mail.SMTPServer, StreamSec.Mail.SMTPDelivery, MAIL.txt.
THE STEP THAT FAILED was TsmSMTPServer's last quota check at the end of
DATA (tSmtpServerSession.MessageComplete). It checked the message as
received, times the number of copies for the mailbox, against the room
left. tSmtpMaildirStore then wrote each copy with a Return-Path and a
Delivered-To field in front of it, and the quota is charged for the
stored copy. Several recipients were also counted as so many copies of
one size, although each copy carries its own Delivered-To.
SYMPTOM, found by reading and reproduced on Win32 and Win64. With 1274
octets left, a message stored as 1275 octets got 250, was stored, and
left the mailbox one octet over its limit. The same happened with a copy
filed into the Junk folder, and with several local recipients. RFC 5321
sec.4.2.2 gives 552 for this: "Requested mail action aborted: exceeded
storage allocation".
Which releases: none. The quota came with entry 77, after 4.1.5.362.
Now:
- Each local copy is sized as the store will write it, the fields it
prepends included. The store composes those fields in one routine,
which both writes the copy and measures it.
- Each mailbox is checked against the sum of its own copies: an alias
and its account are two copies, each of its own size. Every mailbox is
checked before any copy is written, so a message that does not fit one
mailbox is stored in none.
- NEW: iSmtpMailboxCopySize, whose StoredCopySize answers the octets
Deliver or DeliverToFolder would write. tSmtpMaildirStore implements
it. A store given as an iSmtpMailboxStore that has a quota and
prepends anything should implement it too; a store that does not is
taken to store the message as it is. A copy handed to OnLocalDeliver
is checked at the message's own size.
BEHAVIOUR CHANGE: a message whose stored copies do not fit the room left
is 552 5.2.2 at the end of DATA where it was 250. A message whose stored
copies fill the room exactly is still 250.
See MAIL.txt section 3.5.
TESTED with Delphi 13 on Win32, Win64 and Linux64, in-process SMTP
sessions over a store with a quota: one recipient with room for its
stored copy exactly (250) and one octet less (552, nothing stored); a
recipient and its alias into one mailbox, whose copies differ in size,
at exactly the room and one octet over; one mailbox with room and
another one octet short (552, and nothing stored for either); a copy
filed into Junk at exactly the room and one octet over; against the same
tests built from the units before this change, where each case one
octet over got 250 and was stored.
--------------------------------------------------------------------------------
MAIL: CREATE OF A MAILBOX THAT CANNOT HOLD A MESSAGE
================================================================================
92. FIXED - IMAP CREATE answers NO, not OK, when the mailbox it would make
cannot hold a message
StreamSec.Mail.Maildir (iMailboxAccess, tMaildir), MAIL.txt.
THE STEP THAT FAILED was the store's folder creation, which
CreateFolder, CreateNewFolder and the IMAP server's CREATE share. It
made the folder's tmp, new and cur directories without looking at
whether each one was made, then answered from whether the folder's own
directory existed.
SYMPTOM, found by reading and reproduced on Win32 and Win64. Where a
file stood in the place of one of the three - left behind by a creation
cut short, or put there by anything else - that directory could not be
made, and still CreateNewFolder answered True, CreateFolder answered
True and CREATE answered OK, for a mailbox that no message could be
delivered or appended to. RFC 3501 sec.6.3.3: "An OK response is
returned only if a new mailbox with that name has been created." and
"Any error in creation will return a tagged NO response."
Which releases: 4.1.2.355 to 4.1.5.362, on every platform, through
CreateFolder and CREATE.
Now a folder is made only when tmp, new and cur are all directories
afterwards. Otherwise CreateNewFolder answers False with aExisted False,
CreateFolder answers False, no index is published for the folder, and
CREATE answers NO "cannot create that mailbox". Once the obstruction is
gone, the next CREATE completes the folder and answers OK. The
interface is unchanged.
See MAIL.txt section 6.3.
TESTED with Delphi 13 on Win32, Win64 and Linux64, in-process IMAP
sessions over a store: a file in the place of tmp, of new and of cur,
each giving CreateNewFolder False and not existed, CreateFolder False
and CREATE NO without [ALREADYEXISTS], the file left as it was; with the
file gone, CREATE OK and an APPEND into the folder; against the same
tests built from the units before this change, where each answered True
or OK.
--------------------------------------------------------------------------------
MAIL: A BROKEN SIGNATURE IS REFUSED WHATEVER THE DMARC RECORD DOES
================================================================================
93. FIXED, BEHAVIOUR CHANGE - a message the broken-signature rules refuse is
refused 550 when the DMARC record does not answer, instead of being
deferred 451
StreamSec.Mail.MessageAuth, MAIL.txt.
THE STEP THAT FAILED: tSmtpMessageAuthenticator.Decide answered a DMARC
record that could not be retrieved (451 4.4.3) before it applied
RejectAnyBrokenSignature and RejectBrokenSignature (550 5.7.20). A
message whose DKIM signature failed on an answer - its key came and its
body hash did not match - and whose From: domain's DMARC record got
SERVFAIL was answered 451, with EnforceDmarc or RequirePublishedPolicy
on. Every DMARC answer the sender could wait for still leaves the same
550: a signature that failed stays failed whatever the record says. The
same message with EnforceDmarc off was refused 550 at once.
SYMPTOM, found by reading and reproduced on Win32 and Win64. The sender
kept retrying a message this server would never take, for as long as the
DMARC record of the From: domain did not answer, and then bounced it with
a temporary failure rather than the refusal.
Which releases: 4.1.2.355 to 4.1.5.362, on every platform, with
VerifyInbound on, RejectBrokenSignature or RejectAnyBrokenSignature on
and a DMARC record that does not answer (451 4.7.5 there, 451 4.4.3
since entry 85).
Now the broken-signature refusals come before the deferral for the DMARC
record. A DKIM key that did not answer and could still change the
verdict still defers 451 4.7.5, as before: under RejectBrokenSignature a
key that verifies keeps the message out of the refusal. One that cannot
- another signature failed under RejectAnyBrokenSignature - does not.
BEHAVIOUR CHANGE: such a message is refused 550 5.7.20 where it was
deferred 451.
See MAIL.txt section 5.
TESTED with Delphi 13 on Win32, Win64 and Linux64, a loopback listener
on scripted DNS: a body hash mismatch with the DMARC record SERVFAIL
under RejectAnyBrokenSignature and under RejectBrokenSignature, each 550
5.7.20; under RejectAnyBrokenSignature a second signature whose key does
not answer, 550; under RejectBrokenSignature a key that could change the
verdict and does not answer, still 451 4.7.5; against the same tests
built from the units before this change, where the first three got 451
4.4.3.
--------------------------------------------------------------------------------
MAIL: THIS HOST'S NAME WHOLE IN EVERY FIELD IT WRITES
================================================================================
94. FIXED, BEHAVIOUR CHANGE - with a server name longer than 80 characters,
a copy of this host's own Authentication-Results, X-DNS-Warning or
X-Stripped-Fields that arrives with a message is recognised as claiming
to come from this host
StreamSec.Mail.MessageAuth, MAIL.txt.
THE STEP THAT FAILED: tSmtpMessageAuthenticator.BuildResultsHeader cut
the host name of the Authentication-Results it wrote to 80 characters,
and SmtpDnsWarningFields and SmtpStrippedFieldsNote cut theirs to 120.
SmtpFieldNamesHost, which decides whether an incoming field names this
host, compared the name up to 253 characters.
SYMPTOM, found by reading and reproduced on Win32 and Win64 with host
names of 129 and 253 characters. None of the three fields this host
writes was recognised as its own. A sender that copied one of them onto
a message had it kept as another host's field: not renamed X-Forged-,
not counted in X-Stripped-Fields or the spam score, and not filed as a
forgery. With a name of 81 to 120 characters this affected only
Authentication-Results.
Which releases: Authentication-Results, 4.1.2.355 to 4.1.5.362, on every
platform, with VerifyInbound on and a ServerName longer than 80
characters; there such a copy was kept where it should have been
removed. X-DNS-Warning and X-Stripped-Fields, none: they came after
4.1.5.362.
Now every field this unit writes names the host exactly as
SmtpFieldNamesHost compares it, whole up to the 253 characters of a DNS
name (RFC 1035 sec.2.3.4). The name itself is not cut. When it would
take the first line of a field past 78 characters, the field is folded
after the colon instead. RFC 5322 sec.2.1.1: "Each line of characters
MUST be no more than 998 characters, and SHOULD be no more than 78
characters, excluding the CRLF." RFC 8601 sec.2.2 allows the [CFWS]
before the authserv-id. A shorter name is written as before, on the
first line.
BEHAVIOUR CHANGE: with a ServerName that does not fit the first line,
the three fields are written folded after the colon; with one longer
than 80 characters, Authentication-Results carries it whole where it
was cut.
See MAIL.txt section 5.
TESTED with Delphi 13 on Win32, Win64 and Linux64, a loopback listener
on scripted DNS, with host names of 129 and 253 characters: each of the
three fields as this host writes it carries the whole name; an imitation
of each is renamed X-Forged- and counted in the note; against the same
tests built from the units before this change, where none was.
--------------------------------------------------------------------------------
MAIL: SEARCH SETS WITHOUT A LIST OF THE MAILBOX
================================================================================
95. FIXED - IMAP SEARCH with a sequence-set or UID key makes no temporary
the size of the mailbox
StreamSec.Mail.IMAPEngine, MAIL.txt.
THE STEP THAT FAILED was turning a set key of a SEARCH into what the
search tests. Each set, even SEARCH 1, was first expanded into a list
with an entry for every message in the mailbox, and only then
compressed into runs. So the memory a SEARCH took on the way grew with
the number of messages, one Integer per message for every set key, and
not with the length of the command line as entry 73 said.
SYMPTOM, found by reading and reproduced on Win32 and Win64. A client
could make a server holding a large mailbox allocate that much once per
set key in a single command.
Which releases: 4.1.2.355 to 4.1.5.362, on every platform. There a set
key was also kept as such a list for the whole command.
Now a sequence-set or UID key is held as the ranges it was written as,
sorted and merged in place, and a message is tested by its number, or by
its UID for a UID key, against those runs. No list of the selected
messages is built. A sequence number above the message count is still
BAD, and a UID that no message has still selects nothing (RFC 3501
sec.6.4.8). '*' in a UID set is still the highest UID in the mailbox, or
UIDNEXT when it is empty (RFC 3501 sec.9).
See MAIL.txt section 6.3.
TESTED with Delphi 13 on Win32, Win64 and Linux64, in-process IMAP
sessions over 3000 messages, counting the memory requests a command
makes: SEARCH 1, 1:*, *, 2,4:6, UID 1, UID 2:* and UID SEARCH UID 2999:*
each make no request the size of the mailbox; the results of UID
2999:*, UID 5000:*, UID 4000:5000 and 2999:* NOT 3000; against the same
tests built from the units before this change, where each set key made
one or two.
96. FIXED, BEHAVIOUR CHANGE - a mail client signs in to the IMAP server
with a password outside US-ASCII, and the greeting names the
authentication mechanisms
StreamSec.Mail.IMAPEngine, MAIL.txt.
THE STEPS THAT FAILED:
- A client sent LOGIN with its password as a quoted string in UTF-8 and
was refused. tImapSession.TakeLine read every command line as
US-ASCII, which on Windows drops the high bit of each octet above 127,
and tImapSession.CmdLogin passed the result on as the password: a
password with a letter outside US-ASCII never matched the account's.
A password sent as a literal, or through AUTHENTICATE, was not
affected.
- tImapSession.Start sent a greeting whose CAPABILITY response code
lacked the AUTH= mechanisms that the CAPABILITY command lists on a
secure channel. A client that takes its list from the greeting never
learnt of AUTHENTICATE PLAIN and used LOGIN.
- The same decoding turned a mailbox name sent as raw 8-bit octets into
another name: CREATE of a name holding o-umlaut in UTF-8 created a
mailbox whose name had other ASCII letters in its place.
- tImapSession.HandleAuthLine read the AUTHENTICATE PLAIN and LOGIN user
name the same way: a UTF-8 user name never matched its account, and a
name whose octets differ from an account's only in the high bit signed
in as that account. Nothing checked the name for control characters,
as LOGIN does.
- A client sent LOGIN with its user name as a literal and its password
as a quoted string, and was refused: tImapSession.CmdLogin took the
last literal, which was the user name, as the password, and the
quoted password as the user name.
- A client sent LOGIN with an atom user name or password outside
US-ASCII, or such text after the password, and announced a literal:
the server asked for the literal and read it before answering BAD.
- A client sent LOGIN with a TAB before a quoted password holding a
letter outside US-ASCII, and the whole of it, TAB and quotes
included, was taken as the password: tImapSession.CmdLogin decided
whether the password was quoted after a Trim, which skips a TAB, and
the parser skips spaces only.
- A client sent LOGIN with an empty literal, {0}, for the user name or
the password. The empty literal was not kept as an argument, so what
followed it moved up one place: a quoted string after an empty
password literal was taken as the password, a user name and password
after an empty user name literal signed in, and an empty password
literal on its own was answered BAD "LOGIN needs a password".
- A client sent LOGIN with an argument after the password. Text after
it was ignored, and after a literal password a quoted string was
taken as the password.
- A client sent LOGIN with an unterminated quoted string holding a
letter outside US-ASCII and announcing a literal: the server asked
for the literal before answering BAD.
- A client sent CREATE, SELECT, EXAMINE, DELETE, RENAME, SUBSCRIBE,
UNSUBSCRIBE, APPEND, COPY or MOVE with the mailbox name as a literal
and was answered BAD: the name was looked for in the line, where a
literal leaves nothing. The literal was decoded only when an empty
quoted string stood in its place, and then with the high bit of each
octet above 127 dropped, so 8-bit octets named another mailbox.
- A client sent a literal whose count had leading zeros, as {0013},
and was answered BAD: the marker was removed from the command by the
length of the count written without them, and the zeros left behind
became an argument.
- A client sent LOGIN with a parenthesised list as the user name or the
password, or with a literal marker joined to an atom, as wrong{1}:
the list was taken as the operand, and the server asked for the
literal before answering.
SYMPTOM: a mail client signing in over implicit TLS with a password
holding spaces and a-ring, o-umlaut and a-umlaut got "authentication
failed", whatever was typed. Reproduced on Win32 and Win64.
Which releases: 4.1.2.355 to 4.1.5.362, on every platform.
Now:
- A command line is decoded as UTF-8 and nothing else (RFC 3629): a line
that is not valid UTF-8 is answered "<tag> BAD the command line is not
valid UTF-8" and charges the error budget. It is never repaired. CRLF
still ends a line and nothing else does.
- A character outside US-ASCII anywhere but inside LOGIN's quoted user
name and password is BAD: the command is not run, it charges the error
budget, and a literal it announces is not asked for. Nothing is ever
read with a stand-in for such a character, so a flag list (STORE, UID
STORE, APPEND), a search key (SEARCH KEYWORD) or a mailbox name cannot
carry one. A tag holding one, or an octet that is not UTF-8, is not
echoed: the answer is "* BAD", the form RFC 3501 sec.7.1.3 gives for
"a protocol-level error for which the associated command can not be
determined".
- LOGIN takes a quoted user name and a quoted password as UTF-8, as
RFC 9051 sec.9 allows a quoted string to carry it:
QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
"\" quoted-specials / UTF8-2 / UTF8-3 / UTF8-4
The password is the UTF-8 octets the client sent, which is what the
account's verifier is computed over. A user name or password outside
US-ASCII sent as an atom is BAD, as is such text after the password:
it must be quoted. A user name holding a control or
bidirectional character is answered NO [AUTHENTICATIONFAILED], like
every other failure, and the application is not asked.
- LOGIN takes the user name from its first argument and the password
from its second, each the literal sent for it or else an atom or a
quoted string, and never a literal sent for the other one.
- A LOGIN user name or password sent as an atom is US-ASCII without a
control character, as RFC 3501 sec.9 defines an atom:
ATOM-CHAR = <any CHAR except atom-specials>
atom-specials = "(" / ")" / "{" / SP / CTL / list-wildcards /
quoted-specials / resp-specials
Whether an operand is quoted is what the parser found, so a TAB before
a quote makes an atom, and BAD. A LOGIN refused for an atom, or for
text outside US-ASCII after the password, is BAD before a literal it
announces is asked for.
- An operand is there because something stands at its place, never
because its octets are not empty. RFC 3501 sec.4.3: "A literal is a
sequence of zero or more octets", so an empty literal is the user
name or password it stands for. An empty user name, as a literal or
as "", is NO [AUTHENTICATIONFAILED] without asking the application;
an empty password, as a literal or as "", is a password like any
other and NO [AUTHENTICATIONFAILED] when it is wrong.
- LOGIN takes two arguments, as RFC 3501 sec.9 has it:
login = "LOGIN" SP userid SP password
Any argument after the password - an atom, a quoted string or a
literal, empty or not - is BAD, before a literal it announces is
asked for, whatever form the password took. So is an argument that
does not parse, such as an unterminated quoted string.
- A mailbox name sent as a literal is taken from its place, as LOGIN's
operands are, and is held to the rule of a command line: an octet
above 127 in it is BAD, charged to the error budget, and the command
is not run. The literal has been read by the time this is known, so
the BAD comes after it. A mailbox name outside US-ASCII is sent in
modified UTF-7 (RFC 3501 sec.5.1.3). An APPEND message literal is
data, kept as the octets sent.
- A literal's count may have leading zeros, as RFC 3501 sec.9 has it:
literal = "{" number "}" CRLF *CHAR8
number = 1*DIGIT
The whole marker, every digit of it, is the literal's place.
- A LOGIN user name and password are each an astring (RFC 3501 sec.9):
astring = 1*ASTRING-CHAR / string
ASTRING-CHAR = ATOM-CHAR / resp-specials
A parenthesised list, or an atom holding a parenthesis, "{", a
wildcard, a quote or a backslash, is BAD, and so is a literal marker
that does not stand alone as an operand; both before a literal is
asked for.
- The AUTHENTICATE PLAIN and LOGIN user name is strict UTF-8 too, by the
same rule as a command line. One that is not, or that holds a control
or bidirectional character, is answered NO [AUTHENTICATIONFAILED] and
counted as every other failure; the application is not asked. It is
NO and not BAD because the name came inside a valid base64 SASL
response. The password is the octets sent, and the PLAIN
authorisation identity is still ignored.
- Every other command reads US-ASCII as before. A mailbox name sent as
raw 8-bit octets is BAD, not created under another name; send it in
modified UTF-7 (RFC 3501 sec.5.1.3).
- The greeting, CAPABILITY and the OK of LOGIN and AUTHENTICATE list one
set of capabilities. RFC 3501 sec.7.1 says of the CAPABILITY response
code: "This can appear in the initial OK or PREAUTH response to
transmit an initial capabilities list." On a secure channel before
authentication it includes AUTH=PLAIN and AUTH=LOGIN as AuthMechanisms
says; on a cleartext channel STARTTLS and LOGINDISABLED, as before.
BEHAVIOUR CHANGE: CAPABILITY sent after authentication no longer lists
AUTH=, because AUTHENTICATE is refused then. A command line that is not
UTF-8 is BAD where it used to be read with its high bits dropped. A
command line holding a character outside US-ASCII is BAD, except inside
LOGIN's quoted user name and password: a mailbox name in raw 8-bit octets
is BAD where it used to be renamed, and a STORE or APPEND flag list or a
SEARCH KEYWORD holding such a character is BAD where it used to name
another keyword. A tag outside US-ASCII is answered "* BAD". An
AUTHENTICATE user name that is not UTF-8 is NO [AUTHENTICATIONFAILED]
where it used to be read with its high bits dropped. A LOGIN user name
or password sent as an atom holding a control character is BAD, and so
is LOGIN with anything after its password, where it used to be ignored.
An empty literal password is NO where it used to be BAD. A mailbox name
sent as a literal is accepted where it was BAD, and one holding an
octet above 127 is BAD. A LOGIN user name or password that is a
parenthesised list, or an atom holding a parenthesis, "{", "%",
"*", a quote or a backslash, is BAD where it used to be accepted.
See MAIL.txt section 6.3.
TESTED with Delphi 13 on Win32 and Win64, in-process IMAP sessions over
implicit TLS and cleartext: the greeting against CAPABILITY on both;
LOGIN with a password holding spaces, a-ring, o-umlaut and a-umlaut as a
quoted UTF-8 string, as a literal and through AUTHENTICATE PLAIN; the
same password in ISO-8859-1 octets (BAD, no sign-in, and the session
still usable); CREATE and SELECT of mailbox names in raw UTF-8 and
ISO-8859-1 octets (BAD, nothing created); STORE, UID STORE and APPEND
with a keyword holding a-ring (BAD before the literal, nothing stored or
appended, FETCH FLAGS unchanged), SEARCH KEYWORD and UNKEYWORD with it
(BAD), a verb and a tag holding it in UTF-8 and in ISO-8859-1 (BAD, the
tag not echoed), LOGIN with it in an atom user name or after the
password (BAD); AUTHENTICATE PLAIN and LOGIN with a UTF-8 user name
holding o-umlaut (signs in), and with a user name that is "alice@..."
with the high bit of its first octet set, one in ISO-8859-1 octets, one
holding U+0085 and one holding U+202E (each NO [AUTHENTICATIONFAILED],
no sign-in, and the session still signs in); LOGIN with a literal user
name and a quoted password, a quoted user name and a literal password,
two literals, and a literal user name and an atom password (a wrong
password NO, the right one signs in), a literal user name with a quoted
password equal to it (NO), one account's password as the literal user
name and its name as the quoted password (NO), and a literal user name
with a quoted UTF-8 password holding spaces, a-ring, o-umlaut and
a-umlaut (signs in); LOGIN with an atom user name, an atom password, an
atom after the password and a quoted string after the password holding
a-ring, each announcing a literal (BAD, no literal asked for), with a TAB
before a quoted UTF-8 password equal to the account's password with the
TAB and quotes (BAD, no sign-in), and with an atom password holding a
TAB (BAD); LOGIN with a quoted password after an empty password
literal, a user name and password after an empty user name literal, a
quoted string after a literal password and an atom after a quoted
password (each BAD, no sign-in), an empty password and an empty user
name, each as a literal and as "" (each NO [AUTHENTICATIONFAILED], and
the session still signs in), and an unterminated quoted string holding
a-ring that announces a literal (BAD, no literal asked for); CREATE,
SELECT, RENAME and APPEND with a literal mailbox name in UTF-8 and in
ISO-8859-1 octets, and COPY and MOVE to one, while the names those
octets make with their high bits dropped exist (each BAD, nothing
created, selected, renamed, appended, copied or moved), CREATE and
SELECT of a modified UTF-7 name sent as a literal (OK), and APPEND of
a message holding 8-bit octets (stored octet for octet); a LOGIN
password literal counted {0013} (signs in) and {00} (NO
[AUTHENTICATIONFAILED]), CREATE of a literal name counted {0005} and
APPEND of a message counted with leading zeros (OK); LOGIN with a
parenthesised list as the password equal to the account's (BAD, no
sign-in), with a parenthesised user name and with wrong{1} (each BAD,
no literal asked for). Against the same tests built from the unit
before this change, 60 of them failed.
--------------------------------------------------------------------------------
PKIX: THE REVOCATION VERDICT A CERTIFICATE STORE KEEPS
================================================================================
97. FIXED, BEHAVIOUR CHANGE - the revocation verdict a certificate store keeps
is not used once a CRL is added or replaced, nor past
RevocationCacheMaxAge when the clock is set back, nor under rpHardFail
when it was inconclusive; RevocationCacheMaxAge 0 uses none but a revoked
one; a TLS peer whose certificate the store holds is checked for
revocation, and refused once that certificate has expired
StreamSec.Mobile.X509Comp, PKIX.txt.
THE STEPS THAT FAILED:
- TsmX509TrustedCertificates keeps the revocation verdict of each
certificate it holds. CheckRevocation, which VerifyCertificate and
AddCertificate go through, answered with that verdict, without asking
OCSP or looking at a CRL, while it was younger than
RevocationCacheMaxAge seconds. Its age was the wall clock now minus the
wall clock when the verdict was reached. When the clock was set back the
age was negative, and a negative age is younger than any
RevocationCacheMaxAge, 0 included: the verdict was used until the clock
had come back to where it had been, however long that took.
- The verdict did not say which lists it was reached from. A CRL added
with AddCRL, or assigned to CRLs[], after the verdict was reached was not
looked at for that certificate until the verdict was RevocationCacheMaxAge
seconds old: in the store itself, and in a store that hands its
revocation checks to its TrustedCACertificates store, as the
CollectedCertificates store of TsmStreamSecII does to its CACertificates
store.
- A store that hands its revocation checks to its TrustedCACertificates
store looked for a verdict it could use with its own
RevocationCacheMaxAge, and then again with that store's: a verdict was
used if either value allowed it, so RevocationCacheMaxAge 0 on one of the
two stores did not stop it.
- A verification that found an OCSP check of the same certificate running
answered with the last verdict kept, whatever had changed since and
whatever RevocationCacheMaxAge said.
- An inconclusive verdict was kept like any other: under rpHardFail, a
certificate refused with crcRevocationUnknown or crcCRLExpired while the
OCSP responder could not be reached, or no fresh CRL was held, went on
being refused from that verdict, without OCSP being asked again, for
RevocationCacheMaxAge seconds after the responder answered again or a
fresh CRL arrived.
- A verdict kept was used after RevocationPolicy changed. Under
rpSoftFail an inconclusive check is kept as crcOK, so after a change to
rpHardFail a certificate whose revocation could not be established was
accepted for RevocationCacheMaxAge seconds.
- An OnCheckOcsp handler that set aStatus to crcOK and then raised left
that crcOK as the verdict kept, although the check answered as
inconclusive: the next verifications within RevocationCacheMaxAge
answered crcOK without asking again, under rpHardFail too. So did a
crcOK set with aHandled left False, when the CRL step after it raised.
- The import of a TLS peer's chain, ImportChainFromTLS, through which
TsmStreamSecII checks every peer certificate, took a peer whose
certificate the store already held as trusted without any revocation
check: only a certificate the store did not hold yet went through
CheckRevocation. That was so whatever RevocationPolicy and
RevocationCacheMaxAge said, and also when a verification had already
found the certificate revoked.
- The same import accepted a peer whose certificate the store held but
which was outside its validity period - expired, or not yet valid - and
not allowed to be (BeforeImportTLSCert). It verified that certificate
again, found crcExpired, or crcRevoked when a CRL or OCSP answer
revoked it, put that in the status set and returned True: the TLS
handshake refuses a peer only when the import returns False. A peer
certificate the store did not hold yet was refused when expired.
SYMPTOM, found by reading; reproduced on Win32, Win64 and Linux64; the step
of the clock in a test build, the system clock untouched. A store holding
a CA certificate, the CA's CRL and a certificate it had verified against
them was given the CA's next CRL, which revokes that certificate.
VerifyCertificate went on answering crcOK for it for up to
RevocationCacheMaxAge seconds, 3600 by default, and longer by as much as
the clock was set back in the meantime. With RevocationCacheMaxAge 0,
which reads as "look at the lists every time", the same happened once the
clock had been set back, to a verification made while an OCSP check of
the same certificate was running, and through a store whose
TrustedCACertificates store had another value. A TLS peer whose
certificate the store had collected on an earlier connection was accepted
with no revocation check at all, for as long as the store held it, and
was accepted after that certificate had expired, revoked or not.
Which releases: the verdict, 4.1.1.349 to 4.1.5.362, on every platform;
4.1.0.348 kept no verdict. The import of a TLS peer whose certificate the
store held, unchecked for revocation and accepted when expired, 4.0.1.313
to 4.1.5.362; 4.0.1.313 is the first StreamSec Tools 4 release tag carrying
StreamSec.Mobile.X509Comp.
Now:
- The age of a verdict is measured both on the monotonic tick
(stTlsUtils.GetTickCount64) and on the wall clock, and a verdict is used
only while both ages are below RevocationCacheMaxAge and the wall-clock
age is not negative. Neither a step of the wall clock nor a suspend of
the system, which the monotonic tick of Linux and Android does not
count, lengthens the use: a clock set back past the moment the verdict
was reached ends it, a clock set forward or a suspend shortens it or
ends it, and a change of the time zone alone does not affect it. A
CRL's thisUpdate and nextUpdate are still compared with the wall clock,
as before.
- A crcOK is used again within RevocationCacheMaxAge, and a revoked
verdict for good. An inconclusive verdict, crcRevocationUnknown or
crcCRLExpired, is kept as such under every policy, and the policy of
the store that decides the check is applied when it is used: under
rpSoftFail it answers crcOK within RevocationCacheMaxAge, as before;
under rpHardFail it is not used, and the next verification asks OCSP
or looks at the lists again. A change of RevocationPolicy to rpHardFail
so ends the use of an inconclusive verdict kept under rpSoftFail, and
of no other verdict. An OnCheckOcsp handler that leaves aHandled False,
or raises, gives no answer, whatever it set aStatus to.
- RevocationCacheMaxAge 0 uses no verdict kept but a revoked one: every
verification asks OCSP or looks at the lists held. A store that hands
its revocation checks to its TrustedCACertificates store uses a verdict
only within the smallest RevocationCacheMaxAge of the stores the check
passes through, so 0 on any of them is kept.
- NEW: CRLSetGeneration counts the changes to the lists of every store in
the process: a list added or replaced by AddCRL, a list assigned to
CRLs[], Clear of a store that held lists, and a store given another
TrustedCACertificates or losing it while it holds certificates or
another store hands its checks through it. A verdict is kept with the
count read before OCSP or the lists were consulted, and is used only
while the count is unchanged, so a list that arrives while a check is
running is not taken as consulted either. A list AddCRL refuses, and a
list it already holds sent again, change nothing: a refresh that fetches
the same list keeps the verdicts.
- A verification that finds an OCSP check of the same certificate running
uses the verdict kept by the same rules as any other verification:
revoked, or reached under the lists held now less than
RevocationCacheMaxAge seconds ago. Otherwise, or when there is none
yet, it looks at the lists itself and leaves OCSP to the check that is
running.
- A revoked verdict is kept for good, as before, and is no longer
overwritten by a check that ends after it. A check that ends with a
revocation after another check recorded a verdict of newer lists is
kept too; any other verdict reached under older lists does not replace
one reached under newer ones.
- Under rpIgnore no revocation check is made, as before, and a revoked
verdict kept from before still answers crcRevoked, as TRevocationPolicy
says: a definite revocation is honoured under every policy. The import
of a TLS peer below follows the same rule.
- The import of a TLS peer's chain checks the revocation of the peer's
own certificate when the store already holds it, by the revocation
step of VerifyCertificate, and refuses the peer when that step answers
crcRevoked, crcRevocationUnknown or crcCRLExpired, with that status. The
refusal is offered to OnCertNotAccepted, as AddCertificate offers one;
Retry there repeats the check. The issuer is looked up in the stores
only, without the AIA caIssuers fetch of OnFetchCAIssuer, which the
first import made. A self-signed peer certificate has no revocation
step, as on its first import. The CA certificates above the peer's
certificate are entry 98.
- The import refuses a peer whose certificate the store holds but which
is outside its validity period, unless BeforeImportTLSCert allows it,
as it refuses one it does not hold: with crcExpired in its status, or
the revocation status found.
- NEW: iCertRevocationStatusAsOf, implemented beside iCertRevocationStatus
by the store's per-certificate slot: EndCheckAsOf records a verdict with
the count it was reached under. iCertRevocationStatus and its GUID are
unchanged; its EndCheck records with the count read when it is called,
and its CachedStatus follows the rules above, handing an inconclusive
verdict to the caller, whose policy decides it.
BEHAVIOUR CHANGE: after a CRL is added or replaced anywhere in the process,
the next verification of every certificate a store holds asks OCSP or
looks at its lists again instead of using the verdict kept; with an
OnCheckOcsp handler that is one more OCSP request per certificate. Under
rpHardFail, while OCSP cannot be reached and no fresh CRL is held, every
verification asks again instead of answering from the inconclusive
verdict kept, also after a change from rpSoftFail. With the clock set
back, or after a suspend, a verdict is no longer used past
RevocationCacheMaxAge; with RevocationCacheMaxAge 0 on a store, or on a
store it hands its checks to, no verdict but a revoked one is used at
all.
For TLS, a handshake with a peer whose certificate the store holds now:
- refuses a revoked peer, and under rpHardFail a peer whose revocation
cannot be established - the OCSP responder unreachable, the CRL past
its nextUpdate, the issuer not found - which every release accepted;
- refuses a peer whose certificate has expired, which every release
accepted;
- checks the peer's revocation whenever the verdict kept cannot be used,
where every release made no check: with an Ocsp component or an
OnCheckOcsp handler, one OCSP request; and when that gives no answer
and no fresh CRL of the peer's issuer is held, a download of the CRL
the peer's certificate names in its cRLDistributionPoints, which
TsmCustomTLSInternalServer has the store make with or without an Ocsp
component (OnFetchCRL). The Ocsp component's Timeout, or 15 seconds
for the download without one, bounds each wait for the server to take
or send data, not the name lookup and not the request or the download
as a whole. A held peer is so checked once every
RevocationCacheMaxAge seconds, a peer whose download fails under
rpSoftFail included, and at every handshake with RevocationCacheMaxAge
0 on either store, or under rpHardFail while the check stays
inconclusive; and again after a CRL is added or replaced anywhere in
the process, as above. That includes a CRL another TLS engine fetches
for its own peer, such as the engine a TsmCustomRESTClient with trust
of its own makes for one exchange when it has no TLSEngine, which
downloads its peer's CRL at every call: give such a client a
long-lived TLSEngine. The request and the download run inside the
certificate import, which holds the store's lock and the lock of the
TsmStreamSecII engine: the engine's other connections wait for them,
as they always did for a peer certificate the store did not hold yet.
TESTED with Delphi 13 on Win32, Win64 and Linux64: a store holding a CA, its
CRL and a certificate verified against them, with an OnCheckOcsp handler
that answers nothing, crcOK or crcRevoked and counts the checks: the
verdict used while the lists are unchanged; the same CRL added again, the
verdict still used and the certificate not revoked; the CA's next CRL
added, the certificate revoked at the next verification and staying
revoked; the next CRL assigned to CRLs[]; RevocationCacheMaxAge 0 through
the same steps, every verification counted; RevocationCacheMaxAge 2 with a
wait of a little over two seconds, the clock not touched; the CRLs in the
TrustedCACertificates store of the store that verifies, the next CRL added
there; RevocationCacheMaxAge 0 on either of the two stores; a store that
holds no certificate but that the verifying store hands its checks
through, and the verifying store itself, given another
TrustedCACertificates store; that store freed; Clear of another store; a
verification made while a check of the same certificate is running, after
the next CRL was added, with RevocationCacheMaxAge 0, and with a verdict
older than RevocationCacheMaxAge 1; a CRL added while the OCSP check runs;
a revocation from OCSP that ends after a verification of newer lists; the
import of a TLS peer's chain whose certificate the store holds, before and
after the CA's next CRL, with OnCertNotAccepted told of the refusal and
asking for a retry; an expired peer certificate held, with no CRL and
with one that revokes it; a pinned peer certificate whose issuer no store
holds, with an AIA caIssuers URL, imported three times, the fetches and
trust prompts counted; under rpHardFail with OCSP the only source, the
responder not answering, then answering; rpIgnore with a revoking CRL
and no revoked verdict kept, then after a revocation, and the policy
changed back; a change from rpSoftFail to rpHardFail with an inconclusive
verdict kept, and with a crcOK a CRL gave; RevocationPolicy set on
another store; an OnCheckOcsp handler that set crcOK and raised, under
rpHardFail and before a change to rpHardFail, and one that set crcOK with
aHandled False before a CRL download that raised; TLS 1.2 and 1.3
handshakes with client authentication,
three per case, the server holding the client's certificate from the
first: revoked by OCSP on the second, RevocationCacheMaxAge 3600 and 0
with the OCSP requests counted, rpHardFail with the responder down then
up and with a retry from OnCertNotAccepted, a change to rpHardFail with
no revocation source, rpIgnore after a revocation, RevocationPolicy set
on an engine made and freed between handshakes, and a CRL added to such
an engine, the held peer asked about again; against the same
tests built from the units before this change. In a test build,
the tick and the wall clock the verdict is aged on were stepped apart,
the system clock untouched: the wall clock set back, a suspend (the wall
clock on, the tick not) and the tick past RevocationCacheMaxAge with the
wall clock not; the same against units without either age test.
--------------------------------------------------------------------------------
PKIX: A CA CERTIFICATE THAT A CRL OF THE TRUSTED STORE REVOKES
================================================================================
98. FIXED, BEHAVIOUR CHANGE - a CA certificate above a certificate is looked up
in the CRLs of the store's TrustedCACertificates store as well as in the
store's own, and a TLS peer whose certificate the store holds goes through
that CA check too
StreamSec.Mobile.X509Comp, StreamSec.Mobile.StreamSecII,
StreamSec.DSI.PkixCRL, PKIX.txt.
THE STEPS THAT FAILED:
- VerifyCAChain of TsmX509TrustedCertificates, the step of
VerifyCertificate, AddCertificate and the import of a TLS peer's chain
that goes through the CA certificates above a certificate, asked
IsRevoked about each of them. IsRevoked reads only the CRLs the store
holds itself, never those of its TrustedCACertificates store.
TsmStreamSecII keeps its CRLs in CACertificates (on
TsmCustomTLSInternalServer, RootCerts) and the certificates peers send
in CollectedCertificates, which hands its checks to CACertificates as
its TrustedCACertificates store. An intermediate CA certificate held in
CollectedCertificates was so never compared with a CRL in CACertificates
that revokes it.
- The intermediate's own revocation check, which does read the
TrustedCACertificates store, runs when the intermediate is added or
imported. A CRL that arrives later is not seen by it, and a new
certificate under an intermediate the store holds is taken before the
intermediate is looked at again.
- The import of a TLS peer's chain, ImportChainFromTLS, did not go through
the CA certificates at all for a peer whose certificate the store held.
A CRL that revokes the intermediate CA did not refuse such a peer, also
when the store held that CRL itself, and neither did an intermediate CA
certificate that had expired.
- IsRevoked of iCertificateList read the certificateIssuer extension of
an indirect CRL's entries (RFC 5280 section 5.3.3) only for a
certificate of another issuer than the CRL's, and only on the entry
with that certificate's serial number. An entry of another certificate
issuer so revoked a certificate of the CRL's own issuer that had the
same serial number, and an entry without the extension, which has the
certificate issuer of the entry before it, was never taken for that
issuer. From 4.1.1.353 a CRL read from DER and not decoded in full, as
a CRL added to a store is, matched no certificate of another issuer at
all.
- The chain step went round for ever, holding the store's lock, when the
certificate found first at each level led back to one it had passed:
two CAs that certify each other, with those two certificates held
ahead of the self-signed certificates of the CAs. VerifyCertificate
and the first import of a certificate under them did not return.
SYMPTOM, found by reading; reproduced on Win32, Win64 and Linux64. A TLS
engine that has accepted a peer whose chain runs through an intermediate
CA is given the root CA's next CRL, which revokes that intermediate, in
its CACertificates store. The same peer was accepted at its next
handshake, VerifyCertificate of its certificate answered crcOK, and a
peer with a new certificate from the revoked intermediate was accepted.
The same chain seen for the first time after that CRL was refused. No
OCSP responder or download enters into it: the CRL was held and was not
read.
Which releases: a CRL of the TrustedCACertificates store not applied to a
CA certificate, and the import of a peer whose certificate the store
holds without a CA check, releases 4.0.1.313 through 4.1.5.362, on every
platform. 4.0.1.313 is the first StreamSec Tools 4 release tag carrying
StreamSec.Mobile.X509Comp. In 4.0.1.313 through 4.1.0.348 the
intermediate's own revocation check read only the store's own CRLs as
well, so the first import of such a chain was accepted too; from
4.1.1.349 it was refused. The reading of an indirect CRL's entries,
releases 4.0.1.313 through 4.1.5.362; no certificate of another issuer
matched in a CRL not decoded in full, 4.1.1.353 through 4.1.5.362. The
chain step that did not end, releases 4.0.1.313 through 4.1.5.362.
Now:
- The CA step looks each CA certificate up in the CRLs the store holds,
as before, any entry counting as a revocation. It then looks it up
through every certificate the stores hold of the CA certificate's
issuer, so that one without cRLSign does not hide the list of one that
has it, in the store's lists and those of the stores it delegates to:
its TrustedCACertificates store and, in turn, that store's. One of
those lists counts when the certificate it is looked up through signed
it, whatever its dates: a list past its nextUpdate still says that the
certificate was revoked, and the store's own lists have always counted
so. The step makes no OCSP request and downloads no CRL; those stay
with the CA certificate's own revocation check, when it is added or
imported, except for one the import of a peer the store holds brings
in (below). So does what an inconclusive state decides: no list of the
issuer, or an expired one that does not name the CA certificate,
refuses nothing in this step, under rpHardFail too. The lists are read
at every verification, so no verdict kept (entry 97) stands in the way
of a CRL added since, and no verdict kept counts here: a CA certificate
that only an OCSP answer says is revoked does not refuse a certificate
under it.
- In that second look an entry with the reason removeFromCRL revokes
nothing, and a CA certificate on hold (certificateHold) is no longer
revoked once a later list of the same issuer and scope, signed with
the key that signed the hold, says so (RFC 5280 sections 5.2.4 and
5.3.1): a delta CRL with a higher CRL number, whose BaseCRLNumber the
list with the hold reaches, with a removeFromCRL entry for it, or a
complete CRL with a higher CRL number that no longer names it, or has
a hold of its own, which then counts in its place. Any other reason,
an entry with no reason, and a list whose CRL number is missing or
cannot be read, or whose BaseCRLNumber is negative, keep the CA
certificate revoked. That reading is the second look's alone: a list
the store holds that the first look finds revokes whatever the reason.
The CA certificate's own check when it is added or imported is as it
was: it stops at the first usable list of the issuer and reads no
reason, so that a chain whose CA certificate was released is still
refused on its first import while a list with the hold is the first
one met.
- When the stores hold more than one certificate of a CA, such as cross
certificates, a CA certified by two roots or a renewal, the step goes
on through the first of them, in the order the stores are looked up,
that signed the certificate below it, passes the step's other tests
(cA, pathLenConstraint, keyCertSign, the Netscape certificate type)
and has a way up, ending at a self-signed certificate or one with no
issuer held, with no revoked or expired CA certificate on it. Whether
one is found does not depend on the order in which they were added. If
none is, the chain is refused for the first reason met. The signature
of a certificate added or imported for the first time is then still
verified with the certificate of its CA found first, as in every
release: with no authorityKeyIdentifier, under a name two keys share,
it is refused with crcInvalidSignature when the other key's certificate
comes first. A circle of cross certificates is no way up, and a chain
step that comes back to a certificate it has passed ends: with nothing
above the circle the answer is crcCANotTrusted. One search looks at no
more than 256 certificates (a limit chosen, not measured) and refuses
the chain with crcConstraintFault beyond that. Name constraints and
certificate policies apply to the path taken and do not steer the
search. With one certificate of the CA held, it is the step it was.
- AddCRL asks the same of the CA that signed the list. When the
certificate of the CA it finds first is revoked, has expired or has no
good chain, the list is taken if another certificate of that CA signed
it and passes those tests, and is verified with that certificate;
otherwise AddCRL answers for the first one, as before.
- Setting TrustedCACertificates to the store itself, or to a store that
delegates to it directly or through other stores, raises
ETLSEngineError and changes nothing. Through 4.1.5.362 the assignment
was taken, and a look-up that followed the circle, as one does for a
certificate whose issuer the first store does not hold and at a
revocation check, ended in a stack overflow; a program that never made
one ran. To reverse a delegation, clear the link there is first,
A.TrustedCACertificates := nil, and then set the new one,
B.TrustedCACertificates := A. In the other order the first assignment
raises. CACertificates and CollectedCertificates of TsmStreamSecII ask
the store first: when it raises, the component is as it was.
- FindRevocation of the store reads a CRL's entry without adding anything
to it, also on a list that is not read-only, and honours its
certificateIssuer as it did. IsRevoked of the store no longer reads that
extension: what it read was never used.
- IsRevoked of iCertificateList follows the certificate issuer of each
entry of an indirect CRL: the one its certificateIssuer names, else
that of the entry before it, and for the first entry the CRL's issuer.
This applies to every certificate looked up, the peer's own included.
A list without the indirectCRL flag is read as before for a certificate
of its own issuer.
- Under rpIgnore on the store that decides the revocation checks, the
second look is not made, so the lists of the stores delegated to are
not read, as before. The CRLs the store holds itself are, as they
always were.
- The import of a TLS peer's chain runs that step for a peer whose
certificate the store holds, after the revocation step of entry 97. It
is the step VerifyCertificate runs for a certificate the store holds,
with what BeforeImportTLSCert says of expired certificates. The issuers
are looked up in the stores only, without the AIA caIssuers fetch of
OnFetchCAIssuer. A peer certificate has no chain to check when no
certificate the stores hold under its issuer's name signed it, as with
one trusted explicitly whose issuer is not held, or when all that is
held above it is a circle of cross certificates: the chain step refuses
nothing for it and OnCertNotTrusted is not asked; under rpHardFail the
revocation step of entry 97 still refuses it when no issuer is held.
VerifyCertificate goes by the name when one certificate is held under
it, signed or not, and answers crcCANotTrusted for a circle and for
several that did not sign. A self-signed peer certificate has no such
step, as on its first import.
When the step refuses, those of the certificates sent above the peer's
own that have cA TRUE in basicConstraints and that the store does not
hold are added, as on a first import but without any explicit trust
BeforeImportTLSCert gave the peer's certificate and from what the
stores hold: no OCSP request, CRL download or AIA fetch is made for
them, and under rpHardFail one with no usable list of its issuer is
not added. A certificate without cA TRUE is not added. The step then
runs once more: a CA renewed or certified anew does not lock out a
peer the store holds. A refusal is offered to OnCertNotAccepted, as
AddCertificate offers one; Retry there repeats the check and the adding
of the certificates the peer sent.
That adding happens when the Certificate message is read, before the
peer has proved that it holds the private key: anyone presenting the
public certificate of a certificate the store holds, whose chain the
step refuses, can have the CA certificates they send stored if those
pass these tests. A CA certificate added this way has had no OCSP or
CRL-download check of its own. The check it did have leaves no verdict
(entry 97), so the next verification of that certificate itself, by
VerifyCertificate or as a peer's own certificate, makes those checks
as for any other certificate; a certificate under it is judged by the
CA step above, which makes neither. A verification that a handler makes
meanwhile, of the CA certificate being added as of any other, asks OCSP
and for the CRL download as usual. No AIA caIssuers fetch is made for
it: a certificate whose issuer only that fetch would supply is answered
as one whose issuer is not held: crcCANotTrusted, or
crcRevocationUnknown under rpHardFail.
- The status set of that import then holds crcCAExpiredOrRevoked, and
crcRevoked when a CA certificate is revoked or crcExpired when one has
expired, so that the TLS alert is certificate_revoked or
certificate_expired, as on the first import of such a chain; a TLS 1.2
server refusing a client certificate sends bad_certificate whatever the
status, on the first import too. The same goes for a certificate
refused for its CA on its first import, also when the peer did not send
the CA certificate the store holds, whichever certificate of the chain
that CA is above; the chain followed is that of the peer's own
certificate, and a CA that failed for another certificate it sent is
not named. On a first import what was refused of those other
certificates is in the status as well, as in every release: an expired
one among them adds crcExpired, and the alert is then
certificate_expired. The import of a certificate the store holds
reports only the chain of the peer's own certificate: what else the
peer sent adds nothing to its status.
VerifyCertificate and AddCertificate answer crcCAExpiredOrRevoked, as
they do for a CRL the store holds itself. IsRevoked of the store still
answers for the store's own CRLs alone.
- NEW in StreamSec.DSI.PkixCRL: CRLNumberIsHigher compares the CRL numbers
of two lists in arbitrary precision; CRLFollows says whether a later
list can say what has become of an entry of an earlier one (RFC 5280
section 5.2.4); CRLEntryExtension reads an extension of a CRL's entry
without adding a missing one to a list that is not read-only. None of
them authenticates a list.
BEHAVIOUR CHANGE: a certificate under a CA certificate that a CRL in the
TrustedCACertificates store, or in a store that one delegates to, revokes
is now refused where it was accepted: VerifyCertificate and
AddCertificate answer crcCAExpiredOrRevoked, AddCRL refuses a CRL signed
by such a CA or by a CA under one unless another certificate of the CA
gives it a good chain, and a TLS peer with a certificate under such a CA
is refused. AddCertificate so also refuses a local certificate for
TsmCustomTLSInternalServer's MyCerts once that CRL is held. A local
certificate already held is not looked at again: the choice of the
certificate to present (FindCert) and TLSSetupServer ask only
about the certificate itself in the store's own CRLs, so the engine goes
on presenting it. A TLS handshake with a peer whose certificate the store
holds is now also refused when a CA certificate above it has expired,
unless BeforeImportTLSCert allows that, or fails the other checks of the
CA step (crcConstraintFault, crcInvalidKeyUsage), which every release
accepted. There is no OCSP request and no download for this: the
handshake reads the lists the stores hold, under the store's lock, as
the first import of a peer does. Such a handshake, when the chain is
refused, can bring CA certificates into the store, as a first import can,
before the peer has proved that it holds the private key.
Setting TrustedCACertificates so that stores would delegate in a circle,
which every release took, raises ETLSEngineError, also where the circle
would have lasted only until the next assignment, as in the reversal of a
delegation with the new link set first (above).
VerifyCertificate and AddCertificate now accept a chain
they refused for a certificate of a CA that was revoked, had expired or
failed the step's other tests, when another certificate of that CA gives
it a good way up. An indirect CRL's entry of another certificate issuer
no longer revokes a certificate of the CRL's issuer with the same serial
number. IsRevoked of iCertificateList, called directly, now finds the
certificate of that other issuer that the entry names or inherits. A
store does not apply another issuer's indirect CRL to a CA certificate or
a peer's certificate: FindCRLs selects the lists by the certificate's
issuer, and IsRevoked of the store counts an entry only in a list of that
issuer.
KNOWN LIMITS, not changed by this entry:
- The first usable list of an issuer decides a certificate's own
revocation check, whatever the list's scope (RFC 5280 section 6.3.3).
With a partition (issuingDistributionPoint) or a complete list of the
issuer met first, a certificate that another list the store holds
revokes, a delta CRL or a partition or complete list behind the first,
is taken as not revoked, under rpHardFail too, and the CRL download
for its own partition is not made. AddCRL compares the CRL numbers of
an issuer's lists across their scopes when the list added is a
partition or a delta CRL, and can refuse it with crcSuperseeded because
a list of another scope has as high a number. Hold one complete CRL
per issuer in a store, and no partitions or delta CRLs; where an issuer
publishes only partitions, use OCSP, which is asked first. The CA step
above reads every list of the issuer and does not have this limit.
- A certificate's own revocation check looks for the lists through the
certificate of its issuer found first. When that is a cross certificate
of the CA without cRLSign, held ahead of the CA's own certificate, the
CA's list is not found: when OCSP gives no answer, a certificate that
list revokes is accepted under rpSoftFail, and every certificate of
that CA is refused as inconclusive under rpHardFail. A store is
searched before the store it delegates to, and a TLS peer can bring
such a cross certificate into the store that delegates, as
CollectedCertificates does, when its Certificate message is read,
before it has proved that it holds the private key. The order in the
store delegated to then does not help, and under rpHardFail the
refusals last until that certificate is taken out of the store. Hold
the CA's own certificate in the store the check starts from, ahead of
its cross certificates and of anything a peer can add, or use OCSP,
which is asked first. The CA step above goes through every certificate
of the issuer and does not have this limit.
TESTED with Delphi 13 on Win32, Win64 and Linux64: a root and its CRL in
the store delegated to, and an intermediate CA and certificates under it
in the store that delegates; the chain imported under a clean list, then
the root's next list, revoking the intermediate, added there; the held
certificate imported again and verified, with the OCSP requests and CRL
downloads counted; a new certificate imported with the intermediate in
its chain and alone, and verified; OnCertNotAccepted told of the refusal
and asking for a retry; the same chain first imported after that list;
three stores with the list in the second and in the third; the list in
the store that holds the intermediate; the intermediate and the list in
the store delegated to; the CA above the issuing CA revoked; a list in
the root's name that the root did not sign; rpIgnore; an expired
intermediate, refused and allowed by BeforeImportTLSCert; a CRL signed by
the revoked intermediate, with the revoking list delegated to and held
by the store, and under rpIgnore; a new sub-CA and certificate under the
revoked intermediate with that intermediate not sent; one intermediate
key certified by two roots, either certification added first, one
revoked, then both; a second certification beside a path through a
revoked mid-level CA; another key under the issuing CA's name, which
does not stand in for it; a revoked and an expired cross certificate
beside the self-signed anchor, and the revoked one without it; a cross
certificate of the issuer without cRLSign; indirect CRLs whose entries
name another certificate issuer, inherit it, and name the root again; a
CA certificate on hold, released by a delta CRL and on hold again; a
release entry alone, and one after another reason; a circle of cross
certificates beside the path to the root and ahead of it, that path
revoked and not; two self-signed CAs certifying each other, and a circle
with nothing above it; a CA certified twice under a revoked CA and once
by a clean root, either added first; a certificate with cA FALSE and a
pathLenConstraint of 0 among those of a CA; more certificates of a CA
than a search looks at; another key under the issuer's name found first;
a new certificate that names no key under a name two keys share, either
added first; a certificate trusted explicitly beside certificates of
other keys, or one with cA FALSE, under its issuer's name; a CA's own
CRL with its certification by one root revoked, either added first, and
a revoked cross certificate with cRLSign beside the self-signed one;
another certificate of a CA with no issuer held and an AIA URL, with the
fetches counted; another certification and a renewal sent by a peer the
store holds, a certificate of the same key that nothing trusts, one that
is revoked, one with no list of its issuer under rpHardFail, and one
whose root OnCertNotAccepted trusts before a retry, with the OCSP
requests, CRL downloads and AIA fetches counted; the next verification of
a certificate so brought in, and its import as a peer's own, under
rpSoftFail and rpHardFail, with an OCSP answer, with none and a CRL
download, and after a fresh list that does not name it; a certificate
with cA FALSE among those sent; another certificate, and the one being
added, verified from a handler meanwhile, and a retry of the store's own
check; a CRL the store holds behind a cross certificate without cRLSign;
delta and complete CRLs of
the same and of another scope that do and do not end a hold, a negative
BaseCRLNumber, one beyond 64 bits, and a list signed by another key of
the issuer's name; a CRL left writable, with and without an
authorityKeyIdentifier; a certificate outside the chain among those
sent, under an expired CA and expired itself; an indirect CRL held by a
store; stores delegating in a circle, the reversal of a delegation in
both orders, and a refused CACertificates and CollectedCertificates of
the engine, and a CollectedCertificates store that delegates to the one
it replaces; IsRevoked and FindRevocation of a store on a CRL left
writable; against the same tests built from the units before this
change.
--------------------------------------------------------------------------------
TIME ZONES: OFFSETS THAT ARE NOT WHOLE HOURS
================================================================================
99. FIXED - on Linux64, macOS, iOS and Android OffsetFromUTC returns the
whole offset from UTC, and the UTC the library works out from it is no
longer 30 or 45 minutes off in a zone with a half or quarter hour
stTlsUtils (OffsetFromUTC).
THE STEP THAT FAILED: built with Delphi for a POSIX target, OffsetFromUTC
returned TTimeZone.Local.UtcOffset.Hours. Hours is the hours component
of a TTimeSpan, not its length, so the minutes of the offset were
dropped: 5 at +5:30 (India), 5 at +5:45 (Nepal), -3 at -3:30
(Newfoundland in winter), 10 at +10:30 (South Australia in summer). It
now returns the whole offset in hours, 5.5, 5.75, -3.5 and 10.5 in those
zones, to the minute as on Windows.
SYMPTOM, found by reading and reproduced on Linux64. The library works
out the current UTC as Now - OffsetFromUTC / 24. In these zones that was
30 or 45 minutes ahead of the real UTC east of Greenwich, and 30 minutes
behind it west of Greenwich (Newfoundland, the Marquesas). The system
clock was right, and no setting, time zone file, certificate or CRL
entered into it. To tell whether a machine is affected, read
OffsetFromUTC: it shows a whole number where the zone's offset has
minutes. Zones on whole hours did not have this defect and their result
is unchanged. A result that is one of the zone's own offsets, only not
the one in force at that moment, is not this defect either, whether it
is a whole hour off or, on Lord Howe Island, half an hour (10.5 where 11
applies): on these targets which offset applies at a given moment is
still TTimeZone.Local's answer, and this change does not touch that.
TTimeZone takes the time repeated when daylight saving ends as standard
time, so during the first pass through it the UTC is ahead by the zone's
daylight saving, on Lord Howe 30 minutes for half an hour each year.
What that UTC was used for:
- The thisUpdate and nextUpdate of a CRL in
TsmX509TrustedCertificates.CRLUsable (StreamSec.Mobile.X509Comp), of an
OCSP response (StreamSec.DSI.AbstractOcsp) and the nextUpdate of a
stapled one (StreamSec.Mobile.StreamSecII), and the notBefore and
notAfter of a certificate in TstCustomKeyFilterChain
(StreamSec.DSI.PkixKeyFilter). East of Greenwich a list, response or
certificate counted as out of date up to 30 or 45 minutes before it
was, and a certificate not yet valid was accepted that much early;
west of Greenwich the other way round. Any clock skew allowed applied
on top of that.
- The clock-skew window around the genTime of a time-stamp token
(StreamSec.DSI.Tsp): a fresh token fell outside a window narrower than
the error.
- What the library dates itself: the signing time of a CMS signature
(StreamSec.DSI.PkixCms), the revocation date of a CRL entry
(StreamSec.DSI.PkixCRL), the times in an OCSP response and the Date,
Last-Modified and Expires headers of a cacheable one
(StreamSec.DSI.PkixOcspServer) and the validity of the tls-alpn-01
challenge certificate (StreamSec.Mobile.StreamSecII).
- The date of a PDF signature (StreamSec.Pdf.Signer): local digits with
the zone written as +05'00' at +5:30, an instant 30 minutes off.
- The renewal schedule of certificates (StreamSec.Mobile.AcmeRenewal) and
the expiry warning of a reloaded certificate
(StreamSec.Mobile.CertificateReload).
The library's other route to UTC, TTimeZone.Local.ToUniversalTime, had
the whole offset all along: tValidity.CheckValidity without an argument,
the HTTP dates of StreamSec.Mobile.HTTPS, StreamSec.Mobile.HTTPSClient,
StreamSec.Http.Http2Conn and StreamSec.Http.Http3Server, and the dates
of mail were not affected.
Which releases: built with Delphi for macOS, iOS or Android, 4.0 beta
0.305 to 4.1.5.362. Built for Linux64, 4.0.1.327 to 4.1.5.362, and with
Delphi 10.2 Tokyo already from 4.0.1.323; stTlsUtils does not compile
for Linux64 in the releases before those. Windows builds and FPC builds
have branches of their own that read the offset in minutes and were not
affected.
TESTED with Delphi 13 on Linux64 under WSL, each zone in a process of its
own through that process's TZ environment variable: Asia/Kolkata,
Asia/Kathmandu, America/St_Johns, Australia/Adelaide, Pacific/Marquesas
and Pacific/Chatham, the same kinds of offset as POSIX zone strings with
no time zone database involved, and as controls zones on whole hours
east and west of UTC, with and without daylight saving. OffsetFromUTC was
compared with the offset the C library reports for the zone, and the UTC
worked out from it with the system's. Against the unit before this
change the zones with half and quarter hours failed and the zones on
whole hours passed. macOS, iOS and Android have the same line of code and
were not run.
--------------------------------------------------------------------------------
SNIF: KAPA.txt
======================================================================
100. FIXED (documentation only) - KAPA.txt reports a machine-checked proof of
the login exchange, and no claim has been weakened
KAPA.txt.
No code changed: the StreamSec.Snif units are as in 4.1.5.362, and no claim
the document makes has been weakened. The one new thing it states is that a
Tamarin analysis has machine-checked conditional symbolic properties of the
login exchange, with what that analysis assumes and what remains
outstanding. Some sentences were reworded without changing the conclusions
of the document as a whole. G1 is among them: that an adversary who gets the
server file can use it to confirm a correctly guessed password has always
been known.