Feature notes
Release notes 4.1.4.361
================================================================================
CHANGES - StreamSec Tools
(StreamSec Security Library for Embarcadero Delphi)
================================================================================
Grouped by subject and numbered straight through. Entries marked BEHAVIOUR
CHANGE alter what existing code does without any source change on your part -
read those before upgrading.
WHAT THIS FILE COVERS. Changes made SINCE release 4.1.4.360, which was
released on 2026-09-27. What that release itself brought is in
CHANGES_4.1.4.360.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.
--------------------------------------------------------------------------------
THE DOCUMENTS: HOW A VULNERABILITY REPORT IS HANDLED
================================================================================
1. NEW - SECURITY.txt, the coordinated vulnerability disclosure policy
How to report a vulnerability in a StreamSec product, what happens to the
report, and when the details become public: the policy that Annex I, Part
II, point (5) of the Cyber Resilience Act asks a manufacturer to put in
place and enforce. It ships beside PRODUCTINFO.txt, is a topic in the help
file, and is also published at
https://www.streamsec.com/index.php?id=security.
IN SHORT. A report sent to support@streamsec.se is read on the day it
arrives. A fix is published as soon as it is ready, as a free source patch
in the Announcements section of the support forum, with an advisory that
names the releases affected and gives the severity as a CVSS v4.0 score
with the vector it was computed from. The reporter is credited unless
they ask not to be. An advisory is identified by the releases it applies
to and a patch number; CVE identifiers are not used. Customers are not
contacted before a fix is published, except where Article 14 of the Cyber
Resilience Act requires an earlier warning of an actively exploited
vulnerability. There is no bug bounty, and no legal action against
research done in good faith on a licensed copy and reported under the
policy before it is made public.
PRODUCTINFO.txt SECTION 2 CHANGES WITH IT. It said that a formal policy
was not yet published, and that a disclosure timetable would be agreed
with the reporter. It now names SECURITY.txt, and the publication date is
no longer agreed with the reporter: a fix is published as soon as it is
ready.
--------------------------------------------------------------------------------
THE SET3 CIPHER-STREAM CONTAINER: READING A FILE THIS LIBRARY DID NOT WRITE
================================================================================
SET3 is the container tEncryptStream writes and tDecryptStream reads, in
stCipherStream.pas. It stays DEPRECATED, for the reasons it was deprecated for:
it is a StreamSec format that nothing else reads, it carries no version number,
and nothing in it obliges the data to be authenticated. Use a standard format
such as CMS for anything new.
What deprecation means here is that data already written must still open, so the
reading side has to cope with a file that is not what it expects. The five
entries below are all on that side. None of them changes a single octet of what
the library writes, and every file written by an earlier release reads back
unchanged.
The first three are about a header that did not come from this library - altered
in transit or on disk, or produced by something else. An application that only
ever reads back files it wrote itself, and keeps them where nothing else can
alter them, did not reach any of the three.
2. FIXED - a SET3 header naming an algorithm, mode or padding number that this
library does not define
The header stores the cipher algorithm, the mode and the padding as one
octet each, and tDecryptStream.ReadHeader used all three directly to select
the classes that do the work. Nothing checked that the octet is one of the
numbers the library actually defines.
Selecting a class is a lookup in a fixed table, and these units compile with
range checking off, so a number past the end of a table read whatever octets
lie beyond it and handed them back as though they were a class. Those are
not nil often enough to matter: on one 32-bit build, 44 of the 241 padding
numbers outside the range, and 28,311 of the algorithm-and-mode pairs
outside theirs, produced a value that was not nil. The library then called
through it, and the call went to an address taken from memory that has
nothing to do with ciphers. What a reader sees is the application faulting
on a file it opened.
ReadHeader now checks each of the three against the range the library
defines, before either lookup, and returns False for a header carrying
anything else - the same answer it already gave for a header naming an
algorithm that is not registered.
NOT INVOLVED: the key, the password, the nonce, and everything the file
carries after the header. The check runs before any of that is touched and
before the key is applied to anything, so no key material reached the
defect. No file this library wrote is affected either: it only ever writes
numbers that are in range.
3. FIXED - reading a SET3 stream back in CBC, CTR, CFB or OFB, when the reader
takes the algorithm from the header
A tDecryptStream can be created without a cipher and left to take the
algorithm, mode, padding and nonce from the header instead. That is the
point of the header, and it is what the CipherStream demo does. In that
case, for CBC, CTR, CFB and OFB, ReadHeader went on to ask the cipher the
stream had been CONSTRUCTED with for the shape of its initialisation vector.
A stream constructed without a cipher has no such object, and the call ended
in an access violation.
So a SET3 stream in any of those four modes could not be read back that way
at all. ReadHeader now takes the vector from the cipher the header named,
which is the one it is setting up.
NOT INVOLVED: the file, the key, the password, the padding, and the nonce in
the header. Nothing was written wrongly and no data was lost - a file
written in any of these modes, by any release, reads back correctly once the
reading side is fixed. The discriminating test: a program that constructed
the stream WITH the cipher, instead of letting the header choose, never met
this, because that is the path that left the object the code was reading set.
EAX and GCM were unaffected for the same reason.
4. FIXED - a SET3 header declaring a nonce length the format has no room for
The header stores the nonce in one of two shapes: up to 16 octets, or
exactly 32. A length between 17 and 31 matched neither, so no nonce was read
from the stream at all - and ReadHeader still answered True, telling the
caller the header had been understood.
The library can write such a header. A 256-bit block cipher - SHACAL-2 is
the one that ships - will accept a nonce of, say, 20 octets. It could never
read one back: everything after the nonce was then taken from the wrong
offset, and the read ran on to fail at the tag with 'Invalid MAC - you must
discard all data'. So no file that could be read before has become
unreadable; what changes is the answer. ReadHeader returns False at the
header, instead of letting the read continue and end with a message telling
the reader to discard data that had never been decoded in the first place.
Nonces of 16 octets or fewer, and of exactly 32, are unaffected.
5. FIXED - Done could not close a SET3 stream that had been read in CCM mode
Done reads the authentication tag that follows the ciphertext. In CCM the
tag does not follow the ciphertext: it belongs to the message, and the read
has already taken it and checked it. Done looked for a second tag, found the
end of the stream, and raised eCipherError with 'Unable to read MAC from
data stream'. Every CCM read ended that way, so a stream read in CCM could
not be closed at all.
Done now makes the same exception for CCM that the writing side has always
made - tEncryptStream.Done does not write a trailing tag in CCM, for exactly
the same reason.
NOT INVOLVED: the checking. The data was authenticated before Done was
called, and a CCM stream whose ciphertext, length or tag had been altered
was refused before this change and is refused after it. What failed was the
closing, not the verifying. The one CCM arrangement in which the tag IS
written after the ciphertext - where the application declares the whole
message length in advance - still has that tag read and verified by Done,
unchanged.
6. FIXED - a truncated SET3 stream in CCM mode was reported as a failed tag
check, whatever had actually run out
Two reads did not look at how much they had been given: the one that takes
the message length written ahead of the ciphertext, and the one that takes
the tag. Both read into a buffer that had not been cleared, so on a file
that ends early the length - or the tag that is then compared - was built
partly out of whatever the buffer happened to be holding.
Nothing was accepted that should not have been: a truncated file failed
before and fails now. What was wrong was what it said. Every case reported a
tag verification failure, including a file that ended before any tag had
been read at all, and a file that ended inside the length itself.
Both reads are now checked the way Done checks its own, and a file that ends
early says which of the two ran out. The tag length is taken once, rather
than separately for the read and for the check, so the number of octets read
cannot differ from the number verified.
--------------------------------------------------------------------------------
THE DOCUMENTS: SSH ALGORITHM SELECTION
================================================================================
7. FIXED - SSH.txt described a default SSH algorithm offer that does not exist
Section 3 of SSH.txt listed the key exchanges and ciphers "in default
preference order", called chacha20-poly1305@openssh.com the "default first
choice", and said the engine was post-quantum by default. Section 8 said
the default offer still included SHA-1 and CBC fallbacks for interop.
There is no default offer. Every cipher, MAC and key-exchange selection
starts empty, the host-key offer follows the keys the application loads,
and only compression starts selected, at "none". An SSH client or server
negotiates nothing until the application selects its algorithms, and the
order of that selection is its preference order. The lists in section 3
are what the library registers - what can be selected - in registration
order, and both sections now say so.
PRODUCTINFO.txt SECTION 9.2 CHANGES WITH IT. It now lists SSH algorithm
selection among the decisions that are yours, and says to select the SHA-1
and CBC names the library registers for older peers only for a peer that
needs them.
NOT INVOLVED: the code. What SSH negotiates has not changed; the documents
now describe it.
--------------------------------------------------------------------------------
THE DOCUMENTS: WHAT AN EVALUATION COPY IS SUPPORTED FOR
================================================================================
8. PRODUCTINFO.txt: an evaluation copy carries no long-term support, and a
problem reported in the current trials is addressed
Section 7 said that the trial distributions carry no support period and
no security updates. It now says that they carry no long-term support. A
problem reported in the current version of the trials is addressed, and
in most cases the answer is that it will be fixed in the next release. A
report about any obsolete version of the trials is answered with the
current version.
NOT INVOLVED: a licensed release. Its support period and its security
updates are as section 7 describes, and nothing about them has changed.
--------------------------------------------------------------------------------
THE DOCUMENTS: THE AUTOMATIC CRL AND ISSUER-CERTIFICATE FETCH
================================================================================
9. FIXED - PRODUCTINFO.txt presented the automatic CRL and issuer-certificate
fetch as something you enable; the TLS components do it by default
Section 9.2 said that a TLS server "can be wired" to fetch a CRL or a
missing issuer certificate from the address in the certificate being
validated, and advised leaving the fetch "unwired" where an outbound
request to an address a peer chooses is unacceptable. There is nothing to
wire. Every TLS component, client and server, fetches by default, using
the library's own platform-independent HTTP client, and no published
property unwires it.
Section 9.2 now describes what the code does: when the fetch happens, what
is done with the response, the limits that apply, and what avoids it -
holding a fresh CRL from every CA whose certificates you validate, or
RevocationPolicy rpIgnore, which stops revocation checking with it. The
issuer fetch has no published switch. Sections 0, 8 and 8.5, which also
treated the fetch as opt-in, now say the same.
NOT INVOLVED: the code. What the TLS components do has not changed; the
document now describes it.
--------------------------------------------------------------------------------
SSH: PINNING A SERVER'S HOST KEY ON A CLIENT
================================================================================
An SSH client pins a server's host key by assigning a key component to
ServerRSAKey, ServerECDSAKey, ServerEdDSAKey or ServerDSSKey: a component
holding the server's public key, such as a TstECDSAPublicKey, or a
TstSSHPublicKeyList holding it under the identifier in the matching
ServerXxxKeyIdentifier. The client is then meant to accept that key and no
other. A server assigns its own host key to the same four properties.
The entries below are about the client. Entries 12, 13 and 14 are BEHAVIOUR
CHANGES: read them if your client pins a host key. A client that pins no key
behaves as before.
A server whose host-key component holds its key when it is assigned offers
the same algorithm names, and signs with the same key, as before. The two
cases in which a server behaves differently are in entry 13.
10. FIXED - a client could not pin an ECDSA host key
Assigning a component that holds the server's ECDSA PUBLIC key - a
TstECDSAPublicKey, the kind a client pins with - to ServerECDSAKey
registered nothing, and the property read back nil. The setter took the
curve, and with it the algorithm name, only from a private key, and a
client holds the server's public key.
It could be worse than a pin that did not take. Assigning the property
removes the ecdsa-sha2-nistp256, -nistp384 and -nistp521 entries the
client registers for itself, which accept any key. If those names were
already selected - TsnipClient selects every name when it is created -
the removed entries stayed in use (entry 13 says why), and the client
accepted any ECDSA host key while the application had assigned a pin.
The curve is now read from the key's parameters, which a public key and a
private key both carry, and the key is registered under the name of its
curve.
THE DISCRIMINATING TEST: read ServerECDSAKey back after assigning it. An
affected release returns nil.
NOT INVOLVED: the key exchange and the signature check, and a server's
own ECDSA host key. A server assigns a private key, which was registered
correctly before and is registered the same way now.
11. FIXED - a TstSSHPublicKeyList could not be assigned to ServerECDSAKey or
ServerEdDSAKey
The list answered the lookups for RSA and DSS keys only, so assigning it
to ServerECDSAKey or ServerEdDSAKey registered nothing and the property
read back nil, whatever keys the list held. It now answers all four.
A list returns whatever key it holds under the identifier, and each of
the four properties now registers that key only if it is of the
property's own family. So one list can be assigned to all four properties
with the same identifier - the server's name, say - and pins the key on
file for that server, whatever its type. Before, ServerRSAKey registered
an ECDSA or EdDSA key under the RSA names, ServerDSSKey registered an
ECDSA key under a DSS name - entries that could only refuse - and
ServerDSSKey raised EIntfCastError for an RSA key.
A list backed by a file keeps its ECDSA and EdDSA keys in that file too;
see entry 24.
12. BEHAVIOUR CHANGE - an Ed448 host key assigned to ServerEdDSAKey on a
client was registered as ssh-ed25519
ServerEdDSAKey chose the name ssh-ed448 only for a private key with a
57-octet seed, and registered every other key as ssh-ed25519, after
removing ssh-ed448. A client pinning a server's Ed448 public key held it
under the wrong name and had no ssh-ed448 entry at all, so it could not
connect to that server: the key exchange ended with "Host key not
verifiable".
The name is now taken from the key's curve, which a public key and a
private key both carry: ssh-ed25519 for Ed25519, ssh-ed448 for Ed448. A
key that is not an EdDSA key - which a TstSSHPublicKeyList can hold under
the identifier, see entry 11 - is registered under neither name.
NOT INVOLVED: a server's own Ed448 host key, a private key, which was
named ssh-ed448 before and still is, and Ed25519 keys, public or private.
13. BEHAVIOUR CHANGE - a pin that yielded no key accepted any host key of its
algorithm
A key component that yields no key - it has not been loaded yet, or the
list holds nothing under the identifier - was registered without one.
ServerRSAKey registered rsa-sha2-256, rsa-sha2-512 and ssh-rsa with no
key, ServerDSSKey the five ssh-dss names, and ServerEdDSAKey ssh-ed25519;
ServerECDSAKey registered nothing but could leave the client's own entries
in use (entry 10). An entry with no key accepts whatever key the server
presents, so a client whose pin had not taken accepted any host key of
that algorithm, and nothing told the application.
None of the four registers an entry without a key now. A component that
yields no key of the property's family - no key at all, or a key of
another family - leaves that family with no entry, and a server using the
algorithm is refused with "Host key not verifiable". The component stays
assigned, so setting ServerXxxKeyIdentifier afterwards, or assigning the
component again, resolves it again. A component of the wrong class - a
TstRSAPublicKey assigned to ServerECDSAKey, say - was silently set back to
nil; it now stays assigned and pins nothing.
IF YOUR CLIENT assigns the key component first and loads the key into it
afterwards, it was not pinned: it accepted any key of that algorithm. It
now refuses every server of that algorithm. Load the key before assigning
the component, or assign the component again once the key is loaded.
A REMOVED ENTRY IS NOW OUT OF NEGOTIATION. Assigning a ServerXxxKey
property, and ServerKeyOptions.RemoveOption, remove entries by name, but
the selection kept the removed entry itself, and the selection is what is
negotiated. Until the next entry was added, a removed one went on being
used: that is what kept the entries of entry 10 in use, and a server
whose ServerRSAKey, ServerECDSAKey or ServerEdDSAKey was set to nil went
on offering that key and signing with it. A removed entry now holds no
key and accepts none. A client drops the names of removed entries from
what it offers when it connects; ServerKeyOptions.ResolveSelection, which
is new, does the same on request.
ON A SERVER, two things change. A host-key component that held no key
made the server offer algorithm names it could not sign with, and a
client that chose one was disconnected; those names are no longer
offered. And a host key that is un-assigned is no longer used.
14. BEHAVIOUR CHANGE - a pinned host key held only for its own algorithm
family
A client registers an entry with no key for each standard host-key
algorithm when it is created. Assigning ServerECDSAKey, say, replaced the
ECDSA entries with the pinned key and left the RSA, Ed25519 and Ed448
entries as they were. The server chooses the host-key algorithm from the
ones the client offers, so any server holding a key of one of those other
algorithms was accepted without its key being compared with anything. The
pin held only against a server that used the pinned algorithm, and a
server impersonating it does not have to.
When any of ServerRSAKey, ServerECDSAKey, ServerEdDSAKey and ServerDSSKey
is assigned, ConnectToHost now first removes every entry that holds no
key, with the new ServerKeyOptions.RemoveKeylessOptions. A client that
pins accepts only its pinned keys, whichever algorithm the server picks.
It offers only the pinned algorithms, so a server that has keys of
several algorithms is still reached with a pin of one of them.
THE DISCRIMINATING TEST: pin one server's ECDSA key and connect to a
server that has only an Ed25519 key. An affected release connects; this
one refuses with "Host key not verifiable".
NOT CHANGED: a client that pins no key. Its entries with no key accept
the first host key a server presents, as before. Selecting names is
still the application's part: assigning a key registers entries but
selects none, and a name that was selected before the assignment stays
selected if the assignment registers it again.
--------------------------------------------------------------------------------
INTERFACES DECLARED WITH ANOTHER INTERFACE'S GUID
================================================================================
Supports, as and QueryInterface know an interface only by its GUID. Two
interfaces had been declared with the GUID of another interface, so asking an
object for one of them was the same question as asking it for the other, and
an object that had only the other answered yes. Both entries are BEHAVIOUR
CHANGES in what Supports and as answer. Neither changes what the library
itself does: no path in it asked either question of the wrong object.
15. BEHAVIOUR CHANGE - an ML-DSA or SLH-DSA key answered Supports for
iSignKeyIF, the RSA key interface
iSignKeyIF, in StreamSec.DSI.PKTypes, holds the members only an RSA key
has: SignEncoding, EncryptEncoding, MGFHashAlg and SaltLen. It was
declared with the GUID of iSignKey, the interface it extends, so asking a
key for iSignKeyIF asked only whether it implements iSignKey. An ML-DSA
or SLH-DSA key does, and answered True, handing back its iSignKey
interface, which has none of the RSA members. Through it,
SignatureDigestAlg and Data worked. Each RSA member called some other
method of the key - on an ML-DSA key, reading MGFHashAlg called
QueryInterface and setting SaltLen called GetKeySize - or jumped to an
address that is not code: setting SignEncoding raised EAccessViolation,
"Execution of address 00000002".
iSignKeyIF now has a GUID of its own, and only an RSA key answers it. An
ML-DSA or SLH-DSA key answers False to Supports, and as raises
EIntfCastError. An RSA key answers iSignKey and iSignKeyIF as before.
IF YOUR CODE asks for iSignKeyIF to reach SignatureDigestAlg or Data on a
key of any family, ask for iSignKey. RSA, ML-DSA and SLH-DSA keys answer
it; DSS, ECDSA and EdDSA keys answer iSignKeyDL instead, as they always
did, and a composite ML-DSA key answers neither.
THE DISCRIMINATING TEST: Supports(Key, iSignKeyIF) for the public key of a
TstMLDSAKey. An affected release returns True, this one False.
NOT INVOLVED: RSA keys, and DSS, ECDSA and EdDSA keys, which never
answered iSignKeyIF. The library uses the RSA members only on RSA keys -
the key an SSH component's ServerRSAKey yields, the RSA key of an X.509
certificate - and those behave as before.
16. BEHAVIOUR CHANGE - an SSH host-key option and a user's subsystem option
answered Supports for each other's interface
iSSHUserSubSystemOption, in StreamSec.SSH.Options, was declared with the
GUID of iSSHKeyOption. A tSSHUserSubSystemOption therefore answered
Supports for iSSHKeyOption, and a tSSHKeyOption for
iSSHUserSubSystemOption, each handing back its own interface. The members
the two interfaces share worked; the others did not. On a subsystem
option, Key called GetSubSystemName, and GetHashAlgorithm,
PublicKeyFormat and SetKey jumped to addresses that are not code
(GetHashAlgorithm raised EAccessViolation, "Execution of address
00000001"). On a host-key option, SubSystemName called GetKey.
iSSHUserSubSystemOption now has a GUID of its own, and each class answers
only its own interface.
NOT INVOLVED: SSH connections. The library keeps the two kinds of option
in separate lists - host keys in ServerKeyOptions, a user's permitted
subsystems in the user's SubSystems list - and neither list can be given
an option of the other kind, so it never asked one for the other.
--------------------------------------------------------------------------------
SSH: A SERVER STARTED AFTER ANOTHER WAS STOPPED
================================================================================
17. FIXED - after an SSH server was deactivated, every SSH server activated
later in the same process left each channel open unanswered
Deactivating a TstSSHSocketServer while CloseAllOnDeactivate is True, the
default, raises a flag that tells every SSH session in the process to
close. Setting Active to False does it, TsnipServer.Stop does it, and so
does freeing a server that is active. Nothing lowered the flag again. A
server activated afterwards - the same component once more, or another
one on another port - accepted connections, and the key exchange and the
user authentication completed. But the part of each connection that
handles channels saw the flag and stopped as soon as it started, so no
channel open was answered. A client waited for its session channel
indefinitely.
TsnipClient.Start waited for its snip channel with no time limit
(entry 27). A program that stopped a TsnipServer and then started
another therefore hung in the first TsnipClient.Start against the new
server, using a whole processor core. Depending on timing, the client
could instead raise EAccessViolation, a read of address 0, while opening
the channel.
Activating a server now lowers the flag again, as it already did for the
other flag that deactivation raises.
THE DISCRIMINATING TEST: in one process, activate a TstSSHSocketServer,
deactivate it, activate one again, and open a session channel on it. An
affected release completes the login and never answers the channel open;
this one opens it. A program that activates its servers once and
deactivates them only when it exits was not affected.
NOT INVOLVED: the host key - ECDSA and Ed25519 servers failed alike - the
key exchange and user authentication, which completed as before; and the
Snif class registry, which is shared by every server in the process and
which the new server used as before.
NOT CHANGED: deactivating a server with CloseAllOnDeactivate True still
closes every SSH session in the process, those of other active servers
included, as the property's documentation says. Entry 27 limits how long
TsnipClient.Start waits for a channel open that a server does not answer
for some other reason.
--------------------------------------------------------------------------------
THE SET3 CIPHER-STREAM CONTAINER: WHAT HAS BEEN PROVED BEFORE THE DATA IS
HANDED OVER
================================================================================
A second pass over the same container as entries 2 to 6, on a different
question. Those entries were about a header that cannot be trusted. These two
are about WHEN the library knows that the data behind a trustworthy header is
genuine, and what it has already given you by then.
18. BEHAVIOUR CHANGE - a SET3 stream in an authenticated mode now checks the
tag before Read returns any plaintext
In EAX and GCM the tag sits after the ciphertext, so it could only be
checked once the ciphertext had been read - which is to say, after Read had
already handed the plaintext to the caller. Done is where that check
happened. An application that read a stream and never called Done therefore
never authenticated it, and was told nothing; an application that did call
Done was told, but only after it had been given data it then had to throw
away. Either way, a length or an offset lifted out of the plaintext had
already been acted on before anything proved it was genuine.
tDecryptStream now reads the whole message and checks its tag BEFORE Read
returns its first octet. A tampered stream raises from the Read that finds
it and yields no plaintext at all, whether or not Done is ever called. Done
still exists, still reports the outcome, and is still worth calling; it is
no longer the only thing standing between a forged file and your data. This
is what CCM has always done here, so the container already had one mode
that behaved this way.
WHAT IT COSTS, AND HOW TO DECLINE IT. The message is held in memory while
it is checked. For a stream too large to hold, set
VerifyBeforeRelease := False
before the first Read, and the old behaviour is restored exactly:
plaintext is streamed as it decrypts and the tag is checked when you call
Done - which you must then do, and whose result you must act on. Nothing
else changes.
A NEW PROPERTY WORTH ASSERTING ON. Authenticated is False until a tag has
been read and found correct. With VerifyBeforeRelease left alone it is True
before Read returns anything, so an application can check it instead of
having to remember what calling Done implies.
ALSO FIXED BY THE SAME CHANGE: reading past the end of the plaintext used
to return the tag, decrypted, as though it were data. A 19-octet message
asked for 64 octets answered with 35 - the 19 that were written, and the 16
octets of the tag. It now answers with 19.
NOT AFFECTED: unauthenticated modes, which have no tag to wait for and
stream as they always did; CCM, which already worked this way; and CBC, ECB
and ABC, which take a different path through the class. Nothing about what
the library WRITES changes, and no stored data needs rewriting.
19. FIXED - a length read out of a SET3 stream was used without being checked
against the stream it came from
SafeCopyTo can be asked to take the length of the data from the stream
itself, as an eight-octet count ahead of the data, and SafeCopyToWithSize
always does. That count then decides how much memory to allocate and how
long to go on reading, and nothing compared it with how much data the
stream actually holds.
Any eight octets are a number. With the top bit among them set it is a
negative one, and it reached the buffer allocation as a negative size; a
very large positive one set the copy reading until the stream ran out. A
caller passing its own negative aCount reached the same place, on this side
and in tEncryptStream.SafeCopyFrom.
The count is now required to be between zero and the number of octets that
remain, and is refused with eCipherError if it is not.
IN AN AUTHENTICATED MODE THIS IS NOW THE SECOND LINE, NOT THE FIRST. After
entry 18 the length has been authenticated before SafeCopyTo can act on it,
so a tampered one is caught by the tag and never reaches this check. The
check is what stands behind VerifyBeforeRelease := False, and behind the
modes that have no tag at all.
--------------------------------------------------------------------------------
SSH: A PACKET THAT DID NOT GO OUT
================================================================================
20. BEHAVIOUR CHANGE - an SSH packet that went out in part, or not at all,
was not reported, and a send after the peer disconnected raised
EAccessViolation
Every SSH message a client or a server sends - key exchange, channel
open, channel data, disconnect - is encrypted into a packet and handed
to the connection's raw send, which reports how many bytes it wrote. Two
checks at that step did not work.
The check that the whole packet was written compared the wrong values
and could never fail. When the raw send reported fewer bytes than the
packet held, the message counted as sent and the next one followed it.
The raw send reports fewer bytes:
- when the connection's socket has already been closed after an earlier
error on it, for example on a server whose client reset the
connection;
- when the operating system cannot take the whole packet at once. A
server's accepted connections on Windows, and every SSH socket on
Linux, do not wait for room in the send buffer: when it is full they
write part of the packet or nothing, and report the part or -1. A
client's socket on Windows waits for room, and was not affected by
this. Since entry 36 the socket components write the rest themselves,
waiting for room, and fall short here only after their SendTimeout;
- in a TstSSHClient or TstSSHServer whose OnRawSend handler does not set
aResult (see IF YOUR CODE below).
The peer then received part of the packet, or none of it. Each packet's
integrity check depends on its place in the stream - the MAC covers the
packet's sequence number (RFC 4253, section 6.4) - so the packets after
it failed that check at the peer: the connection broke there, typically
with a MAC error, while the sender saw nothing. A raw send that falls
short now raises eExternalSendError, "An error occured while sending an
outgoing packet", from the send that fell short.
The check that the transport was still connected created its exception
and did not raise it. When the peer sends SSH_MSG_DISCONNECT, the
transport discards its encryption state. A send after that - a channel
open or a service request from another thread, say - went on to use the
discarded state and raised EAccessViolation, a read of address 0: the
EAccessViolation that entry 17 mentions. It now raises
eSSHTransportError, "Transport is not connected".
IF YOUR CODE drives a TstSSHClient or a TstSSHServer through its own
OnRaw... handlers - the two SSH components without a socket of their
own, where OnRawSend IS the send - set aResult in OnRawSend to the
number of bytes the handler wrote. A handler that leaves it at 0 now
fails the first packet, the key exchange init, with eExternalSendError.
Before, such a handler worked, because nothing read the value.
TstSSHSocketClient, TstSSHSocketServer, TsnipClient and TsnipServer set
it themselves. On a TstSSHSocketClient, OnRawSend only observes the
traffic and finds the socket's count already in aResult; a handler there
that leaves aResult alone is not affected.
THE DISCRIMINATING TEST: give a TstSSHClient OnRawConnect, OnRawRecv,
OnRawRecvLength and OnRawSend handlers, let OnRawSend leave aResult at 0,
and call ConnectToHost. An affected release sends the key exchange init
and goes on to read the server's identification line; this one raises
eExternalSendError from that send, before reading anything.
NOT INVOLVED: a connection whose raw sends always write the whole packet
- every TstSSHSocketClient connection on Windows, and in practice any
connection whose peer keeps up - behaves exactly as before.
A FULL SEND BUFFER. With this entry alone, a socket component that met a
full send buffer - a server that produced data faster than its client
took it, such as a large SFTP download or forwarded traffic over a slow
link - still ended the connection, now with eExternalSendError on the
server instead of a MAC error on the client. Entry 36 makes the socket
components wait for room instead, up to their new SendTimeout.
NOT CHANGED: the identification line, the first thing a client or a
server writes, is still sent without the check.
--------------------------------------------------------------------------------
EXCEPTION OBJECTS THAT WERE CREATED AND DROPPED
================================================================================
21. FIXED - writing a public key that carries no certificate, and a failed
decryption through a cipher component's iCipher interface, each leaked
an exception object
In both places the library created an exception object to report a
condition, and then neither raised it nor freed it. What the caller got
was right, and is unchanged; the object stayed allocated until the
program ended, one per occurrence, and a memory manager that reports
leaks at shutdown listed them.
- The certificate and SubjectPublicKeyInfo key formats for RSA, DSS,
ECDSA, ML-KEM, ML-DSA, SLH-DSA and the composite ML-KEM and ML-DSA
keys, in StreamSec.DSI.X509Format, first look for a certificate that
carries the key they are asked to write. A key read from a certificate
carries one. A generated key, or one read from a key file, does not,
and for such a key each write created an eKeyFormatError, "No
certificate associated with public key", and dropped it. The
SubjectPublicKeyInfo formats then wrote the bare key, and the
certificate formats raised "Not a RSA certificate" and so on, as they
still do.
- A TstCipher, or any other TstCustomCipherComponent, used through its
iCipher interface created an eSecComp, "Decryption failed", each time
Decrypt, DecryptPtr, DecryptToBuf or DecryptToPtr failed. The call
returned False, as iCipher specifies, and the component's next call
raised "Initialization Vector not set" until a new IV was set, as it
still does: the failure was reported, not hidden. The component's own
public Decrypt methods call the cipher directly, and did not leak.
NOT INVOLVED: the EdDSA key formats, which do not look for a
certificate, and reading keys, which never did.
--------------------------------------------------------------------------------
INTERFACES DECLARED WITH ANOTHER INTERFACE'S GUID: THE REST
================================================================================
The defect of entries 15 and 16, in five more places, found by the same scan
of the package. Six interfaces had been declared with the GUID of another
interface. As there, what changes is what Supports and as answer, not what the
library itself does: every place in it that asks one of these questions asks
an object of the right kind.
22. BEHAVIOUR CHANGE - six more interfaces get GUIDs of their own, and an
object no longer answers Supports for an interface it does not implement
Asking an object for one of these interfaces succeeded if the object
implemented the other interface of its pair, and handed back that other
interface. The members the two inherit from a common ancestor worked.
Each of the rest called a different method of the object, or jumped past
the end of the shorter interface's method table. Each class now answers
only for the interfaces it implements: asked for another, Supports returns
False and as raises EIntfCastError.
StreamSec.SSH.Options: iSSHCipherOption, iSSHMacOption and iSSHKexOption
were ONE GUID, so tSSHCipherOption, tSSHMacOption and tSSHKexOption each
answered all three. A cipher option asked for iSSHMacOption returned its
cipher class as HashClass and its key length as MacLength, and its
KeyLength jumped past the end. A KEX option asked for iSSHCipherOption
returned its client key-exchange class as CipherClass and its server
key-exchange class as KeyLength. iSSHMacOption and iSSHKexOption now have
GUIDs of their own.
stDERUtils: iReadOnlyDERHeader was declared with the GUID of iDERHeader,
and iDERData with that of iDERDataReadWrite. A tInterfacedDERHeader
answered iReadOnlyDERHeader with its iDERHeader. CheckType, Constructed,
Cls and Tag worked; ActualTag called GetLength, Length called GetVarName,
VarName called GetTypeName and TypeName called SetCheckType.
iReadOnlyDERHeader and iDERData now have GUIDs of their own. No class in
the package implements iReadOnlyDERHeader, iDERData or iDERDataReadWrite,
so no class answers them any more.
StreamSec.DSI.CMSAlgorithms: iAesGcmParameter was declared with the GUID
of iRC2CBCParameter. A tRC2CBCParameter answered iAesGcmParameter:
ICVLength called get_iv and aesNonce returned the RC2 parameter version. A
tAesGcmParameter answered iRC2CBCParameter: iv returned the ICV length, an
integer where an interface is expected, and rc2ParameterVersion returned
the nonce. A tCEParams - the parameters of a CBC content-encryption
algorithm - answered iAesGcmParameter by switching its CHOICE to rc2-CBC.
Asked of the parameters of an aes128-CBC algorithm, the question left them
as rc2-CBC parameters and raised eClassRegistration, "Unable to find
required cipher class: caARC2,cmCBC", because the package has no RC2
cipher. iAesGcmParameter now has a GUID of its own, and that question
answers False and changes nothing.
StreamSec.DSI.PKTypes: iDSIEC, the elliptic-curve arithmetic, carried the
GUID of iSsMPEC in the legacy unit stMPPKTypes. The EC arithmetic that
MustGetDSIEC returns therefore answered iSsMPEC with its iDSIEC, whose
methods are in different places from the first one on. iDSIEC now has a
GUID of its own, as iDSIDLArith, iDSIFF and iDSIIF already had.
IF YOUR CODE asks an object for one of these interfaces, it is affected
only where the object does not implement it. There it was handed the
wrong members, and it is now told no. An object that implements the
interface answers as before, and iSSHCipherOption, iDERHeader,
iDERDataReadWrite, iRC2CBCParameter and iSsMPEC keep their GUIDs.
THE DISCRIMINATING TEST: Supports(Option, iSSHMacOption) for a
tSSHCipherOption. An affected release returns True, this one False.
NOT INVOLVED: SSH connections, CMS and PKCS #12 messages, and
certificates. The key exchange takes each negotiated algorithm from the
option list of its own kind, and each list holds options of that kind
only, so it asks a KEX option for iSSHKexOption, a cipher option for
iSSHCipherOption and a MAC option for iSSHMacOption. The CMS code selects
the parameter CHOICE before it asks, so it asks AES-GCM parameters for
iAesGcmParameter and RC2 parameters for iRC2CBCParameter. Nothing in the
library asks for iReadOnlyDERHeader, iDERData or iDERDataReadWrite.
stMPPKTypes asks for iSsMPEC only of the legacy arithmetic classes
registered with RegisterMPArithClass, which cannot be given the DSI
arithmetic, and the EC code asks the EC arithmetic for iDSIEC, which it
implements.
--------------------------------------------------------------------------------
SSH: THE FILE BEHIND A TstSSHPublicKeyList
================================================================================
A TstSSHPublicKeyList with a PublicKeyFileName keeps its keys in that file: a
server's authorized client keys, or a client's known host keys. The file is a
series of RFC 4716 blocks ("---- BEGIN SSH2 PUBLIC KEY ----"), one per key,
each naming the identifier its key is held under in a Subject header.
23. FIXED - a file-backed key list loaded empty
An SSH2 public-key file (RFC 4716) carries its headers - Subject, Comment -
above the base64, wrapped at 72 columns with a trailing backslash where a
line continues. Writing one worked. Reading one back did not: the loop that
splits the header block was bounded by the list it had just cleared, so it
ran zero times whatever the file contained, and the header came back empty.
The consequence was quiet and complete. TstSSHPublicKeyList keys each entry
by the Subject header and adds nothing when it is empty, so a key list with
a PublicKeyFileName loaded no keys at all and answered every lookup with
nil - whether it was a server's authorized-client-keys store or a client's
known-host-keys store.
A second fault in the same loop would have stopped it working even if it
had run: the index it used for the last octet of a line was wrong in both of
the library's two OctetString configurations, one short in the one used on
Windows and one past the end in the other, so the continuation test could
not have matched. Both are fixed.
WHO SEES A DIFFERENCE. A key list backed by a file now has the keys in it.
An application that had worked around the empty load by registering its
keys at run time keeps working; the file's keys are added as well.
24. BEHAVIOUR CHANGE - a key list keeps its ECDSA and EdDSA keys in its file
SaveKeys skipped ECDSA and EdDSA keys, so they lived in memory only and had
to be added with SetPublicKey each time the program started. It now writes
them as RFC 4716 blocks, like the RSA and DSS keys, with the identifier in
the Subject header, and LoadKeys reads them back. One file holds any mix of
RSA, DSS, ECDSA (nistp256, nistp384, nistp521) and EdDSA (Ed25519, Ed448)
keys.
Three formats are new for this, in StreamSec.SSH.KeyFormat:
SSH-Base64-ECDSA, SSH-Base64-ED25519 and SSH-Base64-ED448, the RFC 4716
forms of the SSH-ECDSA, SSH-ED25519 and SSH-ED448 blobs. The list uses them
for its file whatever RSAPublicKeyFormat and DSSPublicKeyFormat select.
Select them on DSSPublicKeyFormat for GetKeyText and SetPublicKeyText,
which follow that property, or on a TstECDSAPublicKey or TstEdDSAPublicKey
to load one key from an RFC 4716 file - one exported with ssh-keygen -e,
say.
WHY IT IS A BEHAVIOUR CHANGE. A program that adds an ECDSA or EdDSA key
with SetPublicKey and saves the list - with AutoSave, when the list is
disabled or freed - now finds that key in the file, and in the list the
next time the file is loaded. Bear it in mind before taking such a file
back to an earlier release, whose reader was written for RSA and DSS blocks
only.
NOT INVOLVED: RSA and DSS keys, which are written as before.
25. FIXED - loading a key list's file did not return when no format was
selected
LoadKeys reads the file one key at a time with the formats selected on
RSAPublicKeyFormat and DSSPublicKeyFormat. With nothing selected on either,
which is how a list starts, nothing read anything, the position in the file
never moved, and LoadKeys looped for ever: setting EnabledRunTime to True,
which is what loads the list, never returned. It now stops where nothing
more can be read, and reads the ECDSA and EdDSA keys of entry 24 whatever
is selected.
A file may mix key types freely. Every reader starts at the same place, and
a block none of them reads - an RSA key when RSAPublicKeyFormat selects no
format, a key type the library does not know, a certificate, stray text -
is skipped whole.
THE DISCRIMINATING TEST: a list with nothing selected on either property,
a PublicKeyFileName naming a file that holds at least one key, and
EnabledRunTime set to True. An affected release does not return from that
assignment.
26. FIXED - an RFC 4716 file exported by OpenSSH could not be read
RFC 4716 limits a line to 72 octets and sets no width; ssh-keygen -e
writes 70. The SSH-Base64-RSA and SSH-Base64-DSS readers expected the
base64 lines to be 64, 72 or 76 characters wide and took a line of any
other width for the last one, so they stopped after the first line of a
key exported by OpenSSH and read no key. That reader serves a key list's
file and a TstRSAPublicKey or TstDSSPublicKey loading an RFC 4716 file
alike. Both now read every line up to the END line, as the new ECDSA and
EdDSA formats of entry 24 do.
Checked against OpenSSH 10.2, both ways: a key exported with ssh-keygen -e
reads as the key ssh-keygen generated, and a file this library writes is
imported by ssh-keygen -i as the same key - for RSA, ECDSA nistp256,
nistp384 and nistp521, and Ed25519. OpenSSH has no Ed448.
NOT INVOLVED: what is written - blocks are written 72 characters wide, as
before - and the PEM certificates and keys the library reads, which go
through another reader.
--------------------------------------------------------------------------------
SNIP OVER SSH: THE CLIENT'S WAIT FOR ITS CHANNEL
================================================================================
27. BEHAVIOUR CHANGE - TsnipClient.Start waited without a time limit, using
a whole processor core, for a server that did not answer its channel
open
After the SSH login, TsnipClient.Start - through TsnipSSHClient.Start,
which does this part - opens the SSH session channel that carries the
snip connection and waits for the server to confirm or refuse the open.
That wait had no time limit, and it looked at the channel again and
again without pausing. A server that never answered - one whose channel
handling had failed, or a hostile one - therefore held the calling
thread in Start for ever, using a whole processor core.
Nor did the wait end with the connection. A server that closed the
connection instead of answering left the channel waiting for an answer
that could no longer come, and Start went on waiting with it. That is
what the servers of entry 17 did: they sent SSH_MSG_DISCONNECT right
after the login.
The wait now has a limit: ChannelOpenTimeout, a new published property
of TsnipClient and of TsnipSSHClient, in milliseconds. It is 20000 by
default, the allowance TsnipTLSClient.HandshakeTimeout gives a whole TLS
handshake. When it runs out, Start raises EsnipTimeout, because the SSH
connection is still up and the server is silent rather than gone. When
the connection closes first, Start raises EsnipClosed at once, as it
already did for a refused open, naming the state the channel was left
in. Between looks at the channel the wait now sleeps, and costs next to
no processor time however long it lasts.
IF YOUR PROGRAM relies on Start waiting for as long as a server takes,
set ChannelOpenTimeout to 0: Start then waits without a limit, but
still sleeps between looks and still stops when the connection closes.
After EsnipTimeout, call Stop before calling Start again. The server may
still answer the abandoned open, and the channel it opens then stays
unused until the connection closes.
A START THAT FAILS NOW LEAVES Active False. TsnipSSHClient.Start set
Active to True before it opened the channel, and left it True when it
raised - for a refused open as much as for any other failure. A second
Start then returned at once without opening anything, and Stop, which
TsnipClient.Stop calls first, raised EsnicNoConnection, so the SSH
connection was not closed.
THE DISCRIMINATING TEST: with the default settings, call TsnipClient.Start
against a server that completes the SSH login and then never answers the
channel open. An affected release does not return, and the calling
thread keeps a processor core busy; this one raises EsnipTimeout after 20
seconds.
NOT CHANGED: what Start does once the channel is open. A server that
opens the channel and grants the snip subsystem, and then never sends
its part of the snip handshake, still holds Start without a time limit.
To end the wait for the channel from another thread, call Stop: entry 34.
28. FIXED - the snip frame decoder sized its allocations from numbers the peer
sent, without asking whether the frame could be carrying them
A snip message carries length-prefixed values, and the decoder took each
prefix at its word. DecodeBytes read a length and called ZeroBytes with it
before reading a single octet of the payload, so a dozen octets declaring
2^31-1 committed a 2 GiB allocation - and ZeroBytes is SetLength followed by
FillChar, so every page of it was touched - and only then did ReadBuffer
discover the frame was short and raise. DecodeArray and DecodeRecord did the
same with an element count, where the element type is managed and each entry
costs far more than an octet.
The ceiling was already to hand and nobody was using it. ExtractMsgStream
materialises the WHOLE frame into a TBytesStream before any of this runs, so
what remains unread in that stream is exactly how many octets the frame can
still honestly be carrying. All three now refuse a length or a count larger
than that remainder. It costs one subtraction, and it does not depend on
field order, on which method is being called, or on whether the class named
is registered at all.
SEPARATELY, NESTING HAD NO LIMIT. A value's depth is not a length, so no size
bound reaches it: an array holding one array holding one array costs the
sender two octets per level, so a frame of a few kilobytes - well under any
frame size anyone would think to cap - recursed thousands of levels deep and
exhausted the serving thread's stack. DecodeValue now counts depth and
refuses past cMaxValueDepth, which is 32. That is far above anything a
declared Delphi type produces: the marshaller only admits nesting a real
parameter type has, and a record of arrays of records is three.
All three transports share this framing - SSH, TLS and the in-memory buffer
connection all descend from TsnipBaseOctetConnection and override only the
Raw* primitives - so this covers every one of them, in both directions.
WHO SEES A DIFFERENCE. A peer that sends a frame declaring more than it
carries, or nesting deeper than 32, now gets EsnipProtocol where it
previously got an allocation. Nothing a client or server built on this
library produces comes close to either bound.
29. FIXED - a remoted stream answered a read with more octets than were asked
for, and they were written past the end of the caller's buffer
A TStream argument or result is not copied across: the peer is handed a
reference and fetches ranges on demand. When this end asked for N octets,
the answer's start, end and count were checked - but only against EACH
OTHER, and all three came off the wire together with the payload. A peer
that sent a self-consistent triple satisfied every check at any size it
liked. The count it sent then overwrote the count this end had asked for,
and the payload went into the caller's buffer through a bare Move.
So a peer answering a 16-octet read with 64 KiB wrote 64 KiB into a
16-octet buffer, with content of its own choosing. Both directions were
affected: TsnifServerStream.Read, where a server pulls a client's stream
argument, and TsnicClientResultStream.Read, where a client pulls a server's
stream result.
Both now keep the count the caller asked for and refuse an answer larger
than it. The value was already in scope; it was simply overwritten one line
too early.
WHO SEES A DIFFERENCE. Only a peer that over-answers, which nothing in this
library does. Releases 4.1.1.354 to 4.1.3.359 are affected. There is no
advisory: the precondition is an application that publishes a remoted method
taking or returning a TStream, and no deployment in the field does.
30. FIXED - the diagnostic for the last failed call was shared by every
connection of a server, and COMPILE-TIME BREAK where it moved
When a remoted call raised something the framework did not expect, the
exception's class and message were kept so the response could carry them.
They were kept on the one TsnifApplication object a server owns - so every
connection's serving thread wrote to the same field, and read it a few
statements later to build its reply. Two consequences, from the one cause: a
caller could be handed the text of a failure that belonged to another
connection, and two threads assigning a managed string to one unsynchronised
variable could release the same reference twice.
The value is per-request, so it now lives on the connection: TsnifContext.
LastCallError. No lock is needed there - the request loop already holds the
context's monitor across processing and the reply, and a callback takes the
same monitor - and nothing is shared to leak.
WHO SEES A DIFFERENCE. TsnifApplication.LastCallError is gone; code that
read it no longer compiles. Read TsnifClassServer.CurrentContext.
LastCallError instead, which is the connection being served on this thread.
31. FIXED - tearing down a context that owned a mediated instance wrote into an
unrelated object
A colleague reaches an owner's instance through a mediator - a session, a
user, a role, or the application itself for viaApplication. The mediator
keeps a list of what it mediates, and that list holds the served INSTANCES.
The destructor walked it casting each entry to TsnifObjectDescriptor and
calling UnMediate on it. UnMediate is not virtual, so nothing faulted on
dispatch: it wrote a nil straight into the instance at the offset where a
descriptor keeps its mediator - past the end of any object smaller than
that. Because the application context is itself the viaApplication mediator,
and is destroyed when the server is, any server that had served one
viaApplication colleague call did this at shutdown.
The walk is gone. There was nothing to undo in it: releasing an object
already clears the descriptor's own back-pointer on every path that frees
it.
STILL OPEN, and stated here rather than left to be found: a mediator's list
can outlive an instance it names. Releasing one object through
ReleaseObject unhooks it from its mediator, but destroying a whole context
does not, and the destructor cannot simply do the same - the application
frees its users, roles, sessions and contexts in that order, so a context's
viaUser or viaRole mediator is already gone by the time the context is
destroyed, and nothing clears a descriptor's mediator from the mediator's
side. Closing it needs the list to hold descriptors rather than instances,
so that a mediator can unhook them itself. Nothing dereferences the stale
entry today; FindMediated, which would, has no caller.
32. FIXED - expiring sessions or connections raised as soon as it expired
anything
ExpireSessions and ExpireConnections walked their list upwards while
deleting from it. Delphi evaluates a for-loop's bound once, so after any
deletion the last iteration indexed past the end of the list - and the
element after each one removed was skipped. The effect was that the two
routines an application calls to reclaim idle sessions and stale
connections raised EStringListError precisely when they had something to do,
and never completed a sweep. Both now count downwards.
WHO SEES A DIFFERENCE. An application with a housekeeping timer that called
either routine and swallowed the exception was never reclaiming anything;
it now does. Sessions outlive the connections that opened them by design, so
on a long-running server there may be a large number to collect the first
time.
33. FIXED - a mediated call naming an owner that does not exist dereferenced nil
Reaching a colleague instance names the owner to join. For a per-connection
class an unknown name was already handled; for a per-session or per-user one
it was not, and the checks that follow dereferenced the nil the lookup had
returned. An authenticated caller that named a session or user which had
expired, or never existed, took an access violation on the serving thread.
It surfaced to the caller as a failed call, because the dispatcher catches
everything, but it is not a fault to leave standing. Both branches are now
guarded the way the per-connection one always was.
--------------------------------------------------------------------------------
SNIP OVER SSH: STOPPING A CLIENT THAT IS STILL STARTING
================================================================================
34. FIXED - TsnipClient.Stop, called from another thread while Start waited
for the server to answer the SSH channel open, raised EsnicNoConnection
and left the SSH connection open
TsnipClient.Stop does two things in order: it stops its internal
TsnipSSHClient, which closes the snip connection, and then it closes the
SSH connection. The first step failed. TsnipSSHClient.Stop read
ClassClient.Connection to see whether there was a snip connection to
close, and reading Connection when none is assigned raises
EsnicNoConnection. While Start is waiting for the channel open, none is
assigned yet: Start builds the snip connection only once the server has
answered. So Stop raised before it reached the SSH connection, and Start
went on waiting - until ChannelOpenTimeout ran out, or, with
ChannelOpenTimeout 0, until something else closed the connection.
TsnipSSHClient.Stop called on its own raised the same way.
NOT INVOLVED: Stop at any other time. A Stop after a Start that returned,
or after one that raised (entry 27), found what it needed and closed the
connection, and still does.
Now Stop asks without raising, through TsnicClassClient.TryGetConnection,
which is new: it returns False, and no connection, when none is
assigned. And Stop now ends a Start that is still waiting for the
channel. Start raises EsnipClosed within milliseconds, with a message
that says Stop was called while it was waiting. TsnipClient.Stop returns
without an exception and closes the SSH connection. TsnipSSHClient.Stop
on its own returns the same way and leaves the SSH connection up, as it
always has.
NO CONNECTION OUTLIVES A STOP. Stop, and the step at the end of Start
that hands the new snip connection to ClassClient, take the same lock.
If the server's answer and the Stop arrive together, Start closes the
snip connection it has just built instead of handing it over, and raises
EsnipClosed. Before, a Start that went on past a Stop could assign a
connection to ClassClient with Active already False, and a later Stop,
which does nothing when Active is False, never closed it.
THE DISCRIMINATING TEST: set ChannelOpenTimeout to 10000, connect to a
server that completes the SSH login and then never answers the channel
open, and call TsnipClient.Stop from a second thread 1.5 seconds into
Start. An affected release raises EsnicNoConnection in that thread,
SSHClient.Connected stays True, and Start raises EsnipTimeout after 10
seconds. This one returns from Stop with the SSH connection closed, and
Start raises EsnipClosed at 1.5 seconds.
NOT CHANGED: Stop does not close the channel whose open Start was waiting
for. After a TsnipSSHClient.Stop on its own, a server that answers that
open later leaves the channel open and unused until the SSH connection
closes, as after EsnipTimeout (entry 27). A Stop that comes after the
channel has opened, while Start requests the snip subsystem and waits for
the server's part of the snip handshake, keeps Start from building a
connection, but Start raises only when that step returns. And only the
wait for the channel open was tested: a TsnipClient.Stop while Start is
still making the SSH connection and logging in, before that wait, is not
covered by this entry.
--------------------------------------------------------------------------------
THE CIPHER COMPONENT: AN IN-PLACE ENCRYPTION OR DECRYPTION THAT DID NOT HAPPEN
================================================================================
35. BEHAVIOUR CHANGE - TstCipher.Encrypt and EncryptPtr returned normally
when the cipher had not encrypted the buffer, which still held the
plaintext; Decrypt and DecryptPtr did the same with the ciphertext
Encrypt, EncryptPtr, Decrypt and DecryptPtr, on TstCipher and every
other TstCustomCipherComponent, encrypt or decrypt a buffer in place.
Each passes the buffer to the cipher the component was keyed with, and
the cipher answers whether it did the work. None of the four looked at
the answer, in any release since the first 4.0. When the cipher
declined, it had not changed one octet of the buffer, and the method
returned as though it had succeeded. After Encrypt, the caller went on
to send or store its plaintext as though it were the ciphertext; after
Decrypt, it went on with the ciphertext as its plaintext. Nothing raised
afterwards either; the component took the next call as readily as the
first.
A ROUND TRIP DID NOT SHOW IT. Where the sender and the receiver used the
same settings, the cipher declined on both sides, so the receiver ended
up with exactly the octets the sender started with: the plaintext,
which had gone between them unencrypted. A MAC assigned through the MAC
property agreed on both sides too, because Encrypt gave it the
plaintext in place of the ciphertext and the receiver's Decrypt gave it
the same octets. Measured, from one component to another, with AES in
cmSSH and cmSSHCTR, 3DES and RC2 in cmKeyWrap, ARC4 in cmSSH, and AES in
CCM.
All four now raise eSecComp - "Encrypt: Encryption failed", "EncryptPtr:
Encryption failed", "Decrypt: Decryption failed" or "DecryptPtr:
Decryption failed" - and leave the buffer as it was. Encrypt and
EncryptPtr raise before they pass anything to the MAC, so the MAC is
given only ciphertext the component has produced. The component then
refuses every further in-place call - Encrypt, Decrypt and their Bytes,
Intf, Ptr and Str forms - with "Initialization Vector not set" until a
new IVector is set. That is what the component's iCipher interface has
always done after a failed decryption (entry 21). In CCM, EAX and GCM,
where IVector does not start a message, the component ends the message
instead, and every further call raises "Nonce not set" until N and
Initialize start the next one (entry 66).
WHERE THE CIPHER DECLINES. A TstCipher was keyed with each algorithm and
mode the library registers, on Win32 and on Win64, and asked to encrypt
32 octets and to decrypt 32 octets. The cipher declined both in exactly
these, and for AES in each of the library's four AES implementations:
- The SSH transport modes, cmSSH and cmSSHCTR, with every block cipher
that has them (AES, 3DES, TwoFish, Blowfish, Camellia and SHACAL-2),
ARC4 in cmSSH, and AES in cmSSHGCM when StreamSec.SSH.BlockPadding is
in the program (entry 39). The SSH packet layer drives these ciphers;
they never encrypt or decrypt in place.
- cmKeyWrap with 3DES or RC2, whose key wrap and unwrap are
KeyWrapEncrypt and KeyWrapDecrypt. AES in cmKeyWrap works in place and
is not affected.
- CCM (AES, TwoFish and Camellia), for data beyond the MessageLength set
through iCCMParameters - which is all of it when none was set.
It also declines, whatever the algorithm and mode, in two states the
component can be left in:
- After EncryptStr or DecryptStr with a padding such as bpmPKCS5 or
bpmCTS, until a new IVector is set. Those two finish a message,
padding and all, and the cipher then waits for a new IV. Outside ECB,
where what they returned was not a whole number of blocks, the next
in-place call already raised "Initialization Vector not set", and
still does; otherwise it returned normally.
- After an EncryptToDst or DecryptToDst stream was abandoned -
DestinationStream set to nil before DoneToDst - while the cipher still
held part of it.
Everywhere else - ECB, CBC, CFB, OFB, CTR and ABC, the stream ciphers,
EAX, and GCM with PaddingMode bpmGCM - the four methods behave as
before, but for a length that is not a whole number of blocks in ECB,
CBC and ABC, which entry 42 covers, and for a call outside a message in
EAX and GCM, which entry 66 covers.
IF YOUR PROGRAM encrypted in place in cmSSH or cmSSHCTR, or with 3DES
or RC2 in cmKeyWrap, it never encrypted anything that way, and in CCM
nothing beyond the MessageLength it had set: what it sent or stored
is the plaintext, and a receiver or reader with the same settings
will now raise on it instead of passing it through. (In cmSSHGCM an
affected release raised EInvalidCast instead, entry 39, and nothing
was sent.) If it calls Encrypt,
EncryptPtr, Decrypt or DecryptPtr after EncryptStr or DecryptStr on the
same component, set IVector first, as a new message needs anyway; the
buffer then encrypts or decrypts. In the other cases the buffer was
never encrypted or decrypted, and the exception makes visible what was
already going wrong.
THE DISCRIMINATING TEST: key a TstCipher for AES in cmSSH, set an
IVector, and call Encrypt on any 32 octets. An affected release returns
and leaves the 32 octets as they were; this one raises "Encrypt:
Encryption failed". Decrypt answers the same way, with "Decrypt:
Decryption failed".
NOT CHANGED, and stated here rather than left to be found:
- EncryptBytes, EncryptIntf, DecryptBytes and DecryptIntf report the
same failure by returning False, as before. EncryptStr and DecryptStr
go through the cipher's EncryptToBuf and DecryptToBuf instead, and
report a failure there by returning an empty string. (What
EncryptBytes and EncryptIntf give the MAC is entry 48.)
--------------------------------------------------------------------------------
SSH: A PACKET THAT MEETS A FULL SEND BUFFER
================================================================================
36. BEHAVIOUR CHANGE - an SSH connection whose peer read more slowly than it
was written to ended with eExternalSendError; a packet now waits for
room in the send buffer, up to the new SendTimeout
TstSSHSocketServer and TstSSHSocketClient write every SSH packet - channel
data, window adjustments, key exchange - to the connection's socket in one
call, and the socket reports how many bytes it took. When the operating
system's send buffer for the connection is full, a socket that does not
wait for room takes part of the packet, or none of it. That is every
connection a TstSSHSocketServer accepts on Windows, and every SSH socket
on the other platforms, where the library makes all sockets
non-blocking. The component then reported the short count, and the
transport raised eExternalSendError (entry 20); before entry 20 the peer
failed with a MAC error instead. So a server that wrote faster than its
client read - a large SFTP download, forwarded traffic, a client on a
slow link - ended the connection as soon as the buffer was full: some
hundreds of kilobytes ahead of the client on Windows, a few megabytes on
Linux.
Now the rest of the packet follows the part the socket took, and when
the buffer is full the send waits for room and tries again with the same
bytes. A peer that reads slowly slows the sender down instead of ending
the connection.
SendTimeout, a new published property of TstSSHSocketServer and of
TstSSHSocketClient, in milliseconds, bounds that wait for a peer that has
stopped reading altogether. It is 30000 by default; 0 waits without a
limit. When not one byte has been taken for that long, the socket is
closed and the send raises eExternalSendError, as it used to do at once.
Part of the packet may already be on its way, so the connection cannot go
on, and closing the socket lets the peer see the end at once. The time
counts from the last byte taken, so a slow peer that keeps reading never
reaches it. On a server, a change applies to connections accepted after
it.
WHILE A PACKET WAITS, ITS CONNECTION WAITS WITH IT. Packets go out one at
a time and in order, and the connection reads what the peer sends under
the same lock. So another thread sending on the same connection, the
connection's own reading, and TstSSHSocketClient.Close all wait until
the packet is written or SendTimeout runs out. To end a client's wait at
once from another thread, close its SocketClient. Freeing a
TstSSHSocketServer, or deactivating it with CloseAllOnDeactivate True -
the default - ends a server's waiting send at once, and the send raises
the EstSocketError that a send on a server that is shutting down already
raised.
IF YOUR PROGRAM relied on eExternalSendError to end a connection whose
peer had stopped reading, it now comes SendTimeout later; set
SendTimeout lower to have it sooner.
THE DISCRIMINATING TEST: put a TCP relay between a TstSSHSocketClient and
a TstSSHSocketServer, and have the server send 4 MB on a channel whose
window is larger than that, while the relay stops reading from the
server for four seconds. An affected release raises eExternalSendError on
the server as soon as its send buffer is full - in that test about 180 KB
in on Windows and 2.6 MB in on Linux - and the client never receives the
rest. This one waits, and once the relay reads again all 4 MB arrive. A
relay that never stops, and only forwards more slowly than the server
writes, is enough on its own to end the connection in an affected
release.
NOT INVOLVED: the SSH layer's own flow control. A channel's window limits
how much may be sent before the peer's application has read it; the
buffer that filled lies below it, in the operating system, and fills
whenever the peer's network or its reading thread is slower than the
sender, whatever the window. The key exchange, the ciphers and the MACs
were not involved either.
NOT CHANGED: a TstSSHSocketClient on Windows waits for room inside the
operating system's own send, without a limit, as before, so SendTimeout
does not come into play there - unless WaitForData has been called on its
SocketClient, which makes the socket stop waiting on its own; then it
waits as described here. TstSSHClient and TstSSHServer, which have no
socket of their own, send through their OnRawSend handler as before (entry
20). And the threads that carry forwarded connections write what arrives
on the channel to their TCP connections through a path of their own,
which this entry does not change.
--------------------------------------------------------------------------------
SNIF: THE STORED RECORD OF THE LEGACY LOGIN
================================================================================
37. FIXED - about one new Snif user record in 150 refused its own password,
every time
The legacy Snif login (StreamSec.Snif.Authentication: the Login,
LoginPlain and ChangePassword classes) keeps each user as three numbers:
a modulus N, a secret exponent S and a verifier V made from the password.
TsnifAuthentication.GetData packs them into the record the server keeps -
the fAuthData of a user list entry, 544 octets: 256 for N, 32 for S, 256
for V. InitPlain and InitDigest followed by GetData is how a record is
made, for UpdateUserList, for a user store, and for the new record that
ChangePassword.Commit takes.
S and V are random numbers, so now and then one of them is shorter than
its slot. GetData wrote a short number at the START of its slot and left
the zero octets it lacked at the end. The numbers are big-endian, so that
multiplied the number by 256 or a power of 256, and the record then held
a verifier for no password at all. Of 7,000 records made with InitPlain
and GetData, 46 were like that.
THE STEP THAT FAILED is the server's check of the client's answer to its
challenge, on every attempt for that user: TsnipClient.Start raised
EsnipError "the server rejected the challenge response for user ...",
Login.VerifyResponse returned False, LoginPlain.Verify returned False,
and ChangePassword.Commit returned False - with the right password. The
other users of the same server logged in as before. Trying again does
not help, because it is the record that is wrong.
GetData now right-aligns each number in its slot, so the missing octets
become leading zeros. The fix is in the program that MAKES the record:
for ChangePassword that is the client, which sends the new record to the
server.
A RECORD MADE BY AN AFFECTED RELEASE STAYS AS IT IS. This release reads
records exactly as before, so a record that refused its password still
refuses it, and nothing in the record tells it apart from a good one. The
user needs a new record: set the password again (InitPlain + GetData, then
UpdateUserList or your user store). The user cannot do that through
ChangePassword, which first checks the old password against the old
record.
THE DISCRIMINATING TEST: with the stored record and the user's password,
call InitData with the record and then VerifyPlain with the user name and
password, both as UTF-8. It returns False for an affected record and True
for a good one, on any release.
NOT CHANGED: every record that verified before; for those, GetData writes
exactly the same 544 octets as before. The challenge, the answer the
client computes, the password digest and the modulus, which is always of
full length, are unchanged. The post-quantum login in
StreamSec.Snif.AkeAuthentication keeps its records in another way and was
not affected.
--------------------------------------------------------------------------------
SSH SERVER: RELEASING A CONNECTION WHOSE SUBSYSTEM HAD STOPPED
================================================================================
38. FIXED - an SSH server on Windows did not free a closed connection whose
subsystem thread had ended first, and a Win32 program then ended with
"Runtime error 217"
On the server side of an SSH connection, every session channel that runs
a subsystem - SFTP, snip, or a TstCustomSSHSubSystem of your own - has a
thread that calls the subsystem's ReadData. When the connection closes,
or the server is stopped, the server releases the connection and ends
those threads.
THE STEP THAT FAILED is ending such a thread when it had already ended
by itself. The server suspended each thread before telling it to stop,
and Windows refuses to suspend a thread that has finished. Releasing the
connection therefore raised EThread ("Access is denied") halfway, inside
the object that owns the connection's channels, and the server's
connection thread caught the exception without reporting it. What had
not been freed by then stayed in memory until the program ended: the
connection's SSH transport, with its session keys and buffers, and that
session channel. The socket was closed as usual, and the client saw a
normal close.
THE SYMPTOM. In a Win32 program, the check that stMemoryMapFiler makes
at exit then raised "Instance count N", which shows as "Runtime error
217" after the program's last line of output. A Win64 program showed
nothing, and kept the memory all the same. Each affected connection kept
its own, so a server that runs for a long time grew with every one.
HOW A SUBSYSTEM THREAD ENDS FIRST. A ReadData that raises ends the
thread; the channel stays open. With snip (TsnipServer) no code of yours
had to raise. A client that closes its snip channel before its SSH
connection - TsnipClient.Stop and TsnipClient.Free both do - made the
server's snip subsystem start a second session on that channel. That
raised EsnipState ("this server connection is already bound to a
channel") and ended the thread. Whether the server released the
connection before or after that was a matter of timing, and the after
was common: a Win32 program that made two snip connections and freed
its server ended with runtime error 217 in 10 runs of 25.
NOT INVOLVED: the Snif login, the classes a TsnipServer serves and the
mediator; the host key, the ciphers and the key exchange; the client
side. Stopping and freeing the server does not recover what an affected
connection kept; nothing refers to it.
PLATFORMS. Measured on Win32 and Win64. Linux64 was not affected: its
run-time library does not suspend one thread from another
(TThread.Suspend only records the request), so the release never raised
there, and Android uses the same code. macOS and iOS were not tested;
their run-time library does suspend one thread from another, as Windows
does, so treat them as affected.
Now the server ends a subsystem thread without suspending it: it tells
the thread to stop, wakes it and waits until it has finished, whether
it was waiting for data, idle with no subsystem attached, never started,
or finished already. And the snip subsystem runs one session per
channel. The wake-ups that reach it after that session has ended - the
client's data, its EOF and its CLOSE each count as one - no longer start
another.
THE DISCRIMINATING TEST: read stMemoryMapFiler.InstanceCount while the
server runs, before a client connects and again a few seconds after the
client has closed its SSH connection. Start from a program's second
connection: its first also creates objects the program then keeps for
good. For a deterministic case, give the server a TstCustomSSHSubSystem
whose subsystem's ReadData raises; from a client, open a session channel
for it, send one octet, wait a second and close the SSH connection with
the channel still open. On Win32 and Win64 an affected release reads two
more after the connection than before - the transport and the channel -
every time, and this one reads the same. With snip, connect a
TsnipClient, make a call and free it: an affected release reads two more
in some runs, this one in none.
NOT CHANGED: a subsystem whose ReadData raises still ends its thread and
leaves its channel open, without telling the client, until the
connection closes; only the release that follows is fixed. And when a
client closes a snip channel, the server answers the close but goes on
counting the channel against SSHServer.MaxChannels until the SSH
connection closes - which TsnipClient does straight after.
--------------------------------------------------------------------------------
THE CIPHER COMPONENT: GCM WITHOUT A PADDING MODE
================================================================================
39. FIXED - a TstCipher in cmGCM raised EInvalidCast, "Invalid class
typecast", from every call that reached the cipher, unless PaddingMode
had been set to bpmGCM after Mode
Setting Mode on TstCipher, or on any other TstCustomCipherComponent,
also sets PaddingMode when the padding already chosen cannot serve the
new mode: bpmPKCS5 for ECB, CBC and ABC, bpmCCM for cmCCM, bpmEAX for
cmEAX, bpmNone for the rest. GCM was missing from that list, and the
class behind bpmNone, the default, declared that it could serve GCM,
which it cannot. So PaddingMode stayed bpmNone. Keying the component -
SetKeyBuf, SetKeyStr, SetKeyPtr, SetKeyIntf, SetKeyPassword,
SetKeyFromKeyRing - then put a no-padding object on the AES-GCM cipher
in place of the GCM one the cipher had made for itself. GCM keeps its
authentication state in that object and reads it there, so every call
that reached the cipher raised EInvalidCast: setting the nonce through
iGCMParameters, Encrypt, Decrypt, EncryptStr, DecryptStr and the ToDst
methods. Each raised instead of returning, so no affected release
produced GCM output, and there is none that this one reads differently.
The same happened with PaddingMode bpmCTS, set before or after Mode,
and in cmSSHGCM. The key, its length and the platform played no part.
The AES-GCM ciphers and their GCM padding needed no change, and neither
did TLS, SSH, CMS or tEncryptStream / tDecryptStream, which keep the
padding a GCM cipher makes for itself or attach the right one, and were
not affected. Nor was the Cipher demo, which sets PaddingMode to bpmGCM
when GCM is chosen.
NOW Mode := cmGCM sets PaddingMode to bpmGCM, and cmSSHGCM to
bpmSSHGCM. In both modes bpmNone and bpmCTS are refused the way bpmPKCS5
already was: assigning them leaves PaddingMode as it is. A program that
set PaddingMode := bpmGCM itself behaves as before. A form saved with
this release stores PaddingMode = bpmGCM, which earlier releases load
and run the same way.
Checked on Win32 and Win64, through a TstCipher with no PaddingMode set,
against 40 known answers: McGrew and Viega's GCM test cases 1 to 4, and
36 vectors from pyca/cryptography (OpenSSL) with AES-128, -192 and -256
keys, 0 to 255 octets of plaintext and 0 to 33 of additional data. All
40 match with EncryptStr and DecryptStr, and with Encrypt and Decrypt in
place taking the tag from iCipherMAC.GetFinalBuf and VerifyFinalBuf; the
36 that are not empty also match with EncryptToDst, DecryptToDst and
DoneToDst. A changed tag is refused on every route.
HOW A MESSAGE STARTS, as the Cipher demo does it: key the component,
then set (Cipher1 as iGCMParameters).N to the 12-octet nonce and call
Initialize. Additional authenticated data goes in through
(Cipher1 as iCipherMAC).EncryptToNil, before the first octet of the
message. For each further message on the same component, set N to the
new nonce and call Initialize again; entry 66 says what the component
does with a message that has no new nonce.
THE DISCRIMINATING TEST: create a TstCipher, set Mode to cmGCM and read
PaddingMode. An affected release reads bpmNone, this one bpmGCM. Keyed
with any 16 octets and given a nonce through iGCMParameters, an affected
release raises EInvalidCast and this one does not.
ALSO: the classes behind bpmNone and bpmCTS, tBlockPaddingNone and
tBlockPaddingCTS, no longer accept a cipher in cmGCM or cmSSHGCM.
Creating one for such a cipher, or assigning its BlockPaddingMode
through iSetPadding, raises ePaddingError at once - "Unsupported mode",
wrapped for bpmNone as "tBlockPaddingNone inherited constructor
failure" - and the cipher keeps its GCM padding and works. Before, the
padding was attached and the first use raised EInvalidCast.
NOT CHANGED, and stated here rather than left to be found:
- IVector does not set the GCM nonce. With IVector alone, EncryptStr
returned output that no GCM implementation reads, this one included;
it now raises "Nonce not set" (entry 66).
- cmSSHGCM is the SSH transport's AES-GCM, and its padding is in
StreamSec.SSH.BlockPadding. A program without that unit gets
eClassRegistration, "Unable to find required padding class:
bpmSSHGCM", from the SetKey call. With it, the mode behaves like
cmSSH and cmSSHCTR (entry 35): Encrypt raises "Encryption failed"
and Decrypt "Decryption failed", and both leave the buffer as it was.
- DecryptToDst mishandled a call that carried no more octets than the
tag. That is entry 43.
--------------------------------------------------------------------------------
SSH: A TRANSFER LONGER THAN ONE CHANNEL WINDOW
================================================================================
40. FIXED - a transfer on an SSH channel stopped after one window's worth
of data when the two ends numbered the channel differently, as OpenSSH
always does
Each end of an SSH channel has its own number for it, and every message
about the channel is addressed with the number the RECEIVING end uses.
A receiver lets the sender send one window's worth - DefaultWindowSize,
1 MB unless you change it, on TstSSHClient and TstSSHServer alike - and
once the program at the receiving end has read all of it, the receiver
reopens the window with SSH_MSG_CHANNEL_WINDOW_ADJUST (RFC 4254 section
5.2).
THE STEP THAT FAILED is that window adjustment. The client and the
server both addressed it with the number the SENDING end uses, and the
peer looked that number up among its own channels. Where the two ends
numbered the channel alike, the adjustment arrived. Where they did not,
the peer found no channel by that number and dropped the message, the
sender waited for a window that did not reopen, and the transfer
stopped after exactly one window. Neither end reported an error: the
channel stayed open, and a read waiting for the rest - an SFTP read, for
example - waited without a limit.
WHERE THE NUMBERS DIFFER. Both components number their channels from the
top of their MaxChannels range down, so a client and a server of this
library that both keep the default MaxChannels of 16 number a
connection's first channel alike, 15. That is why it went unnoticed.
Where MaxChannels differs, the numbers differ from the first channel on;
they can also come apart when both ends open channels, as with remote
port forwarding. OpenSSH numbers its channels from 0 - sshd gave the
session channel 0 - so against OpenSSH every transfer longer than one
window stopped:
- a download by our SFTP client (tSFTPTransport, which TstSFTPClient
uses) from an OpenSSH server stopped after 1 MB, the client's window,
and sshd logged "Received window adjust for non-open channel 15";
- an upload by OpenSSH's sftp to our server stopped after the server's
first window, and sftp printed the same message.
The same holds for any peer that numbers the channel differently, and
for whatever the channel carries: SFTP, a shell or exec session, or a
forwarded connection.
WHEN THE NUMBER BELONGED TO ANOTHER CHANNEL, that channel's window was
reopened instead. The peer could then send that channel one window more
than its receiver had room for, and the receiver dropped the octets that
did not fit, again without an error. Measured with two channels: the
channel whose window was reopened that way lost 1 MB of the 2 MB sent
on it, while the channel the adjustment was meant for stopped after its
first window.
Now the window adjustment is addressed with the number the receiving
end uses, as the channel's data, EOF and CLOSE already were.
THE DISCRIMINATING TEST: connect a TstSSHSocketClient with the default
MaxChannels of 16 to a TstSSHSocketServer with MaxChannels 4, so that
the client numbers the first channel 15 and the server 3, and send 4 MB
on it in either direction with the default windows, the receiving end
reading as the data arrives. An affected release delivers exactly
1048576 octets and then nothing; this one delivers all 4 MB. With
MaxChannels 16 at both ends the same transfer completes on either
release. So a transfer that stops after exactly one window of channel
data - for SFTP, a little less than that of file data - between two
ends that number the channel differently, is this defect.
NOT INVOLVED: the window and packet sizes, the key exchange, the ciphers
and MACs, and SFTP itself. A larger DefaultWindowSize only moved the
point where a transfer stopped; a transfer shorter than one window was
never affected. The channel's data, EOF, CLOSE and subsystem request,
and the replies to the peer's channel opens and channel requests, were
addressed correctly before and are unchanged.
NOT CHANGED: the numbers the components give their channels, and
MaxChannels. The legacy units stSSHClientChannel and stSSHServerChannel,
which no longer ship, have the same defect and are not changed.
--------------------------------------------------------------------------------
SNIP OVER SSH: A START THAT FAILS ON AN OPEN CHANNEL
================================================================================
41. FIXED - a TsnipClient.Start that failed after the server had opened its
SSH channel kept the snip connection it had begun to build, and left
the channel open
After the SSH login, TsnipClient.Start - through TsnipSSHClient.Start,
which does this part - opens the SSH session channel that carries the
snip connection (entries 27 and 34) and then builds the snip connection
on it: it asks the server for the snip subsystem, sends its connect
message and waits for the server's accept.
THE STEP THAT FAILED is what Start did when that handshake raised. It
had created the snip connection, a reference-counted object, without
holding a reference to it, so nothing ever freed it, and nothing closed
the channel either. Start raised, with Active False as entry 27 made it,
but the connection stayed in memory and the channel stayed open at both
ends. The handshake raises when the server
- refuses the snip subsystem: eSSHClientChannelError, "The server
refused the "snip" subsystem request" (on Windows, see below);
- closes the channel before its accept, or sends another kind of
message in its place: EsnipClosed, "the server sent no accept
message";
- sends an accept that does not decode: EsnipProtocol;
and when the SSH connection closes during the wait for the accept, as
TsnipClient.Stop called from another thread does: EsnipClosed.
WHAT WAS KEPT. Every such Start kept its snip connection object until
the program ended. Except after a refused subsystem, that object also
held the channel, so the channel object was kept too, with the receive
buffer every channel allocates when it is created: SSHClient.
DefaultWindowSize octets, 1 MB by default. Closing the SSH connection
released neither, and a Win32 program then ended with "Runtime error
217" after its last line of output, from the check stMemoryMapFiler
makes at exit. While the SSH connection stayed up, each channel also
stayed open at both ends, and so kept its place among the connection's
SSHClient.MaxChannels, 16 by default. Measured on Win32 and Win64: three
failed Starts on one SSH connection left three snip connections and
three open channels, in each of the ways above, and three channel
objects once the connection had closed - none after a refused
subsystem.
NOW Start holds a reference to the snip connection from the moment it
creates it, so a handshake that raises frees it, and Start closes the
channel before it raises. The SSH connection stays up, and Start raises
the same exception as before.
NO CLOSE AFTER A STOP. A channel is not safe against its SSH connection
closing on another thread at the same time. Start therefore closes the
channel only if no Stop has come since it began, and does it under the
lock that Stop takes (entry 34): a Stop, and the SSH close that
TsnipClient.Stop makes after it, wait for that close instead of running
into it. Nor does Start close a channel whose SSH connection has closed
already, which releases every channel itself. And a snip connection
whose handshake failed no longer counts as up, so freeing it sends
nothing on the channel. After a TsnipSSHClient.Stop on its own, a Start
whose handshake then fails therefore frees the snip connection but
leaves the channel open until the SSH connection closes.
THE DISCRIMINATING TEST, on Windows: give a TsnipServer an
SSHServer.OnAuthSubSystem handler that sets aOK to False, and call
TsnipClient.Start against it. Every release raises
eSSHClientChannelError and leaves the SSH connection up. Then count the
channels still in use on it: each I below SSHClient.MaxChannels for
which SSHClient.Broker.GetLocalChannel(I) is assigned. An affected
release counts one; this one counts none within a second.
NOT CHANGED:
- Once the channel has opened, Start waits for the server's accept
without a time limit, as entry 27 says: ChannelOpenTimeout covers the
wait for the channel open only. The wait sleeps between looks, and it
ends when the SSH connection closes, but not on a TsnipSSHClient.Stop
on its own (entry 34).
- Only on Windows does tSSHClientChannel.RequestSubSystem wait for the
server's answer, and raise on a refusal. Elsewhere Start goes on with
its connect message after a refusal, and then waits for an accept
that no subsystem will send. That is read from the code; it was not
measured on those platforms.
--------------------------------------------------------------------------------
THE CIPHER COMPONENT: A PARTIAL LAST BLOCK IN PLACE
================================================================================
42. BEHAVIOUR CHANGE - in ECB, CBC and ABC, TstCipher.Encrypt returned
normally with the octets after the last whole block still plaintext;
a length that is not a whole number of blocks is now refused
Encrypt, EncryptPtr, Decrypt and DecryptPtr, on TstCipher and every
other TstCustomCipherComponent, pass the buffer and its length to the
cipher. In ECB, CBC and ABC the cipher works in whole blocks: 16 octets
for AES, TwoFish, Camellia and SEED, 8 for 3DES, Blowfish and RC2, 32
for SHACAL-2. Given a length that is not a whole number of blocks, it
processed the whole blocks, left the rest as it was, and reported back
how many octets it had processed.
THE STEP THAT FAILED is that report. The four methods take the length
as a plain value and had nowhere to put the shorter count, so they
dropped it and returned normally. Encrypt of 20 octets with AES in CBC
encrypted the first 16 and left the last 4 in plaintext, and the caller
could not tell. Below one block - 7 octets, or 20 with SHACAL-2 -
nothing was encrypted at all. Decrypt did the same with the ciphertext.
A ROUND TRIP DID NOT SHOW IT. The receiver's Decrypt stopped at the
same place and left the rest as it came, so the receiver got all 20
octets of plaintext back, the last 4 having gone between the two
unencrypted. A MAC assigned through the MAC property did show it:
Encrypt gave the MAC the 16 octets it had encrypted and the receiver's
Decrypt gave it all 20, so the two MACs differed.
All four now raise eSecComp - for example "Encrypt: 20 octets are not a
whole number of 16-octet blocks" - before they touch anything. The
buffer is as it was, the MAC has been given nothing, and the cipher is
where it was: the next call goes ahead as though this one had not been
made, and no new IVector is needed. Measured on Win32 and on Win64 with
every algorithm the library registers in ECB, CBC and ABC, for 20 and
for 7 octets, through each of the four methods. Every other mode, and
every length that is a whole number of blocks, behaves as before.
IF YOUR PROGRAM encrypted such lengths in place, the octets after the
last whole block of each call were sent or stored as plaintext. Pad the
data to a whole number of blocks first, or let EncryptStr and
DecryptStr pad it with a PaddingMode such as bpmPKCS5, or use a mode
that takes any length, such as CTR. EncryptBytes and DecryptBytes, which
return the count they processed in aCount, are not changed by this
entry; entry 48 is about the octets EncryptBytes gave the MAC.
THE DISCRIMINATING TEST: key a TstCipher for AES in cmCBC, set an
IVector, and call Encrypt on 20 octets. An affected release returns and
leaves the last 4 octets as they were; this one raises "Encrypt: 20
octets are not a whole number of 16-octet blocks" and leaves all 20 as
they were.
--------------------------------------------------------------------------------
THE CIPHER COMPONENT: DECRYPTING TO A STREAM IN PIECES
================================================================================
43. BEHAVIOUR CHANGE - TstCipher.DecryptToDst wrote wrong octets into the
plaintext, or refused a genuine message, when a call was no longer than
the tag or the padded last block, and on every message after the first
that a component decrypted this way
DecryptToDst, and DecryptStreamToDst, DecryptStrToDst and DecryptPtrToDst,
which call it, decrypt a message handed over in any number of calls and
write the plaintext to DestinationStream; DoneToDst then checks the end of
the message and says whether it was genuine. That end is the tag in GCM,
EAX and CCM - 16 octets, or the MACLength set - and the padded last block
in ECB, CBC and ABC with a padding such as bpmPKCS5, 16 octets for AES.
Since any octets received so far may turn out to be that end, DecryptToDst
keeps the last of them back for DoneToDst and decrypts the rest. This is
the same on TstCipher and on every other TstCustomCipherComponent, and has
been since the first 4.0 beta.
THE STEP THAT FAILED is a DecryptToDst call that brought no more octets
than that end. Nothing was decrypted in such a call, but the component
wrote its output buffer to DestinationStream all the same - zero octets,
48 of them for a 16-octet call with AES - and then kept back only this
call's octets, so the octets it had kept back before were decrypted as
message. Measured with AES:
- A GCM or EAX message of 0 octets, which is the tag alone, in one call:
48 zero octets, and DoneToDst returned True.
- A short FIRST call: the plaintext came out behind zero octets - 42 of
them for a 30-octet GCM message given as 10 and 36 octets - and
DoneToDst returned True. The same in EAX, CCM and CBC with bpmPKCS5.
- A short LAST call: in GCM and EAX, DoneToDst returned False for a
genuine message; in CCM the call raised "DecryptToDst: Encryption
failed". In CBC with bpmPKCS5, 31 octets of plaintext given as 22 and
10 octets came out as 57, and DoneToDst returned True. In EAX with an
8-octet tag, a last call of exactly 8 gave 54 octets for 30, and
DoneToDst returned True.
- A call of 0 octets wrote zero octets as well: 32 of them in GCM and in
CBC with bpmPKCS5, 16 in CTR.
DecryptStreamToDst makes such calls on its own. With BufferSize set, it
calls DecryptToDst once per BufferSize octets and once for what is left,
so every input whose last chunk was no longer than the tag, or the padded
block, went wrong. With BufferSize 0, the default, it makes one call, and
only a message of 0 octets went wrong - and every second message (below).
Every way of giving a message in up to three calls, calls of 0 octets
included, gave the plaintext and True in 1,477 of 21,549 cases for 17
GCM messages, 2,647 of 11,099 for 15 CCM messages, 1,804 of 16,544 for 24
EAX messages and 105 of 6,737 for 9 CBC messages with bpmPKCS5.
NOTHING LET A CHANGED MESSAGE THROUGH. A changed tag, or a changed octet
of the message, was refused in every split, before as now; so was a
message one octet short or one octet long. What went wrong was the
plaintext the component wrote around a check that was itself right.
THE SECOND MESSAGE. The octets kept back were never let go - not by
DoneToDst, and not by SetKeyBuf, SetKeyStr, SetKeyIntf or the other
SetKey methods that begin the next message. So the next message on the
same component began with the last octets of the one before, its tag or
its last block, decrypted as message: in GCM and EAX DoneToDst returned
False, in CCM the first call raised "DecryptToDst: Encryption failed",
and in CBC with bpmPKCS5 the plaintext came out too long, mostly with
DoneToDst True. That held whether the second message came in one call or
in several, and also after a message abandoned before DoneToDst. The
Simple Schemes Recipient demos open each message with the same TstCipher
in CBC with bpmPKCS5, re-keyed with SetKeyIntf and decrypted with one
DecryptStreamToDst. That sequence, run in a test program against an
affected release, decrypted no message after the first correctly.
AND A READ PAST THE END OF THE CALLER'S BUFFER. With bpmNone in CBC,
after a call whose octets did not end on a block boundary, and with
bpmCTS from the first call on, a call asked the cipher to decrypt one
octet more than it had been given. On Linux64, valgrind reports those
reads; with bpmCTS, a call of 0 octets with a nil pointer raised
EAccessViolation.
NOW DecryptToDst keeps back exactly the last octets received that can
still be the end - as many as the tag or the padded block - however the
input is split, decrypts only octets that can no longer belong to it, and
writes only what the cipher produced. What it keeps back is let go when
DoneToDst finishes and whenever the component is keyed again. Any split
gives the same plaintext and the same DoneToDst answer as a single call.
CCM needed one change of its own. When no octet of the message came
before the tag - a message of 0 octets - its VerifyFinalBuf did not close
the additional data, as the first octet of the message does, and so
refused such a message whenever there was additional data, however right
the tag. It now closes it itself. That is iCipherMAC.VerifyFinalBuf on a
CCM cipher, given the tag alone; through DecryptToDst it made DoneToDst
refuse such a message in every split.
Checked on Win32, Win64 and Linux64 against known answers from outside
the library, with AES-128, -192 and -256, 0 to 64 octets of plaintext and
0 to 20 of additional data: 17 GCM messages - McGrew and Viega's test
cases 1 to 4 and pyca/cryptography (OpenSSL) - 15 CCM messages from
pyca/cryptography, with tags of 16, 8 and 4 octets, and 24 EAX messages:
the ten test vectors of the EAX paper by Bellare, Rogaway and Wagner,
and 14 from an EAX built for the test on pyca/cryptography's AES and
CMAC, which reproduces those ten. Also 9 CBC messages with bpmPKCS5 and 7
CTR messages from pyca/cryptography. Every split into up to three calls,
DecryptStreamToDst with every BufferSize, the changed and cut messages
above in every split into two calls, and one component decrypting
message after message: all 72,567 checks as expected, the same on the
three platforms. valgrind on Linux64 reports no invalid access.
THE DISCRIMINATING TEST: key a TstCipher for AES in cmGCM with 16 zero
octets, set (Cipher1 as iGCMParameters).N to 12 zero octets and call
Initialize, set DestinationStream to an empty TMemoryStream, and call
DecryptToDst with the 16 octets 58E2FCCEFA7E3061367F1D57A4E7455A: the tag
of an empty message, McGrew and Viega's test case 1. An affected release
leaves 48 zero octets in the stream, this one none; DoneToDst returns
True in both.
WHAT EXISTING CODE SEES DIFFERENTLY, apart from right output:
- DoneToDst after a decrypt in CTR, CFB or OFB, or with PaddingMode
bpmNone on whole blocks, returns True. It returned False after every
such decrypt, with the right plaintext in the stream.
- With bpmNone and ciphertext that does not end on a block boundary,
DoneToDst returns False as before, and now also sets the stream back
to where it started, as it does for every message it refuses; before,
the whole blocks stayed in the stream.
- A decrypt the cipher declines, as in CCM beyond the MessageLength set,
raises "DecryptToDst: Decryption failed". It said "Encryption failed".
The class is eSecComp, as before.
- The CCM VerifyFinalBuf above accepts a right tag it refused.
NOT INVOLVED: the ciphers, and the tags they compute and check;
EncryptToDst, which gave the known answers in every split before as now;
DecryptStr and the in-place methods. TLS, SSH, CMS and the SET3 streams
do not use DecryptToDst, and TLS and SSH do not use CCM. The SET3
tDecryptStream does call the CCM VerifyFinalBuf, but with the tag alone
only for a CCM message of 0 octets, which tEncryptStream never writes.
NOT CHANGED, and stated here rather than left to be found:
- DecryptStreamToDst and EncryptStreamToDst given an EMPTY source, CCM
finishing an encrypted message of 0 octets with additional data, and
DoneToDst when the padding cannot finish what EncryptToDst was given:
see entry 49, which changes all three.
- DecryptToDst and DoneToDst with bpmStrSecII, which gave back almost
no message, and with bpmCTS, which raised ePaddingError "Buffer too
small" in some splits: see entry 58, which changes both.
--------------------------------------------------------------------------------
SSH CHANNELS: DATA READ WHILE MORE IS ARRIVING
================================================================================
44. FIXED - data read from an SSH channel while more was arriving could
contain bytes that were not yet written
Every SSH channel, on the client side and on the server side, keeps the
data that arrives for it in a buffer the size of its window until the
program reads it. The thread that reads the SSH connection puts each
packet of channel data into that buffer. RecvLength tells a reader how
much is waiting, and Recv - and InputStream, on a client channel - hands
it over.
THE STEP THAT FAILED is putting a packet into the buffer. The
connection's thread counted the packet as waiting first, and copied it
in after. A reader on another thread that asked in that moment was told
the packet was there, and was handed what the buffer held at those
places instead: zeros, or - once the window had been adjusted and the
buffer was in use again - bytes it had already read. The number of bytes
always came out right, and no byte was lost, repeated or moved; some were
simply not the ones sent. Each wrong stretch lay within one packet, at
its start or in its last 32 bytes. Nothing reported it: the data had
reached the channel intact and passed the connection's MAC check, and
the damage was done between the buffer and the reader.
WHO READ ON ANOTHER THREAD. On the client side: an application reading
a channel it opened with TstSSHSocketClient or TstSSHClient, the SFTP
client, and snip over SSH (TsnipSSHClient). On the server side, every
subsystem, whose ReadData runs on the channel's own subsystem thread:
the SFTP server, the snip server and any TstCustomSSHSubSystem of your
own. Recv's blocking form was affected as well as the non-blocking one:
both go by the count RecvLength gives. A reader that asked just before or
just after a packet was copied got the right bytes, so whether a
transfer came through damaged was a matter of timing, and the same
transfer could be damaged one time and intact the next.
Now a packet is copied into the buffer first and counted as waiting
after. A program that reads a channel needs no change.
THE DISCRIMINATING TEST: send 16 MB over a channel, byte N a function of
N, and read it on another thread with RecvLength and then Recv(Buffer,
0, n, False) in a tight loop, checking every byte against its position -
on the client side, and in a subsystem's ReadData on the server side,
through a window larger than the transfer and through a 256 KB one. An
affected release got 56 of 160 such transfers wrong on Win32 and 66 of
160 on Win64, and each of its 20 runs of 16 transfers had at least one;
this one got none of 320 wrong. The byte count was right in every one of
them. To tie it to the order: with a pause of 0.2 ms put between
counting and copying, an affected release got 95 of 96 transfers wrong;
with the same pause put between copying and counting, this release got
none of 96 wrong.
PLATFORMS. Measured on Win32 and Win64. The same code runs on every
platform, so every platform was affected.
NOT INVOLVED: the network, the ciphers and MACs, and what the peer sent,
which reached the channel intact. Nor the size of the window: a window
larger than the transfer, never adjusted, was affected, and so was a
small one adjusted every 256 KB. Port forwarding was not affected: a
forwarded channel is read on the connection's own thread, right after
each packet is copied in.
NOT CHANGED: what RecvLength, Recv and InputStream return; the window,
its adjustment, and the order of the bytes. The legacy units
stSSHClientChannel and stSSHServerChannel, which no longer ship, have
the same defect and are not changed.
--------------------------------------------------------------------------------
INTERFACES DECLARED WITH ANOTHER INTERFACE'S GUID: THE LEGACY iSignKeyIF
================================================================================
Entry 15 gave iSignKeyIF in StreamSec.DSI.PKTypes a GUID of its own. Its
namesake in the legacy unit stMPPKTypes, which still ships for its types, kept
the GUID of iSignKey, and so still asked only whether a key implements
iSignKey.
45. BEHAVIOUR CHANGE - the legacy stMPPKTypes.iSignKeyIF gets a GUID of its
own, and no key answers it any more
Code whose iSignKeyIF is the one in stMPPKTypes - the name resolves there
when stMPPKTypes comes after StreamSec.DSI.PKTypes in the uses clause, or
is the only one of the two - asked a key the question entry 15 fixed for
the DSI interface: does it implement iSignKey. An ML-DSA or SLH-DSA key
does, and answered with its iSignKey interface, which ends before the RSA
members, so MGFHashAlg, SignEncoding and EncryptEncoding jumped past the
end of it. An RSA key answered with its iSignKeyIF from
StreamSec.DSI.PKTypes, which has SaltLen where the legacy interface has
SignEncoding: through it, reading SignEncoding called GetSaltLen, setting
it called SetSaltLen, reading EncryptEncoding returned the sign encoding
and setting it set the sign encoding.
stMPPKTypes.iSignKeyIF now has a GUID of its own. No key the library
creates implements it, so every key answers False to Supports, and as
raises EIntfCastError.
IF YOUR CODE asks a key for iSignKeyIF and the name resolves to
stMPPKTypes, name StreamSec.DSI.PKTypes.iSignKeyIF instead, or put
StreamSec.DSI.PKTypes after stMPPKTypes in the uses clause. An RSA key
answers that interface as before, with the members it declares.
THE DISCRIMINATING TEST: Supports(Key, stMPPKTypes.iSignKeyIF) for the
public key of a TstRSAKey. An affected release returns True, this one
False.
NOT INVOLVED: iSignKey and StreamSec.DSI.PKTypes.iSignKeyIF, which keep
their GUIDs and are answered as before; and the library itself, in which
no unit asks for the legacy interface. The legacy key classes of stMPIF,
which is no longer shipped, implement the legacy iSignKeyIF and list
nothing else of the kind: compiled against this stMPPKTypes they answer
iSignKeyIF, and no longer answer iSignKey.
--------------------------------------------------------------------------------
SSH: A CHANNEL SEND OF 32 KB OR MORE
================================================================================
46. FIXED - an SSH client channel raised eSSHTransportError "Too large
buffer" on a Send of 32760 octets or more when the server's maximum
packet size was 32768, as OpenSSH's and TstSSHServer's are, so an SFTP
upload in writes of 32 KB or more failed on its first write
When an SSH channel opens, each end tells the other the largest packet
of data it will take on the channel. RFC 4254 section 5.1:
"The 'maximum packet size' specifies the maximum size of an
individual data packet that can be sent to the sender."
OpenSSH's sshd gives a session channel 32768, and so does TstSSHServer,
whose DefaultPacketSize is 32768 unless you set it lower (it cannot be
set higher). A channel's Send cuts the octets it is given into packets
and sends each as an SSH_MSG_CHANNEL_DATA message, which carries
1 + 4 + 4 = 9 octets besides the data: the message number, the channel
number and the length of the data. The transport sends a message of at
most 32768 octets and raises eSSHTransportError "Too large buffer" for a
longer one. That figure is the one RFC 4253 section 6.1 guarantees:
"All implementations MUST be able to process packets with an
uncompressed payload length of 32768 bytes or less and a total
packet size of 35000 bytes or less (including 'packet_length',
'padding_length', 'payload', 'random padding', and 'mac')."
So one packet can carry at most 32768 - 9 = 32759 octets of data,
whatever the peer would take. RFC 4254 section 5.2 says the connection
layer
"MUST NOT generate data packets larger than its transport layer is
willing to send, even if the remote end would be willing to accept
very large packets."
THE STEP THAT FAILED is that cut on the client's end of a channel,
tSSHClientChannel.Send, which everything a TstSSHClient sends on a
channel goes through. It cut at the server's maximum packet size alone.
With a server's 32768, a packet of 32768 octets of data made a message
of 32777 octets, and the transport raised "Too large buffer" before
anything was sent. So a Send of 32760 octets or more raised on its
first packet, while a Send of 32759 octets or less went out whole - and
any amount of data went through in Sends of that size. Measured on
Win32 and Win64:
- Against OpenSSH 9.5 (the sshd and sftp-server of Windows' OpenSSH):
tSFTPTransport.WriteFile of 32768 or of 131072 octets raised on the
first write, and so did TstSFTPClient.PutFile of a 4 MB file, which
writes 131072 octets a request. An SFTP write request is its file
data plus 25 octets and the file handle, and OpenSSH's handles are 4
octets, so a write of 32731 octets of file data or more raised; a
4 MB download on the same connection worked.
- Against TstSSHServer with its default DefaultPacketSize: a Send of
32760, 32768 or 131072 octets on the client's channel raised the same
way, and the server received nothing.
By the code, remote port forwarding with TstSSHForwardingClientSocket
was affected too: it sends what one read from the forwarded local
connection returns, up to 32768 octets, in one Send, and when a Send
raised it closed that connection without reporting anything. That was
not measured.
Now the client's end of a channel limits a packet's data to 32759
octets as well as to the server's maximum packet size, whichever is
smaller. The server's end has done so all along, which is why a server
sending to a client was not affected: a TstSSHServer sending 4 MB to our
client in Sends of 32768 and of 131072 octets delivered all of it before
the fix as after, and OpenSSH's sftp reading from our SFTP server in
requests of 32 KB worked.
A PEER ADVERTISING 2^31 OR MORE. The maximum packet size is an unsigned
32-bit number, but both ends of a channel held it in a signed integer,
so a value of 2^31 (2147483648) or more became negative. The server's
end compared it as a signed number, so its limit let it through, and
the client's end had no limit. With a negative limit a channel's Send
did not finish: by the code, each round built a CHANNEL_DATA message
one octet too short for its length field, wrote the field anyway - one
octet past the end of the message's memory - sent the message, and
went round again with more left to send, not less. Measured with this
library at both ends, one of them advertising 2^32 - 1, in either
direction: on Win32 the first Send had not returned after 90 seconds
and nothing had arrived; on Win64 the program failed with
EInvalidPointer, in two runs of six then with an access violation. A
client can advertise such a value to a server only after it has logged
in, since channels open after authentication, and a server only to a
client that has logged in to it. What a peer can do with it beyond
stopping the sending thread or ending the process has not been traced.
Now both ends take the value as the unsigned number it is, and limit it
to 32759 like any other value above that.
THE DISCRIMINATING TEST: connect a TstSSHSocketClient to a
TstSSHSocketServer, both with the default DefaultPacketSize of 32768,
open a session channel, and Send 32768 octets on the client's end. An
affected release raises eSSHTransportError "Too large buffer" and the
server receives nothing; this one delivers all of them. On either
release a Send of 32759 octets goes through, and so does a Send of any
size on the server's end. So an upload that raises "Too large buffer"
on its first write, while downloads on the same connection work, is
this defect.
NOT INVOLVED: the window size, the key exchange, the ciphers, MACs and
compression, and SFTP itself. What a channel receives was never
affected, and neither was what the server's end sends, except to a
client advertising 2^31 or more (above).
NOT CHANGED:
- DefaultPacketSize, the maximum packet size the components advertise,
and the transport's limit of 32768 octets a message.
- TstSFTPClient.PutFile without aAppend, to a server that speaks SFTP
version 3 as OpenSSH's sftp-server does, still fails, now on its
first write with eSFTPStatusError "Permission denied": it opens the
file without asking to write to it (no SSH_FXF_WRITE), which that
server allows, and the server then refuses the writes. That is a
separate defect, fixed in entry 53. PutFile with aAppend, and
tSFTPTransport.WriteFile on a file opened with fo3Write, upload in
full (measured against OpenSSH 9.5).
- The legacy units stSSHClientChannel and stSSHServerChannel, which no
longer ship, are not changed.
--------------------------------------------------------------------------------
TWOFISH ON WIN64: THE ADDRESS OF THE KEY
================================================================================
47. FIXED - on Win64, TwoFish raised EAccessViolation whenever its cipher
object lay above 4 GB - with Delphi 11 and later, every time - in
every release that runs on Win64, 4.0 PREVIEW 0.282 (2012) up to and
including 4.1.4.360
Every TwoFish encryption in a Win64 program goes through one assembler
routine in stTwoFish, the one that encrypts a single 16-octet block.
That is so for TstCipher with Algorithm caTwoFish, for every tTwoFish_
cipher class in stTwoFish, for the SSH ciphers twofish-cbc, twofish-ctr
and twofish128/192/256-cbc and -ctr, and for the StreamSec extended TLS
suites WITH_TWOFISH_..., which are off by default.
THE STEP THAT FAILED is the routine's first one: it combines the block
with four words of the key schedule, and it read those four words
through a 32-bit register, so it used only the low half of their 64-bit
address. While the cipher object lies below 4 GB, the low half is the
whole address and the routine works. Above 4 GB it read from an address
that is not mapped, and raised EAccessViolation, "Read of address
00000000xxxxxxxx" - the object's address with its top half cut off. The
rest of the routine, the key schedule and the decryption routine
addressed memory correctly.
WHAT RAISED:
- Every encryption, in every mode: ECB, CBC, CFB, OFB, CTR, ABC, EAX,
CCM and the two SSH modes.
- Decryption in CFB, OFB, CTR, EAX, CCM and the SSH counter mode, which
run the block encryption to decrypt as well. EAX and CCM raised
already in Initialize, before any data.
- Not decryption in ECB, CBC and ABC: it always returned the right
plaintext.
An SSH connection that negotiated one of the TwoFish ciphers therefore
failed at the first packet encrypted after the key exchange: a
TstSSHSocketClient raised EAccessViolation from Login.
WHEN IT SHOWED DEPENDS ON THE DELPHI VERSION, because the version
decides where a Win64 program's heap lies. Measured with the
command-line compiler of every version from XE2 to 13:
- Delphi 11, 12 and 13 put it above 4 GB. There every TwoFish
encryption raised, from the first.
- XE2 to 10.4 put it below 4 GB in a program of ordinary size, and
there TwoFish worked, until a cipher object came from above 4 GB - as
one does in a program whose heap has grown past 4 GB. With the
address space below 4 GB filled on purpose, every version from XE2 to
10.4 raised exactly as 11 to 13 do.
Win32 programs were never affected; they run a separate 32-bit routine.
CATCHING THE EXCEPTION DID NOT MAKE IT SAFE. The fault struck after the
routine had changed registers that belong to its caller and before it
put them back, so the code that caught the exception went on with
those registers wrong. A test program that caught each fault and went
on crashed outright, or raised EStackOverflow, after about 75 of them,
with every Delphi version.
The four reads now use the whole 64-bit address. On Win64 TwoFish now
gives the same result as on Win32, as the test vectors of the TwoFish
paper, and as two independent implementations, libgcrypt and nettle: in
ECB, CBC, CFB, OFB, CTR, EAX and CCM, with 128-, 192- and 256-bit keys,
with every Delphi version from XE2 to 13. TwoFish SSH connections, CBC
and counter mode, now work on Win64 as they do on Win32.
DATA ALREADY ENCRYPTED. The routine read the right key words or raised;
no test run ever produced a wrong block. So what an affected release
did encrypt - on Win32, or on Win64 with the object below 4 GB - is
correct, and decrypts as before. In principle the cut-off address could
have fallen on memory that can be read; that block would then have
been encrypted with four wrong key words, and would not decrypt with
any release.
THE DISCRIMINATING TEST: in a Win64 program built with Delphi 11 or
later, create a tTwoFish_ECB with a key of 16 zero octets and encrypt a
block of 16 zero octets in place. An affected release raises
EAccessViolation; this one gives 9F589F5CF6122C32B6BFEC2F2AE8C35A, the
first test vector in the TwoFish paper. Built with XE2 to 10.4, an
affected release passes this test unless the object lies above 4 GB.
NOT CHANGED: the Win32 routines, the key schedule, and the result of
every TwoFish operation that completed before.
--------------------------------------------------------------------------------
THE CIPHER COMPONENT: WHAT EncryptBytes AND EncryptIntf GIVE THE MAC
================================================================================
48. BEHAVIOUR CHANGE - TstCipher.EncryptBytes gave the MAC the octets that
follow the ciphertext instead of the ciphertext, and EncryptBytes and
EncryptIntf gave it the plaintext when the cipher had not encrypted it
A MAC assigned to the MAC property of a TstCipher, or of any other
TstCustomCipherComponent - a TstHash given a key, or any other
TstCustomMAC - is given the ciphertext of every call that encrypts or
decrypts, so that a sender and a receiver compute it over the same
octets. EncryptBytes encrypts aCount octets of a tBytes array in place,
from aOffset on; EncryptIntf encrypts the octets of an iSecretKey in
place. Both date from the first 4.0 beta, and so do the two defects
below.
THE STEP THAT FAILED WHEN EncryptBytes SUCCEEDED is where it took the
octets for the MAC. The cipher encrypts the aCount octets and moves
aOffset past them, so that the next call can carry on where this one
ended. EncryptBytes then gave the MAC aCount octets from the moved
aOffset: the ciphertext was right and in place, but the MAC was given
what followed it. Measured:
- 32 octets at offset 0 of a 64-octet array: the MAC was given octets
32 to 63 of the array, whatever they held.
- 96 octets encrypted in a loop of 32-octet calls, which is what
aOffset is for: each call gave the MAC the next 32 octets, not yet
encrypted, so the MAC was given the plaintext from octet 32 on, and
then 32 octets from past the end of the array.
- Wherever the ciphertext ended at the end of the array - a call on the
whole array, or on its last octets - the MAC was given aCount octets
read from the memory that follows the array.
- In ECB, CBC and ABC, given a length that is not a whole number of
blocks, the cipher encrypts the whole blocks and returns their number
in aCount (entry 42); the MAC was given that many octets from after
them.
So a MAC computed while encrypting with EncryptBytes was never the MAC
of the ciphertext, and a receiver computing it while decrypting - with
DecryptBytes, Decrypt or DecryptToDst, which give the MAC the
ciphertext - got a different one. With AES-128 in CBC and a TstHash
with SHA-256 and a key as the MAC on both sides, the receiver's MAC
was that of the ciphertext and the sender's was not, whether the
array went on after the ciphertext or ended with it.
THE STEP THAT FAILED WHEN THE CIPHER DECLINED. Where the cipher cannot
encrypt in place - the cases entry 35 lists, such as AES in cmSSH, 3DES
and RC2 in cmKeyWrap, CCM beyond the MessageLength set, and a padded
mode after EncryptStr until a new IVector is set - EncryptBytes and
EncryptIntf return False and leave the plaintext as it was. They then
gave that plaintext to the MAC all the same, on every such call, as
though it were ciphertext.
NOW EncryptBytes gives the MAC aCount octets from where aOffset was when
it was called: the ciphertext, and in ECB, CBC and ABC the whole blocks
it encrypted. When the cipher declines, EncryptBytes and EncryptIntf
give the MAC nothing, as Encrypt, EncryptPtr, EncryptStr and
EncryptToDst do. Measured on Win32 and Win64 with AES-128 in CBC and
CTR and 3DES in CBC, at offsets inside the array, with the ciphertext
ending at its end, and in a loop; and, for a declining cipher, with
each case named above, the padded one being AES in CBC with bpmPKCS5.
Everything else the two calls do - what they return, what they leave
in the buffer, in aOffset and in aCount, and how the component takes
the next call - was the same before and after, in every case measured.
IF YOUR PROGRAM encrypts with EncryptBytes and has a MAC assigned, the
MAC it computes changes: it is now the MAC of the ciphertext, the one a
receiver computes while decrypting. A MAC that an affected release
computed this way and stored with the data is not the MAC of that
data's ciphertext; compute it again, over the ciphertext, to be able to
check it. If your program went on after EncryptBytes or EncryptIntf
returned False, the MAC no longer includes the plaintext of that call.
EncryptIntf, when it succeeds, gives the MAC the same octets as before.
THE DISCRIMINATING TEST: key a TstCipher for AES in cmCBC, set an
IVector, and assign to its MAC property a TstHash with HashAlgorithm
haSHA256 and a key set with SetKeyStr. Call EncryptBytes with aOffset 0
and aCount 32 on a 64-octet array, then the TstHash's Done, and compare
its Digest with that of a second TstHash, with the same key, given the
first 32 octets of the array with HashData. An affected release gives
two different digests; this one gives the same.
NOT INVOLVED: the ciphers, and the ciphertext EncryptBytes and
EncryptIntf leave in place, which were right before as now; Encrypt,
EncryptPtr, EncryptStr and EncryptToDst; and the decrypting calls,
which give the MAC what they are given before they decrypt it. Nor the
library's own encryption - TLS, SSH, CMS, the SET3 streams and the
simple scheme components among them - which calls the ciphers
directly, or a TstCipher's EncryptStr.
NOT CHANGED: EncryptBytes and EncryptIntf report a declining cipher by
returning False, not by raising, and a False does not by itself make
the component ask for a new IVector, as Encrypt and EncryptPtr do
(entry 35). DecryptBytes and DecryptIntf are not changed either.
--------------------------------------------------------------------------------
THE CIPHER COMPONENT: FINISHING AN ENCRYPTION TO A STREAM
================================================================================
49. BEHAVIOUR CHANGE - TstCipher.EncryptStreamToDst stored nothing for an
empty source, not even the tag; in CCM, DoneToDst refused to finish an
empty message with additional data; DoneToDst raised ERangeError when
the padding could not finish the input
EncryptToDst, and EncryptStreamToDst, EncryptStrToDst and
EncryptPtrToDst, which call it, encrypt a message handed over in any
number of calls and write the ciphertext to DestinationStream; DoneToDst
then writes what finishes the message - the tag in GCM, CCM and EAX, the
padded last block in ECB, CBC and ABC with a padding such as bpmPKCS5 -
and lets the key go. Entry 43 describes the decrypting side. This is the
same on TstCipher and on every other TstCustomCipherComponent. Three
steps failed; each was measured with AES, on Win32 and on Win64.
THE FIRST STEP THAT FAILED is EncryptStreamToDst or DecryptStreamToDst
given an EMPTY source: no octets from where it starts reading to the end
of the stream. Which way DoneToDst goes is set by Direction, or - with
Direction at cdAuto, the default - by the first EncryptToDst or
DecryptToDst call after the key. The two stream methods make one such
call per chunk they read, and so for an empty source none at all.
DoneToDst then went neither way: it returned False, wrote nothing and
kept the key. An empty message encrypted this way was stored as nothing:
in GCM, CCM and EAX not even its tag, which is all the ciphertext an
empty message has, and with bpmPKCS5 not its block of padding. No
receiver could authenticate or decrypt that. In CTR, CFB and OFB, and
with bpmNone, where the ciphertext of an empty message is empty, only
the False was wrong, when encrypting and when decrypting.
THE SECOND is the tag of a CCM message of 0 octets with additional data.
CCM closes the additional data when the first octet of the message goes
through; with no octet it stayed open, and making the tag refused it.
With Direction set to cdEncrypt before the key, so that the first step
did not bite, DoneToDst raised ePaddingError, "The length of the input
data does not match the parameters"; so did iCipherMAC.GetFinalBuf on a
CCM cipher. An EncryptToDst call of 0 octets first closed the additional
data and avoided it. Entry 43 made the same repair to the check of such
a tag on the decrypting side. GCM and EAX were not affected.
THE THIRD is DoneToDst on the encrypting side when the padding has
nothing to finish the input with: with bpmNone when the octets given so
far are not a whole number of blocks - 17 with AES in CBC - and with
bpmCTS when they are fewer than one block - 15 with AES. The padding
reports that as a final length of -1, and DoneToDst asked for a buffer
of that length: ERangeError, "Range check error", which names neither
the padding nor the input.
NOW:
- EncryptStreamToDst and DecryptStreamToDst pass an empty source on as
one call of 0 octets, the call a program using EncryptToDst itself can
make. Encrypting, DoneToDst then writes the tag, or the block of
padding, of the empty message and returns True; in CTR, CFB, OFB and
with bpmNone it writes nothing and returns True. Decrypting, it refuses
an empty source where a tag or a padded block is due - False, nothing
written - and accepts it as the empty message in CTR, CFB, OFB and with
bpmNone.
- CCM closes the additional data itself when it makes the tag of a
message of 0 octets, so DoneToDst writes the right tag with or without
an EncryptToDst call. Additional data shorter than the
AdditionalDataLength set, or no message where a MessageLength above 0
was set, is refused with the same ePaddingError as before.
- DoneToDst raises eSecComp, "DoneToDst: The input is not a whole number
of 16-octet blocks, and padding mode None does not pad it" or
"DoneToDst: The input is shorter than one 16-octet block, the least
that padding mode CTS can finish", before it writes anything or lets
the key go. The message stays open: EncryptToDst calls that complete
it, then DoneToDst, give the same ciphertext as though the refused
call had not been made.
Checked on Win32 and Win64 against known answers from outside the
library: the 72 messages of entry 43 and 32 more. 21 of them are empty
messages - 6 GCM with 1 to 64 octets of additional data and 10 CCM with
tags of 4 to 16 octets and 0 to 64 of additional data, from
pyca/cryptography (OpenSSL), and 5 EAX with tags of 4 to 16 octets and 1
to 64 of additional data from the EAX of entry 43, which reproduces the
ten test vectors of the EAX paper - bringing the empty GCM, CCM and EAX
messages to 9, 14 and 9. The other 11 are AES in CBC and ECB without
padding and in ECB with bpmPKCS5, from pyca/cryptography. Every empty
message comes out right through EncryptStreamToDst of an empty source,
with BufferSize 0 and 1 and with Direction cdAuto and cdEncrypt, through
DoneToDst with Direction cdEncrypt and no call, and after one and after
three EncryptToDst calls of 0 octets; CCM additional data one octet
short, and a missing message, are still refused. With bpmNone in CBC and
ECB, every stop that leaves a partial block, 1 to 63 octets into
messages of 16 to 64, is refused twice with the eSecComp above without
a write, and the message, finished after that, is pyca/cryptography's
ciphertext. With bpmCTS, every stop at 0 to 15 octets is refused the
same way, and the message, finished after that, is pyca/cryptography's
CBC ciphertext for 16 to 64 octets in whole blocks, and for 17 to 47
octets the ciphertext the same message gives in one call. Entry 43's
checks - every split of every message, both ways - still pass: 85,783
checks as expected, the same on both platforms. An affected release
fails 627 of them, every one in the three steps above.
THE DISCRIMINATING TESTS:
- Key a TstCipher for AES in cmGCM with 16 zero octets, set (Cipher1 as
iGCMParameters).N to 12 zero octets and call Initialize, set
DestinationStream to an empty TMemoryStream, and call
EncryptStreamToDst with another, empty, TMemoryStream and 0, then
DoneToDst. An affected release returns False and leaves the stream
empty; this one returns True and leaves the 16 octets
58E2FCCEFA7E3061367F1D57A4E7455A, the tag of McGrew and Viega's test
case 1.
- Set Direction to cdEncrypt, key a TstCipher for AES in cmCCM, set
(Cipher1 as iCCMParameters).LengthLength to 2, N to 13 octets,
MessageLength to 0 and AdditionalDataLength to 1, and call Initialize;
give one octet to (Cipher1 as iCipherMAC).EncryptToNil, set a
DestinationStream and call DoneToDst. An affected release raises
ePaddingError; this one writes the 16-octet tag.
- Key a TstCipher for AES in cmCBC with PaddingMode bpmNone, set an
IVector and a DestinationStream, call EncryptToDst with 17 octets and
then DoneToDst. An affected release raises ERangeError; this one
eSecComp with the first text above, and after EncryptToDst with 15
more octets DoneToDst returns True.
IF YOUR PROGRAM encrypts with EncryptStreamToDst and Direction cdAuto
and can meet an empty source, what it stored for one is empty where a
tag or a block of padding belongs, and cannot be authenticated. Treat
such a stored message as missing and encrypt the source again; do not
accept an empty ciphertext as an empty message.
WHAT EXISTING CODE SEES DIFFERENTLY, apart from right output:
- After EncryptStreamToDst or DecryptStreamToDst of an empty source with
Direction cdAuto, DoneToDst finishes the message and lets the key go,
as after any other message; the next message needs a SetKey method
first. Before, the key stayed set.
- The encrypting DoneToDst that cannot finish the input raises eSecComp
where it raised ERangeError.
- A source the two stream methods cannot read from raises
"EncryptStreamToDst: Unable to read from stream" or
"DecryptStreamToDst: Unable to read from stream". Both said
"EncryptToDst: ...". The class is eSecComp, as before.
- iCipherMAC.GetFinalBuf on a CCM cipher gives the tag of a message of 0
octets with additional data, which it refused.
NOT INVOLVED: the ciphers, and the tags and padding they compute;
messages of one octet or more through the stream methods, and
EncryptToDst and DecryptToDst themselves, which were right before as
now; DoneToDst on the decrypting side; EncryptStr, which makes a call of
0 octets of its own before the tag and so gave the tag of an empty CCM
message with additional data before as now. TLS, SSH, CMS and the SET3
streams do not use the ToDst methods, and TLS, SSH and CMS do not use
CCM; the SET3 tEncryptStream never makes a CCM message of 0 octets. The
Simple Schemes Sender demos set Direction to cdEncrypt on their
TstCipher, and so stored the block of padding of an empty file before
as now.
NOT CHANGED:
- DoneToDst with Direction cdAuto and no EncryptToDst or DecryptToDst
call since the key cannot tell which way it is going: it returns False
and writes nothing, as before. A program that calls EncryptToDst
itself and may have nothing to give it sets Direction before the key,
or makes a call of 0 octets.
- Count 0 to EncryptStreamToDst and DecryptStreamToDst means the whole
stream from position 0, as documented, not 0 octets. A program that
works out the length of a stored ciphertext and passes it as Count
must not pass 0 for an empty one - an empty CTR message, say - or the
whole stream is read.
- EncryptStr, which does not go through DoneToDst. It refused such
input with ERangeError, or with bpmNone and a block or more with
ePaddingError; entry 64 makes it raise the eSecComp above.
--------------------------------------------------------------------------------
SSH SERVER: A SUBSYSTEM THAT COMPLETES ITS OWN CHANNEL'S CLOSE
================================================================================
50. FIXED - an SSH server could free a connection while a subsystem that
had closed its own channel was still running; the subsystem's thread
then used the freed connection, and a Linux64 program crashed
On the server side of an SSH connection, every session channel that runs
a subsystem - SFTP, snip, or a TstCustomSSHSubSystem of your own - has a
thread that calls the subsystem's ReadData. When the client closes such a
channel first, the server answers its CHANNEL_CLOSE and leaves the
channel for the subsystem to complete (entry 38 describes the same
parts). A subsystem completes it by calling the channel's Close from its
ReadData; the SFTP subsystem does so when it sees that the client has
closed the channel. A thread cannot wait for itself, so the channel then
lets its thread go on alone: the thread finishes that ReadData and ends
by itself.
THE STEP THAT FAILED is releasing the connection while such a thread was
still in its ReadData. Nothing waited for it. The object that holds the
connection's channels was freed - when the client closed the SSH
connection, or when the server was stopped or freed - and the thread,
ending, reported its end through that object: it fires the server's
OnEndSubSystemThread. What happened then depended on what the freed
memory held by that time. On Windows the call failed with an access
violation that the thread caught without a word, so
OnEndSubSystemThread never fired for that thread, and a program that
pairs it with OnBeginSubSystemThread - to end a database session, or
COM - was one short each time. On Linux64 the program crashed:
EAccessViolation at an address in no module. A server that was being
freed could be gone as well.
Measured with a test subsystem whose ReadData, once the client had
closed the channel, completed the close and then went on for a second
and a half, and a client that closed its SSH connection straight after:
the server released the connection within 16 milliseconds, and the
thread's report went wrong, in every one of six connections per run on
Win32 and Win64. On Linux64 the first such connection crashed the
program. The same happened when the server was freed while the thread
was still in its ReadData.
Now releasing a connection waits until every subsystem thread of its
channels has ended, including one that has left its channel, and each
thread reports its end while the connection, and the server, are still
there.
WHO WAS AFFECTED: a subsystem whose ReadData can still be running after
it has completed its channel's close. The SFTP subsystem returns straight
after its close, which leaves only a narrow window. Snip completes the
client's close from its ReadData only from this release on (entry 52),
which is why this entry comes first.
IF YOUR SUBSYSTEM blocks in ReadData after closing its channel, closing
the SSH connection, and stopping or freeing the server, now waits for
it, as they already waited for every subsystem thread still attached
to its channel. Return from ReadData once the channel is closed.
NOT INVOLVED: the key exchange, the ciphers, the authentication and the
client side; forwarded connections, which run no subsystem; a subsystem
whose channel is closed by the client's answer to a CLOSE the subsystem
sent, which the server's own reading thread completes.
THE DISCRIMINATING TEST: give a TstSSHServer a TstCustomSSHSubSystem
whose subsystem's ReadData, when the channel's State is csClosing, calls
the channel's Close and then sleeps for two seconds, and count the
server's OnEndSubSystemThread calls. From a client, open a session
channel for that subsystem, close the channel, wait for the server's
CLOSE to reach the client and close the SSH connection. An affected
release on Windows never fires OnEndSubSystemThread for that thread, and
on Linux64 it crashes; this one fires it after the two seconds, and only
then frees the connection.
NOT CHANGED: a subsystem whose ReadData raises still ends its thread and
leaves its channel open until the connection closes (entry 38).
--------------------------------------------------------------------------------
SSH SERVER: A SUBSYSTEM FREED WHILE ITS ReadData RAN
================================================================================
51. FIXED - an SSH server could free a subsystem while the subsystem's
ReadData was still running
The thread that calls a subsystem's ReadData (entry 50) took no
reference to the subsystem for the call; it called it through the
channel's own reference. The channel lets go of its subsystem when the
close is completed: when the client answers a CLOSE the subsystem has
sent, when the connection is released, and when the subsystem completes
the client's close itself. Where the channel's reference was the last
one - it is for SFTP, and for a subsystem that is created for its
channel and held nowhere else - the subsystem was freed there.
THE STEP THAT FAILED is ReadData going on after that. The first two
happen on the server's reading thread, at any point in a ReadData that
is still running; the third happens inside the subsystem's own call of
the channel's Close, so the rest of that ReadData always ran on a freed
object. The SFTP subsystem closes its channel from ReadData and then
clears a field of its own, so when an SFTP client closed the channel
before the server had closed it, the server wrote into freed memory.
That was read from the code; it was not measured with SFTP.
Measured with a test subsystem that records whether it is freed while
its ReadData runs, and holds ReadData until the close is complete: it
was freed inside its ReadData in every connection, on Win32, Win64 and
Linux64, both when it had closed the channel itself and the client
answered, and when the client closed the SSH connection meanwhile.
Now the thread holds references of its own to the subsystem and to the
channel for the length of each ReadData call, and the channel's
reference is taken and dropped under a lock. A subsystem that the
channel lets go of while its ReadData runs is freed when that ReadData
returns, on the subsystem's thread, rather than on the thread that let
go of it.
NOT INVOLVED: what the subsystem does in ReadData; the key exchange, the
ciphers and the client side.
THE DISCRIMINATING TEST: give a TstSSHServer a TstCustomSSHSubSystem
whose subsystem sets a flag in its destructor, and whose ReadData, on the
first octet it is sent, closes the channel and then waits until the
channel's State is csClosed, and a moment more, before it returns. From a
client, open a session channel for it, send one octet and answer the
server's CLOSE. An affected release runs the destructor before ReadData
returns, every time; this one after.
NOT CHANGED: ChannelClosed is called on the thread that releases the
channel, which may be while ReadData runs on the subsystem's thread; the
snip subsystem relies on it to end its session. That was so before.
--------------------------------------------------------------------------------
SNIP OVER SSH: A CHANNEL THE CLIENT CLOSED FIRST
================================================================================
52. BEHAVIOUR CHANGE - a TsnipServer did not complete the close of a snip
channel that the client closed first, and did not close a channel
whose snip session ended without a close from either side
A snip connection over SSH runs one snip session on one SSH session
channel (entry 38). When the client closes the channel first -
TsnipClient.Stop and TsnipClient.Free both do - the server answers its
CHANNEL_CLOSE at once and leaves the channel for its consumer, the snip
connection, to complete (entry 50).
THE STEP THAT FAILED is the end of the snip session. The connection
closed its channel only if it still counted as up, that is while the
channel had not been closed. So it completed nothing: when the client's
CHANNEL_CLOSE arrived before the session had read the client's snip
close message, or came without one. The channel then kept its place in
the connection's table, and counted against SSHServer.MaxChannels, until
the SSH connection closed. A client that keeps its SSH connection and
stops and starts its snip channel (TsnipSSHClient.Stop and Start) was
refused a channel once the table was full: Start raised EsnipClosed,
"the SSH channel settled in state csClosed instead of csConnected".
Measured with MaxChannels 8: channels that the client closed without a
snip close message were refused from the ninth on, every time, on
Win32, Win64 and Linux64. With TsnipSSHClient.Stop and Start, which sends
the close message first, the ninth or tenth was refused every time on
Win32 and Win64; on Linux64 the session read the close message first,
and none was refused in six connections.
And when a session ended with the channel still open - a client whose
first frame was not a connect message, or that sent a frame the server
could not read - the connection left the channel open at both ends,
without a word to the client, until the SSH connection closed.
NOW the snip connection closes its channel when its session ends,
unless it has closed the channel itself. A channel the client closed
first is completed at once and its place freed. A channel neither side
had closed is closed by the server: THE CLIENT NOW RECEIVES A
CHANNEL_CLOSE where it received nothing before. A channel the connection
closed itself is not closed a second time; it waits for the client's
answering CLOSE, as before, so that its number is not given to a new
channel while that CLOSE is still on its way (RFC 4254, section 5.3).
NOT INVOLVED: the Snif login and the classes the server serves; the key
exchange and the ciphers; the client side (TsnipClient, TsnipSSHClient),
which is not changed; SFTP.
THE DISCRIMINATING TEST: set SSHServer.MaxChannels of a TsnipServer to
8. On one SSH connection to it, open a session channel, run the snip
handshake on it (TsnipClientSSHOctetConnection.Connect) and close the
SSH channel without a snip close message, and repeat. An affected
release refuses the ninth channel open; this one opens as many as you
like.
--------------------------------------------------------------------------------
SFTP: UPLOADING A FILE WITH THE SFTP CLIENT COMPONENT
================================================================================
53. FIXED - TstSFTPClient.PutFile without aAppend, to a server that speaks
SFTP version 3 as OpenSSH's sftp-server does, failed on its first
write, after its open had created the remote file empty or emptied the
file it was to replace
PutFile opens the remote file, writes the source to it in requests of
131072 octets, and closes it. In SFTP version 3 the open request
carries flags like those of open(2), and draft-ietf-secsh-filexfer-02
section 6.3 gives one of them as
"SSH_FXF_WRITE
Open the file for writing. If both this and SSH_FXF_READ are
specified, the file is opened for both reading and writing."
THE STEP THAT FAILED is that open. Without aAppend, PutFile asked for
SSH_FXF_CREAT and SSH_FXF_TRUNC - create the file, or truncate the one
that is there - and not for SSH_FXF_WRITE. OpenSSH's sftp-server does
as it is asked: by its source it opens the file for reading only,
creating or truncating it, and hands back a handle. So the open
succeeded, and the first write on the handle was refused. Measured
against OpenSSH 9.5p2 for Windows, on Win32 and Win64:
- PutFile of 4 MB to a file that did not exist raised eSFTPStatusError
"Permission denied" on its first write and left an empty file;
- PutFile of 4 MB over a file of 4 MB + 64 KB raised the same and left
that file EMPTY: the open had truncated it before the write was
refused.
OpenSSH on a Unix system reports the refusal differently. By its source
(sftp-server.c; not measured here), a write on a descriptor open for
reading only fails with EBADF, which it reports as SSH_FX_NO_SUCH_FILE:
there the message is "No such file", about a file the same PutFile has
just created. Whether an existing file is emptied there too is up to
the system - POSIX leaves O_TRUNC unspecified on an open for reading
only - and was not measured.
On a release without the fix of entry 46, a PutFile of 32731 octets or
more raised eSSHTransportError "Too large buffer" on its first write
instead, by the code after the same open; so there this defect showed
as itself only for smaller files.
A server that speaks SFTP version 5, as TstSSHServer's SFTP subsystem
does, was not affected: PutFile asks it for write access in a field of
its own (but see NOT CHANGED after entry 56). The SFTP Client demo
uploads with PutFile without aAppend, so by its code its upload failed
the same way against an OpenSSH server; the demo needs no change.
Now PutFile without aAppend asks for SSH_FXF_WRITE, SSH_FXF_CREAT and
SSH_FXF_TRUNC.
THE DISCRIMINATING TEST: PutFile without aAppend to OpenSSH's
sftp-server. An affected release raises eSFTPStatusError on the first
write - "Permission denied" from a Windows server, and by OpenSSH's
source "No such file" from a Unix one - and the remote file is there
and empty; this release uploads the file. On either release PutFile
with aAppend onto an existing file uploads it (measured), and so does
tSFTPTransport.OpenFile with [fo3Write, fo3Create, fo3Truncate]
followed by WriteFile: code that opens the file itself was never
affected.
NOT INVOLVED: the path, the file's permissions on the server and the
rights of the user logged in, whatever the message says; SSH,
authentication and the channel; GetFile, Size and CmpFile, which open
with SSH_FXF_READ.
54. FIXED - TstSFTPClient.PutFile of a source of 2 GiB or more either never
returned, having sent nothing, or sent a part of the source and
returned as if it had sent all of it
Before each write request PutFile works out how much of the source is
left, Size - Position, a 64-bit number, and sends up to 131072 octets
of it. It put that number into a 32-bit integer before it capped it,
so of a number above 2^31 - 1 only the low 32 bits were left, read as
a signed number. With r the number of octets to send modulo 4 GiB
(2^32):
- r below 2 GiB: PutFile sent the first r octets and returned without
raising, the rest unsent;
- r = 0 (4 GiB, 8 GiB, ...): it returned at once, having sent nothing;
- r of 2 GiB or more: it never returned. It went round its loop
without sending anything, and kept a processor busy doing so.
So only a source under 2 GiB was uploaded whole. Measured on Win32 and
Win64, with a source that computes its octets and an SFTP server inside
the test program: a source of 2^32 + 5 octets went out as one write of
5 octets and PutFile returned; one of 2^32 octets sent nothing and
returned; one of 3 GiB had not returned after 20 seconds (by the code,
having sent nothing). The open, and with it the truncation of an
existing file, came first in each case. With aAppend the same applied
to what was left from the source's position.
Now PutFile keeps that number in 64 bits.
THE DISCRIMINATING TEST: PutFile of a file of 3 GiB does not return and
the server receives no write; PutFile of a file of 5 GiB returns
normally with its first GiB on the server. Both releases upload a file
of less than 2 GiB in full.
NOT INVOLVED: the protocol version and the server; GetFile.
55. BEHAVIOUR CHANGE - TstSFTPClient.PutFile with aAppend, to a server
that speaks SFTP version 3, creates the remote file when it does not
exist, as it always did with version 5
With aAppend PutFile does not truncate: it writes the source from its
current position to the same offset in the remote file, so a source
positioned where the remote file ends appends to it. To a version 5
server it asked to open the file or create it (SSH_FXF_OPEN_OR_CREATE,
draft-ietf-secsh-filexfer-05 section 6.3.1). To a version 3 server it
asked for SSH_FXF_WRITE alone, and a file that did not exist was
refused: measured against OpenSSH 9.5p2 for Windows, eSFTPStatusError
"No such file". Now it asks for SSH_FXF_CREAT as well, and version 3
behaves as version 5 does. To an existing file nothing changes: a
source of 4 MB positioned after its first 2 MB, put with aAppend onto a
file holding those 2 MB, made the file whole, before and after.
What changes for existing code: with aAppend, to a version 3 server, a
missing remote file is created instead of raising. Code that relied on
that exception to learn whether the file exists must ask first;
TstSFTPClient.Size raises eSFTPStatusError for a file that does not
exist.
The comment on PutFile's declaration said that aAppend opened the file
"for appending to existing content". It now says what PutFile does,
which is not changed: each request goes to the offset in the remote
file that equals its position in the source.
56. BEHAVIOUR CHANGE - TstSFTPClient.PutFile raises eSFTPClientError when
the server answers a write with SSH_FX_EOF, instead of going on with
the next write and returning as if the file were complete
tSFTPTransport.WriteFile raises eSFTPStatusError for every status a
server can answer a write with except two: SSH_FX_OK, for which it
returns True, and SSH_FX_EOF, for which it returns False. PutFile did
not look at the result, so a write answered with SSH_FX_EOF was lost
without a word: PutFile went on with the next request and returned
normally, and the remote file had a hole - zeros, or with aAppend what
was there before - where those octets should have been. Measured on
Win32 and Win64, with a server inside the test program that answered
the second of four writes with SSH_FX_EOF, speaking version 3 and then
version 5: PutFile sent all four and returned, and the server had
written 274489 of the 405561 octets.
The drafts give SSH_FX_EOF to reads and directory listings.
draft-ietf-secsh-filexfer-02, section 7:
"SSH_FX_EOF
indicates end-of-file condition; for SSH_FX_READ it means that
no more data is available in the file, and for SSH_FX_READDIR
it indicates that no more files are contained in the
directory."
By their code, neither OpenSSH's sftp-server nor TstSSHServer's SFTP
subsystem ever answers a write with SSH_FX_EOF - they give it to reads
and directory listings only - so against them this could not happen;
it takes a server that answers a write that way.
Now PutFile raises eSFTPClientError, "Unable to write to file <name>:
the server answered the SSH_FXP_WRITE request at offset <n> with
SSH_FX_EOF", sends nothing more, and closes the handle; the remote file
holds what was written before offset <n>. What changes for existing
code: a PutFile that returned may now raise, and only when the upload
was incomplete.
NOT CHANGED, for entries 53 to 56:
- tSFTPTransport, including OpenFile and WriteFile and what WriteFile
returns: a program that opens and writes through the transport
itself gets what it asks for, as before.
- GetFile, Size and CmpFile open for reading - SSH_FXF_READ, or
SSH_FXF_OPEN_EXISTING in version 5 - which was right.
- THE ACCESS A VERSION 5 SERVER IS ASKED FOR. PutFile asked a version 5
server for write access with the wrong number, 0x00000804 where
ACE4_WRITE_DATA | ACE4_WRITE_ATTRIBUTES is 0x00000102, and GetFile,
Size and CmpFile for read access with 0x00000401 where ACE4_READ_DATA
| ACE4_READ_ATTRIBUTES is 0x00000081. That is a separate defect, not
changed by these entries: entry 63 changes it.
- The legacy unit stSFTPClient, which no longer ships, has the same
PutFile and is not changed.
--------------------------------------------------------------------------------
SSH CHANNELS ON ARM: READING WHAT HAS ARRIVED
================================================================================
57. FIXED - on ARM processors, a program reading an SSH client channel while
more was arriving could still be handed bytes that were not yet written:
entry 44 put the storing of a packet in order, this entry the reading
Since entry 44, the thread that reads the SSH connection copies each
packet into the channel's buffer first and counts it as waiting after. A
reader on another thread asks RecvLength how much is waiting, and Recv -
or InputStream, on a client channel - then reads that much from the
buffer.
THE STEP THAT COULD FAIL is the reader's. An ARM processor may perform a
read that comes later in a program before an earlier one, unless the
program tells it not to, and RecvLength did not: it read the count as an
ordinary read. So the reads of the buffer that follow it in Recv could be
performed first and return what the buffer held before the packet was
copied in - zeros, or bytes of the previous window once the window had
been adjusted - while the count, read after them, already included the
packet. That is entry 44's symptom: the number of bytes right, some of
them not the ones sent, and nothing reported. On x86 and x64 processors
reads take effect in program order, so Win32, Win64, Linux64 and macOS on
Intel were not affected, and entry 44 alone was the whole fix there.
Now RecvLength reads the count with acquire ordering: on ARM the read is
followed by a memory barrier (the DMB instruction), and the reads of the
buffer are performed after it. On Windows the generated code is the same
as before.
WHO. A program reading a channel on another thread than the
connection's, as in entry 44 - an application reading a channel of
TstSSHSocketClient or TstSSHClient, and the SFTP client - built for
Android (32- or 64-bit), iOS, the iOS simulator on Apple silicon, or
macOS on Apple silicon. The server's end of a channel has the same
change, but StreamSec.SSH.ServerChannel compiled only for Windows and
Linux64, both x86-64, until entry 87, so no server was affected; snip
over SSH (TsnipSSHClient) uses that unit and could not be built for ARM
either.
HOW IT WAS FOUND. From the code and the ARM architecture's ordering
rules, and confirmed in the code the compilers generate: for Android,
iOS and macOS on ARM, Delphi 13 compiles the old read of the count as a
plain load with no barrier, and the new one as a load followed by DMB;
so do 10.4 Sydney for Android and iOS and 11 Alexandria for macOS on ARM.
It was not seen to fail: no ARM device was available to run a transfer
on, before or after.
THE DISCRIMINATING TEST: none that fails on demand. What separates this
from entry 44 is the processor: with a release that has entry 44, wrong
bytes read from a channel on x86 or x64 are not this defect.
PLATFORMS. Measured on Win32, Win64 and Linux64, where the fix changes
nothing a program can observe: entry 44's test - 16 MB transfers read
while they arrive, at both ends of a channel, through a window larger
than the transfer and through a 256 KB one - got none of 16 transfers
wrong on each. Compiled, and not run, for the ARM targets above.
NOT INVOLVED: storing the packet (entry 44), the window and its
adjustment, the network, the ciphers and MACs, and port forwarding, whose
channels are read on the connection's own thread.
NOT CHANGED: what RecvLength, Recv and InputStream return.
InterlockedGet in StreamSec.SSH.Types still makes an ordinary read for
its other callers; the unit gains InterlockedGetAcquire. The mark a
channel sets when the peer sends SSH_MSG_CHANNEL_EOF, and a channel's
State when it opens, are put in order by entry 60. The legacy units
stSSHClientChannel and stSSHServerChannel, which no longer ship, are not
changed.
--------------------------------------------------------------------------------
THE CIPHER COMPONENT: DECRYPTING TO A STREAM WITH bpmStrSecII AND bpmCTS
================================================================================
58. BEHAVIOUR CHANGE - with PaddingMode bpmStrSecII, TstCipher.DoneToDst
refused almost every message DecryptToDst had decrypted and added 32
zero octets to the rest; with bpmCTS it raised ePaddingError "Buffer
too small" in many splits, and in some wrote past the end of a buffer
bpmStrSecII and bpmCTS are the two paddings whose ciphertext is exactly
as long as the plaintext, whatever its length: bpmStrSecII, StreamSec's
own, in CBC and ABC, and bpmCTS, the library's ciphertext stealing, in
ECB, CBC, CFB, OFB, CTR and ABC. The library never chooses either; a
program does, with PaddingMode on a TstCipher or BlockPaddingMode on a
cipher. Both keep the unfinished end of the message themselves while it
is decrypted - bpmStrSecII a partial last block, bpmCTS the last one or
two blocks - and DoneToDst has the padding finish that end. This is the
same on every TstCustomCipherComponent. Entry 43, which made
DecryptToDst right however a message is split across calls, left these
two paddings out and said so.
THE STEP THAT FAILED WITH bpmStrSecII is that finishing, in two ways:
- The padding finished a partial last block only when DoneToDst handed
it over, and refused one it already held. DecryptToDst passes every
octet on to the padding except those it keeps back for DoneToDst, and
with bpmStrSecII it keeps back only as many as the padding holds at
the time: none, in the first call. So a message that did not end on
a block boundary was refused - DoneToDst returned False and set the
stream back - in one call and in almost every split.
- A message that did end on a block boundary was accepted, but the
padding told DoneToDst that it had decrypted as many octets as there
was room for, two blocks, and DoneToDst wrote them - zero octets -
after the plaintext.
Measured with AES-128 in CBC, key, IVector and plaintext all zero:
- 0, 16 or 32 octets in one call: the plaintext and 32 zero octets,
DoneToDst True.
- 17 or 33 octets in one call, or 33 given as 20 and 13 or as 32 and 1:
nothing, DoneToDst False.
- 33 given as 1 and 32: right. After the first call the padding held
one octet, so DecryptToDst kept one back; such splits worked by
chance.
THE STEP THAT FAILED WITH bpmCTS is the room DoneToDst gave the padding
for the end of the message: two blocks, 32 octets with AES. Besides the
one or two blocks it held, the padding had to write out what
DecryptToDst had kept back for it, up to two blocks more. When that did
not fit it raised ePaddingError, "Buffer too small" - for 33 octets
given as 16 and 17 or as 17 and 16, 64 as 32, 16 and 16, and 100 as 40
and 60, among others.
AND IT WROTE PAST THE END OF BUFFERS. When the padding held two whole
blocks and was given more octets, it counted the room it needed one
block short, and wrote up to one block beyond the room it had been
given:
- In DoneToDst. 64 octets given as 16, 16 and 32 came out right, with
DoneToDst True, after the last 16 had been written past the end of
DoneToDst's buffer on the heap and read back from there. On Win64
nothing noticed; on Win32 the next decryption in the same program
raised EAccessViolation, and with 3DES in CBC the heap failed later
with EInvalidPointer. valgrind on Linux64 reports the write itself.
- In tDecryptStream, the deprecated SET3 reader, which gives the cipher
65,536 octets of room for each read of up to 65,536 octets from its
data stream. When one read returned exactly as many octets as filled
the padding's two blocks and the next the full 65,536, the padding
wrote 16 octets past that room, a buffer on the stack. Measured with
a 70,000-octet container read through a stream that returned 16, 16
and then 65,536 octets: on Win32 the program jumped to an address
made of four octets of the plaintext and raised EAccessViolation; on
Win64 the same run read the plaintext. A TMemoryStream or TFileStream
does not return such short reads in the middle of the data.
- In a program's own calls to EncryptToBuf, DecryptToBuf, EncryptToPtr
or DecryptToPtr on a cipher with bpmCTS, given no more room than the
padding claimed to need.
What was written past the end was the plaintext of the message being
decrypted, or through EncryptToBuf the ciphertext. Who can choose those
octets, and what could be done with them, has not been traced.
NOW:
- bpmStrSecII finishes a partial last block whether DoneToDst hands it
over or it holds it already, and reports the octets it decrypted.
- bpmCTS counts its room right, also when it holds two whole blocks: a
call given too little returns False before it writes anything.
- DoneToDst gives the padding room for what DecryptToDst kept back and
two blocks more.
Any split then gives the same plaintext and True as a single call.
Checked on Win32, Win64 and Linux64 with AES-128 - bpmStrSecII in CBC
and ABC, bpmCTS in ECB, CBC, CFB, OFB, CTR and ABC - and with 3DES:
bpmStrSecII in CBC and ABC, bpmCTS in CBC. ABC with AES was checked on
Win32 only; its class is in stRijndael, which is not in the package and
compiles for Win32 alone. Neither padding has a published test vector,
so the reference is the one-shot EncryptStr and DecryptStr, which give
each other's input back and gave the same ciphertext before as now. For
22 messages of 0 to 257 octets: every split into up to three calls,
calls of 0 octets included (into two above 65 octets), both ways;
DecryptStreamToDst with every BufferSize; one component keyed again
message after message and after a message abandoned half way; messages
bpmCTS cannot take, shorter than a block, refused with nothing left in
the stream; and the cipher's own EncryptToBuf and DecryptToBuf with
every destination exactly as large as its piece. bpmPKCS5 and bpmNone
ran alongside as controls. All 500,316 checks on Win32 and 424,406 on
Win64 and Linux64 as expected, and valgrind reports no invalid access.
Before, with fewer splits, it reported 18,012 in the ciphers' own
EncryptToBuf calls, and in DoneToDst 210 after DecryptToDst and 355
after DecryptStreamToDst. Before,
every split gave the plaintext in 424 of 12,542 cases with bpmStrSecII
and AES, and in 4,735 of 12,266 with bpmCTS and AES in each mode; with
3DES in CBC and bpmCTS the run crashed. The checks of entries 43 and 49
still pass, all 72,567 and all 85,783.
THE DISCRIMINATING TESTS:
- Create a TstCipher, set Algorithm to caRijndael, Mode to cmCBC and
PaddingMode to bpmStrSecII, key it with 16 zero octets and set an
IVector of 16 zero octets. Set DestinationStream to an empty
TMemoryStream, call DecryptToDst with 0 octets, then DoneToDst. An
affected release leaves 32 zero octets in the stream, this one none;
both return True.
- The same with PaddingMode bpmCTS: EncryptStr 33 zero octets, then on
a second such component call DecryptToDst with the first 16 octets of
the ciphertext, then with the last 17, then DoneToDst. An affected
release raises ePaddingError, "Buffer too small"; this one writes the
33 zero octets and returns True.
WHAT EXISTING CODE SEES DIFFERENTLY, apart from right output:
- DoneToDst returns True where it returned False (bpmStrSecII) or
raised ePaddingError (bpmCTS).
- A bpmStrSecII message that ends on a block boundary comes out without
the zero octets that followed it: 32 with AES.
- iCipherMAC.VerifyFinalBuf on a bpmStrSecII cipher finishes a partial
block that earlier DecryptToBuf calls left with the padding, which it
refused, and for a message ending on a block boundary returns in
aDstCount the octets it decrypted, not the room it was given.
DecryptStr gives it exactly the room the message needs, and so was
right before as now.
- EncryptToBuf, DecryptToBuf, EncryptToPtr and DecryptToPtr on a bpmCTS
cipher return False where they wrote up to one block past the room
they were given.
- tDecryptStream reading a bpmCTS container through the short reads
above raises eCipherError, "Unable to encrypt buffer", before it
returns any plaintext.
NOT INVOLVED: the ciphers and what they compute; EncryptToDst,
EncryptStr and DecryptStr, which gave the same output before as now,
EncryptToDst in every split, without an invalid access; the in-place
Encrypt and Decrypt, which do not go through the padding; and every
other padding. TLS, SSH, CMS, PKCS#8 and PKCS#12 never use bpmStrSecII
or bpmCTS.
NOT CHANGED:
- bpmPKCS5 counted its room one block short in the same way, and so did
bpmZeroes, bpm10s and bpmSSL3, which share the code: once one held a
whole block, a call of the cipher's DecryptToBuf whose octets did not
end on a block boundary could write up to one block past the room it
claimed to need. DecryptToDst and DecryptStr gave it enough room; a
program's own calls might not. Entry 71 fixes it.
- tDecryptStream's Done raises eCipherError, "Unable to read MAC from
data stream", after a bpmCTS container has been read to the end,
before as now.
--------------------------------------------------------------------------------
INTERFACES DECLARED WITH ANOTHER INTERFACE'S GUID: LEGACY NAMESAKES THAT NO
LONGER MATCH
================================================================================
stMPPKTypes and StreamSec.DSI.PKTypes declare many interfaces under the same
name and the same GUID, on purpose: they are one interface, and a key of either
family answers it. That holds only while the two declarations stay alike. For
three of them the DSI declaration changed and the legacy one did not, so the
GUID went on joining two interfaces that were no longer the same.
59. BEHAVIOUR CHANGE - the legacy iSignPublicKeyIF, iSignPrivateKeyIF and
iDLKey in stMPPKTypes get GUIDs of their own, and a key no longer
answers its DSI namesake's GUID with the legacy interface or the other
way round
- iSignPublicKeyIF and iSignPrivateKeyIF, the RSA key interfaces, have
SaltLen in StreamSec.DSI.PKTypes, placed after MGFHashAlg, and the
legacy interfaces do not. Asked for the legacy interface, an RSA key
answered with its DSI one, so every member after MGFHashAlg reached the
wrong method: reading SignEncoding returned the salt length, setting
MGFHashAlg read the sign encoding, and setting SignEncoding set
MGFHashAlg. On a public key, reading EncryptEncoding called SetSaltLen,
which stored whatever value happened to be at hand as the key's salt
length, and setting EncryptEncoding set SignEncoding.
- iDLKey returns different types in the two units. Its Pool is
iSsMPDLArith in stMPPKTypes and iDSIDLArith in StreamSec.DSI.PKTypes,
and the two share nothing after QueryInterface, _AddRef and _Release.
Its Params is the iDiscreteLogField of stMPArithTypes in one and of
StreamSec.DSI.PKTypes in the other, which are different interfaces. And
its SignScheme can return dlssaDSAFixedTime or dlssaEdDSA, which the
legacy tDLSignatureScheme does not have. Asked for the legacy iDLKey, a
DSA, Diffie-Hellman, ECDSA or EdDSA key answered with its DSI one, and
the Pool it then handed out was the DSI arithmetic, which a caller of
the legacy interface calls as the legacy one.
The same went the other way: a key class from the legacy units,
implementing one of these, answered the DSI interface with the legacy
one.
Each of the three legacy interfaces now has a GUID of its own. A key
answers the interfaces it implements, and no longer those of the other
family.
IF YOUR CODE asks a key for one of these interfaces and the name resolves
to stMPPKTypes - it comes after StreamSec.DSI.PKTypes in the uses clause,
or is the only one of the two - name the one in StreamSec.DSI.PKTypes
instead, or put StreamSec.DSI.PKTypes after stMPPKTypes. The keys the
library creates answer those as before.
THE DISCRIMINATING TEST: Supports(Key, stMPPKTypes.iDLKey) for the public
key of a TstECDSAKey. An affected release returns True, this one False.
NOT INVOLVED: the library. Nothing in it asks a key of one family for an
interface of the other. The one place that asks for the legacy
iSignPublicKeyIF at all, the constructor of tMPPrivateKeyIF in
stMPPKTypes, is reached only from the legacy key manager
stPkixKeyManager, which no longer ships. The DSI interfaces keep their
GUIDs. The other interfaces the two units share - iSignKey,
iSignPublicKey, iSignPrivateKey, iSignKeyDL, iMPPK, iMPPublicKey and six
more - are declared alike in both, down to the types they name, and are
still one interface each.
--------------------------------------------------------------------------------
SSH CHANNELS ON ARM: THE PEER'S EOF, THE WINDOW, AND OPENING A CHANNEL
================================================================================
60. FIXED - on ARM processors, an SSH channel could report the end of the
peer's data while data the peer sent before it was still unread, and a
program that saw a channel open could send on it before the channel's
details had reached it: entry 57 put one value a channel's threads share
in order, this entry the others
Entry 57 is about one value: the count of what has arrived on a channel,
which the thread that reads the SSH connection sets and a reader on
another thread reads. The connection's thread sets three more values for
other threads to read, and each had the same flaw. An ARM processor may
make an ordinary store visible to other processors before an earlier
one, and may perform a read that comes later in a program before an
earlier one, unless the program tells it not to. None of the three did.
THE END OF THE PEER'S DATA. When the peer sends SSH_MSG_CHANNEL_EOF, the
connection's thread marks the channel - the mark PeerEOF reports - after
it has counted every packet the peer sent before it. When nothing is
waiting, Recv and InputStream read the mark and, if it is set, read the
count again to see that nothing is left; a program can do the same with
PeerEOF and RecvLength. The mark was set with an ordinary store and read
with an ordinary read, so on ARM a reader could find it set and still
read a count without the peer's last packets. Recv then returned what it
had read so far, possibly nothing, and InputStream returned nil, as at
the end of the data, while those packets were still in the channel's
window. A program that stopped reading there lost the end of what the
peer sent, and nothing was reported; one that called Recv again got it.
THE WINDOW AT THE PEER'S EOF. When a Recv has read everything the
channel's window held, it asks the peer for more with
SSH_MSG_CHANNEL_WINDOW_ADJUST, unless the peer has sent its EOF: then it
overwrites the window with zeros and releases it. At the EOF the
connection's thread sets the mark first and then closes the window where
the data ends. Recv read where the window ends and then the mark, with
ordinary reads, so on ARM it could find the window closed and the mark
not yet set. It then sent a WINDOW_ADJUST after the peer's EOF, which is
harmless on the wire, and the window was never overwritten: what the
peer had sent in it was left in memory, also after the channel was
freed.
OPENING A CHANNEL. When the peer confirms a channel, the connection's
thread stores the peer's number for the channel, the peer's window and
its maximum packet size, and then sets State to csConnected. A program
waits for State to leave csConnecting and then sends, and so do the
library's SFTP client and port-forwarding clients. State was set
with an ordinary store and read with an ordinary read, so on ARM a
program could find csConnected and still read the channel's details as
they were before the confirmation. Its first Send could then send nothing
and return 0, send empty data messages until the packet size reached it,
or send its data to channel number 4294967295, which the peer never
assigned.
THE SERVER'S TEARDOWN. Since entry 50 a TstSSHServer connection waits,
before it is freed, until every subsystem thread that used it has ended.
It read their count with an ordinary read, so on ARM the teardown could
read what a thread had left in the connection as it was before that
thread's last changes. StreamSec.SSH.ServerChannel compiled only for
Windows and Linux64, both x86-64, until entry 87, so this, and the
server's end of the three above, affected no program that could be
built.
Now the mark and State are each set with release ordering - on ARM a DMB
instruction before the store - and read with acquire ordering - a DMB
after the read - wherever what the reader does next depends on them.
Where the window ends and the count of subsystem threads are read with
acquire ordering; their stores already had release ordering. In
StreamSec.SSH.Types, InterlockedGetAcquire gains an overload for
Boolean, and InterlockedSet for a Boolean, off Windows, puts a memory
barrier before its store. On Windows the generated code does what it did
before; on Linux64 the barriers are MFENCE instructions.
WHO. A program built for Android (32- or 64-bit), iOS, the iOS simulator
on Apple silicon, or macOS on Apple silicon that reads an SSH client
channel on another thread than the connection's, or waits for a channel
to open and then sends on it: an application using a channel of
TstSSHSocketClient or TstSSHClient, TstSFTPClient, and the
port-forwarding clients TstSSHForwardingClient and
TstSSHForwardingClientSocket. On x86 and x64 processors stores become
visible, and reads are performed, in program order, so Win32, Win64,
Linux64 and macOS on Intel were not affected. Snip over SSH
(TsnipSSHClient) is not among them: it uses StreamSec.SSH.ServerChannel
and so could not be built for ARM either until entry 87.
HOW IT WAS FOUND. Reviewing the channels after entry 57, from the code
and the ARM architecture's ordering rules, and confirmed in the code the
compilers generate. For Android, iOS and macOS on ARM, Delphi 13 compiled
the mark's store as an ordinary byte store, the reads of the mark, of
where the window ends and of State as ordinary loads, and the store of
State with nothing to keep it after the stores of the channel's details.
With this entry each has its DMB, in those compilers and in 10.4 Sydney
for Android and iOS and 11 Alexandria for macOS on ARM, and the server's
end, which compiles for ARM since entry 87, has the same. It was not
seen to fail: no ARM device was available before the fix.
THE DISCRIMINATING TEST: none that fails on demand. On x86 and x64, an
end of data reported early, a WINDOW_ADJUST after the peer's EOF, or a
first send that goes wrong is not this defect.
PLATFORMS. Measured on Win32, Win64 and Linux64, where the fix changes
nothing a program can observe: entry 44's test - 16 MB transfers read
while they arrive, at both ends of a channel, through a window larger
than the transfer and through a 256 KB one - got none of 16 transfers
wrong on each; the tests of entries 36 and 40 on Win32 and Win64, and a
port-forwarding self-test on Win32 and Linux64, passed as before. Run
on macOS on an Apple M1 since the fix, with entries 87 and 88: entry
44's test got none of 16 transfers wrong, and the tests of entries 36,
40, 46, 65, 69, 76 and 84 passed - entry 84's reads a client channel up
to the peer's EOF - and, with entry 91 as well, so did the
port-forwarding self-test. Compiled, and not run, for Android and iOS.
NOT INVOLVED: storing and counting what arrives (entries 44 and 57), the
window the peer grants and its counting, the network, the ciphers and
MACs.
NOT CHANGED: what Recv, InputStream, RecvLength, PeerEOF, State and Send
return, other than in the cases above. InterlockedGet in
StreamSec.SSH.Types still makes an ordinary read. The legacy units
stSSHClientChannel and stSSHServerChannel, which no longer ship, are not
changed.
--------------------------------------------------------------------------------
SSH PORT FORWARDING: DATA TO A TCP END THAT FALLS BEHIND
================================================================================
61. BEHAVIOUR CHANGE - a forwarded connection whose far TCP end read more
slowly than the SSH side delivered lost data, kept a processor core
busy, or ended; the data now waits for room, up to the new SendTimeout
The port-forwarding components carry one TCP connection over one SSH
channel each. TstSSHSenderControllerSocket is the server side of local
("-L") forwarding: it connects out to a target and writes to it what
arrives on the channel. TstSSHListenerControllerSocket is the server
side of remote ("-R") forwarding: it listens, and writes to the TCP
client that connects what arrives on the channel.
TstSSHForwardingClientSocket is the client side of remote forwarding:
it connects to a target and writes to it what arrives on the channel.
Each writes on the thread that reads the SSH connection.
THE STEP THAT FAILED is that write. It was a single send. A socket that
does not wait for room - every socket on the POSIX platforms, and on
Windows the accepted socket of a "-R" listener, and any socket
WaitForData has been called on - takes only part of what is offered once
its send buffer is full, or none of it, and reports how much it took. A
would-block, reported as -1, was read as a very large unsigned count and
moved the write position BACKWARDS, so the component sent bytes it had
already sent and then read before the start of its buffer; where the
socket merely took part of the data, the rest was dropped. Either way the
far end received the stream corrupted or cut short, and no error was
raised. On Windows the thread then offered the same full socket again at
once, without waiting, so a forwarded connection to a peer that had
stopped reading held a processor core busy.
Now the rest of what was read follows the part the socket took, and when
the buffer is full the write waits for room and tries again with the
same bytes. A far end that reads slowly slows the forwarding down instead
of losing data or spinning.
SendTimeout, a new published property of all three components, in
milliseconds, bounds the wait for a far end that has stopped reading
altogether. It is 30000 by default; 0 waits without a limit. When not one
byte has been taken for that long, the forwarded TCP connection is
closed and then the SSH channel, while the SSH connection itself and its
other channels go on. The time counts from the last byte taken, so a far
end that reads slowly but keeps reading never reaches it. A change
applies to forwarded connections opened after it.
WHILE THOSE BYTES WAIT, THE SSH CONNECTION WAITS WITH IT. The write runs
on the thread that reads the SSH connection, so until it is done, or
SendTimeout runs out, that connection handles nothing else it receives,
for this channel or any other on it. A forwarded connection to a peer
that has stopped reading therefore holds up the whole SSH connection for
up to SendTimeout; lower it where a forwarded peer may stall. Freeing the
SSH server, or deactivating it with CloseAllOnDeactivate True - the
default - ends a waiting forwarding write at once.
THE DISCRIMINATING TEST: forward a TCP connection over an SSH connection
of this library, our client and our server, and have the sending end put
several megabytes on it - more than a socket buffer and more than the SSH
window - while the far TCP end stops reading for a few seconds; make the
channel window larger than the transfer, so the SSH window never holds
the sender up, and give the bytes a pattern that depends on their
position. An affected release delivers a few hundred kilobytes and then
the wrong bytes or nothing, and on Windows a core runs at full while the
far end is stopped; this one delivers every byte once and in order once
the far end reads again. With the far end never reading and SendTimeout
at, say, 1500 ms, an affected release never ends the connection while
this one closes it 1.5 s after the last byte and carries a new forwarded
connection on the same SSH connection afterwards. So a forwarded transfer
to a slow or paused TCP end that arrives corrupted, cut short, or with a
core pinned, is this defect.
NOT INVOLVED: the SSH channel window. That limits how much the peer may
send before its application has read it; the buffer that filled here is
below it, in the operating system, and fills whenever the far TCP end is
slower than the SSH side delivers, whatever the window. The key exchange,
the ciphers and the MACs were not involved, nor was the other direction -
what a forwarding component reads from its TCP end and sends on the
channel, which is the next entry.
NOT CHANGED: a channel that is not a forwarded one, and the SSH
connection's own sends, which entry 36 covers. The "-L" client side opens
its channel with tSSHClientChannel.ConnectToHost and reads it in the
application, with no forwarding component and no socket of the library's
between; it is unchanged. The legacy units stSSHDirectSenderSocket,
stSSHForwardedListenerSocket and stSSHForwardingClientSocket, which no
longer ship, have the same defect and are not changed.
--------------------------------------------------------------------------------
SSH PORT FORWARDING: DATA FROM A TCP END WHEN THE CHANNEL WINDOW IS SHUT
================================================================================
62. FIXED - a forwarded connection lost the data it read from its TCP end
when the SSH peer left the channel's window shut for about a second
The same three components carry the other direction too: each reads what
arrives on its TCP connection and sends it on the SSH channel -
TstSSHSenderControllerSocket and TstSSHForwardingClientSocket from a
target they connected to, TstSSHListenerControllerSocket from the TCP
client of its listener.
THE STEP THAT FAILED is that send on the channel. A channel sends only
while the peer's window has room, and gives up after about a second with
the window still shut, returning fewer bytes than it was given. The
forwarding thread passed each read to the channel with a single send and
did not look at how much it took, so whatever the channel had not sent
when the window stayed shut that long was read past and lost. The stream
the far end received was cut short, at a window boundary, and no error was
raised. The peer's window stays shut while the program at the peer's end
of the channel is not reading it - a forwarded connection whose other end
pauses, or whose window is small and whose reader is momentarily behind.
Now the forwarding thread sends all of what it read, waiting for the
window to reopen for as long as the channel is open, so the send finishes
once the peer reads again. It stops early only if the channel closes or
the SSH server is shutting down, which end the forwarded connection.
THE DISCRIMINATING TEST: forward a TCP connection over an SSH connection
of this library, our client and our server, with channel windows much
smaller than the transfer - say the 64 KB the components would negotiate
with a peer that set DefaultWindowSize low - and have the TCP end send
several megabytes while the program at the far end of the channel stops
reading for a few seconds; give the bytes a pattern that depends on their
position. An affected release delivers about one window and stops; this
one delivers every byte once and in order once the reader catches up. So
a forwarded transfer FROM a TCP end that stops after roughly one window
of channel data when its channel reader falls behind is this defect.
NOT INVOLVED: the window adjustment of entry 40 and the read race of
entry 44, which are about the channel itself, not forwarding; a transfer
whose window was never shut for a full second was not affected. The key
exchange, the ciphers and the MACs were not involved, nor was the other
direction - what a forwarding component writes to its TCP end, which is
the previous entry.
NOT CHANGED: a channel that is not a forwarded one; a program that sends
on a channel with tSSHClientChannel.Send or through a subsystem already
gets back how much was sent and is unchanged. The legacy units
stSSHDirectSenderSocket, stSSHForwardedListenerSocket and
stSSHForwardingClientSocket, which no longer ship, have the same defect
and are not changed.
--------------------------------------------------------------------------------
SFTP VERSION 5: THE ACCESS RIGHTS ON THE WIRE
================================================================================
63. BEHAVIOUR CHANGE - TstSFTPClient and tSFTPTransport asked a server that
speaks SFTP version 5 for other access than they meant: PutFile asked
for ACE4_APPEND_DATA where it meant ACE4_WRITE_DATA and
ACE4_WRITE_ATTRIBUTES, and GetFile, Size and CmpFile did not ask for
ACE4_READ_ATTRIBUTES; version 5 ACL entries and a server's "supported"
extension were written and read with the same wrong numbers
An SFTP version 5 open request carries the access wanted in a field of
its own, desired-access. draft-ietf-secsh-filexfer-05 section 6.3.1:
"The 'desired-access' field is a bitmask containing a combination of
values from the ace-mask flags from section 5.7."
Section 5.7 lists those values, taken from NFS version 4. It begins
#define ACE4_READ_DATA 0x00000001;
#define ACE4_LIST_DIRECTORY 0x00000001;
#define ACE4_WRITE_DATA 0x00000002;
#define ACE4_ADD_FILE 0x00000002;
#define ACE4_APPEND_DATA 0x00000004;
#define ACE4_ADD_SUBDIRECTORY 0x00000004;
and further down gives ACE4_READ_ATTRIBUTES as 0x00000080 and
ACE4_WRITE_ATTRIBUTES as 0x00000100. The same numbers are the ace-mask of
each entry of an ACL in version 5 file attributes (section 5.7), and the
supported-access-mask a server may advertise in the "supported"
extension of its SSH_FXP_VERSION reply, which by section 4.4
"MAY be applied to the SSH_FXP_OPEN (Section 6.3.1) desired-access
field or the ace-mask field of an ACL."
In the library these rights are the set type tACEMask, a set of
tACEMaskEnum, in StreamSec.SFTP.Version5Types. THE STEP THAT WAS WRONG is
turning the set into that number and back. tSFTPTransport.OpenFile (the
overload for version 5) and tACLItem put the set on the wire as the
set's own bits, and tACLItem and tSupportedStructure read a number back
into the set the same way. Bit n of that number is the n-th member of
tACEMaskEnum, which is not the member's value in section 5.7: of the 17
members only acemReadData, the first, went out as its own value. No
order of the members could have made them agree, because section 5.7
gives two names one value three times - the same right, named for a
file and for a directory.
Measured on Win32 and Win64, with an SFTP server inside the test program
that records each request:
- PutFile, with or without aAppend, asks for [acemWriteData,
acemWriteAttributes]. It sent 0x00000804 - ACE4_APPEND_DATA and a bit
section 5.7 does not define - where ACE4_WRITE_DATA |
ACE4_WRITE_ATTRIBUTES is 0x00000102.
- GetFile, Size and CmpFile ask for [acemReadData, acemReadAttributes].
They sent 0x00000401 - ACE4_READ_DATA and a bit section 5.7 does not
define - where ACE4_READ_DATA | ACE4_READ_ATTRIBUTES is 0x00000081.
- An ACL entry whose ACEMask was [acemDelete] went out as 0x00001000
instead of ACE4_DELETE, 0x00010000. An entry received with the
ace-mask ACE4_WRITE_DATA was read as [acemListDirectory], one with
ACE4_READ_ACL as no right at all, and one holding only bits section
5.7 does not define (0xFFE0FE00) as seven rights, acemDeleteChild to
acemWriteOwner.
- A server advertising the supported-access-mask 0x00030183
(ACE4_READ_DATA, WRITE_DATA, READ_ATTRIBUTES, WRITE_ATTRIBUTES, DELETE
and READ_ACL) was reported by TstSFTPClient.ServerSupported.AccessMask
as [acemReadData, acemListDirectory, acemWriteNamedAttrs, acemExecute,
acemSynchronize].
WHO WAS AFFECTED. A program using TstSFTPClient or tSFTPTransport with a
server that speaks SFTP version 5. Version 3 has no access mask - its
open request carries flags like those of open(2) - so a program that
talks to OpenSSH's sftp-server, which speaks only version 3, was not
affected. TstSSHServer's SFTP subsystem, which speaks version 5, reads
desired-access by section 5.7's values and counts ACE4_WRITE_DATA or
ACE4_APPEND_DATA as asking to write, so it took the write request above
as one: our SFTP client and server worked together before this change
and do after it (measured: the test of our client against our server,
31 checks, passes before and after, on Win32). What another version 5
server made of a write request without ACE4_WRITE_DATA, or of a read
request without ACE4_READ_ATTRIBUTES followed, as in GetFile and Size, by
a request for the open file's attributes, was not measured: no other
version 5 server was at hand.
Now tSFTPTransport.OpenFile, tACLItem and tSupportedStructure convert
member by member. StreamSec.SFTP.Version5Types gains cACEMaskACE4, the
section 5.7 value of each tACEMaskEnum member, and the functions
ACEMaskToACE4 and ACE4ToACEMask. A set goes out as the values of its
members combined, so acemReadData and acemListDirectory both send
0x00000001. A number read gives every member that has one of its bits:
0x00000001 gives [acemReadData, acemListDirectory], so a program testing
for either name finds it. A bit section 5.7 does not define gives no
member.
WHAT CHANGES FOR EXISTING CODE:
- Each version 5 open request asks for the access its set names: PutFile
for ACE4_WRITE_DATA and ACE4_WRITE_ATTRIBUTES; GetFile, Size and
CmpFile for ACE4_READ_DATA and ACE4_READ_ATTRIBUTES; a call of
tSFTPTransport.OpenFile for what its aAccess names. A server that
decides by what it is asked for now decides on the access the program
meant.
- An ACL entry a program sends, in the attributes given to OpenFile or
SetStat, carries the rights its ACEMask names.
- ServerSupported.AccessMask, and the ACEMask of an ACL entry read from
the server, hold the rights the server sent, with both members of a
pair that share a value. A program that compared such a set with = to
a set holding one member of such a pair must test with in instead.
THE DISCRIMINATING TEST: the desired-access of the open request as the
server records it. On an affected release PutFile sends 0x00000804, and
GetFile, Size and CmpFile 0x00000401; this release sends 0x00000102 and
0x00000081. To OpenSSH's sftp-server both releases send the same open
requests.
NOT INVOLVED: the flags of a version 5 open request (tFileOpenFlags5:
SSH_FXF_CREATE_TRUNCATE, SSH_FXF_OPEN_EXISTING, SSH_FXF_OPEN_OR_CREATE
and the rest), which go out as the draft gives them (measured, before
and after); the ace-type and ace-flag of an ACL entry, whose tACEType and
tACEFlag members line up with section 5.7's values by their
declarations; version 3; SSH, authentication and the channel;
TstSSHServer's SFTP subsystem, which is not changed.
NOT CHANGED:
- tACEMask and tACEMaskEnum, and the sets TstSFTPClient asks for: only
their conversion to and from the wire.
- tSupportedStructure reads the extension names at the end of the
"supported" extension as a 32-bit length followed by the names.
Section 4.4 gives no such length:
uint32 supported-attribute-mask
uint32 supported-attribute-bits
uint32 supported-open-flags
uint32 supported-access-mask
uint32 max-read-size
string extension-names[0..n]
So TstSFTPClient's Connect raises when a server sends the extension
laid out that way: with no names, having read four octets past its
end, eSSHDecodeError "Buffer too short"; with the name md5-hash-handle,
eSSHFormatError "Unable to read data" (measured, with the server in
the test program). It is a separate defect, fixed in entry 75.
TstSSHServer's SFTP subsystem does not send the extension.
- The legacy units stSFTP5Types, stSFTPTransport and stSFTPClient, which
no longer ship, have the same conversion and are not changed.
--------------------------------------------------------------------------------
THE CIPHER COMPONENT: EncryptStr WITH INPUT ITS PADDING CANNOT FINISH
================================================================================
64. BEHAVIOUR CHANGE - TstCipher.EncryptStr raised ERangeError, "Range
check error", when PaddingMode bpmNone or bpmCTS could not finish the
input, and kept the input, so that the next call encrypted it in front
of its own
EncryptStr encrypts a whole message in one call and finishes it: it
pads the last block, or with bpmCTS steals ciphertext for it. Two
paddings cannot finish every message. bpmNone does not pad, so it
cannot finish a message that is not a whole number of blocks, except in
CFB, OFB and CTR, which need no whole blocks; bpmCTS cannot finish one
shorter than one block. The library never chooses bpmCTS; a program
does. bpmNone is the PaddingMode a new TstCipher starts with, and
setting Mode keeps it wherever it can serve the new mode - ECB, CBC and
ABC among them - so a program that sets Mode to cmCBC and not
PaddingMode encrypts without padding. This is the same on every
TstCustomCipherComponent, and on a TstSimplePKCEncryptor, which
encrypts through the TstCipher assigned to its Cipher property.
THE STEP THAT FAILED is where EncryptStr made room for the end of the
message. The cipher takes the input, encrypts the whole blocks and
holds the rest back for the padding; EncryptStr then asked the padding
how long the end would be. The padding answers -1 when it has nothing
to finish the input with, and EncryptStr added that to the length
encrypted so far. With fewer octets than one block, none of them
encrypted, that asked for a result of -1 octets, and the run-time
library refused it with ERangeError, "Range check error". The message
names neither the padding nor the input, and it is not a range check
that failed: no array was indexed out of bounds, a build without range
checking raises it just the same, and nothing was read or written
outside a buffer. With a block or more, 17 octets with AES, the length
came out one short of what had been encrypted, and the padding raised
ePaddingError, "Unable to process pending input" - after the whole
blocks had been encrypted, and their ciphertext was dropped. Measured
with AES, TwoFish and 3DES, the same on Win32 and on Win64:
- bpmNone, in ECB, CBC and ABC, and in cmSSH and cmSSHCTR: ERangeError
for fewer octets than one block, ePaddingError for more that are not
a whole number of blocks - 1 to 15 and 17 to 31 with AES and TwoFish,
1 to 7 and 9 to 15 with 3DES. In cmKeyWrap, whose block is 8 octets,
ERangeError for 1 to 7.
- bpmCTS, in ECB, CBC, CFB, OFB, CTR, ABC and cmKeyWrap: ERangeError
for 0 to 15 octets, 0 to 7 with 3DES and in cmKeyWrap.
- Neither with bpmNone in CFB, OFB and CTR, nor with bpmPKCS5,
bpmZeroes, bpm10s, bpmSSL3 or bpmStrSecII, which finish any length.
THE SECOND STEP THAT FAILED is what such a call left behind: the octets
the cipher held back stayed with it, and the next EncryptStr on the
component took them as the start of its own message, with no new
IVector asked for. With bpmCTS, EncryptStr of 15 octets raised, and
EncryptStr of another 15 returned 30 octets: both, encrypted as one
message. With bpmNone the refused octets went in front of each later
call until a call made them up to a whole number of blocks: of 2,001
calls of 10 octets on one component in CBC, 250 returned a ciphertext,
made in part of octets from calls that had raised. Of 60 messages of 16
to 48 octets, encrypted after a refused call of 1, 10 or 15 octets, none
came out as on a fresh component: with bpmCTS all 42 came out longer,
the refused octets encrypted in front, and with bpmNone all 18 raised
ePaddingError, though each was a whole number of blocks.
NOW:
- TstCipher.EncryptStr refuses such input before the cipher is given
any of it, with eSecComp: "EncryptStr: The input is not a whole
number of 16-octet blocks, and padding mode None does not pad it", or
"EncryptStr: The input is shorter than one 16-octet block, the least
that padding mode CTS can finish" - the texts of DoneToDst (entry
49), with the cipher's block size. Nothing is encrypted, kept or
given to the MAC, and no new IVector is needed: the component takes
the next call as though the refused one had not been made. The 60
messages above now come out as on a fresh component, those with
bpmNone as pyca/cryptography's AES gives them, and 2,001 refused
calls on one component leave nothing behind.
- The EncryptStr of a cipher used without the component (a tCipher)
raises ePaddingError in place of ERangeError, with the texts above,
before the cipher takes any of the input; so does the component when
a program has left input with the cipher through the component's
iCipher interface (EncryptToBuf and the like) and EncryptStr cannot
finish it. Entry 73 describes both.
THE DISCRIMINATING TEST: create a TstCipher, set Algorithm to
caRijndael and Mode to cmCBC and nothing else, call SetKeyStr with 16
octets, set an IVector of 16 octets, and call EncryptStr with 10
octets. An affected release raises ERangeError, "Range check error";
this one eSecComp with the first text above. Set up a second one the
same way but with PaddingMode bpmCTS before the key, call EncryptStr
with 10 octets, catch what it raises, and call it again with 10: an
affected release returns 20 octets, this one raises eSecComp again.
IF YOUR PROGRAM went on using the component after EncryptStr raised,
without setting a new IVector, what it encrypted next with bpmCTS, or
with bpmNone once the octets came to a whole number of blocks, carried
the octets of the call that raised at its front, and does not decrypt
to the message meant: encrypt those messages again. A program that
meant to pad sets PaddingMode, bpmPKCS5 for instance, before the key.
WHAT EXISTING CODE SEES DIFFERENTLY, apart from right output:
- eSecComp where EncryptStr raised ERangeError, and where it raised
ePaddingError, "Unable to process pending input", with bpmNone and a
block or more.
- A call after one that raised is not affected by it: where it raised
too, or returned the earlier octets with its own, it now behaves as
on a fresh component.
- In cmKeyWrap with bpmNone, EncryptStr of a length that is not a
multiple of 8 raises eSecComp; it returned an empty string, as it
does for every length there (a key is wrapped with KeyWrapEncrypt).
NOT INVOLVED: the ciphers and the paddings and what they compute -
every ciphertext EncryptStr returned before is the same octet for octet
now, 627 of them on each platform, but for the 72 that carried the
octets of a refused call; DecryptStr, whose 676 results are the same;
the in-place and ToDst methods. Nor the library's own encryption: TLS,
CMS, PKCS#8 and the SET3 streams do not call EncryptStr, and SSH,
PKCS#12 and the user password list call it with paddings that finish
any length, as the EncryptString functions do. The Simple Schemes demos
set PaddingMode bpmPKCS5 on their TstCipher.
NOT CHANGED:
- A cipher used without the component kept the input it could not
finish, and its next EncryptStr took it as the start of the message;
entry 73 changes that.
- DecryptStr of a ciphertext its padding cannot have produced returns
an empty string. With bpmPKCS5 and the other last-block paddings the
next DecryptStr needs a new IVector, as after any message. With
bpmNone and bpmCTS the octets stayed with the cipher and the next
DecryptStr failed; entry 73 changes that.
--------------------------------------------------------------------------------
SFTP SERVER: A REQUEST THAT ARRIVES WITH THE CLIENT'S EOF
================================================================================
65. FIXED - the SFTP server closed the channel without answering the
client's last request when that request arrived together with the
client's SSH_MSG_CHANNEL_EOF while the server was still answering an
earlier one; it then carried the request out after the close
The SFTP server (TstSFTPServerSubSystem) is woken whenever data arrives
on its channel. It takes everything that has arrived, answers every
complete request in it, and closes the channel once the client has sent
SSH_MSG_CHANNEL_EOF, meaning the client will send nothing more.
THE STEP THAT FAILED is the order of the last two. The server asked
whether the EOF had arrived after it had answered what it took, not
before it took it. A request that arrived, followed by the EOF, while the
server was still answering the earlier ones was not among what it had
taken, yet the EOF was there when it asked: the server closed the
channel, and the client got the close instead of an answer. The request
was not lost, though: the server went on to carry it out after closing,
with no way left to tell the client. So a request that changes something
- a WRITE, the CLOSE of a handle, a REMOVE, a RENAME, a SETSTAT - took
effect while the client saw the conversation end without an answer to
it.
Now the server asks whether the EOF has arrived before it takes what has
arrived. The client sends everything before its EOF, so when the answer
is yes, what the server takes is all there is. When the EOF arrives
later, the server is woken again for it, and then answers whatever came
with it before it closes.
WHO MET IT. A client that sends its EOF while a request is still
unanswered: a program that writes its requests into the channel and
half-closes it without waiting for the answers, such as a script piping
a prepared request stream into "ssh -s sftp", or a client that sends a
last CLOSE and its EOF back to back. A client that waits for every answer
before it sends its EOF cannot meet it; OpenSSH's sftp waits for each
command to finish, so its session ends only after the last answer.
THE DISCRIMINATING TEST: send a request; while the server is still
answering it, send a second request and SSH_MSG_CHANNEL_EOF. An affected
release answers the first, closes the channel, and does not answer the
second; this one answers both and then closes. The test program
Test\sftpinterop\SftpEofRaceTest holds the first request up in the server
through SFTPServerTrace. An affected release left the second request
unanswered in 15 of 15 attempts on Win32 and 15 of 15 on Win64, and
carried it out after closing in all 30; this one answered every one.
PLATFORMS. Measured on Win32 and Win64, before and after, and on Linux64
after (15 of 15 answered). The order is not platform-dependent, so every
platform the server runs on was affected.
NOT INVOLVED: the SSH channel, which had delivered the request intact;
the SFTP protocol version; the jail and the requests themselves.
NOT CHANGED: an EOF that arrives with nothing unanswered still closes the
channel at once, and so does one that arrives while the server is busy,
once the server has answered. A client that sends SSH_MSG_CHANNEL_CLOSE
instead of an EOF has closed its end: requests that arrived before it
are carried out, before as now, and their answers cannot reach it.
--------------------------------------------------------------------------------
THE CIPHER COMPONENT: ONE MESSAGE AFTER ANOTHER IN GCM, CCM AND EAX
================================================================================
66. BEHAVIOUR CHANGE - a TstCipher in cmGCM, cmCCM or cmEAX refused a new
message with "Initialization Vector not set" although N and Initialize
had given it a new nonce, yet took a message that had no new nonce
In these three modes a message starts, once the component is keyed,
with the nonce set through the cipher's parameters -
(Cipher1 as iGCMParameters).N, iEAXParameters or iCCMParameters, for
CCM also MessageLength and AdditionalDataLength - and Initialize. Those
calls reach the cipher directly; the component never sees them. This is
the same on TstCipher and on every other TstCustomCipherComponent.
THE STEP THAT FAILED is a rule the component applies in every block
cipher mode but ECB: after an in-place call - Encrypt, Decrypt,
EncryptStr, DecryptStr and their Bytes, Intf and Ptr forms - whose
result is not a whole number of blocks, it refuses every further
in-place call with "Initialization Vector not set" until IVector is
set. In a chaining mode that keeps the next call from starting on a
chaining state that a partial block has left unusable. In GCM, CCM and
EAX a call may have any length, EncryptStr's result is the ciphertext
and the tag - 76 octets for 60 octets of plaintext in GCM - and IVector
does not start a message, so the rule got it wrong both ways:
- A new message on the same component, given its own nonce through N
and Initialize, raised whenever the message before it had not come to
a whole number of blocks. Eight messages of 64, 60, 0, 17, 16, 33,
100 and 1 octets raised from the third on, in all three modes, and
keying the component again did not clear it.
- One message given in several in-place calls - 10 octets, then 20,
then the rest, with the tag through iCipherMAC - raised at the second
call.
- After a call the cipher declined, such as CCM beyond its
MessageLength (entry 35), a new message raised even when N and
Initialize had started it; only IVector cleared it.
- A message given NO new nonce was not refused when the one before it
had come to a whole number of blocks. Measured with 64 octets and
neither N nor Initialize in between: in GCM a second EncryptStr
returned 80 octets under the nonce already used, and a second
iCipherMAC.GetFinalBuf returned the 16 octets that every GCM tag
under that nonce is masked with - pyca/cryptography gives the same 16
octets as the tag of an empty message under that key and nonce -
which GCM depends on never being revealed. In EAX a second EncryptStr
returned new ciphertext under the first message's tag, and a second
DecryptStr accepted a changed ciphertext under that tag and returned
64 octets. CCM refused a second EncryptStr and DecryptStr, with an
empty string.
- Initialize without a new N was accepted in GCM and EAX and left the
message counter where it was, so the next message went under the
nonce just used. CCM advances its counter at the tag and raised
"Nonce N is not set".
A program that set N and called Initialize for every message never sent
or accepted a message without a new nonce; it met the first three.
NOW, in these modes, the component leaves the start and the end of a
message to the cipher. It takes calls of any length within a message,
and IVector plays no part. A message runs from Initialize until its tag
is made or checked - by EncryptStr, DecryptStr or DoneToDst, or by
iCipherMAC.GetFinalBuf or VerifyFinalBuf:
- Before the first Initialize and after the tag, every call on the
component - the in-place methods above and the ToDst methods - raises
eSecComp, for example "EncryptStr: Nonce not set - set N and call
Initialize before each message". Setting IVector does not change
that.
- GCM and EAX now use up the nonce at the tag, as CCM always has: the
message counter advances, and a nonce with no room for one - a
12-octet N in GCM, a 16-octet N in EAX, in CCM an N of 15 octets less
the LengthLength - is cleared, so Initialize without a new N raises
ePaddingError, "Nonce N is not set". Where N leaves room for a
counter, Initialize alone starts the next message under the next
counter value, in all three modes.
- iCompoundMode.Finalize called after the tag no longer advances the
GCM or EAX counter a second time, so a program that called it after
every message gets the nonces it got before. In CCM it advances it
again, as it always has.
- When the cipher declines a call within a message - CCM beyond its
MessageLength - the call raises as entry 35 says, and the component
ends the message: every call after it raises "Nonce not set" until N
and Initialize, where the other modes wait for a new IVector.
- EncryptStr raises "EncryptStr: Encryption failed" when the cipher
refuses the message, where it returned an empty string. In these
modes every message has a tag, the empty one too.
The ciphers refuse the same states for any caller. After the tag, GCM
and EAX take no data, no associated data and no second GetFinalBuf,
which raises ePaddingError, "GCM mode not initialized" or "EAX mode not
initialized", and CCM refuses a second GetFinalBuf with "CCM mode not
initialized". GCM and EAX take no data before their first Initialize
either. CanEncryptInplace and CanDecryptInplace on the cipher return
False in each of those states.
IF YOUR PROGRAM sets N and calls Initialize for every message, it now
works on one component whatever the lengths; the IVector that entry 39
asked for is no longer needed, and does no harm. If it gives GCM or EAX
an N shorter than the whole nonce, leaving room for a MessageCounter,
and neither sets MessageCounter nor calls Finalize, the second message
on a component went under counter 0 again and now goes under counter 1.
With the same N that was the first message's nonce a second time, and
this is the fix; with a new N for every message, the receiver must now
count the same way, or set MessageCounter itself.
NOT AFFECTED: TLS, CMS and the SET3 streams, which set a nonce and call
Initialize for every record, message or stream; and SSH, whose AES-GCM
keeps its own invocation counter and is left out of the new end of
message. The output of the ciphers for a message is the same as before.
EAX ASSOCIATED DATA, stated here because it looks like part of the
above and is not. In EAX the associated data stays with the cipher for
later messages until new associated data is given: a message for which
EncryptToNil is not called is authenticated with the associated data of
the last message that had some, not with none. So a component that
encrypts a message with associated data and then decrypts one that had
none refuses the second. This is deliberate - EAX lets the work on
associated data that repeats be done once - and is NOT CHANGED. For a
message without associated data after one that had some, call
(Cipher1 as iCipherMAC).EncryptToNil with a count of 0 after
Initialize. GCM and CCM start every message without any.
Checked on Win32 and Win64 through a TstCipher, against
pyca/cryptography (OpenSSL) AESGCM and AESCCM, and an EAX built for the
test on pyca/cryptography's AES-CMAC and AES-CTR, which reproduces the
ten test vectors of the EAX paper by Bellare, Rogaway and Wagner; pyca
itself reproduces McGrew and Viega's GCM test cases 1 to 4 and RFC 3610
packet vectors 1 to 3. On one component per mode: eight messages of 0
to 100 octets, whole blocks and not, with and without associated data -
in CCM with 12- and 13-octet nonces and 16- and 8-octet tags -
encrypted and then decrypted, and interleaved, with and without the
IVector of entry 39; one message in calls of 10, 20 and 70 octets; the
published vectors, keying the component again for each; nonces with a
counter over four messages, with and without Finalize; and every
refusal above. 317 checks, all as expected and the same on both
platforms; the same program built against the sources before this
change fails 146 of them. TLS 1.3 and TLS 1.2 with AES-GCM against
OpenSSL 3.5.7, and SSH with aes256-gcm@openssh.com and
aes128-gcm@openssh.com against OpenSSH - a 4 MB SFTP download - work as
before.
THE DISCRIMINATING TEST: key a TstCipher for AES in cmGCM, set
(Cipher1 as iGCMParameters).N to 12 octets, call Initialize and
EncryptStr 60 octets; set N to 12 other octets, call Initialize and
EncryptStr 60 octets again. An affected release raises "EncryptStr:
Initialization Vector not set" at the second EncryptStr, this one
returns 76 octets. A third EncryptStr with no N and Initialize before
it raises "EncryptStr: Nonce not set - set N and call Initialize before
each message".
--------------------------------------------------------------------------------
TWOFISH AND SHACAL-2 WHERE THE COMPILER HAS NO ASSEMBLER
================================================================================
67. BEHAVIOUR CHANGE - on every platform but Win32 and Win64, TwoFish and
SHACAL-2 had no block function: every operation raised
EAssertionFailed, or, with assertions compiled out, reported success
and gave output that did not depend on the key. TwoFish now raises
eCipherError there, and SHACAL-2 is not registered there
THE STEP THAT FAILED is the block function, the routine that encrypts
or decrypts one block and that every mode of a block cipher calls. In
stTwoFish and stSHACAL it is written only in x86 and x64 assembler.
Only the Delphi compilers for Win32 and Win64 have an inline assembler;
those for Linux64, macOS (Intel and ARM), iOS and Android do not. For
them the four block functions of each unit were compiled as an
assertion and nothing else, and stSHACAL's key setup as nothing at all.
Both units registered their classes all the same, so FindCipherClass,
a TstCipher with Algorithm caTwoFish or caSHACAL2, a SET3 file
(stCipherStream) whose header names either, and the SSH ciphers
twofish* and shacal256-*@streamsec.com used them. What they did then
depended on whether assertions were compiled into the unit:
- With assertions, the compiler's default, every encryption and
decryption raised EAssertionFailed.
- With assertions compiled out, every call returned True and the block
function changed nothing. Measured on Linux64 in ECB, CBC, CFB, OFB,
CTR, ABC, EAX and CCM: a message encrypted under two different keys
gave the same output, and decrypting it with the wrong key gave the
plaintext back. ECB and CCM output the plaintext itself; the other
modes combined it with values that do not depend on the key, such as
the IV. EncryptToBuf in ECB left its destination as it was. SHACAL-2,
measured in ECB, CBC, CFB and OFB, behaved the same.
The Android64 object code of stTwoFish is the same: the assertion, or
with assertions compiled out a function that returns at once. It was
not run on a device.
NOW, on those platforms, with or without assertions:
- TwoFish stays registered, and every encryption and decryption, in
every mode, raises eCipherError, for instance "tTwoFish_CBC: there is
no TwoFish block function on this platform - it is written only in
x86 and x64 assembler, which this compiler does not accept". So does
a TstCipher with Algorithm caTwoFish. An SSH connection cannot use a
twofish* cipher there: the cipher raises on the first packet it
encrypts or decrypts. TwoFish is deprecated: entry 68.
- SHACAL-2 is not registered, in any mode. FindCipherClass(caSHACAL2,
...) returns nil; MustFindCipherClass, and a TstCipher with Algorithm
caSHACAL2, raise eClassRegistration, "Unable to find required cipher
class: caSHACAL2,cmCBC"; the SSH ciphers shacal256-cbc@streamsec.com
and shacal256-ctr@streamsec.com are no longer offered. A tSHACAL2_
class created directly raises eCipherError from its first block, as
TwoFish does.
WHO WAS AFFECTED: only a program built for one of those platforms that
has stTwoFish or stSHACAL in its uses clause and chooses TwoFish or
SHACAL-2 - by TstCipher.Algorithm, by the SSH cipher names (also
through AllOptionNames), by a SET3 header, or by a class from the
registry. No library unit uses either unit, and nothing chooses either
by default.
DATA ALREADY WRITTEN there with assertions compiled out was never
encrypted with its key: treat it as unprotected. This release raises
eCipherError on it, and Win32 and Win64 cannot decrypt it either,
because they do apply the key.
THE DISCRIMINATING TEST: in a program for Linux64 or Android, create a
tTwoFish_ECB with a key of 16 zero octets and encrypt a block of 16
zero octets in place. An affected release built with assertions raises
EAssertionFailed; built without them it returns True and leaves the 16
zero octets; this release raises eCipherError. On Win32 and Win64 the
result is 9F589F5CF6122C32B6BFEC2F2AE8C35A, the first test vector of
the TwoFish paper (on Win64, see entry 47).
NOT CHANGED: Win32 and Win64, where the assembler is compiled. There
TwoFish and SHACAL-2 give the same output as before, byte for byte, in
ECB, CBC, CFB, OFB and CTR and through TstCipher, and TwoFish passes
its 57 test vectors from libgcrypt and nettle as before.
--------------------------------------------------------------------------------
DEPRECATED: TWOFISH
================================================================================
68. DEPRECATED - TwoFish: caTwoFish and the stTwoFish cipher classes, the
SSH ciphers twofish* and MACs twofish-*-omac@streamsec.com, and the
StreamSec extended TLS suites WITH_TWOFISH_...
TwoFish works as it did on Win32 and Win64. Deprecated means: do not
use it for new data or new connections; it is kept so that existing
data can still be read. The declarations carry the word, and what to
use instead:
- caTwoFish (tCipherAlg) and the tTwoFish_ classes. Use AES
(caRijndael).
- The SSH ciphers twofish-cbc, twofish-ctr and twofish128/192/256-cbc
and -ctr, which OpenSSH does not offer. Use aes*-ctr or an AEAD
cipher.
- The SSH MACs twofish-128/192/256-omac@streamsec.com. Use
hmac-sha2-256 or hmac-sha2-512.
- TTLSOptions.BulkCipherTwoFish128, 192 and 256 and the three CTR
ones, which select StreamSec extended (non-IANA) TLS suites. Leave
them prNotAllowed, as they are by default.
On every platform but Win32 and Win64, TwoFish raises eCipherError
(entry 67).
SHACAL-2 (stSHACAL) is NOT deprecated: it is the only block cipher in
the library with a 256-bit block. It is registered where its assembler
is compiled, Win32 and Win64 (entry 67).
--------------------------------------------------------------------------------
SSH CHANNELS: EXTENDED DATA, AND THE SERVER'S KEEPALIVE REQUESTS
================================================================================
69. FIXED - an SSH channel that was sent extended data (a command's
stderr) stopped short of one window, and an SSH client left the
server's keepalive requests unanswered, so an OpenSSH server with
ClientAliveInterval set ended the connection once it fell silent
A channel carries two streams: its data, and extended data, which a
server uses for a command's stderr (SSH_MSG_CHANNEL_EXTENDED_DATA, RFC
4254 section 5.2). Both count against the channel's one receive window.
The receiver lets the sender send one window's worth - DefaultWindowSize,
1 MB unless you change it, on TstSSHClient and TstSSHServer alike - and
reopens the window with SSH_MSG_CHANNEL_WINDOW_ADJUST once all of it has
been taken in (entry 40).
THE FIRST STEP THAT FAILED is taking in extended data. The channel,
client side and server side alike, took the message off the connection
and dropped it without counting it against its window. The sender had
counted it. So the window never came out used up at the receiver, it
was never reopened, and the transfer stopped: with the default window,
after 1 MB of data less the octets of extended data the window had
carried. Neither end reported an error; the channel stayed open, and a
read waiting for the rest waited without a limit.
WHO SENDS EXTENDED DATA. Measured against OpenSSH 9.5 on Windows: sshd
sends a command's stderr as extended data when the channel runs an exec
request - a command writing 1000 octets to stderr and then 2 MB to
stdout delivered exactly 1,047,576 octets of stdout to our client, and
then nothing - but it discards a subsystem's stderr, and the same
program run as a subsystem delivered all 2 MB on an affected release
too. This library's client asks for subsystems - SFTP, snip - and for
port forwarding, not for exec or a shell, so against OpenSSH its
channels met no extended data. A server that passes a subsystem's stderr
on did stop them. Clients do not normally send extended data - the one
kind RFC 4254 defines is stderr - but a client that sent it stopped a
channel to TstSSHServer the same way.
THE SECOND STEP THAT FAILED is answering the server. A server may send
SSH_MSG_CHANNEL_REQUEST on a channel and SSH_MSG_GLOBAL_REQUEST on the
connection, and when it sets want_reply the client must answer: with
SSH_MSG_CHANNEL_FAILURE or SSH_MSG_REQUEST_FAILURE when it does not act
on the request (RFC 4254 sections 5.4 and 4). The client took both off
the connection and dropped them. OpenSSH's sshd, when ClientAliveInterval
is set in sshd_config, sends keepalive@openssh.com that way each time the
client has been silent that long - as a channel request while a channel
is open, as a global request while none is - and ends the connection
once ClientAliveCountMax of them have gone unanswered, logging "Timeout,
client not responding". Measured with ClientAliveInterval 1 and
ClientAliveCountMax 2: a channel running the sftp subsystem, left silent
for 6 seconds, was gone - the next send raised EstSocketError, Windows
socket error 10054, "An existing connection was forcibly closed by the
remote host" - and after the same silence with no channel open, no
channel would open. ClientAliveInterval is off by default; servers set up
to drop dead clients turn it on, and then an SFTP session that sat idle
long enough was dropped.
NOW extended data is counted against the window and then discarded, and
the window is reopened once the data read and the extended data together
have used it up, whichever of the two comes last - so also when extended
data ends a window whose data has all been read. A channel request or a
global request with want_reply is answered SSH_MSG_CHANNEL_FAILURE or
SSH_MSG_REQUEST_FAILURE. The channel failure is addressed with the
server's number for the channel, and is not sent once the channel has
sent its CLOSE (RFC 4254 section 5.3). A request without want_reply -
exit-status, exit-signal, hostkeys-00@openssh.com - is dropped, as
before. Measured on Win32 and Win64, at both ends of a channel: 1000
octets of extended data ahead of 4 MB of data, and 1000 octets ending a
window whose data had all been read, ahead of 1 MB more, both arriving
intact; and each kind of request answered, with no answer to a request
without want_reply.
THE DISCRIMINATING TESTS. For the keepalive: start an OpenSSH sshd with
ClientAliveInterval 1 and ClientAliveCountMax 2, log in with a
TstSSHSocketClient, start the sftp subsystem on a channel, send nothing
for 6 seconds, then send an SFTP request. An affected release gets no
answer, and sshd logs "Timeout, client not responding"; this one gets
the answer, and sshd - at LogLevel DEBUG - logs "Got 100/... for
keepalive" about once a second. For extended data: an affected release
stops a channel after exactly DefaultWindowSize octets of data less the
octets of extended data the window carried - 1,047,576 with the default
window and 1000 octets of stderr - and this one does not stop. A
transfer that stops after exactly one window, not less, is entry 40.
PLATFORMS. Measured on Win32 and Win64. The same code runs on every
platform, so every platform was affected.
NOT INVOLVED: the window and packet sizes (a larger window only moved
the point where a transfer stopped), the key exchange, the ciphers and
MACs, SFTP itself, the channel numbers of entry 40 and the packet size
limit of entry 46.
NOT CHANGED:
- Extended data is not handed to the program: its content was lost
before and is discarded now. Neither are exit-status and exit-signal.
- The client sends no keepalive requests of its own.
- How TstSSHServer handles a client's channel requests and global
requests.
- The legacy units stSSHClientChannel and stSSHServerChannel, which no
longer ship, have the same defects and are not changed.
--------------------------------------------------------------------------------
SSH: A PACKET WHOSE MAC ARRIVES IN TWO PARTS
================================================================================
70. FIXED - an SSH connection stopped delivering what the peer sent when the
end of a packet's MAC arrived later than the rest of the packet: the
client's channels received nothing more while the connection stayed
open, and the server closed the connection
Each end of an SSH connection takes in what arrives on its socket as it
comes, decrypts it, and hands each packet on once the MAC at the packet's
end has arrived whole and checks out. TCP delivers a stream, not packets,
so what the socket holds at a given moment can end anywhere in a packet,
partway through its MAC included.
THE STEP THAT FAILED is the read that follows one which ended partway
through a MAC. It asked the socket for the full length of a MAC more, not
for the part still missing, in one read, and took anything less as a
broken connection. Until the rest of the MAC had arrived, a socket that
does not wait - every socket on the POSIX platforms, and on Windows the
connections a TstSSHSocketServer accepts - had nothing to give or less
than that; a socket that waits gave back the rest of the MAC alone when
nothing had been sent after it. The read then raised eExternalRecvError,
and nothing reported it:
- on the client side it ended the thread that reads the connection. The
connection stayed open, but no channel on it received anything more,
and nothing said why;
- on the server side it ended the connection, and the client found it
closed at its next send.
Now the part of a MAC that has arrived is kept, and the next read takes
what the socket holds, as a read does when nothing is kept. The packet is
handed on once its MAC is whole.
WHO. Both ends of a connection: TstSSHSocketClient on the client side -
with the SFTP client, snip over SSH (TsnipSSHClient) and port forwarding
- and TstSSHSocketServer on the server side, with every subsystem; and
TstSSHClient and TstSSHServer where their raw receive events return what
has arrived rather than wait for the count asked for. Whether it struck
depended on where the reads of the stream happened to end, so the same
transfer could fail one time and come through the next. It needs the
rest of the MAC to arrive late, which a network does when it cuts a
packet near its end and the sender then pauses, as it does between the
packets of an interactive session or while it waits for a reply. Over
loopback on Linux64 one pattern struck nearly every time: a client that
stopped reading while the server sent 4 MB received 192 KB less than was
sent once it read again, cut off at the same place on every run.
THE DISCRIMINATING TEST: put a relay between our client and our server
that forwards the last 8 bytes of everything it reads 30 ms after the
rest, and have one end send 20 packets of 1000 bytes with a pause after
each, so that each read ends where a packet ends and each packet arrives
without the end of its MAC at first. An affected release delivers none
of the 20000 bytes to the client; sent the other way, the server takes in
the first packet at most and then closes the connection. This one
delivers every byte once and in order, both ways. Measured on Win32,
Win64 and Linux64 with chacha20-poly1305@openssh.com, and on Win32 also
with aes256-gcm@openssh.com and with aes128-ctr and hmac-sha2-256. And the
pattern above, with no relay tricks: on Linux64 the client that stops
reading for 4 s while the server sends 4 MB received 3997696 of the
4194304 bytes on 10 of 10 runs of an affected release, and all of them on
10 of 10 runs of this one.
PLATFORMS. Every platform: the same code reads the connection on each.
Measured on Win32, Win64 and Linux64.
NOT INVOLVED: the cipher and the MAC - a MAC of 16 bytes and one of 32
failed alike; the sending side, which wrote every packet whole (entry
36); the channel window; and the read race of entry 44, which lies
further on, in the channel's buffer.
NOT CHANGED: what is taken in and handed on, and a read after one that
did not end inside a MAC. On the client side, a receive that fails for a
real reason - a MAC that does not check out, a socket error - still ends
the thread that reads the connection without a word. The legacy unit
stSSHTransport, which no longer ships, has the same defect and is not
changed.
--------------------------------------------------------------------------------
THE CIPHERS: DecryptToBuf IN PIECES WITH bpmPKCS5, bpmZeroes, bpm10s OR bpmSSL3
================================================================================
71. BEHAVIOUR CHANGE - with BlockPaddingMode bpmPKCS5, bpmZeroes, bpm10s or
bpmSSL3, a cipher's DecryptToBuf or DecryptToPtr, given a message in
several calls, could write up to one block past the room it was given
and return True; it now returns False
These four paddings pad the last block of a message, so a cipher that
decrypts with one of them keeps back the last block it has been given
until it is told that no more follows: VerifyFinalBuf then removes the
padding from that block alone. They serve ECB, CBC and ABC. This entry
is about a cipher used without a component - a tBlockCipher such as
tRijndael_CBC or t3DES_CBC, created by a program, with BlockPaddingMode
set - and decrypted with DecryptToBuf or DecryptToPtr. Those take a
destination and, in aDstCount, the room in it; a call given too little
room returns False before it writes anything.
THE STEP THAT FAILED is that room check, in one state: the cipher
already held a whole block, and the octets of the call did not end on a
block boundary. The call then writes the block it held and the whole
blocks of the new octets, and keeps back their partial end; but it
counted room for the whole blocks of the new octets only, one block
short. Given no more room than that, it returned True, reported in
aDstCount the octets it had written, and had written up to one block -
16 octets with AES, 8 with 3DES - past the end of the room. Given no
room at all, it wrote nothing, still reported the block as written, and
the plaintext of that block was lost. What it wrote past the room was
the plaintext of the message being decrypted. Who can choose those
octets, and what could be done with them, has not been traced.
Measured with every split into three calls of AES and 3DES messages of
14 lengths from 0 to 33 octets, bpmPKCS5 in CBC, each call given exactly
as much room as the octets it passed: in 292 splits a call reported
more octets than its destination held, and valgrind on Linux64 counted
51,002 invalid accesses. On Win32 and Win64 the same run damaged the
heap: later calls raised EAccessViolation (Win32) and EInvalidPointer
(both), and the run ended in one of them.
In every other state the check asked for no less than the call writes,
and in encryption with these paddings, which keeps back only a partial
block, for exactly as much.
NOW the check counts the block the cipher holds. A call given less room
than it writes returns False, writes nothing and leaves aDstCount and
the cipher as they were, so the same call can be made again with more
room. In that state the count is exact: room for exactly what the call
writes is enough, and a call whose octets do end on a block boundary
still needs no more room than they are long, as before.
WHO. A program that decrypts one message in several DecryptToBuf or
DecryptToPtr calls on such a cipher, not all of which end on a block
boundary, and gives a call less room than its octets and one block
more - for instance a destination as long as the piece it passes.
iCipherMAC.VerifyFinalBuf, given the rest of a message while the cipher
held a whole block, passes those octets on in the same way first, and
was affected in the same way. A program that decrypts a message in one
call, or gives each call room for its octets and one block more, was
not affected.
THE DISCRIMINATING TEST: create a tRijndael_CBC with a key of 16 zero
octets, set IVector to 16 zero octets and BlockPaddingMode to bpmPKCS5.
Call DecryptToBuf with 16 zero octets and aDstCount 16: it keeps them,
returns True and sets aDstCount to 0, before as now. Call DecryptToBuf
again with 1 zero octet, a destination of 16 octets and aDstCount 1. An
affected release returns True, sets aDstCount to 16 and writes 16
octets; this one returns False, leaves aDstCount at 1 and writes
nothing. With aDstCount 16 both return True and write 16 octets.
WHAT EXISTING CODE SEES DIFFERENTLY, apart from no write past the room:
- DecryptToBuf and DecryptToPtr return False in that state when the
room is short, where they returned True.
- VerifyFinalBuf, given octets that do not end on a block boundary
while the cipher holds a whole block, returns False as it did - such
a message is not a whole number of blocks - but no longer writes past
the room first.
NOT INVOLVED: the cipher components - TstCipher.DecryptToDst gives the
cipher room for the octets of each call and one block more, and
DecryptStr gives it a whole message in one call - and TstCipherMAC,
whose CBC-MAC uses bpmZeroes and bpm10s but never decrypts. Nor the
library's own decryption: CMS, PKCS#8, PKCS#12 and PEM messages give a
new cipher the whole ciphertext in one call, and tDecryptStream, the
deprecated SET3 reader, gives each read of at most 65,536 octets 65,536
octets of room, which is enough. TLS and SSH do not use these paddings.
Nor the ciphers, what they decrypt, or how the padding is checked and
removed; encryption; and bpmNone, bpmCTS (entry 58) and bpmStrSecII.
Checked on Win32, Win64 and Linux64 with all four paddings, with AES-128
and 3DES in ECB and CBC and 3DES in ABC (AES in ABC is in stRijndael,
which is not in the package), for messages of 0 to 4 blocks and one
octet, 5 blocks less one octet, 5 blocks, and 8 blocks and one octet.
In ECB and CBC the reference is pyca/cryptography (OpenSSL), over the
plaintext padded as each padding pads it; ABC has no published test
vector, and its reference is the cipher's own one-shot encryption.
Every split into three calls, calls of 0 octets included, both ways:
each call is first given one octet less room than it writes, and must
return False with nothing written, then exactly as much, and must take
it and fill it; then VerifyFinalBuf, or GetFinalBuf, must complete the
plaintext or the reference ciphertext. All 1,562,948 checks as expected
on Win32, Win64 and Linux64, and valgrind reports no invalid access.
Before, 42,444 failed, every one a decrypting call in the state above
that took one octet less room than it wrote, in each of the four
paddings; for messages of up to 2 blocks and one octet valgrind counted
213,080 invalid accesses. The measurement above now passes all 6,520 of
its checks on the three platforms, and valgrind reports no invalid
access. The checks of entries 43, 49 and 58 give the same results as
before: 72,567, 85,783, and 500,316 on Win32 and 424,406 on Win64 and
Linux64.
NOT CHANGED: when the cipher holds no block or only part of one, a call
whose octets end on a block boundary still asks for room for all of
them, one block more than it writes, since it keeps the last block
back. So DecryptToBuf of a whole message in one call needs room for all
of it, and VerifyFinalBuf of a whole message room for the whole
ciphertext, not only the plaintext. Given less, they return False, before
as now.
--------------------------------------------------------------------------------
SFTP CLIENT: A READ AT THE END OF A FILE
================================================================================
72. FIXED - TstSFTPClient.GetFile of a remote file of 0 octets raised
EAccessViolation, "Read of address 00000000", instead of returning
True; so did tSFTPTransport.ReadFile at the end of any file, and
GetFile wherever it read there
A server answers an SFTP read request, SSH_FXP_READ, with the octets it
read in SSH_FXP_DATA, or with a status, SSH_FXP_STATUS, when it has none
to give. draft-ietf-secsh-filexfer-02, section 6.4:
"If an error occurs or EOF is encountered before reading any data,
the server will respond with SSH_FXP_STATUS."
The status for the end of the file is SSH_FX_EOF; by section 7, "for
SSH_FX_READ it means that no more data is available in the file".
OpenSSH's sftp-server and TstSSHServer's SFTP subsystem both answer a
read at or past the end of a file that way (measured, below).
THE STEP THAT FAILED is where tSFTPTransport took that answer. Both
ReadFile overloads - the one that returns the octets as tBytes and the
one that writes them to a stream - have a helper send the read and wait
for the reply, and then look at the reply's packet type: the octets of
SSH_FXP_DATA are taken, anything else gives none. For a status the
helper checked the code - an error status raised eSFTPStatusError, as it
should - and then handed back no reply at all, nil, and ReadFile asked
nil for its packet type: EAccessViolation, "Access violation at address
... Read of address 00000000". The declaration of ReadFile promises an
empty result at the end of the file ("nil at EOF"); the caller got the
access violation instead. It was a read of address 0, before ReadFile
touched any octet or the stream: nothing was read or written out of
place, and the handle stayed open, as a read leaves it.
WHO MET IT. GetFile reads until it holds as many octets as the file's
attributes (SSH_FXP_FSTAT) give, or until a read brings none. So it
read at the end of the file, and raised, when:
- the remote file was empty: GetFile reads once at offset 0 even so;
- with aResume, the local file or stream already held the whole remote
file: its one read was at the end;
- the file was shorter when GetFile read it than its attributes had
said: cut short in between, or on a server whose attributes give more
than it serves.
GetFile closed the handle, and the local file or stream held what had
been read, which in the first two cases was all of the file. A download
of a non-empty file ends when the count is reached, with no read at the
end, and was not affected. A program that calls tSFTPTransport.ReadFile
itself met it at each read at or past the end of a file. A server that
answers as the drafts say answers such a read with a status, so every
such server was concerned, with SFTP version 3 and version 5 alike.
NOW a status that reports the end of the file, SSH_FX_EOF, gives
ReadFile no octets: the tBytes overload returns nil, the stream overload
writes nothing, and GetFile stops there and returns True. An error
status raises eSFTPStatusError, before as now. SSH_FX_OK, which reports
success, carries no octets and is not an answer the drafts give to a
read, raises eSFTPClientError, "Unexpected SSH_FX_OK status in reply to
a read"; before, it raised EAccessViolation too.
THE DISCRIMINATING TEST: GetFile of an empty remote file into a
TMemoryStream. An affected release raises EAccessViolation, "Read of
address 00000000"; this one returns True, and the stream stays empty.
Both download a file of 5 octets whole from the same server. Measured:
- with an SFTP server inside the test program, speaking version 3 and
version 5 (Test\sftpinterop\SftpPutFileTest, step 10), on Win32 and
Win64: before, 8 checks failed, each on EAccessViolation - GetFile of
an empty file with each version, GetFile with aResume of a file the
stream already held, GetFile of a file of 5 octets whose attributes
gave 10, each ReadFile overload at offset 5 of a file of 5 octets, and
a read answered SSH_FX_OK; now all 111 of its checks pass. A read
answered SSH_FX_FAILURE raised eSFTPStatusError, code 4, before and
after;
- against TstSSHServer's SFTP subsystem over loopback (SftpSelfTest, on
Win32, where it is built) and against the sftp-server of OpenSSH 9.5p2
for Windows (SftpVsOpenSSH, on Win32 and Win64): GetFile of an empty
file, and ReadFile at offset 16 of a file of 16 octets, raised
EAccessViolation before and now return nothing without raising.
PLATFORMS. Every platform: the same code takes the reply on each.
Measured on Win32 and Win64.
NOT INVOLVED: the server, which answered as the drafts say; SSH and the
channel; the open, the file's attributes and the handle; uploads
(PutFile), and directory listings (ReadDir and List), which take
SSH_FX_EOF as the end of the listing, before as now.
NOT CHANGED:
- TstSFTPClient.Size raises EAccessViolation, "Read of address
00000000", when the server answers the request for the open file's
attributes with SSH_FX_OK or SSH_FX_EOF rather than with the
attributes or an error status: tSFTPTransport.Stat, LStat and FStat
return nil for those two, and Size asks nil for the size (measured,
with the server in the test program). GetFile takes nil there as
attributes it does not know, and reads until the end of the file,
where it now stops. TstSSHServer's SFTP subsystem answers with the
attributes or an error status (by its code), and so did OpenSSH's
sftp-server in every measurement here. It is a separate defect and is
not changed here.
- tSFTPTransport.OpenFile, OpenDir, ReadLink and RealPath return an
empty handle or name when a server answers them with SSH_FX_OK or
SSH_FX_EOF, as before.
- The legacy unit stSFTPTransport, which no longer ships, has the same
defect and is not changed.
--------------------------------------------------------------------------------
THE CIPHERS: EncryptStr AND DecryptStr OF WHAT THE PADDING CANNOT FINISH
================================================================================
73. BEHAVIOUR CHANGE - the EncryptStr and DecryptStr of a cipher itself
took input bpmNone or bpmCTS could not finish and kept it, so that the
next call on the same cipher encrypted it in front of its own, or
failed
Entry 64 describes TstCipher.EncryptStr. This entry is about the
EncryptStr and DecryptStr of the cipher object underneath: a tCipher
created from MustFindCipherClass, or reached through an iCipher, which
TstCipher and every other TstCustomCipherComponent call to do the work.
Two paddings cannot finish every message, and the same holds for its
ciphertext: bpmNone one that is not a whole number of blocks, except in
CFB, OFB and CTR, and bpmCTS one shorter than one block.
THE STEP THAT FAILED is where the cipher took the input: all of it,
before anything asked whether the padding could finish it. The whole
blocks were encrypted or decrypted, the rest was kept for the padding,
and only then did the call fail. Nothing it did ended the message, so
the next call on the same cipher went on from where the failed one had
stopped, with the octets it had kept in front of its own. Measured with
AES in ECB, CBC, CFB, OFB and CTR and 3DES in CBC, the same on Win32 and
on Win64, with entry 64 in place:
- EncryptStr raised the padding's ePaddingError, "Unable to process
pending input" with bpmNone, "Too little input for CTS padding" with
bpmCTS, after the cipher had taken the input. A second EncryptStr then
encrypted both as one message: with bpmCTS and AES in CBC, EncryptStr
of 10 octets raised, and EncryptStr of another 10 returned 20 octets;
with bpmNone, 8 octets and then 8 more returned 16. A message
encrypted after that came out wrong, or as an empty string.
- DecryptStr returned an empty string, as for any ciphertext that does
not check out, but kept the octets: the next DecryptStr of a sound
ciphertext returned an empty string too with bpmNone, and raised
ePaddingError, "Buffer too small", with bpmCTS - as a second
DecryptStr of a short ciphertext did once the two came to a block.
- TstCipher.DecryptStr calls the cipher's, and did the same. So did
TstCipher.EncryptStr when a program had left input with the cipher
through the component's iCipher interface (EncryptToBuf and the
like): the check entry 64 added leaves that case to the cipher.
NOW the cipher asks its padding first, and the padding counts any input
it already holds:
- EncryptStr raises ePaddingError before the cipher is given any of the
input: "EncryptStr: The input is not a whole number of 16-octet
blocks, and padding mode None does not pad it", or "EncryptStr: The
input is shorter than one 16-octet block, the least that padding mode
CTS can finish" - the texts of entry 64, with the cipher's block size.
The next call goes ahead as though the refused one had not been made.
- DecryptStr returns an empty string, as before, without giving the
ciphertext to the cipher, so the next call is not affected by it.
- Input already held counts: after EncryptToBuf of 5 octets with bpmNone
and AES, EncryptStr of 11 octets finishes a message of 16, and
EncryptStr of 12 is refused.
Checked on Win32 and Win64 against known answers from pyca/cryptography
for whole blocks - AES-128 in CBC, ECB and CTR and 3DES in CBC, without
padding. Every length bpmNone or bpmCTS cannot finish is refused twice,
by the cipher and by TstCipher, and the message encrypted after that on
the same cipher or component is pyca/cryptography's for the IVector
first set (in CFB and OFB, a fresh cipher's). Every such ciphertext is
turned away twice by DecryptStr, and a sound ciphertext decrypted after
that gives the message. With 1 to 15 octets already held (1 to 7 with
3DES), through the cipher and through TstCipher's iCipher, a tail that
cannot finish them is refused, and one that completes one or two
blocks then gives pyca/cryptography's ciphertext. Everything that can
be finished comes out as before. 5,508 checks, the same on both
platforms; with entry 64 but not this one, 2,544 of them fail, every
one on the paths above. In entry 64's own measurements, what changed is
the refused calls and the calls after them; no ciphertext or plaintext
returned before is different. The checks of entries 43, 49 and 58
still pass: 85,783, and 500,316 on Win32 and 424,406 on Win64.
THE DISCRIMINATING TEST: create a cipher with
MustFindCipherClass(caRijndael,cmCBC).Create and 16 octets of key, give
it CTS padding with MustFindPaddingClass(bpmCTS).Create, set an IVector
of 16 octets, and call EncryptStr with 10 octets, catching what it
raises; then call it again with 10. A release with entry 64 but not
this one returns 20 octets the second time; this one raises
ePaddingError again, with the second text above. Or, on such a cipher,
call DecryptStr with 8 octets and then with the 32-octet ciphertext of a
message under the same IVector: the release with entry 64 raises
ePaddingError, "Buffer too small", the second time; this one returns
the message.
IF YOUR PROGRAM went on with a cipher after its EncryptStr raised,
without setting a new IVector, what it encrypted next with bpmCTS, or
with bpmNone once the octets came to a whole number of blocks, carried
the octets of the call that raised in front, and does not decrypt to
the message meant: encrypt those messages again.
WHAT EXISTING CODE SEES DIFFERENTLY, apart from right output:
- The texts above where the cipher's EncryptStr raised "Unable to
process pending input" or "Too little input for CTS padding"; the
class is ePaddingError, as before. In cmKeyWrap with bpmNone, where
EncryptStr never gives a ciphertext, a length that is not a multiple
of 8 is refused the same way: for 1 to 7 octets it raised "Unable to
process pending input", and for the others returned an empty string.
- A call after one that was refused is not affected by it: where it
raised too, or returned the earlier octets with its own, it now
behaves as on a fresh cipher.
- TstCipher.EncryptStr, with input left through iCipher, raises the
cipher's ePaddingError before the input is taken, not after.
NOT INVOLVED: bpmNone in CFB, OFB and CTR, and bpmPKCS5, bpmZeroes,
bpm10s, bpmSSL3 and bpmStrSecII, which finish any length (a ciphertext
that is not whole blocks, with the first four, is entry 77);
TstCipher.EncryptStr of input the cipher does not already hold, which
entry 64 refuses; the in-place and ToDst methods. Nor the library's own
encryption: TLS, CMS, PKCS#8 and the SET3 streams do not call EncryptStr
or DecryptStr, and SSH, PKCS#12 and the user password list call them
with paddings that finish any length. PKCS#8, which asks the padding
for the final part itself, encrypts with bpmPKCS5, which always has
one. The EncryptString and DecryptString functions give ECB, CBC and
ABC bpmPKCS5.
NOT CHANGED:
- With bpmPKCS5, bpmZeroes, bpm10s and bpmSSL3, DecryptStr of a
ciphertext that is not a whole number of blocks, or is shorter than
one block, kept octets that the next call took in front of its own:
entry 77 changes that. A ciphertext of whole blocks ends the message,
whether it checks out or not, so the next DecryptStr needs a new
IVector, as before; given one, it decrypts.
- tEncryptStream.Done (the deprecated SET3 container) returns -1 and
writes nothing when bpmNone holds part of a block or bpmCTS less than
one block, so the stream lacks those octets: the last 1 of 17 with
AES and bpmNone, all 15 of 15 with bpmCTS.
--------------------------------------------------------------------------------
SSH: A CONNECTION THAT ENDS WITHOUT A DISCONNECT
================================================================================
74. BEHAVIOUR CHANGE - an SSH connection that was closed or reset without an
SSH_MSG_DISCONNECT being read went unnoticed at both ends:
TsnipClient.Start waited out its ChannelOpenTimeout, and a server kept
the connection of a client that had gone
Each end of an SSH connection has a thread that reads what the other end
sends: on a TstSSHSocketClient the channel broker, SSHClient.Broker; on a
TstSSHSocketServer one thread per connection. That thread reads only when
the socket reports octets waiting. An end that shuts a connection down
sends SSH_MSG_DISCONNECT first, and reading it is how the other end
learned that the connection was over.
THE STEP THAT FAILED is noticing the end of a connection when there was no
DISCONNECT to read: the peer closed its end without one - its process was
ended, it crashed, or it simply closes without it - or the connection was
reset. A connection that has ended has no octets waiting either, so the
reading thread went on looking for ever. On Windows a reset also throws
away what had arrived and not been read yet, a DISCONNECT included. That
is what happens when a client sends into a connection the server has just
closed: the server's system answers with a reset, and the DISCONNECT the
server sent before closing is lost.
WHAT IT LOOKED LIKE:
- TsnipClient.Start, or TsnipSSHClient.Start, raised EsnipTimeout after
ChannelOpenTimeout, 20 s by default, saying the SSH connection was still
up, where it should have raised EsnipClosed at once; before entry 27 it
did not return at all. Against a server that disconnects right after
the login, 2 runs in 120 on Win32 did this, and 1 in 120 on Win64.
- On a TstSSHSocketClient whose server had gone, SSHClient.Broker kept
running, SocketClient.Connected stayed True, and CreateChannel sent its
open into the dead connection and returned a channel that stayed
csConnecting.
- ConnectToHost to a server that accepted the TCP connection and closed it
without sending its version string retried the read 30,000 times with a
sleep between - 33 s on Linux, more than a minute on Windows, where a
short sleep lasts up to 15.6 ms - and then failed all the same.
- A TstSSHSocketServer kept the connection of a client that had gone
without a DISCONNECT - its thread and its channels - until the server
was deactivated.
NOW, whenever nothing is waiting, TstSSHSocketClient and TstSSHSocketServer
also ask the socket whether the connection has ended, without waiting and
without taking anything from it. When it has, the transport ends the
connection the way it does after reading a DISCONNECT - it closes the
socket and discards the session keys - and raises the new
eSSHConnectionLost, an eSSHDisconnect whose ErrorCode is
SSH_DISCONNECT_CONNECTION_LOST (10). Where the channel broker is reading,
that stops the broker, and what follows is what follows a DISCONNECT:
TsnipClient.Start raises EsnipClosed, CreateChannel and every other send
raise eSSHTransportError "Transport is not connected", and
SocketClient.Connected is False. Where your own thread is reading -
ConnectToHost, Login - eSSHConnectionLost reaches it. Measured: the
client's broker stops, and the server ends the connection, within 65 ms
of the close or the reset, on Win32, Win64 and Linux64.
WHAT IT COSTS. The reading thread polls every few milliseconds - every
millisecond or two once any program on the machine has raised the timer
resolution, as many do - and asking the socket costs a system call of its
own, about 2 microseconds on Win32. So the question is asked at most every
50 ms per connection, which bounds it to 20 asks a second at each end of an
idle connection, whatever the poll rate, and adds at most 50 ms to the time
it takes to notice the end. Asked on every poll instead, it added 2 to 4 ms
of processor time a second per idle connection at the 1 ms timer
resolution; spaced out like this, 32 idle connections showed no difference
beyond the noise of the measurement.
IF YOUR PROGRAM PROVIDES THE SOCKET ITSELF, through the OnRawRecvLength,
OnRawRecv and OnRawSend events of TstSSHClient or TstSSHServer: set
aResult in OnRawRecvLength to a negative number when nothing is left to
read and the connection has ended, and the transport ends it as above. A
negative number used to count as 0. A handler of TstSSHSocketClient's own
OnRawRecvLength now sees -1 in that case.
NEW: tAbstractSocket.ConnectionEnded (stSocket.pas), which answers that
question for tWinSocket and tPosixSocket: True once the peer has closed its
end and everything it sent has been read, once the connection has failed,
and once the socket is closed. ReceiveLength reads 0 in all three cases,
just as it does for a connection that is merely idle. ConnectionEnded is
virtual, not abstract, so a descendant of your own still compiles, and
there it answers only the last case.
THE DISCRIMINATING TEST: log in with a TstSSHSocketClient through a TCP
relay, then have the relay close its side toward the client, or reset it
(SO_LINGER 0, then close), without sending anything more. An affected
release leaves SSHClient.Broker running and SocketClient.Connected True
for as long as you wait, and CreateChannel returns a channel that stays
csConnecting; this one stops the broker within milliseconds, and
CreateChannel raises eSSHTransportError. For a server, have the relay do
the same toward the server: an affected server keeps that connection's
thread until it is deactivated.
NOT INVOLVED: the key exchange, the ciphers, the MACs and the channel
protocol. A connection that ends WITH a DISCONNECT that arrives was ended
properly before, and still is.
NOT CHANGED:
- A connection whose peer vanishes WITHOUT closing it - a cable pulled, a
machine switched off, a NAT or firewall that forgets the connection in
silence - still looks up, because nothing reaches this end to say
otherwise. The library does not probe an idle connection; TCP
keepalive, or a request of your own with a time limit, finds those.
- What the channels that were open when the connection ended report, and
when a thread waiting in their Recv returns, is entry 84: as after a
DISCONNECT. SSHClient.Broker.Finished tells that the connection has
ended.
- A server that ends a connection still closes its socket straight after
the DISCONNECT, so a client that sent something the server did not read
can still lose that DISCONNECT to a reset. Such a client now ends the
connection all the same.
- The legacy units stSSHSocketClient, stSSHSocketServer and
stSSHTransport, which no longer ship, are not changed.
--------------------------------------------------------------------------------
SFTP VERSION 5: THE EXTENSION NAMES A SERVER ADVERTISES
================================================================================
75. FIXED - TstSFTPClient and tSFTPTransport could not connect to an SFTP
version 5 server that sends the "supported" extension as the draft
lays it out: Connect raised eSSHDecodeError or eSSHFormatError. From
ProFTPD, which lays it out otherwise, they connected, but kept none of
the extension names it advertises
A server that speaks SFTP version 5 may say what it supports in an
extension of its first reply, SSH_FXP_VERSION, named "supported".
draft-ietf-secsh-filexfer-05, section 4.4, gives it five 32-bit fields -
supported-attribute-mask, supported-attribute-bits,
supported-open-flags, supported-access-mask and max-read-size - and then
string extension-names[0..n]
the names of the extensions the server offers, one string after another
to the end of the extension, with no count before them. Where the draft
puts a count before a list it writes the count out, as the "uint32
count" of SSH_FXP_NAME (section 7) and the "uint32 ace-count" of an ACL
(section 5.7). Of the names section 4.4 says
"The extension names may be empty (contains zero strings)"
tSFTPTransport reads the extension, as it connects, into the
tSupportedStructure that TstSFTPClient shows as ServerSupported. Both ask
for version 5, so a server that speaks it answers with version 5.
THE STEP THAT FAILED is reading the names. tSupportedStructure.Decode
read a 32-bit number after max-read-size, took it as the length in
octets of the names, and read names until that length was used up. The
draft has no such number, so Decode took the first four octets of the
first name - that name's length - as the length of them all:
- With the one name md5-hash-handle, the octets after max-read-size are
00 00 00 0F and the 15 characters of the name. Decode took the 15 as
the length of the names, and the next four octets, "md5-", as the
length of the first one: 0x6D64352D, 1,835,283,757 octets. Connect
raised eSSHFormatError, "Unable to read data". So it did for any list
whose first name was not empty.
- With no names, the extension ends after max-read-size, and Decode
read its number from the four octets after the end, past the end of
the buffer the transport had copied the extension into. The number was
only compared with the octets left, and was not used or passed on
otherwise; what Connect did depended on it. In every measurement it
raised eSSHDecodeError, "Buffer too short".
- Only a list whose first name was empty was read without raising, and
then no name was kept.
Connect comes before the first request of every TstSFTPClient method,
so a program could not use such a server at all.
WHO WAS AFFECTED. A program using TstSFTPClient or tSFTPTransport with a
server that speaks version 5 and sends "supported" as the draft lays it
out. By its source, Apache MINA SSHD's SFTP subsystem sends it so,
whatever version is agreed, and its SFTP client, like WinSCP, reads the
names as strings to the end of the extension. That was not measured: no
such server was at hand. OpenSSH's sftp-server speaks only version 3,
which has no "supported", and TstSSHServer's SFTP subsystem does not
send the extension, so our client and server were not affected.
PROFTPD lays the extension out otherwise (fxp_version_add_supported_ext
in contrib/mod_sftp/fxp.c, by its source, not measured): after
max-read-size a 32-bit 0, for no attribute extensions, then a 32-bit
count and that many names - the two counted lists that end "supported2",
the extension of version 6, in drafts 08 to 13. Decode took the 0 as a
length of no names and stopped there: Connect returned, and
ExtensionNames stayed empty. Read the draft's way, the 0 is an empty name
and the count the length of a string that ends inside the first name,
and the next four octets give a length past the end. So a reader of the
draft's layout alone would have made Connect to ProFTPD raise, where it
worked.
NOW tSupportedStructure.Decode reads the names as section 4.4 lays them
out, strings to the end of the extension. An extension that does not
end that way is read as ProFTPD's: a 32-bit count and that many
attribute-extension names, then a 32-bit count and that many extension
names, to the end. The names of both lists are kept, as in version 5
one list holds both kinds: section 4.4 has the client tell attribute
extensions from extended requests by the name. With the names ProFTPD
sends, its layout could pass for the draft's only if its count were the
octets of the first names with their lengths, 13 or more, and it sends 6
names at most; with no names both readings keep none. Further:
- every read is checked against the length of the extension, and
nothing past it is read;
- a name of 0 octets names no extension and is not kept;
- an extension shorter than its five 32-bit fields, or whose names fit
neither layout, raises eSSHDecodeError - "Buffer too small", or
"Unable to read the extension names" - and leaves ServerSupported as
it was, where Decode had set the masks and max-read-size before it
raised.
THE DISCRIMINATING TEST: connect a TstSFTPClient and read
ServerSupported.ExtensionNames. From a server that sends the draft's
layout, an affected release raises from Connect, and this one lists the
names; from ProFTPD, an affected release lists none, and this one its
names. Measured with an SFTP server inside the test program
(Test\sftpinterop\SftpPutFileTest, steps 11 and 12), on Win32 and
Win64: before, 12 of its 133 checks failed - Connect raised for the
draft's layout with 0, 1 and 2 names, ProFTPD's layout with 5 names gave
none, and GetFile into a stream that already held octets never got as
far as asking for md5-hash-handle, which it asks for when the server
names that extension. Now all 133 pass. The masks and max-read-size read
the same before and after (step 9), and SftpSelfTest, our client against
our server over loopback, passes its 39 checks before and after (on
Win32, where it is built).
PLATFORMS. Every platform: the same code reads the extension on each.
Measured on Win32 and Win64.
NOT INVOLVED: the four masks and max-read-size, which are read as before
(entry 63 converts the access mask); the other extensions in
SSH_FXP_VERSION, such as "newline"; version 3, which has no "supported";
SSH and the channel; TstSSHServer's SFTP subsystem.
NOT CHANGED:
- TstSFTPClient.CmpFile given a local file name, and GetFile given local
file names with aCanOverwrite and aResume, looked for md5-hash-handle
in ExtensionNames before they had connected, and so, as the first call
on a component, took the server for one that does not offer it. That
is a separate defect: see entry 82.
- ProFTPD's extension, by its source, carries its access rights where
section 4.4 puts supported-open-flags, and its open flags where it
puts supported-access-mask. OpenFlags and AccessMask show them as they
arrive.
- "supported2", the extension of version 6, is not read: the library
speaks versions 3 and 5.
- The legacy unit stSFTP5Types, which no longer ships, reads "supported"
the old way and is not changed.
--------------------------------------------------------------------------------
SSH: WHAT A CHANNEL'S Send RETURNS
================================================================================
76. FIXED - an SSH channel's Send returned a number that was not the count
of octets it had sent - 0 on the server's end for a Send that fitted in
one packet, a large number unrelated to the Send on the client's end;
it now returns that count
A channel's Send - iTransport.Send on an iSSHClientChannel, an
iSSHServerChannel or any other iSSHWindowedChannel - passes the octets
to the peer as far as the peer's window allows. When the window shuts
during the Send, it waits about a second for the peer to reopen it and
then returns, with the rest unsent. What it returns is meant to be the
count of octets it passed, so that a caller knows where to go on from.
THE STEP THAT FAILED is working out that count. Send cuts the octets
into packets, and it kept only what the send of the last packet
reported, subtracting that from the offset where the Send ended. On
the server's end the report was the packet's length, so a Send from
offset 0 that fitted in one packet - usually up to 32,759 octets -
returned 0, the same Send from another offset returned that offset,
and a longer one returned the octets of all its packets but the last
plus its offset: 98,277 for 100,000 octets from offset 0. On the
client's end the report was a number built from the connection's
packet counter, and Send returned a large number that changed from one
call to the next: 518,192,964 for a Send of 9 octets, in one run. The
octets themselves were sent right, all of them, once and in order; only
the count was wrong. And on the server's end, Send on a channel whose
close had completed - both ends had sent SSH_MSG_CHANNEL_CLOSE - sent
nothing but returned aOffset + aCount, as if it had sent all of it.
NOW Send returns the count of octets it passed to the peer: aCount, or
fewer when the window shut and stayed shut for about a second, or 0
when the window was shut already. What is left to send starts at
aOffset plus that count. On the server's end, Send on a channel whose
close has completed passes nothing and returns 0 at once; on the
client's end it raises eSSHClientChannelError, as before.
WHO. A program that calls Send on a channel and uses what it returns -
to find what is left to send, or to check that everything went. The
library itself uses the value nowhere: SFTP (TstSFTPClient,
tSFTPTransport and the SFTP server subsystem), snip over SSH
(TsnipSSHClient and TsnipSSHServer) and port forwarding ignore it, so
nothing they do changes. tSFTPTransport.Send and
TsnipSSHOctetConnection.RawSend return the channel's value to their
callers, and now return the right one.
THE DISCRIMINATING TEST: log in to a TstSSHSocketServer with a
TstSSHSocketClient, open a session channel, start a subsystem on it,
and Send 9 octets from offset 0 on the client's channel. An affected
release returns a large number; this one returns 9. The same Send on
the server's channel returned 0; it returns 9. Measured on Win32 and
Win64, at both ends of a channel: Sends of 0 to 100,000 octets from
offset 0 and from offsets 5 to 65,536, within the peer's window; and
against a window of 65,536 octets that nobody read, 1,000 octets and
then 65,536 more, which return 64,536 once the window has stayed shut
for about 1.6 seconds, then 500 into the shut window, which return 0 at
once, and once the window has been reopened 68,536 octets, which return
65,536; and on the server's end of a channel whose close has completed,
100 octets from offset 0 and from offset 5, which return 0. Every count
is right, and every octet arrived once and in its place, before as now.
An affected release returned a wrong count for every one of those Sends
but the ones of 0 octets or into a shut window, which returned 0 then
too; the last two returned 100 and 105.
PLATFORMS. Every platform: the same code runs on each. Measured on
Win32 and Win64.
WHAT EXISTING CODE SEES DIFFERENTLY:
- Send returns the count of octets it passed, where it returned the
values above.
- Send on the server's end of a channel whose close has completed
returns 0, where it returned aOffset + aCount, and no longer counts
octets it does not send against the peer's window.
- A Send during which another thread closes the channel stops before
its next packet and returns what it had passed until then; the
server's end went on counting octets it did not send, and the
client's end could raise an access violation. This was read in the
code, not measured.
- tSSHClientChannelBroker.Send, which a channel's Send calls for each
packet, returns the octets of data in the packet, as the server's
broker already did.
NOT INVOLVED: the octets sent, which were right before as now; the
window and its adjustment (entries 40 and 69); the limit on a packet's
size (entry 46); the key exchange, the ciphers and the MACs.
NOT CHANGED:
- A caller that ignores the count still loses the rest of its octets
when the window stays shut. SendAllOnChannel in StreamSec.SSH.Transport
waits for the window for as long as the channel is open and sends all
of them; port forwarding sends that way (entry 62).
- How long Send waits for a shut window, and that it returns at once
when the window is shut when it is called.
- On the client's end, Send on a channel whose close has completed
raises eSSHClientChannelError.
- The Send of the SSH connection itself (iSSHTransport), which a
program does not normally call, still returns a value built from its
packet counter.
- The legacy units stSSHClientChannel and stSSHServerChannel, which no
longer ship, have the same defect and are not changed.
--------------------------------------------------------------------------------
THE CIPHERS: DecryptStr OF A CIPHERTEXT THAT IS NOT WHOLE BLOCKS
================================================================================
77. BEHAVIOUR CHANGE - with bpmPKCS5, bpmZeroes, bpm10s or bpmSSL3,
DecryptStr of a ciphertext that is not a whole number of blocks, or is
shorter than one block, returned an empty string, as it should, but
kept its last octets, and the next call on the same component or
cipher took them in front of its own
These four paddings pad the last block of every message, so what they
produce is a whole number of blocks, at least one. They serve ECB, CBC
and ABC. A ciphertext cut short or lengthened on its way may be neither.
This entry does for these paddings what entry 73 does for bpmNone and
bpmCTS: it is about TstCipher.DecryptStr, the same on every
TstCustomCipherComponent, and the DecryptStr of the cipher underneath -
a tCipher, created from MustFindCipherClass or reached through an
iCipher - which the component calls to do the work.
THE STEP THAT FAILED is the one of entry 73. The cipher took the whole
ciphertext, decrypted its whole blocks and kept the partial end for the
padding, before anything asked whether such a ciphertext could be
finished. The padding then found no whole last block, and DecryptStr
returned an empty string, but the cipher kept those octets, and nothing
ended the message. The next DecryptStr on the same component or cipher
took its ciphertext as their continuation, and a sound ciphertext
returned an empty string too, as did the next three after it, measured
with bpmPKCS5, until a new IVector was set. Other calls on the
component met the kept octets as well: EncryptStr encrypted them in
front of its own plaintext - 48 octets for 32, not the ones a fresh
component gives - Decrypt and DecryptPtr raised eSecComp,
"Decrypt: Decryption failed", and then refused every in-place call
until a new IVector was set (entry 35), and DecryptBytes and
DecryptIntf returned False.
That is not the state a sound message leaves. After a sound message,
and after a ciphertext of whole blocks whose padding does not check
out, the cipher waits for a new IVector, and DecryptStr and EncryptStr
return an empty string until one is set. After a ciphertext that is not
whole blocks it did not wait: it held the octets, and EncryptStr put
them into its output.
Measured with AES, TwoFish and 3DES in ECB, CBC and ABC (the AES of the
package has no ABC), the same on Win32 and on Win64: on a fresh
component, DecryptStr of every length from 0 to two blocks and one
octet, then DecryptStr of a sound ciphertext. The cipher kept octets
after 800 of those calls - after every length that is not a whole
number of blocks, and after no other - and every one of the 800 sound
ciphertexts that followed them failed.
NOW DecryptStr does not give such a ciphertext to the cipher. It
returns an empty string, as before, and the component or cipher takes
the next call as though this one had not been made: nothing is
decrypted or kept, and no new IVector is needed. As in entry 73, the
padding counts octets it already holds: what a program has left with
the cipher through DecryptToBuf and what DecryptStr is given must come
to whole blocks, at least one. A component still gives the ciphertext
to MAC, as it gives every ciphertext DecryptStr is given. After each of
the 800 calls above the cipher holds nothing, the sound ciphertext
decrypts to what a fresh component returns, and EncryptStr, Decrypt and
DecryptBytes return what they return on a fresh component.
THE DISCRIMINATING TEST: create a TstCipher, set Algorithm to
caRijndael, Mode to cmCBC and PaddingMode to bpmPKCS5, call SetKeyStr
with 16 octets, set an IVector of 16 octets, and encrypt 16 octets with
EncryptStr. Set up a second TstCipher the same way, and call its
DecryptStr with any 6 octets, then with that ciphertext. An affected
release returns an empty string both times; this one returns an empty
string, then the 16 octets. A cipher used directly answers the same:
MustFindCipherClass(caRijndael,cmCBC).Create with 16 octets of key,
MustFindPaddingClass(bpmPKCS5).Create on it, and the IVector.
IF YOUR PROGRAM sets IVector before each DecryptStr, as these paddings
need anyway, it was not affected: setting IVector clears the octets
kept. If it called EncryptStr on a component after a DecryptStr that
returned an empty string, without setting IVector, what EncryptStr
returned carried octets of the ciphertext it had been given in front,
and does not decrypt to the message meant: encrypt it again.
WHAT EXISTING CODE SEES DIFFERENTLY, apart from right output:
- A DecryptStr after one that was turned away goes ahead as on a fresh
component or cipher, where it returned an empty string until a new
IVector was set. After a ciphertext of whole blocks, sound or not, it
still does.
- EncryptStr after one that was turned away returns the ciphertext a
fresh component returns, where it returned a longer, wrong one.
- Decrypt and DecryptPtr after one that was turned away decrypt, where
they raised "Decrypt: Decryption failed".
NOT INVOLVED: the ciphers and the paddings and what they compute -
every plaintext DecryptStr returned before it returns now, octet for
octet, 1,545 of them on each platform, and the 5,508 checks of entry 73
pass as before; what DecryptStr returns for such a ciphertext, and what
a component gives to MAC; EncryptStr of a plaintext, which these
paddings finish at any length; bpmNone and bpmCTS (entry 73), and
bpmStrSecII, which finishes a ciphertext of any length; the in-place
and ToDst methods, but for what they met after such a call. Nor the
library's own decryption: PKCS#12 and the DecryptString functions
decrypt each message with a new cipher, TstSimplePKCDecryptor keys its
TstCipher again for each message, and nothing else in the library
calls DecryptStr with these paddings. The Cipher demo keys its
TstCipher again before each DecryptStr.
NOT CHANGED: a ciphertext of whole blocks ends the message whether its
padding checks out or not. DecryptStr returns the plaintext or an empty
string, and the next call needs a new IVector, as before (entry 35).
--------------------------------------------------------------------------------
SSH CLIENT: CLOSE BEFORE A LOGIN
================================================================================
78. FIXED - TstSSHSocketClient.Close raised eSSHTransportError "No lock
created" on a connection that had not logged in, and left it open at
both ends; TsnipClient.Stop after a TsnipClient.Start that had failed
raised the same
Close ends an SSH connection: it sends SSH_MSG_DISCONNECT, closes the
socket and stops the channel broker, SSHClient.Broker. It sent the
DISCONNECT holding the transport's lock, which keeps the broker's thread
and the channels from sending at the same moment.
THE STEP THAT FAILED is taking that lock. The lock belongs to the channel
broker: the broker creates it, and a Login into 'ssh-connection', the
default service, is what makes the broker. Until such a Login had
succeeded there was no lock, and Close raised eSSHTransportError "No lock
created" before it had sent anything. That was the case
- after ConnectToHost alone;
- after a ConnectToHost that raised: a key exchange that failed, a host
key that was refused, a connection the server closed;
- after a Login that failed: a wrong password raises
eSSHClientChannelError "Login failed. Try password";
- by the code, also after a Login or RequestService into a service other
than 'ssh-connection', which makes no broker (not measured).
It concerns every TstCustomSSHClient: TstSSHSocketClient, TstSSHClient,
and the SSHClient of a TsnipClient.
WHAT IT LOOKED LIKE. Close raised, and the component forgot the
connection - Connected went False - but no DISCONNECT was sent and the
socket was not closed: SocketClient.Connected stayed True, and the server
kept the connection, and its thread for it, until the client component
was freed, which closed the socket without a DISCONNECT. After a
ConnectToHost that raised, the failed step had already closed the
socket, and only the exception was wrong. TsnipClient.Stop calls Close,
so a Stop after a TsnipClient.Start that had failed at ConnectToHost or
at the SSH login raised the same exception, and after a failed login
left the SSH connection up.
NOW Close takes the lock only when there is a channel broker. Before
there is one, no other thread uses the transport, and Close sends the
DISCONNECT without it. So at every stage Close returns without raising,
sends the DISCONNECT if the connection is still up, and closes the
socket; a second Close does nothing, as before. TsnipClient.Stop after a
failed Start returns without raising and closes the SSH connection, and
freeing a client that has connected and not logged in now sends the
DISCONNECT too.
THE DISCRIMINATING TEST: ConnectToHost to an SSH server, then Close. An
affected release raises eSSHTransportError "No lock created",
SocketClient.Connected stays True and the server keeps the connection;
this one returns, SocketClient.Connected is False, and the server ends
the connection. Measured with a TsnipServer on loopback
(Test\snifssh\SshClientCloseTest), on Win32, Win64 and Linux64: before,
10 of its 41 checks failed on each platform - Close raised after
ConnectToHost alone, after a ConnectToHost that failed its key exchange
(no method in common) and after a Login with a wrong password, and
TsnipClient.Stop raised after a TsnipClient.Start with a wrong SSH
password; in all of them but the key exchange the socket stayed open and
the server still held the connection 3 s later. Now all 41 pass, and the
server ends each connection within 35 ms of Close or Stop. A Close after
a Login that succeeded, the control, passed before and after.
Test\snifssh\SshDeadConnectionTest step 6 (a connection closed before
the server's version string) now ends with TsnipClient.Stop, which
raised "No lock created" before.
PLATFORMS. Every platform: the same code closes on each. Measured on
Win32, Win64 and Linux64.
NOT INVOLVED: a client that has logged in, whose Close takes the lock as
before; the server; the key exchange and the login themselves.
NOT CHANGED:
- After a ConnectToHost that raised, SSHClient.Connected stays True until
Close, as before: call Close (or free the component) after a failed
ConnectToHost or Login.
- The legacy unit stSSHClient, which no longer ships, has the same
defect and is not changed.
--------------------------------------------------------------------------------
THE CIPHERS: bpmCTS ON A KEY-WRAP CIPHER
================================================================================
79. BEHAVIOUR CHANGE - bpmCTS attached to a key-wrap cipher (cmKeyWrap):
with AES, EncryptStr and DecryptStr of 9 to 15 octets then wrote 1 to 7
octets past the end of the padding's buffer on the heap, and with every
key-wrap cipher EncryptStr returned its input, whole or in part, as the
ciphertext. bpmCTS no longer attaches to cmKeyWrap
A key-wrap cipher - caRijndael, caDES or caARC2 in cmKeyWrap - wraps a
key whole, with KeyWrapEncrypt and KeyWrapDecrypt (iKeyWrap). Its
EncryptStr and DecryptStr give no wrapped key: with bpmNone they return
an empty string (entries 64 and 73). Yet bpmCTS attached to it, since
the CTS padding turned away only the nonce and SSH modes: a TstCipher
in cmKeyWrap took PaddingMode bpmCTS, and
MustFindPaddingClass(bpmCTS).Create took a key-wrap cipher. Nothing in
the library does either, and the Cipher demo offers no key-wrap mode; a
program had to ask for it.
THE STEPS THAT FAILED are two, both where CTS finishes a message - in
EncryptStr, DecryptStr and DoneToDst, and in iCipherMAC.GetFinalBuf and
VerifyFinalBuf:
- CTS holds the last two blocks of a message back, in a buffer of two
blocks sized from the cipher's block size, and finishes a message
that ends inside the second block by running the block cipher itself
over the last whole block of it, the one that ends where the message
ends. AES key wrap gives its block size as 8 octets, the unit key wrap
works in, but its block function is AES's and takes 16. So for a
message of 9 to 15 octets CTS ran 16 octets starting 1 to 7 octets
into a buffer of 16: the block function read the 1 to 7 octets that
follow the buffer on the heap and overwrote them with octets of its
output, in EncryptStr and DecryptStr alike. Measured on Win32 and
Win64 with each of the four AES implementations of the package
(stAES, stAESNI, stAESCT and stAESBG) and through TstCipher: 9 octets
wrote 1 octet past the buffer, 12 wrote 4, 15 wrote 7. On Linux64,
with stAES, valgrind names the AES block function, called from
tBlockPaddingCTS.GetFinalBuf and VerifyFinalBuf. What followed
depended on what lay next on the heap: on Win32 a later allocation
raised EAccessViolation inside the memory manager a few calls on; on
Win64 the program ran on. The output depended on those octets too.
No correct use reaches it: key wrap (RFC 3394 for AES, RFC 3217 for
3DES and RC2) takes whole 64-bit blocks and checks its own integrity
value, and CTS exists only for lengths that are not whole blocks.
EncryptStr and DecryptStr skip that check with any padding, so no
program could have had a wrapped key this way. This is not a
security update: the fix refuses a misconfiguration.
- A key-wrap cipher does not encrypt a block it is handed outside
KeyWrapEncrypt and KeyWrapDecrypt: its EncryptToBuf and DecryptToBuf
decline it, return False and write nothing. CTS did not look at that
answer; it went on as though its buffer now held the ciphertext, and
gave it out. With 3DES and RC2, whose block function is the 8 octets
they report, nothing was written past the buffer, but EncryptStr of 8
octets returned those 8 octets unchanged, and of 9 to 15 octets a
result whose first 1 to 7 octets were those of the input; DecryptStr
did the same the other way. With AES this came on top of the first
step. From 16 octets on, the cipher declined a block before CTS was
asked to finish, and EncryptStr and DecryptStr returned an empty
string.
NOW:
- bpmCTS does not attach to cmKeyWrap, as no padding attaches to a mode
it cannot serve (entry 39). MustFindPaddingClass(bpmCTS).Create on a
key-wrap cipher raises ePaddingError, "Unsupported mode". A TstCipher
in cmKeyWrap does not take PaddingMode bpmCTS, whether it is set
before Mode or after: PaddingMode stays bpmNone, the one padding that
serves cmKeyWrap, and SetKeyStr and the other SetKey* methods give the
cipher bpmNone.
- Where a cipher declines a block CTS hands it to finish a message,
GetFinalBuf and VerifyFinalBuf raise ePaddingError, "Mode not
supported for CTS padding", and give out nothing. No cipher of the
library that CTS still attaches to declines one; this is for a cipher
class of a program's own, in a mode tBlockCipher does not run.
Measured with an AES class that reports cmPipedPCFB: its EncryptStr of
16 octets returned the 16 octets unchanged before, and raises now.
THE DISCRIMINATING TEST: create a cipher with
MustFindCipherClass(caDES,cmKeyWrap).Create and 24 octets of key, and
call MustFindPaddingClass(bpmCTS).Create on it. An affected release
takes it, and EncryptStr of 8 octets returns the same 8 octets; this one
raises ePaddingError, "Unsupported mode". Use 3DES: with AES the test
writes past the buffer. Or set up a TstCipher with Algorithm caDES, Mode
cmKeyWrap and PaddingMode bpmCTS, and call SetKeyStr with 24 octets: an
affected release reports PaddingMode bpmCTS, this one bpmNone.
IF YOUR PROGRAM used bpmCTS on a key-wrap cipher, what EncryptStr
returned was neither a wrapped key nor an encryption of the input: a
key of 8 octets came back as it was, and one of 9 to 15 octets with its
first 1 to 7 octets as they were. Treat what was kept in that form as
exposed, replace those keys, and wrap keys with KeyWrapEncrypt.
WHAT EXISTING CODE SEES DIFFERENTLY, apart from no write past the
buffer:
- ePaddingError, "Unsupported mode", from
MustFindPaddingClass(bpmCTS).Create on a key-wrap cipher.
- A TstCipher in cmKeyWrap keeps PaddingMode bpmNone where it took
bpmCTS. Its EncryptStr then returns an empty string for a whole
number of 8-octet blocks and raises eSecComp for any other length,
and DecryptStr returns an empty string (entries 64 and 73), where they
returned the output above.
NOT INVOLVED: KeyWrapEncrypt and KeyWrapDecrypt, which wrap without a
padding, and so the library's own key wrapping in CMS. bpmCTS in ECB,
CBC, CFB, OFB, CTR and ABC: every EncryptStr and DecryptStr of the
ciphers it serves gives the same octets as before - 308 pairs on Win32
and Win64 (AES, 3DES, TwoFish, Blowfish, RC2, SEED, Camellia and
SHACAL-2), 273 on Linux64. The other paddings: of every cipher the
package registers, AES in cmKeyWrap is the one whose block function
takes more than its block size, and bpmNone, the one other padding that
attaches to it, never runs the block function itself; bpmZeroes,
bpm10s, bpmPKCS5, bpmSSL3, bpmStrSecII, bpmOMAC and bpmXCBCMAC do not
attach to cmKeyWrap.
NOT CHANGED: tBlockPadding.ChangeCipher, which moves a padding to
another cipher, does not ask whether the padding serves that cipher's
mode. Nothing in the library moves a CTS padding; the SSH transport,
which calls ChangeCipher, moves only its own paddings.
--------------------------------------------------------------------------------
SSH: THE SERVER'S ANSWER TO A GLOBAL REQUEST THAT ASKED FOR NONE
================================================================================
80. FIXED - an SSH server answered SSH_MSG_REQUEST_FAILURE to a global
request it did not act on also when the client had not asked for an
answer, and the client took it for the answer to its next request:
TstSSHForwardingClientSocket.Open raised "Failure opening remote
listener" while the server was listening on the port
A client sends SSH_MSG_GLOBAL_REQUEST for what concerns the whole
connection rather than one channel: tcpip-forward and
cancel-tcpip-forward for remote port forwarding (ssh -R), and requests
of its own, such as OpenSSH's no-more-sessions@openssh.com. Each carries
a want_reply flag. RFC 4254 section 4:
The recipient will respond to this message with
SSH_MSG_REQUEST_SUCCESS or SSH_MSG_REQUEST_FAILURE if 'want reply' is
TRUE.
and, as an answer does not say which request it answers,
it is REQUIRED that replies to SSH_MSG_GLOBAL_REQUESTS MUST be sent in
the same order as the corresponding request messages.
A client therefore takes each answer as the answer to the oldest of its
requests that asked for one and has not had it. TstSSHClient does, and
so does OpenSSH's ssh; OpenSSH's sshd answers only when want_reply is
set. The section also says "If the recipient does not recognize or
support the request, it simply responds with SSH_MSG_REQUEST_FAILURE":
which answer to give, not an answer to a request that asked for none.
Section 5.4 says it outright of channel requests: "If 'want reply' is
FALSE, no response will be sent to the request."
THE STEP THAT FAILED is how TstSSHServer and TstSSHSocketServer handle a
global request that no forwarding listener acts on: a request the server
does not know, a cancel-tcpip-forward of a port that is not forwarded,
and a tcpip-forward to a server with no TstSSHListenerControllerSocket.
The server answered each SSH_MSG_REQUEST_FAILURE without looking at
want_reply. The client took that answer for the answer to its next
request that asked for one, and dropped the real answer, which came
after it, as one nobody was waiting for. What an application saw:
TstCustomSSHClient.GlobalRequest with aWantReply False, then
TstSSHForwardingClientSocket.Open, and Open raised eSSHClientChannelError
"Failure opening remote listener" - although the server had bound the
port, and a connection to it was carried through to the target all the
same. It struck when the stray answer arrived after the next request had
been sent, which it did 10 times in 10 on Win32 and on Win64 when the
two calls came one after the other; an answer that arrived before was
dropped unnoticed.
OpenSSH's ssh sends no-more-sessions@openssh.com without want_reply
only to a server that identifies itself as OpenSSH, and
cancel-tcpip-forward without want_reply (its ~C -KR escape, a
multiplexing client that closes) for a forward it asked for, which the
server answered only if it held no such forward. So in ordinary use
against OpenSSH's ssh the stray answer did not arise. Measured with
OpenSSH 9.5 on Windows, ssh -N -R against a TstSSHSocketServer set to
identify itself as OpenSSH: ssh received an SSH_MSG_REQUEST_FAILURE
after the SSH_MSG_REQUEST_SUCCESS of its tcpip-forward, and dropped it
only because nothing of its own was waiting for an answer by then.
NOW the server reads want_reply first, and answers a global request no
listener acts on only when want_reply is set, as it did already for a
channel request and for a tcpip-forward it refuses. A global request
that ends after its name, with no want_reply, now ends the connection:
the server sends SSH_MSG_DISCONNECT, "Disconnected by application" (11),
as it does for a channel request that ends before want_reply. Before,
one the server did not know was answered SSH_MSG_REQUEST_FAILURE.
THE DISCRIMINATING TEST: log in to a TstSSHSocketServer with a
TstSSHListenerControllerSocket, and send a global request the server
does not know, without want_reply, and at once tcpip-forward on
127.0.0.1 port 0 with want_reply. An affected release answers
SSH_MSG_REQUEST_FAILURE and then SSH_MSG_REQUEST_SUCCESS carrying the
port; this one answers SSH_MSG_REQUEST_SUCCESS alone. Without
want_reply, no-more-sessions@openssh.com, a cancel-tcpip-forward of a
port that is not forwarded, and a tcpip-forward to a server with no
TstSSHListenerControllerSocket each got SSH_MSG_REQUEST_FAILURE from an
affected release and get nothing from this one; with want_reply each is
answered SSH_MSG_REQUEST_FAILURE by both. With OpenSSH's ssh -vvv -N -R
against a server identifying itself as OpenSSH, ssh logs "receive
packet: type 82" after its forward's "type 81" on an affected release,
and no type 82 on this one.
PLATFORMS. Every platform: the same code runs on each. Measured on Win32
and Win64.
NOT INVOLVED: the client, which already answered and matched answers as
the RFC says (it answers the server's requests since entry 69); channel
requests; a tcpip-forward the server grants or refuses, and a
cancel-tcpip-forward of a forward it holds, which were answered as asked
before too; the key exchange, the ciphers and the MACs.
NOT CHANGED:
- What the server acts on: tcpip-forward and cancel-tcpip-forward, as
before, and no other global request. It does not act on
no-more-sessions@openssh.com.
- The forwarding listeners, which read want_reply themselves and send
SSH_MSG_REQUEST_SUCCESS only when it is set.
- The legacy unit stSSHServerChannel, which no longer ships, has the same
defect and is not changed.
--------------------------------------------------------------------------------
THE CIPHERS: GetFinalBuf WHILE A DECRYPTION HOLDS ITS LAST BLOCK
================================================================================
81. BEHAVIOUR CHANGE - with BlockPaddingMode bpmPKCS5, bpmZeroes, bpm10s or
bpmSSL3, GetFinalBuf called while a cipher held back the last block of
a decryption encrypted that ciphertext as the last block of an
encryption, with bpm10s after writing one octet past the buffer it is
held in; it now raises ePaddingError
These four paddings pad the last block of a message, so a cipher that
uses one keeps back the end of what it has been given until it is told
that the message ends. Encrypting, it keeps back only the part of a
block that the plaintext ends in, and GetFinalBuf pads that part and
encrypts it: the last block of the ciphertext. Decrypting, it keeps back
the last block it has been given - a whole block when the ciphertext so
far ends on a block boundary - and VerifyFinalBuf decrypts it and
removes the padding (entry 71). They serve ECB, CBC and ABC. As in entry
71, this is about a cipher used without a component - a tBlockCipher
such as tRijndael_CBC or t3DES_CBC, created by a program with
BlockPaddingMode set - and about a TstCipher's cipher reached through
the component's interfaces (WHO, below).
THE STEP THAT FAILED is GetFinalBuf, which padded what the cipher held
without asking which of the two it was. Called after DecryptToBuf or
DecryptToPtr had left a whole block of ciphertext held back, it padded a
block that was already full:
- bpm10s starts its padding with the octet $80, written after the octets
held. With a whole block held, that is the octet after the buffer the
padding holds the block in - 16 octets for AES, 8 for 3DES, on the
heap. So GetFinalBuf wrote $80 one octet past that buffer, then
encrypted the held ciphertext, returned it as the last block and ended
the message. valgrind on Linux64 reports an invalid write of 1 octet
in tBlockPadding10s.PadCache, 0 octets after a block of 16 (AES) or 8
(3DES). The octet is always $80 and always lands there; what lies
there depends on the memory manager, and what the write can lead to
has not been traced. On Win32 and Win64 nothing visible followed from
it in these measurements.
- bpmPKCS5, bpmZeroes and bpmSSL3 add nothing to a full block, so they
wrote nothing out of place: GetFinalBuf encrypted the held ciphertext
as though it were the padded last block of a plaintext, returned that
and ended the message.
Either way the message was over: VerifyFinalBuf with the rest of the
ciphertext then returned False and wrote nothing.
NOW GetFinalBuf raises ePaddingError, "Unable to process pending input:
the last block of a decryption is held back", before it pads or writes
anything, and leaves the cipher as it was: the block stays held, and
VerifyFinalBuf with the rest of the ciphertext still completes the
decryption. It is the error GetFinalBuf raises with bpmNone when the
cipher holds octets that it cannot finish.
WHO. A program that goes both ways in one message on one cipher: after
DecryptToBuf or DecryptToPtr of at least one block of ciphertext, while
the octets given so far end on a block boundary, and before
VerifyFinalBuf or a new IVector, it asks for the end of an encryption -
GetFinalBuf, GetFinal, or EncryptStr, which is EncryptToBuf and then
GetFinalBuf, of an empty string or of octets that end on a block
boundary. Through a TstCipher the same calls reach its cipher: the
component's iCipher DecryptToBuf and DecryptToPtr pass their octets on
to it, (TstCipher as iCipherMAC) is the cipher's own interface, and
TstCipher.EncryptStr calls the cipher's EncryptStr. Which calls a
program makes, and in what order, is its own; what the data holds does
not decide it, only whether the ciphertext given so far ends on a block
boundary.
NOT INVOLVED: the library's own use of these paddings, which never goes
both ways in one message. TstCipher's DecryptToDst and EncryptToDst keep
to one way per message (the other raises), and DoneToDst finishes that
way; DecryptStr gives the whole message to VerifyFinalBuf, and the
in-place Decrypt, DecryptPtr, DecryptBytes and DecryptIntf do not go
through the padding. TstCipherMAC, whose CBC-MAC uses bpmZeroes and
bpm10s, never decrypts. CMS, PKCS#8, PKCS#12 and PEM, tEncryptStream and
tDecryptStream use each cipher one way. TLS and SSH do not use these
paddings. Nor the ciphers, the padding and its removal, or encryption
and decryption that each keep to one way; and bpmNone, bpmCTS and
bpmStrSecII.
THE DISCRIMINATING TEST: create a tRijndael_CBC with a key of 16 zero
octets, set IVector to 16 zero octets and BlockPaddingMode to bpmPKCS5.
Call DecryptToBuf with 32 zero octets and aDstCount 32: it returns True,
sets aDstCount to 16 and holds back the other 16, before as now. Then
call GetFinalBuf with a buffer of 16 octets. An affected release returns
and fills the buffer; this one raises ePaddingError with the message
above and leaves the buffer as it was. With bpm10s the same, and on an
affected release valgrind reports the write past the padding's buffer.
WHAT EXISTING CODE SEES DIFFERENTLY, apart from no write past the
buffer:
- GetFinalBuf, GetFinal and EncryptStr, of a tBlockCipher and of a
TstCipher as above, raise ePaddingError in that state, where they
returned the held ciphertext encrypted and ended the message.
- After VerifyFinalBuf, or DecryptStr through it, refused a bpmZeroes
padding - the decrypted message did not end in a 0 octet -
GetFinalBuf, and so GetFinal, raise the same ePaddingError, where
they returned without writing anything: bpmZeroes leaves that block
held when it refuses it. After a refused padding of the other three,
GetFinalBuf returns without writing, as before.
- GetFinalBuf given a buffer shorter than a block raises "Final buffer
too small - %d / %d" as before, now with the block length as the
second number - what the buffer must hold - where it gave the number
of octets held.
PLATFORMS. Every platform: the same code runs on each. Measured on
Win32, Win64 and Linux64.
Checked with all four paddings, with AES-128 and 3DES in ECB and CBC and
3DES in ABC, and a message of 3 blocks: the first 2 blocks of its
ciphertext go to DecryptToBuf, which writes 1 and holds 1. Then each of
GetFinalBuf, GetFinal and EncryptStr of an empty string, and through a
TstCipher (as iCipher).DecryptToBuf followed by (as
iCipherMAC).GetFinalBuf or by TstCipher.EncryptStr, must raise
ePaddingError and write nothing, and VerifyFinalBuf of the other 2
blocks must then complete the plaintext; EncryptStr of one block must
raise ePaddingError; and, as before, an encryption finished with
GetFinalBuf must give the reference ciphertext, after which a second
GetFinalBuf neither raises nor writes. All 140 checks as expected on
Win32, Win64 and Linux64, and valgrind reports no invalid access.
Before, 120 failed - all but the last - and valgrind counted 30 invalid
writes, one for each of the six ways with each of the five bpm10s
configurations; and 5 in the measurement that found the defect,
GetFinalBuf after DecryptToBuf of 2 blocks with bpm10s, where it now
counts none. Entry 71's checks give the same results as before, all
1,562,948 as expected on the three platforms, and valgrind reports no
invalid access in them; so do those of entries 43, 49 and 58: 72,567,
85,783, and 500,316 on Win32 and 424,406 on Win64.
NOT CHANGED: going both ways in one message is not refused as such; a
cipher does not record which way its message goes. A decryption whose
ciphertext so far does not end on a block boundary holds only part of a
block, which GetFinalBuf cannot tell from the part an encryption holds:
it pads that part of the ciphertext, encrypts it and returns it, before
as now, without writing outside its buffers. EncryptToBuf and
EncryptToPtr after a decryption go on from where the decryption left
the chaining, and given octets that do not end on a block boundary they
replace a held block, which is lost, before as now.
--------------------------------------------------------------------------------
SFTP CLIENT: COMPARING A LOCAL COPY BY md5-hash-handle
================================================================================
82. FIXED - TstSFTPClient.CmpFile given a local file name raised
eSFTPClientError "Feature not supported" on a component that had not
connected yet, although the server offers md5-hash-handle, and GetFile
given local file names, with aCanOverwrite and aResume, downloaded the
whole file there instead of comparing it part by part
md5-hash-handle is the extension of SFTP version 5 with which a client
asks the server for the MD5 hash of a part of an open file, to compare
it with the same part of a copy it has. draft-ietf-secsh-filexfer-05,
section 8.1:
"This extension allows a client to easily check if a file (or
portion thereof) that it already has matches what is on the server."
A server that offers it names it in the "supported" extension of its
first reply, SSH_FXP_VERSION, which TstSFTPClient reads as it connects
and shows as ServerSupported.ExtensionNames (entry 75). Two methods
given local file names use the extension when the server names it:
- CmpFile, given a local file, a remote file, an offset and a length,
asks for the hash of that part of the remote file and returns whether
it matches the same part of the local file. When the server does not
name md5-hash-handle, it raises eSFTPClientError, "Feature not
supported: the server does not offer the md5-hash-handle extension".
- GetFile, with aCanOverwrite and aResume and a local file that exists,
opens the local file for reading and writing, asks for the hash of
each part of 131,072 octets, and reads from the server only the parts
whose hashes differ. When the server does not name md5-hash-handle, it
empties the local file and downloads the whole file.
THE STEP THAT FAILED is where the two looked for the name. A component
connects - opens the SFTP session and reads SSH_FXP_VERSION - in the
first call that needs the server: Connect, or any method that sends a
request. Both looked in ExtensionNames before they had connected, and
on a component that had not connected yet the list was empty. So, as
the first call on a component:
- CmpFile raised eSFTPClientError, "Feature not supported: the server
does not offer the md5-hash-handle extension", without connecting or
sending anything;
- GetFile emptied the local file and downloaded the whole file. The file
it left was right, but every part was transferred, also those the
local file already held, and a download cut short left less of the
local file than there had been.
On a component that had connected already both went ahead as described.
IN RELEASE 4.1.4.360 the list was empty after a Connect too: that
release kept no extension name from a server that lays out "supported"
as the draft or as ProFTPD does (entry 75). So there CmpFile given a
file name raised "Feature not supported", and GetFile downloaded the
whole file, whether the component had connected or not. Entry 75 makes
the names arrive when the component connects; this entry makes the two
methods see them in the first call too.
WHO WAS AFFECTED. A program using TstSFTPClient with a server that
speaks version 5 and names md5-hash-handle. None was at hand here:
OpenSSH's sftp-server speaks only version 3, and TstSSHServer's SFTP
subsystem does not send "supported". With them, CmpFile raises "Feature
not supported" and GetFile downloads the whole file, before and after.
NOW both connect first, as the other methods do, and then look for the
name. GetFile connects there only when it needs the list: when the
local file exists and both aCanOverwrite and aResume are set. In the
other cases it decides as before, so GetFile of an existing local file
without either flag still raises eSFTPFileAlreadyExists and does not
connect. With a server that does not name md5-hash-handle, CmpFile
raises the same eSFTPClientError, with the same text, now after it has
connected, and GetFile downloads the whole file, as before. On a
component that cannot connect - no Transport, and no channel from
OnGetTransport - both now raise eSFTPClientError "Unable to connect",
as every other method does; before, CmpFile raised "Feature not
supported" there, and GetFile raised "Unable to connect" after it had
emptied the local file (measured).
THE DISCRIMINATING TEST: on a TstSFTPClient that has not connected, call
CmpFile with a local file name against a server that names
md5-hash-handle. An affected release raises eSFTPClientError "Feature
not supported" and sends nothing; this one asks the server for the hash
and returns whether the parts match. Call Connect first, and both give
the same answer. Measured with an SFTP server inside the test program
that names md5-hash-handle and answers it with hashes from the Delphi
RTL (Test\sftpinterop\SftpPutFileTest, step 13; the program links
stMD5, see NOT CHANGED), on Win32 and Win64: before, 6 of its checks
failed. CmpFile raised instead of returning True for a local file
holding the remote file and False for one that differs, and sent no
open request and no md5-hash-handle. GetFile with aCanOverwrite and
aResume, of a local file of 262,144 octets that differs from offset
135,168, asked for no hash and read the whole file, at offsets 0 and
131,072; it now asks for the hash of each of the two parts and reads at
131,072 only. Now they pass. The controls passed before and after: the
same calls after Connect; a server that does not name md5-hash-handle,
where CmpFile raises the same eSFTPClientError, with the same text, and
opens nothing, and GetFile reads the whole file; and GetFile of an
existing local file without aCanOverwrite or aResume, which raises
eSFTPFileAlreadyExists and sends nothing. The local file GetFile left
held the remote file before and after. SftpSelfTest, our client against
our server over loopback, passes its 39 checks (on Win32, where it is
built).
PLATFORMS. Every platform: the same code runs on each. Measured on Win32
and Win64.
NOT INVOLVED: the server; reading "supported", which is entry 75; the
md5-hash-handle request and its answer; the overloads of CmpFile and
GetFile that take a stream, which connected first already; the other
methods; SSH and the channel.
NOT CHANGED:
- The comparison hashes the client's side of each part with the
library's MD5, which a program had only when it linked the unit
stMD5, itself or through a TLS unit; no SFTP or SSH unit linked it.
Without it the comparison went wrong in each of the ways entry 89
describes. That is a separate defect, not changed by this entry;
entry 89 fixes it.
- The legacy unit stSFTPClient, which no longer ships, has the same
defect and is not changed.
83. FIXED - GetFile, comparing by md5-hash-handle, grew a local file that
already held the whole remote file to the next multiple of 131,072
octets, with zeros, when the file was not such a multiple, and left a
stream positioned there, past its end
GetFile compares a local copy with the remote file part by part, by
md5-hash-handle (entry 82), when the server names that extension and
the copy holds octets: given local file names with aCanOverwrite and
aResume, or given a stream that holds octets after its position,
without aResume. The parts are of 131,072 octets from the start of the
file, and the last is shorter unless the file is a multiple of that.
For a part whose hashes match GetFile moves on; a part that differs it
reads from the server.
THE STEP THAT FAILED is moving on after a match. GetFile always moved
131,072 octets on, also after the last part. When the last part matched
and was shorter - the copy held the whole remote file, and the file was
not a multiple of 131,072 octets - GetFile went on to the next
multiple, past the end of the copy and of the remote file, read once
there, was told it was at the end of the file, and returned True. What
that left:
- given local file names, a local file grown to that multiple, since
GetFile sets the file's size to where it ended: a file of 5 octets
became 131,072, one of 131,077 became 262,144, each the octets it held
and then zeros;
- given a stream, a stream of the same size, positioned at that
multiple, past its end.
So a download of a file that had not changed since the last one, which
is what the comparison is for, spoiled the local copy. A copy whose
last part differs has that part read and ends right, before as now.
IN RELEASE 4.1.4.360 the comparison ran only when ExtensionNames named
md5-hash-handle, and that release kept no name from a server that lays
out "supported" as the draft or as ProFTPD does (entry 75), so no server
known here brought it about. Entries 75 and 82 make the comparison run,
and with them alone GetFile would have grown such files from every
server that names md5-hash-handle. It also needed the library's MD5 in
the program, which the SFTP units link since entry 89; without it the
comparison went wrong in the ways entry 89 describes.
NOW after a part that matches GetFile moves on by the octets it
compared: 131,072, or, for the last part, to the end of the copy. That
is also the end of the remote file: had the remote file gone on, the
server would have hashed more octets than the copy holds there, and the
hashes would not have matched. GetFile then stops and reads nothing
more: a local file keeps its size, and a stream its size, with the
position at its end.
THE DISCRIMINATING TEST: on a TstSFTPClient after Connect, in a program
that links stMD5, GetFile with aCanOverwrite and aResume of a local
file that holds a remote file of 5 octets, from a server that names
md5-hash-handle. An affected release reads once, at offset 131,072, and
leaves a local file of 131,072 octets; this one reads nothing and
leaves the 5 octets. Measured with the server in the test program
(Test\sftpinterop\SftpPutFileTest, step 14), on Win32 and Win64, for
remote files of 5, 131,077 and 262,144 octets, given file names and
given a stream: before, 8 of its checks failed, with entry 82 and
without it - for 5 and 131,077 octets GetFile read at the next multiple
of 131,072, and left the file grown to it or the stream positioned
there. Now they pass. For 262,144 octets, a multiple, it read nothing
and changed nothing, before and after. Of the 177 checks of
SftpPutFileTest, 14 failed before entries 82 and 83, and 8 with entry
82 alone; now all pass.
PLATFORMS. Every platform: the same code runs on each. Measured on Win32
and Win64.
NOT INVOLVED: the parts before the last; a part that differs, which is
read as before; GetFile with aResume given a stream, which reads on from
the stream's position without comparing; the server and its hash.
NOT CHANGED:
- The legacy unit stSFTPClient, which no longer ships, has the same
defect and is not changed.
--------------------------------------------------------------------------------
SSH: A THREAD WAITING IN A CHANNEL'S RECV WHEN THE CHANNEL ENDS
================================================================================
84. BEHAVIOUR CHANGE - a thread waiting in Recv on an SSH client channel
never returned when the connection under the channel ended, when the
program closed the SSH client, or when the server closed the channel
without an EOF first; on Win32 it did not return at the server's EOF
either
A program reads a channel of a TstSSHSocketClient (CreateChannel) with
Recv. A Recv that asks for more than has arrived waits: on Win32 on the
channel's semaphore, for ChannelReadTimeout (INFINITE by default),
elsewhere in a loop that polls the channel. It returns when it has what
it asked for, or when the channel is marked as having nothing more to
come and everything that came before has been read - with what it has,
0 when nothing was left. That mark is what PeerEOF reports. A change of
the channel's State does not end the wait.
THE STEP THAT FAILED is marking the channel, and on Win32 waking the
thread waiting on it, when nothing more can arrive:
- The connection ended: the server sent SSH_MSG_DISCONNECT, or the
connection was closed or reset without one (entry 74). The channel
broker stopped and left every channel as it was, an open one
csConnected with PeerEOF False.
- The program closed the SSH client (SSHClient.Close, or Free). That took
the channels off the broker without marking them.
- The server sent SSH_MSG_CHANNEL_CLOSE without an SSH_MSG_CHANNEL_EOF
before it, as a TstSSHSocketServer channel does when it is closed. The
channel went to csClosing, unmarked.
- On Win32 only, the server sent SSH_MSG_CHANNEL_EOF. The channel was
marked, but its semaphore was not released, so a thread already
waiting on it stayed there.
WHAT IT LOOKED LIKE: that Recv never returned, on Win32, Win64 and
Linux64 alike (the EOF case on Win32 only). Closing the SSH client did
not end it, so a program had no way to end such a thread. A Recv made
afterwards, with everything read, waited the same way instead of
returning 0, and Close on a channel whose connection had ended raised
eSSHTransportError "Transport is not connected".
NOW:
- When the channel broker stops - after a DISCONNECT, after the
connection is lost, or because the SSH client is being closed - it
tells every channel that nothing more will arrive. An open channel
goes to csClosing, as when the server closes it: what had arrived can
still be read, then Recv returns 0, and PeerEOF is True. Its Close has
no connection left to send its CLOSE on: it sends nothing and
completes the channel to csClosed without raising. Send on it raises
eSSHTransportError, as before.
- The server's SSH_MSG_CHANNEL_CLOSE marks the channel too, whether or
not an EOF came first: the server sends no data after its CLOSE (RFC
4254 section 5.3). PeerEOF is True after it.
- On Win32 marking the channel releases its semaphore, and Recv no
longer waits on the semaphore once the channel is marked.
Measured over 16 runs: a waiting Recv returned 0 within 125 ms of the
DISCONNECT, the reset or the FIN on Win32 and Win64 and within 40 ms on
Linux64 - most of it the time the client takes to notice that the
connection has ended (entry 74) - and within 32 ms of the server's EOF or
CLOSE, or of SSHClient.Close, on Win32 and Win64, 2 ms on Linux64.
CODE THAT WATCHES A CHANNEL'S STATE sees the connection end now, as it
saw the server close the channel: a snip connection over SSH (TsnipClient,
TsnipSSHClient) stops waiting for its next message, the port-forwarding
threads close their TCP connection, and TstSFTPClient's wait for a reply
raises eSFTPClientError "Channel closed while awaiting an SFTP packet".
Each of them used to wait until the SSH client was closed.
NOT CHANGED:
- The channels stay on the broker until the SSH client is closed; the
broker's thread does not take them off, so a thread using a channel
when the connection ends still finds its broker there.
- A channel whose open the server had not answered when the connection
ended stays csConnecting - it never will be answered - and closing the
SSH client makes it csClosed. TsnipSSHClient.Start raises EsnipClosed
naming csConnecting, as before.
- Closing the SSH client leaves a channel that was open in csClosing, as
before, now with PeerEOF True.
- ChannelReadTimeout, and what Recv returns while the channel is open.
- The legacy unit stSSHClientChannel, which no longer ships, is not
changed.
THE DISCRIMINATING TEST: open a session channel on a TstSSHSocketClient
to a server that sends nothing on it, call Recv(Buffer, 0, 64) on a
thread of its own, and call SSHClient.Close from another. An affected
release never returns from that Recv; this one returns 0 at once. The
same holds when the server disconnects instead, or closes the channel.
NOT INVOLVED: noticing that a connection has ended (entry 74), the
transport, the key exchange, the ciphers, and the server's channels.
--------------------------------------------------------------------------------
THE CIPHERS: SEED ON THE 64-BIT POSIX TARGETS
================================================================================
85. BEHAVIOUR CHANGE - SEED (caSEED) computed something other than SEED on
Linux64, macOS, iOS and 64-bit Android: no RFC 4269 test vector came
out right there, SEED-ECB and SEED-CBC did not decrypt what they had
encrypted, and SEED-CFB and SEED-OFB ciphertext decrypted only on one
of those targets. SEED is SEED on every target now, so SEED-CFB and
SEED-OFB data encrypted there by an earlier release no longer decrypts
SEED is reached three ways: a TstCipher with Algorithm caSEED; a tCipher
from FindCipherClass or MustFindCipherClass with caSEED; and CMS content
encryption with SEED-CBC through TstMPEnvelopedData, which refused
SEED-CBC until entry 90. Nothing else in the library uses it: TLS and
SSH offer no SEED cipher, and the PBES2 encryption of PKCS#8 and
PKCS#12 keys offers no SEED.
THE STEP THAT FAILED is SEED's arithmetic on its 32-bit words, which
stSEED did in LongWord. Delphi's LongWord is 4 octets on Windows and on
32-bit Android, but 8 on the 64-bit POSIX targets. SEED byte-swaps each
word of a block on the way in and on the way out, and rotates the key
by 8 bits between round keys, both with shifts. On those targets the
bits a left shift moves past bit 31, which belong to no 32-bit word,
stayed above it, and the next right shift of the same word moved them
back in:
- in the key schedule, so that the round keys from the second on came
out wrong. Of the four keys in RFC 4269, the all-zero key alone gave
the sixteen round keys the RFC lists; the other three gave only the
first of them.
- in the byte swap on the way out, which ORed octets of the block's own
input into the output. So even with the right round keys, those of
the all-zero key, the output block was wrong.
What that did to each mode, on those targets:
- ECB and CBC: decryption did not give back what encryption was given.
A 64-octet round trip through Encrypt and Decrypt came back
different, and both SEED-CBC test cases of RFC 4196 failed in both
directions. Data encrypted with SEED-ECB or SEED-CBC there could not
be decrypted by the release that encrypted it, and cannot be by this
one. No CMS message held such data: see entry 90.
- CFB and OFB run only the encrypting direction of the block function,
both ways, so a round trip on the same target worked. But the
ciphertext was not SEED's: it did not decrypt on Windows or with any
other SEED implementation, and theirs did not decrypt there.
IF YOUR PROGRAM keeps data it encrypted with SEED-CFB or SEED-OFB on one
of those targets, decrypt it with the release that encrypted it before
upgrading, and encrypt it again after: this release does not decrypt it.
Nothing changes for data encrypted on Windows or on 32-bit Android.
THE DISCRIMINATING TEST is RFC 4269 appendix B.2. Create the cipher with
MustFindCipherClass(caSEED,cmECB).Create and the 16-octet key 00 01 02
.. 0F, and Encrypt 16 zero octets. This release gives C1 1F 22 F2 01 40
50 50 84 48 35 97 E4 37 0F 43 on every target, as the RFC does. An
affected release gives 3F 08 C5 5E E3 C2 A1 BC D4 5D 9B 3C 64 C7 F2 24
on Linux64, and the RFC's answer on Windows.
PLATFORMS. SizeOf(LongWord) is 8 octets on Linux64, macOS (x64 and
ARM64), iOS (device and simulator) and Android ARM64, measured with
every installed compiler for them from Delphi 10.3 Rio to Delphi 13, and
4 on Win32, Win64 and 32-bit Android, measured with Delphi 13. stSEED
has done its arithmetic in LongWord since the first release, so every
release is affected on the 8-octet targets.
SEED was run on Win32, Win64 and Linux64; on the other 8-octet targets
stSEED was compiled, not run. Free Pascal's LongWord is 4 octets
(measured with FPC 3.2.2 on x86-64 Linux), so an FPC build of stSEED
did not have the defect.
NOW stSEED does SEED's arithmetic in UInt32, which is 4 octets on every
target. No declaration in its interface changed. On Windows and 32-bit
Android, where LongWord and UInt32 are the same type, SEED gives the
same octets as before. Measured with Test\seed\SeedKatTest, which runs
the four RFC 4269 vectors (the sixteen round keys, and EncryptBlock,
DecryptBlock and the ToDst pair), the two SEED-CBC cases of RFC 4196
both ways, and CFB and OFB against their definitions: before, 65 of its
88 checks failed on Linux64; now all 88 pass on Win32, Win64 and
Linux64, and all 88 passed on Win32 and Win64 before as well.
NOT INVOLVED: the other ciphers. Of the 294 units in the runtime
package, stSEED was the one that did 32-bit word arithmetic in
LongWord. Four others name it, for no such arithmetic: stSmallPrimes
(a table of small primes), stMemoryPool (a native-width integer on
targets other than x64, and a thread-local-storage slot number),
StreamSec.DSI.ArithTypes (UInt32 for a compiler that lacks it, checked
to be 4 octets) and stSHACAL (tables for its assembler; SHACAL-2 is not
registered where there is no assembler for it, entry 67).
--------------------------------------------------------------------------------
SSH AND SFTP: A STRING CUT SHORT AT THE END OF A MESSAGE
================================================================================
86. FIXED - SSH and SFTP read the length of a string from past the end of
a message that had fewer than 4 octets left for it: a message cut short
there could pass as though it ended with an empty string, or the read
raised EAccessViolation; and SFTP file attributes that counted more
extensions than they held were read on into the memory after them
RFC 4251, section 5, lays out the "string" of the SSH protocols, which
SFTP uses too:
They are stored as a uint32 containing its length (number of bytes
that follow) and zero (= empty string) or more bytes that are the
value of the string.
Names, name-lists, messages, passwords, key blobs, file names and
handles are strings. The library reads each with DecodeBytes in
StreamSec.SSH.Types, directly or through DecodeStr and DecodeUtf8Str,
handing it the message, where the string starts, and how many octets of
the message are left from there.
THE STEP THAT FAILED is reading the length. DecodeBytes read the 4
octets of the length first, and only then compared the length with the
octets left. With 4 or more left that was sound: a length that did not
fit raised eSSHFormatError, "Unable to read data". With 0 to 3 left, the
length was made up of the octets after the message, 1 to 4 of them:
- a length other than 0 raised eSSHFormatError, as for one that did not
fit;
- a length of 0 was taken for an empty string. DecodeBytes returned
nothing, and the count of octets left came back negative. The message
was read on as though the string had been there, empty: the next read
that checks the count raised eSSHDecodeError, "Buffer too small"; a
loop that reads while octets are left stopped; a string read next read
4 octets further on.
So what a message cut short at a string did depended on memory that was
not part of it. Where that memory was:
- The SSH transport hands each message over in a buffer that ends where
the message ends, and the SFTP subsystem of TstSSHServer copies each
request into one of exactly its length. The octets read were those
after the buffer on the heap.
- tSFTPTransport, and so TstSFTPClient, reads a reply into a buffer as
long as all the channel holds at that moment. When the server has sent
more than that one reply, the buffer runs on past it with zeros, so a
string cut short at the end of the reply was read as empty every time.
- A buffer of no octets was read at address 0, which raised
EAccessViolation. That is also where a string inside an empty one was
read, as the signature inside an empty signature blob of
SSH_MSG_USERAUTH_REQUEST.
How far past the message it went: 4 octets for each string read there,
while the octets read were 0. In an SSH message that is at most 40
octets, the ten name-lists of SSH_MSG_KEXINIT, after which a check of the
count ends the connection. In any other message, request or reply, the
reading ends, or comes to a read that checks the count, within a few
strings (by the code). The exception is the extensions of SFTP
file attributes, of versions 3 and 5: a count, then that many name and
value strings. Attributes that counted more extensions than they held
were read on, 8 octets an extension, until a length that was not 0
(eSSHFormatError), memory that cannot be read (EAccessViolation), or the
end of the count - and then they were returned as though they held no
extensions.
WHAT IT LOOKED LIKE, measured with the SFTP server inside
Test\sftpinterop\SftpPutFileTest (step 15), with a second packet behind
the reply in the channel: TstSFTPClient.Connect accepted an
SSH_FXP_VERSION with 1, 2 or 3 zero octets after the version number,
and in version 5 after "supported"; tSFTPTransport.FStat returned the
size from an SSH_FXP_ATTRS that counted 1000 extensions and held none,
having read 8000 octets past it.
WHO WAS AFFECTED. Only a program whose peer sends a malformed message: a
string cut short, or missing, at the end of a message, or attributes
that count extensions they do not hold. A peer that follows the protocol
never sends one. Nothing read past a message was returned, kept or
sent: those octets only decided whether the read raised or went on with
an empty string.
NO ADVISORY. The chain was traced through the code, for each message a
peer can cut short: from a client to TstSSHServer before the login
(SSH_MSG_KEXINIT, the key exchange, SSH_MSG_USERAUTH_REQUEST with a
password or a public key) and after it (global requests, channel opens
and requests, SFTP requests); from a server to the client (the same
key exchange and login replies, channel messages, SFTP replies). In
each, the peer gets what it could have had by sending an empty string,
which the protocol allows - an empty password, key blob or file name is
checked as such - or the message is refused with an exception, which
goes where eSSHFormatError for a length that does not fit went. What
the peer learns of the octets past the message is whether they were 0.
Where the memory after the buffer cannot be read, the read past it
raises EAccessViolation (measured on each platform, with the buffer in
front of a page that cannot be read), and that exception goes the same
way; the SFTP subsystem of TstSSHServer catches any exception from a
request and serves the next (by the code). The read that goes on for
longer is the client's reading SFTP attributes from a server; it ends in
an exception from the call that asked for them, or in attributes without
their extensions, and the server could have failed that call by refusing
the request.
NOW DecodeBytes raises eSSHDecodeError, "Buffer too small", when fewer
than 4 octets are left, and reads nothing - as DecodeUInt32 does for a
32-bit number. DecodeStr and DecodeUtf8Str, which read through it, do the
same. A length that does not fit in what is left raises eSSHFormatError,
"Unable to read data", as before. So a message cut short at a string is
refused the same way whatever lies after it, and the exception goes
where eSSHFormatError for a length that does not fit went: in the cases
above, TstSFTPClient.Connect and FStat raise eSSHDecodeError. A program
that caught eSSHFormatError for a string cut short in its length now
gets eSSHDecodeError; both descend from aSSHTypesError.
THE DISCRIMINATING TEST: DecodeBytes with aLength 2, at an aOffset where
the buffer holds 2 zero octets and more zero octets after them. An
affected release returns nothing, moves aOffset 4 on and leaves aLength
-2; this one raises eSSHDecodeError and leaves both as they were.
Measured with Test\sshinterop\SshDecodeBytesTest on Win32, Win64 and
Linux64. It reads strings with 0 to 3 octets left, from buffers that go
on with zeros and from buffers that end in front of a page that cannot
be read, and SFTP attributes that count extensions they do not hold.
Before, 34 of its 47 checks failed on each platform:
each such read returned an empty string with aLength negative, or raised
EAccessViolation; version 3 and 5 attributes counting 1000 extensions
were read 8000 octets on, and counting 2^31 - 1 were read on to the page
that cannot be read, 4024 and 4020 octets on. Now all 47 pass. In
SftpPutFileTest, on Win32 and Win64, the 6 checks of step 15 that are
not controls failed before; now all 186 of its checks pass. SftpSelfTest,
our client against our server over loopback, passes its 39 checks before
and after (on Win32, where it is built), and the SSH harnesses of the
self-test battery pass on Win32, Win64 and Linux64.
PLATFORMS. Every platform: the same code reads strings on each. Measured
on Win32, Win64 and Linux64.
NOT INVOLVED: a well-formed message, which is read as before; a string
whose length is there but does not fit, which raised eSSHFormatError
before and does now; the extension names of "supported" in SFTP version
5, which are checked before they are read since entry 75.
NOT CHANGED:
- DecodeByte, DecodeUInt32 and DecodeUInt64 without aLength read what
they are asked to, without a check, as before. The client reads the
channel number and the reason code of SSH_MSG_CHANNEL_OPEN_FAILURE
with them, so from a server that cuts that message short it reads up
to 8 octets past its end, and the partial-success flag of
SSH_MSG_USERAUTH_FAILURE is read without a check too (by the code, not
measured).
- The legacy unit stSSHTypes, which no longer ships, has the same defect
and is not changed.
--------------------------------------------------------------------------------
THE SSH SERVER AND SNIP OVER SSH FOR macOS, iOS AND ANDROID
================================================================================
87. FIXED - the SSH server components, snip over SSH and the server's
port-forwarding sockets could not be compiled for macOS, iOS or
Android, although they are marked for those platforms:
StreamSec.SSH.ServerChannel used the unit Windows on every target but
Linux64
TstSSHServer, TstSSHSocketServer, TstSSHServerUsers,
TstSSHSenderControllerSocket, TstSSHListenerControllerSocket, TsnipServer
and TsnipSSHClient are marked for Win32, Win64, macOS, Linux64, iOS and
Android, and the IDE offers them for those platforms. Each of them uses
StreamSec.SSH.ServerChannel, and so do TstSFTPServerSubSystem and every
other server subsystem. That unit used the unit Windows unless LINUX was
defined, and LINUX is defined for Linux64 alone. So a program with any
of them did not compile for Android (32- or 64-bit), iOS, the iOS
simulator, or macOS (Intel or Apple silicon). Delphi 13 stopped with
StreamSec.SSH.ServerChannel.pas(602) Fatal: F1027 Unit not found:
'Windows' or binary equivalents (.dcu/.o)
and 10.4 Sydney and 11 Alexandria with "F2613 Unit 'Windows' not found".
The client side - TstSSHClient, TstSSHSocketClient, TstSFTPClient and
the forwarding clients - does not use the unit and was not affected.
NOW the unit uses Windows on Windows and stTlsUtils everywhere else, as
it did on Linux64: what it takes from them, GetTickCount,
InterlockedIncrement and InterlockedDecrement, stTlsUtils provides for
every POSIX target. On ARM the server's end of a channel now has the
ordering entries 57 and 60 gave it.
THE SFTP SERVER FOR ANDROID 64-BIT then stopped in stFileJail.Posix, the
part of the SFTP server's jail that opens what lies below the served
folder:
stFileJail.Posix.pas(488) Error: E2003 Undeclared identifier: 'st_ino'
For Android's 64-bit ABI the RTL names the inode number of a stat record
__st_ino, in every Delphi from 10.4 Sydney to 13 Florence. The jail now
reads it under that name there. The same unit held the wrong open flags
for Android on 64-bit ARM: $10000 for O_DIRECTORY and $20000 for
O_NOFOLLOW, the values of x86-64. On 64-bit ARM, as on 32-bit ARM, they
are $4000 and $8000 (040000 and 0100000 in the arm64 header of the
Android NDK), and $10000 and $20000 are O_DIRECT and O_LARGEFILE. Built
with them, the jail would have opened each name in a path without
O_NOFOLLOW - the flag with which it refuses a symbolic link - and with
O_DIRECT where it asks for a directory. Android now has the ARM values
on both ABIs. As the unit did not compile for Android 64-bit, no program
was built with the wrong flags; for Android 32-bit it had the right ones
and compiled.
WHO. A program built for Android, iOS, the iOS simulator or macOS that
uses an SSH server, snip over SSH (client or server), one of the
server's port-forwarding sockets, or the SFTP server. It did not
compile, so there is nothing to look for in a running program.
HOW IT WAS FOUND. Checking entry 57 on ARM: the server's end of a
channel could not be compiled for it.
THE DISCRIMINATING TEST: compile a program that uses TstSSHSocketServer
for Android 64-bit or for macOS on Apple silicon. An affected release
stops with F1027 or F2613 on 'Windows'; this one compiles.
PLATFORMS. Compiled, before and after, a unit that uses the server, its
subsystems, the SFTP server, snip over SSH and the forwarding sockets:
with Delphi 13 for Android 32- and 64-bit, iOS, the iOS simulator on
Apple silicon, macOS on Apple silicon and on Intel, and Linux64; with
10.4 Sydney for Android 32- and 64-bit and iOS; with 11 Alexandria for
macOS on Apple silicon; with 10.3 Rio for Linux64. Before, every one but
Linux64 stopped at 'Windows'; now all compile. In the code compiled for
Android 64-bit the jail opens a directory with $84000 (O_DIRECTORY and
O_CLOEXEC) and a file with $88900 (O_NOFOLLOW, O_CLOEXEC, O_NONBLOCK and
O_NOCTTY), and reads the inode number 8 octets into the stat record,
where the NDK's struct stat has it. On Win32, Win64 and Linux64, where
the unit uses what it used before: the package builds; entry 44's test -
16 MB transfers read while they arrive, at both ends of a channel - got
none of 16 transfers wrong on each; the port-forwarding self-test passed
on Win32 and Linux64, and entry 30's SFTP jail test, 20 checks, on
Linux64. Built for macOS on Apple silicon and run on an Apple M1, entry
44's test got none of 16 transfers wrong - with entry 88, without which
its client cannot connect on macOS. Android and iOS were compiled, not
run.
NOT INVOLVED: the SSH client, which compiled for every platform; what
the server does on Windows and Linux64.
NOT CHANGED: the jail's open flags for Linux64, macOS, iOS and Android
32-bit.
--------------------------------------------------------------------------------
TCP CLIENTS ON macOS AND iOS: THE FIRST SEND AFTER CONNECTING
================================================================================
88. FIXED - on macOS and iOS, TstSSHSocketClient could not open a
connection: its first send, made while the TCP connect was still under
way, failed with EstSocketError "send failed (57)"; TsmTLSClient's first
send failed the same way
A client in the library opens its TCP connection with
tAbstractSocket.Open, which on every platform but Windows starts the
connect and returns without waiting for it to complete. The first
octets are then sent at once: TstSSHSocketClient sends its
identification line, and TsmTLSClient and TsmAdvancedTLSClient with
implicit TLS their ClientHello. While the connect is still under way,
Linux and Android answer such a send with EAGAIN, "try again", and both
clients then wait until the socket can be written, which it can once
the connection is up. macOS and iOS answer ENOTCONN, error 57, "socket
is not connected", and the library took that for a broken connection:
it closed the socket, and TstSSHSocketClient raised EstSocketError
"send failed (57)", TsmTLSClient eTLSClientError "TLS client: the
connection dropped while sending." A connect to another machine is
never complete that soon, and on macOS one to 127.0.0.1 was not either:
the SSH socket client failed on every connection.
NOW, while a socket's own connect has not yet been seen to succeed,
tPosixSocket.Send takes ENOTCONN for "try again", and a caller that then
waits and retries - SendAll, which TstSSHSocketClient uses, and
TsmTLSClient's own loop - sends once the connection is up. A connect
that failed is reported with its own error, which macOS keeps in the
socket's SO_ERROR and answers the send with EPIPE: to a port nobody
listens on, "send failed (61)", connection refused, where an affected
release said "send failed (57)". Linux reports 111, connection refused,
as before.
WHO. A program for macOS or iOS that connects with TstSSHSocketClient -
and with it TstSFTPClient or the forwarding clients - or with
TsmTLSClient or TsmAdvancedTLSClient. Windows, Linux and Android were
not affected.
HOW IT WAS FOUND. Running entry 44's test on macOS on Apple silicon,
which entry 87 made possible: none of its 16 transfers started, each
ending in "send failed (57)".
THE DISCRIMINATING TEST: on macOS, connect a TstSSHSocketClient to a
server on 127.0.0.1. An affected release raises EstSocketError "send
failed (57)"; this one connects.
PLATFORMS. Measured on macOS 26 on an Apple M1: 50 connections to a
listener on 127.0.0.1, each followed at once by a SendAll of 16 octets -
none delivered before, each ending in "send failed (57)", all 50 after;
a connect to a port nobody listens on reported 57 before and 61 after;
entry 44's test got none of 16 transfers wrong, twice, where before none
of them started. On Linux64 the same 50 connections were delivered, a
refused connect reported 111, and entry 44's test, the port-forwarding
self-test and entry 30's SFTP jail test passed. TsmTLSClient on macOS,
and iOS, which has the same send, from the code: compiled, not run.
Windows does not use the unit that changed.
NOT INVOLVED: Windows, where Open waits for the connect; the SSH and TLS
protocols; connections a server accepts, which are up when it gets them.
NOT CHANGED:
- Open still returns before the connect completes on every platform but
Windows, and a refused connect is still reported by the first send or
receive, not by Open.
- A caller that sends once, straight after Open, and takes "try again"
(Send returns -1 with no error code) for a failure still fails when the
connect has not completed by then: on Linux and Android for a server on
another machine, on macOS and iOS for any server. Measured: one send
straight after Open, 10 times, was "try again" each time from Linux64
to another machine and on macOS to 127.0.0.1. The HTTP transport of
StreamSec.Http.Client and the OCSP transport of
StreamSec.DSI.AbstractOcsp send so, and raise "HTTP transport: send
failed" or "OCSP transport: send failed"; on macOS and iOS an affected
release raised EstSocketError "send failed (57)" there instead. The DNS
query over TCP in StreamSec.Mail.Dns sends so as well, and returns no
answer. That is a separate matter, not changed here.
--------------------------------------------------------------------------------
SFTP CLIENT: md5-hash-handle IN A PROGRAM THAT DOES NOT LINK stMD5
================================================================================
89. FIXED - comparing a local copy by md5-hash-handle needed the unit stMD5
in the program, and no SFTP or SSH unit linked it. Without it CmpFile
returned False for a local file that matches and GetFile read every
part; from a server that answers an empty quick-check-hash with an empty
hash, CmpFile returned True for a local file that differs, and GetFile
kept the parts that differ and returned True
TstSFTPClient compares a local copy with a remote file by md5-hash-handle,
draft-ietf-secsh-filexfer-05 section 8.1, in CmpFile and in GetFile of a
local copy (entries 82 and 83), and the SFTP transport sends the same
request in MD5Hash and MD5HashHandle (iSFTPClientTransport). The client
hashes the part of its copy with MD5, sends the hash of the first 2048
octets of the part as the quick-check-hash, and compares the hash the
server returns with its own hash of the whole part.
THE STEP THAT FAILED is finding MD5 for the client's side. The client
took MD5 from the library's table of hash classes and did not require it
to be there. MD5 is in the table only when the unit stMD5 is linked, and
no SFTP or SSH unit links it; in the library only the TLS units
StreamSec.Mobile.Tls and StreamSec.Mobile.TlsLayer do. A program with
TstSSHSocketClient, TstSSHSocketServer, TstSFTPClient, the SFTP server
subsystem, stSecComp and the primitives SSH uses, but not stMD5, has no
MD5 (measured). There the client's hash came out empty: it sent an empty
quick-check-hash, which section 8.1 reads as "the client does not have
the data", and compared the server's hash with an empty one.
WHAT THAT DID depended on how the server answers an empty
quick-check-hash:
- With the hash of the part, as the draft has it: no part matched.
CmpFile returned False for a local file holding the remote file, and
GetFile read every part, also those the copy held already. The copy
it left was right.
- With SSH_FX_OP_UNSUPPORTED, which section 8.1 allows: CmpFile and
GetFile raised eSFTPStatusError. GetFile left the local file as it
was.
- With an empty hash, which section 8.1 gives as the answer to a
quick-check-hash that does not match: every part matched. CmpFile
returned True for a local file that differs, and GetFile read nothing,
left the parts that differ in the local file, and returned True - a
copy that differs from the remote file, reported as a download that
succeeded.
WHO WAS AFFECTED. A program that uses TstSFTPClient, or the SFTP
transport, with a server that answers md5-hash-handle, and links neither
stMD5 nor a TLS unit. The SFTP client demo lists stMD5 among the units
it links, and so does SftpSelfTest on Windows, so they had MD5. No server
at hand here answers md5-hash-handle (entry 82), and which of the three
answers a given server gives to an empty quick-check-hash is not known
here.
IN RELEASE 4.1.4.360, and in every release since StreamSec.SFTP.Transport
first shipped, in 4.1.1.354, CmpFile given a stream and the transport's
MD5Hash and MD5HashHandle sent the request this way. CmpFile given a file
name and GetFile did not get that far in 4.1.4.360: that release kept no
extension name from a server that lays out "supported" as the draft or
as ProFTPD does (entry 75), so CmpFile raised "Feature not supported"
and GetFile downloaded the whole file. Entries 75 and 82 make those two
compare.
NOW StreamSec.SFTP.Transport links stMD5, so a program that uses the SFTP
client has MD5, and the client requires it before it sends md5-hash or
md5-hash-handle. The quick-check-hash is the 16-octet MD5 of the first
2048 octets of the part, or of the whole part when it is shorter, and
CmpFile and GetFile compare as entries 82 and 83 describe, whatever the
server would answer to an empty quick-check-hash. The client asks for MD5
with MustFindHashClass, which asks a provider registered with
RegisterProvider when MD5 is not in the table. That reaches a program
whose STPROVIDER resource makes stMD5 leave the registering to the
provider, where MD5 is not in the table until the provider is asked.
With MD5 not in the table and no provider to register it - the program
took it out with UnregisterHashClass, or its provider does not supply
it - CmpFile, GetFile where it compares, MD5Hash and MD5HashHandle raise
eClassRegistration "Unable to find required hash class: haMD5" without
sending the request, and GetFile leaves the local file as it was.
MD5 IS THEN IN THE PROGRAM for every unit that looks it up, as in a
program with a TLS unit. So reading a private key in the old OpenSSL
encrypted PEM form (a DEK-Info header), or a PKCS#8 key encrypted with
PBES1 and MD5, which raised in such a program for want of MD5, now
works. MD5 signatures stay refused whether MD5 is linked or not: the DSI
RSA verifier rejects md5WithRSAEncryption, and the DSI DSA and ECDSA
verifiers leave MD5 out of the digests they accept by default. SSH
registers no MD5 MAC.
THE DISCRIMINATING TEST: in a program that links the SFTP units and not
stMD5, FindHashClass(haMD5) returns nil in an affected release and tMD5
in this one; and with a server that answers md5-hash-handle as the draft
has it, CmpFile of a local file holding the remote file returns False in
an affected release and True in this one. Measured with
Test\sftpinterop\SftpMd5LinkTest, a program that names neither stMD5
nor a TLS unit, against an SFTP server inside the program that answers
in each of the three ways above with hashes from the Delphi RTL, on
Win32 and Win64: before, 25 of its 36 checks failed - no MD5 at start,
an empty quick-check-hash in every request, each of the three results
above, and neither eClassRegistration without MD5 nor a question to a
provider. Now all 36 pass, with the same lines on Win32 as on Win64.
Built with the link to stMD5 and without MustFindHashClass, 8 fail, all
in its two steps without MD5 in the table: with no provider, and with a
provider that registers it. SftpPutFileTest, which links stMD5 itself,
passes its 186 checks on Win32 and Win64, and SftpSelfTest its 39 (on
Win32, where it is built).
PLATFORMS. Every platform: the same code runs on each. Measured on Win32
and Win64, and again on both built with ST4_NO_ASM, which selects the
Pascal MD5 that Linux64 and the other targets without an assembler run.
Not run on those targets.
PACKAGES. Every StrSecIV runtime package that contains
StreamSec.SFTP.Transport contains stMD5 already, so no package gains a
unit. StrSecIV370 builds on Win32 and Win64 with the same warnings and
hints as before.
NOT INVOLVED: the server and what it hashes; which parts GetFile compares
and how it moves on (entries 82 and 83); the extension names (entry 75);
SSH and the channel. A program that links stMD5, directly or through a
TLS unit, compares as before.
NOT CHANGED:
- The hash is MD5 because section 8.1 defines md5-hash and
md5-hash-handle with it. stMD5 stays marked deprecated, as MD5 no
longer resists collisions.
- The legacy units stSFTPClient and stSFTPTransport, which no longer
ship, have the same defect and are not changed.
--------------------------------------------------------------------------------
CMS: SEED-CBC UNDER THE OBJECT IDENTIFIER OF RFC 4010
================================================================================
90. FIXED - TstMPEnvelopedData could neither encrypt nor decrypt CMS
content with SEED-CBC: asked for SEED-CBC, Encrypt raised eASN1Error
"Unidentified type for tCEParams" and wrote nothing, and a SEED-CBC
message from another implementation, such as OpenSSL, did not decrypt
RFC 4010, section 2.1, gives SEED in CBC mode, as a content-encryption
algorithm of CMS, the object identifier
id-seedCBC OBJECT IDENTIFIER ::=
{ iso(1) member-body(2) korea(410) kisa(200004)
algorithm(1) seedCBC(4) }
that is 1.2.410.200004.1.4, and says that the parameters field MUST be
present and hold the IV, an OCTET STRING of 16 octets.
THE STEP THAT FAILED is finding the parameters that go with the
algorithm. StreamSec.DSI.CMSAlgorithms keeps a table of the content-
encryption algorithms: for each OID, the parameters it takes and the
cipher that reads them. The table listed SEED-CBC under
1.2.840.113549.1.1.10.4, an OID under id-RSASSA-PSS that is not SEED's.
The cipher, tSEED_CBC in stSEED, answers the RFC's OID, and a SEED-CBC
message needs the two to agree:
- Encrypt writes the cipher's OID, 1.2.410.200004.1.4, as the algorithm,
then asks the table for the parameters to write the IV into. The
table did not know that OID, so Encrypt raised eASN1Error,
"Unidentified type for tCEParams", naming { iso(1) member-body(2) 410
200004 1 4 }, before it had written anything.
- Decrypt of a message carrying 1.2.410.200004.1.4, as OpenSSL writes
it, stopped at the same table and returned False.
- Decrypt of a message carrying 1.2.840.113549.1.1.10.4 found the
parameters in the table, but no cipher with that OID, and returned
False.
So TstMPEnvelopedData has not written or read a SEED-CBC message in any
release, under either OID: the table has held the wrong OID since
StreamSec.DSI.CMSAlgorithms first shipped, stSEED has always answered
the RFC's, and the component has always written the cipher's (by the
code of the releases). Nothing it wrote carries the old OID. The same
table serves the EncryptedData of StreamSec.DSI.CMS; PKCS#12 reads its
encrypted parts through a table of its own, which has no SEED.
NOW the table lists SEED-CBC under 1.2.410.200004.1.4. Encrypt with
SEED-CBC writes the AlgorithmIdentifier RFC 4010 describes and pads the
content as RFC 5652, section 6.3, says, and Decrypt reads such a
message. stOIDs.GetObjectName names 1.2.410.200004.1.4 id-seedCBC; it
gave that name to 1.2.840.113549.1.1.10.4, which it now names
{ id-RSASSA-PSS 4 }. A message carrying 1.2.840.113549.1.1.10.4 is
refused, as before: the library never wrote it, and it is not SEED's.
THE DISCRIMINATING TEST: give TstMPEnvelopedData one SMIMECapabilities
item with CipherAlg caSEED, CipherMode cmCBC and KeyLength 16, and
Encrypt to an RSA certificate. An affected release raises eASN1Error
"Unidentified type for tCEParams"; this one returns True, and the
message holds 30 1C 06 08 2A 83 1A 8C 9A 44 01 04 04 10 and the 16
octets of the IV, which openssl cms -decrypt, given -provider legacy
-provider default, opens.
Measured with Test\seed\SeedCmsTest. It imports an RSA recipient from
a PFX that OpenSSL 3.5.7 made; decrypts OpenSSL's SEED-CBC messages of
a 48- and a 45-octet plaintext to it, and an AES-128-CBC control;
encrypts both plaintexts with SEED-CBC and checks the octets against
RFC 4010 and the padding against RFC 5652; checks that a program that
asks for no cipher still gets AES-256-CBC; and that the old OID is
refused. Before, on Win32, 16 of its 27 checks failed, all of them
SEED's, and the control passed. Now all 27 pass on Win32, Win64 and
Linux64, and OpenSSL, 3.5.7 on Windows and 3.5.5 on Linux, decrypts the
SEED-CBC messages each of the three builds makes
(Test\seed\_openssl_check.bat on Windows).
PLATFORMS. Every platform: the table is the same on each. On Linux64,
macOS, iOS and 64-bit Android SEED itself was wrong before entry 85.
NOT INVOLVED: the SEED cipher; the other algorithms of the table
(Triple-DES, RC2, AES and Camellia in CBC mode), whose OIDs are those of
RFC 3370, RFC 3565 and RFC 3657; and the cipher chosen when none is
asked for, which linking stSEED does not change.
NOT CHANGED:
- SEED key wrap for KEKRecipientInfo (id-npki-app-cmsSeed-wrap, RFC
4010, section 2.2) is not offered, before or after.
- The legacy unit stCMSAlgorithms, which no longer ships, has the same
OID and is not changed.
--------------------------------------------------------------------------------
FREEING AN SSH SERVER WITH ITS USER DATABASE, AND TsnipServer
================================================================================
91. FIXED - freeing a TsnipServer read memory it had already given back,
twice: its SSH server still referred to its user database
(TstSSHServerUsers) after the user database was freed, and to its snip
subsystem after the subsystem was freed; on macOS TsnipServer.Free
raised EAccessViolation
TsnipServer owns an SSH server (TstSSHSocketServer), the snip subsystem
(TsnipSSHServer) and a user database (TstSSHServerUsers), created in
that order. An owner frees what it owns last-created first, and tells
the others nothing: TComponent reports that a component is freed to the
components that refer to it only when they have different owners, or
when it is freed on its own while its owner lives.
THE USER DATABASE. A TstSSHServerUsers whose Server is set is that
server's Users: the server consults it at every login and when a
subsystem registers with it or leaves it. Freed by an owner it shares
with the server, it was gone while the server still referred to it, and
the snip subsystem, freed next, left the server, which then took the
subsystem's name off every user of the freed database. The same held
for any program that has a TstSSHServer or TstSSHSocketServer, then a
subsystem - TstSFTPServerSubSystem, a port-forwarding socket - and then
a TstSSHServerUsers on one form or data module, when that is freed. And
the other way round, with different owners: a TstSSHServerUsers whose
server had been freed still had it as its Server.
THE SNIP SUBSYSTEM. TsnipServer registered it with its SSH server twice:
setting the subsystem's Server registers it, and the constructor of
TsnipServer registered it again. Freed, the subsystem took one
registration with it; the SSH server, freed next, released the other,
which referred to the freed subsystem.
What was read each time was memory already given back. On Windows and
Linux it still held what it had held, and nothing showed. macOS clears
such memory, and TsnipServer.Free raised EAccessViolation "Access
violation at address ..., accessing address 0000000000000010": first
where the server walked the freed user database, and, with that fixed,
where it released the freed subsystem.
NOW a TstSSHServerUsers, when it is freed, first stops being its
server's Users, and it forgets a server that is freed before it.
TsnipServer registers its snip subsystem once.
WHO. A program built for macOS that frees a TsnipServer, which raised,
and one that frees a server, a subsystem and a TstSSHServerUsers
created in that order through their common owner. On other platforms
nothing was seen, but freed memory was read, and with a memory manager
that hands it out again at once, what the reads found could have been
anything.
HOW IT WAS FOUND. Running entry 38's test on macOS, which entry 87 made
possible: its 190 checks passed, and then freeing the server raised. The
chain of calls was taken on Win32 with a memory manager that fills what
is freed (Test\tls13interop\HeapWatch.pas), where the same reads raised
too, at address F4F4F4FC.
THE DISCRIMINATING TEST: put a TstSSHServer and a TstSSHServerUsers on
two different owners, set the TstSSHServerUsers' Server and free the
server's owner. An affected release still has the server as the
TstSSHServerUsers' Server; this one has nil.
PLATFORMS. New test SshServerTeardownOrderTest (battery rows Win32,
Win64 and Linux64, 17 checks) frees a server and a TstSSHServerUsers in
every order, with one owner and with two, and a TsnipServer. An affected
release fails 3 of the checks on Win32 and Linux64 - the server's Users
as seen by a subsystem freed after the user database, the user
database's Server after the server is freed, and the snip subsystem
registered twice - and 5 on macOS on an Apple M1, where two of the frees
raise; this release passes all 17 on Win32, Win64, Linux64 and the M1.
Entry 38's test: on the M1 it raised after 190 checks and now passes all
192, three times; on Win32 with the memory manager above it raised in
the same place and now passes all 192; with the ordinary memory manager
it passes all 192 on Win32, Win64 and Linux64 as before. Entry 78's test
on the M1 raised when it stopped its server, after its 41 checks, and
now does not; it passes on Win32 as before. The port-forwarding
self-test no longer raises when it stops its server on the M1, and
passes on Win32 and Linux64 as before; on the M1 8 of its 13 checks
fail for another reason, which this entry does not change.
NOT INVOLVED: connections - the reads happened when the components were
freed, with or without a connection; the SSH protocol.
NOT CHANGED:
- TstCustomSSHServer.AddSubSystemController still registers a subsystem
that is registered already. A program that sets a subsystem's Server
and also calls AddSubSystemController for it registers it twice, as
TsnipServer did, and should drop the call.
- A server stops listening when the last subsystem registered with it
leaves, as before. Freeing a TsnipServer now brings its SSH server to
that point when the snip subsystem is freed, just before the server
itself is freed.
--------------------------------------------------------------------------------
SSH CHANNEL AND USER-AUTHENTICATION MESSAGES CUT SHORT
================================================================================
92. FIXED - the SSH channel layer of the client and the server, and the
client's password and public-key authentication, read the fixed fields
of a message the peer sent without checking that the message held them:
a message cut short there was read on into the memory after it, which
raised EAccessViolation, or was acted on with values taken from that
memory
Entry 86 fixed reading a "string" whose 4-octet length ran past the end
of a message. This entry fixes the companion case: the fixed-width fields
- the recipient channel number, a window increment, a data length, a
reason code, the partial-success flag - that the channel brokers and the
client's authentication read with the plain, unchecked DecodeUInt32 and a
direct index into the buffer, named in entry 86's NOT CHANGED list.
THE STEP THAT FAILED. Every channel-layer message begins with a uint32
recipient channel number, and most carry more uint32 fields after it
(RFC 4254). The SSH transport hands each message over in a buffer that
ends where the message ends. The brokers read those fields with the
two-argument DecodeUInt32(aBuf, aOffset), which moves the offset on 4
and reads, with no check that 4 octets are there - unlike the
three-argument DecodeUInt32(aBuf, aOffset, aLength), which raises
eSSHDecodeError when fewer than 4 are left. So a message cut short in one
of those fields was read from the octets after the buffer:
- StreamSec.SSH.ClientChannel, tSSHClientChannelBroker: the recipient
channel of SSH_MSG_CHANNEL_OPEN_CONFIRMATION, _OPEN_FAILURE,
_WINDOW_ADJUST, _DATA, _EXTENDED_DATA, _EOF, _CLOSE, _SUCCESS and
_FAILURE, and the uint32 fields after it (the peer's channel number,
window and packet size in a confirmation; the reason code in a failure;
the increment in a window adjust; the length in a data message).
- StreamSec.SSH.ServerChannel, tSSHServerChannelBroker: the same in
SSH_MSG_CHANNEL_WINDOW_ADJUST, _DATA, _EXTENDED_DATA, _EOF and _CLOSE.
- StreamSec.SSH.ClientAuthentication, the password and public-key
methods: after SSH_MSG_USERAUTH_FAILURE the partial-success flag was
read as lReply[lROffs] - a bare index one past the name-list - with no
check that an octet was there. In password authentication that read is
reached only once the server has issued a change request (before that
the method does not read the flag); in public-key authentication it is
always reached.
The recipient channel of a message cut off before it is complete came
from those octets, so the message was handed to whatever channel that
number selected, or to none; and the values after it - what the channel
was told to do - came from there too. A confirmation cut off after the
recipient channel connected a real channel to the peer's channel number
made up from the octets after the message: the data that channel sent
next then went back to the peer addressed to that number. A message that
ran off the end of readable memory raised EAccessViolation.
WHO WAS AFFECTED. Only a program whose peer sends a malformed message: a
channel or authentication message with a fixed field cut short. A peer
that follows the protocol never sends one. As in entry 86, nothing read
past a message was returned, kept or sent on to a third party; the octets
after the message decided which local channel (if any) was addressed and
what it was told, or made the read raise.
NO ADVISORY. The chain was traced through the code. On the client the
broker runs on its own read thread; an exception from a handler leaves
the thread's dispatch loop, which treats it as the connection ending
(tSSHClientChannelBroker.Execute catches it and terminates, then tells
every channel the connection has ended, as it does for a peer's
DISCONNECT). On the server the broker's exception unwinds to
TstCustomSSHServer.Execute, which frees the broker and ends that one
connection (by the code). A channel message arrives only after the key
exchange and the login, so on the server the peer is an authenticated
user, and on the client the peer is the server the client chose to
connect to and has authenticated by its host key; the partial-success
flag is read from the server during the client's own login. The value a
cut-short message could make up is a local channel number and the
arguments to one of a channel's own operations (open, adjust the window,
deliver or discard data it counts, close), all of which the peer can
drive with well-formed messages on a channel it holds; the one effect
beyond that - a confirmation addressing a real channel to a bogus peer
number, so its next data goes to the wrong number - loses that channel to
the peer that cut its own confirmation short, and gains the peer nothing
it could not do by not opening the channel. What the peer learns of the
octets past the message is whether they formed a valid channel number or
an octet other than 0; where the memory after the buffer cannot be read,
the read raises EAccessViolation, which ends the connection as above.
NOW those fields are read with the checked DecodeUInt32(aBuf, aOffset,
aLength), and the partial-success flag with DecodeBoolean, each raising
eSSHDecodeError, "Buffer too small", when the octets are not there - as
the string reads did since entry 86. A message cut short in a fixed field
is refused, the channel is told nothing, and the exception goes where a
handler's exception went before. The server broker already read
SSH_MSG_CHANNEL_OPEN, _REQUEST, _OPEN_CONFIRMATION and _OPEN_FAILURE with
the checked decoders; the client broker read SSH_MSG_CHANNEL_OPEN,
_REQUEST and _GLOBAL_REQUEST with them. Those are unchanged.
THE DISCRIMINATING TEST: hand the client broker an
SSH_MSG_CHANNEL_OPEN_CONFIRMATION of 5 octets (the message code and the
recipient channel) with a valid local channel number, and octets in the
memory after it. An affected release connects the channel to the peer
number made up from those octets and sends its next data there; this one
raises eSSHDecodeError and leaves the channel unopened.
Measured with Test\sshinterop\SshShortMessageTest on Win32, Win64 and
Linux64. It calls each broker's handlers directly over a fake transport,
and runs the client's password and public-key authentication against a
USERAUTH_FAILURE without its partial-success octet, with the message cut
short after every octet of each fixed field: once ending in front of a
page that cannot be read, and once with the missing octets in the memory
after it. Before, 120 of its 166 checks failed on each platform: the
reads past the message raised EAccessViolation, or the channel was told
what those octets said (a CLOSE, an EOF, a request reply, a window
increment, a data length below zero, and for a confirmation the peer's
channel number, which a real channel then sent its data to). Now all 166
pass. The other SSH harnesses of the self-test battery pass on Win32,
Win64 and Linux64, our client against our server included.
PLATFORMS. Every platform: the same code reads these fields on each.
Measured on Win32, Win64 and Linux64.
PACKAGES. StreamSec.SSH.ClientChannel, StreamSec.SSH.ServerChannel and
StreamSec.SSH.ClientAuthentication are in the StrSecIV packages already;
no package gains a unit. StrSecIV370 builds on Win32 and Win64 with the
same warnings and hints as before.
NOT INVOLVED: a well-formed message, which is read as before; the
"string" fields of these same messages (a data payload, a reason
message, a language tag), which are read with DecodeStr and so were fixed
by entry 86; the fixed fields the brokers already read with the checked
decoders (the two channel-open messages and the channel and global
requests).
NOT CHANGED:
- DecodeByte, DecodeUInt32 and DecodeUInt64 without aLength still read
what they are asked to, without a check, as before; they are correct
where the caller has already made sure the octets are there. This entry
changed the channel-layer and authentication callers that had not.
- The legacy units stSSHClientChannel, stSSHServerChannel and
stSSHClientAuthentication, which no longer ship, have the same defect
and are not changed.
--------------------------------------------------------------------------------
CMS: THE SMIMECAPABILITIES ITEMS OF SEED-CBC AND CAMELLIA-CBC
================================================================================
93. FIXED - TstMPSignedData listed SEED-CBC and Camellia-CBC in the
smimeCapabilities signed attribute without the NULL parameters that
RFC 4010 and RFC 3657 give them, so a correspondent that compares the
items with the octets those RFCs print did not find SEED or Camellia
in the list
The smimeCapabilities attribute (pkcs-9 15) tells a correspondent which
content-encryption algorithms the signer can read, one SMIMECapability,
a SEQUENCE of an OID and optional parameters, per algorithm. RFC 8551,
section 2.5.2, has receivers match them "by binary comparisons", so
each algorithm's RFC prints the octets:
- SEED-CBC, RFC 4010, section 4: the parameter "MUST be
SeedSMimeCapability", which is NULL:
30 0C 06 08 2A 83 1A 8C 9A 44 01 04 05 00
- Camellia-CBC, RFC 3657, section 4: the parameter is NULL, for 128,
192 and 256 bits
30 0F 06 0B 2A 83 08 8C 9A 4B 3D 01 01 01 02 05 00
30 0F 06 0B 2A 83 08 8C 9A 4B 3D 01 01 01 03 05 00
30 0F 06 0B 2A 83 08 8C 9A 4B 3D 01 01 01 04 05 00
- AES-CBC, RFC 3565, section 5.1: the parameters "MUST be absent".
- des-ede3-cbc: no RFC prints them; RFC 8551, section 2.5.2, says that
parameters that do not tell two instances of an algorithm apart "MUST
be omitted and MUST NOT be encoded as NULL".
TstMPSignedData writes the attribute into every signature with signed
attributes, other than a countersignature or Authenticode, whenever its
SMIMECapabilities list is not empty, and the list it fills in by itself
holds every CBC cipher the program has registered: SEED-CBC in a
program that links stSEED, Camellia-CBC in one that links stCamellia.
THE STEP THAT FAILED is writing the parameters of an item. For every
cipher other than RC2 the component selected an empty OCTET STRING as
the parameters, and an empty OCTET STRING is not written, so every item
went out with no parameters: right for AES-CBC and des-ede3-cbc, wrong
for SEED-CBC and Camellia-CBC, which went out as
30 0A 06 08 2A 83 1A 8C 9A 44 01 04
30 0D 06 0B 2A 83 08 8C 9A 4B 3D 01 01 01 02 (and 03, 04)
A correspondent that looks for the RFC's octets finds neither, and may
choose another algorithm from the list, or none, when it encrypts to
the signer. The signature itself was right: it verified, in the
component and in OpenSSL, before and after.
NOW the four items go out with NULL parameters, octet for octet as
RFC 4010 and RFC 3657 print them, and every other cipher as before.
THE DISCRIMINATING TEST: sign with TstMPSignedData in a program that
links stSEED and look at the smimeCapabilities attribute, for example
with openssl asn1parse -inform DER. An affected release writes seed-cbc
with nothing after it (30 0A ...); this one writes seed-cbc followed by
NULL (30 0C ... 05 00).
Measured with the new Test\tls13interop\PkixCmsSmimeCapWireTest. It
signs with an RSA key from a PFX that OpenSSL 3.5.7 made, once with a
list of SEED, AES, des-ede3-cbc and Camellia items and once with the
list the component fills in, and compares each item it wrote with the
octets above, reading them with a DER walk of its own. It also verifies
OpenSSL's signature over a message whose list holds those RFC items and
over one with OpenSSL's own list, and checks what
tSMIMECapabilities.AssignStruct takes from each. Before, 12 of its 51
checks failed on Win32, Win64 and Linux64, all of them the SEED and
Camellia items of the two lists the component wrote. Now all 51 pass on
the three. openssl cms -verify (3.5.7) verifies a message the component
signed, and openssl asn1parse shows the NULL after seed-cbc and after
each camellia item.
PLATFORMS. Every platform: the same code writes the list on each.
Measured on Win32, Win64 and Linux64.
PACKAGES. StreamSec.DSI.PkixCms is in the StrSecIV packages already;
no package gains a unit. StrSecIV370 builds on Win32 and Win64.
NOT INVOLVED: the signature; reading a correspondent's list, where
AssignStruct took SEED-CBC and Camellia-CBC with NULL parameters, and
AES-CBC and des-ede3-cbc without, before and after, and the component
verified OpenSSL's signature over them; the AES-CBC and des-ede3-cbc
items, whose octets are unchanged; the content-encryption algorithms of
EnvelopedData and their parameters (entry 90).
NOT CHANGED:
- An item for SEED or Camellia in another mode, or with KeyedIV set,
still goes out without parameters: no RFC gives such an item any.
- The legacy unit stMpCms, which no longer ships, writes the list with
code of its own and is not changed.
--------------------------------------------------------------------------------
SSH: A CHANNEL CLOSED ON ITS OWN THREAD WHILE THE SSH CLIENT CLOSES
================================================================================
94. FIXED - an SSH client channel that its own thread was closing when the
program closed the SSH client could finish its Close after the SSH
client had freed the channel broker: an access violation on that thread,
raised as it cleared its slot through the freed broker
A TstSSHSocketClient keeps its channels on a channel broker, which it
creates at Login and frees in Close. A channel's Close, once the channel
has left csConnected - the server closed it, or the connection under it
ended - completes it to csClosed and takes it off the broker. When
SSHClient.Close frees the broker, the broker first takes off every channel
still on it. A program that runs each channel on a thread of its own
closes the channel on that thread, and the two can meet. The
port-forwarding threads of TstSSHForwardingClientSocket do this: they
close their channel when the server closes it, and since entry 84 also as
soon as the connection has ended, which closing the SSH client does.
THE STEP THAT FAILED is taking a channel off the broker. The channel's
Close claimed the channel and then emptied its slot in the broker's table
of channels, without the broker's lock. The broker, freeing itself, found
the slot still filled, left the channel to the thread that had claimed
it, emptied the table and was freed - without waiting for that thread.
The channel's Close then emptied its slot through the freed broker: an
access violation on the channel's thread, reading address $BC on Win32
and $178 on Win64 and Linux64 for slot 47, because the freed memory still
held the table's pointer, which emptying the table had set to nil. Had
that memory been handed out again in between, the slot would have been
read and released wherever the new owner's data put it. The broker's loop
also looked at each slot twice and called the channel through the slot
each time, so a slot emptied between a look and its call would have been
called through as nil: an access violation raised out of SSHClient.Close.
None of the runs below caught that one; its window is a few instructions.
HOW OFTEN. Between claiming the channel and emptying its slot, the
channel's thread runs a few instructions - and on Win32 closes the
channel's semaphore - so it had to lose the processor right there, just
as the SSH client closed. Measured with SshChannelCloseRaceTest: 48
channels on one connection, each with a thread that closes it the moment
it leaves csConnected, and the program closing the SSH client. In one run
of 20 rounds, 2 rounds had an access violation on Win32, 1 on Win64 and
none on Linux64. A subclass that overrides InternalBeforeRemoveFromBroker,
as the port-forwarding channel does, runs its code inside that window and
widens it by as long as the code takes: with 0 to 2 ms there, 15 to 20
rounds of 20 had access violations on every platform, and with 200 ms,
all 6 tries did - two steps on each of the three platforms.
NOW:
- A channel leaves its slot under the broker's lock, and only when the
slot is in the table: once the table is emptied, a removal touches
nothing.
- A channel's removal from its broker runs under the channel's own lock
from start to end. The channel's Close, the broker's thread when the
server answers the channel's CLOSE, and the broker being freed can all
call it: the first takes the channel off, and one that comes while it
does waits until the channel is off.
- The broker, freeing itself, calls each channel on a reference of its
own, with its lock released, and is freed only when every channel is
off. So SSHClient.Close waits for a channel's Close that is taking the
channel off on another thread - microseconds, unless a subclass's
InternalBeforeRemoveFromBroker takes longer. A Recv that is reopening
its window when the SSH client closes uses the broker under the same
channel lock, so it too is done with the broker before the broker is
freed.
THE DISCRIMINATING TEST: subclass tSSHClientChannel and have its
InternalBeforeRemoveFromBroker sleep 200 ms on a thread of your own. Open
one on a logged-in TstSSHSocketClient (Create on SSHClient.Broker, then
Connect), have the server disconnect, call the channel's Close on your
thread, and while it sleeps call SSHClient.Close on another. An affected
release returns from SSHClient.Close at once, and the channel's Close
then raises EAccessViolation; this one returns from SSHClient.Close after
the 200 ms, and the channel's Close returns without raising. The same
holds when the server closes the channel instead of disconnecting.
PLATFORMS. Every platform: the same code runs on each. Measured on
Win32, Win64 and Linux64; this release passed all 315 checks of
SshChannelCloseRaceTest on each, in five or more runs of each.
NOT INVOLVED: what a channel sends when it closes, and the states it
goes through; the transport, the key exchange and the ciphers. The
server's channels already left their broker under its lock, but the
server's broker did not wait for a removal under way either: entry 105.
NOT CHANGED:
- A channel still on the broker when the SSH client closes ends as
before: csClosing if it was open (entry 84), and csClosed once its own
Close completes it.
- Send, SendEOF and RequestSubSystem do not wait for SSHClient.Close, nor
it for them: close the SSH client once the threads that send on its
channels have stopped.
- The legacy unit stSSHClientChannel, which no longer ships, is not
changed.
--------------------------------------------------------------------------------
THE SSH SERVER'S SUBSYSTEM THREAD: RESUMING IT ON macOS AND iOS
================================================================================
95. FIXED - on macOS and iOS, an SSH server could raise EThread when it
freed a channel, or when it attached a subsystem to a channel, if the
channel's subsystem thread was just then suspending itself: TThread.
Resume fails there until the thread has suspended
Each channel of an SSH server has a subsystem thread, which hands what
arrives on the channel to the channel's subsystem - SFTP, snip, or an
application's own. When something arrives while no subsystem is
attached, the thread suspends itself (TThread.Suspend, in the thread).
It is resumed when a subsystem is attached (tSSHServerChannel.
SetSubSystem), and when the channel is freed, which ends the thread
(since entry 38).
TThread.Suspend first sets Suspended and then suspends the thread, so
for a moment Suspended is True while the thread still runs. What
TThread.Resume does then depends on the platform:
- macOS and iOS: Resume calls thread_resume, which fails for a thread
that is not suspended, and Resume raises EThread. The thread suspends
a moment later, and nothing resumes it.
- Windows: ResumeThread does nothing, and Suspended stays True. The
thread suspends a moment later.
- Linux and Android: Resume posts to a semaphore, and the thread's wait
returns at once. Nothing is lost.
Freeing a channel, the server resumes the thread until it has ended,
and on Windows that already covered the moment: it looked again a
millisecond later. On macOS and iOS the first EThread left the loop, and
with it the destructor the loop runs in, which must not raise.
Attaching a subsystem, the server resumed the thread once: on
macOS and iOS it raised EThread out of SetSubSystem, and on Windows the
thread stayed suspended with the subsystem attached, so what arrived on
the channel was not handed to it.
Measured with a thread that suspends itself in a loop and another that
resumes it as soon as it sees Suspended: on macOS on an Apple M1 Resume
raised EThread in 199,404 of 200,000 cycles, and on Win64 and Linux64 in
none. In the server the thread suspends itself only when data arrives
for a channel with no subsystem attached, and the moment is as short, so
it is rare there; none of the server's tests met it.
NOW, freeing a channel, the server takes the EThread and resumes the
thread on its next look, a millisecond later. Attaching a subsystem, it
resumes the thread until it runs, for at most 5 seconds.
WHO. A program for macOS or iOS with an SSH server - TstSSHServer or
TstSSHSocketServer, with SFTP, snip or a subsystem of its own - that
frees a channel just as data arrives for it after its subsystem has
left, which could raise while freeing it; and a program on macOS, iOS or
Windows whose server attaches a subsystem to a channel whose thread has
suspended itself.
HOW IT WAS FOUND. From the code, while making the server compile for
macOS (entry 87): TThread.Resume for macOS in System.Classes, and the
two places the server calls it. Then measured, as above.
THE DISCRIMINATING TEST: none in the server that fails on demand. The
measurement above shows the platform's side: a Resume that comes while
Suspended is True and the thread has not suspended raises EThread on
macOS and iOS.
PLATFORMS. The loop of the measurement, resuming through the server's
new routine, copied into it, raised in none of 375,755 resumes on the
M1. Entry 38's test passes all 192 checks on the M1 (three runs), Win32,
Win64 and Linux64; entry 44's test passes on the M1, Win32, Win64 and
Linux64, entry 91's test on the M1 and Win32, entry 78's test on Win32,
and the port-forwarding self-test on Win32 and Linux64, as before.
Compiled for the platforms and versions of entry 87.
NOT CHANGED: when the thread suspends itself, and that it does.
TThread.Suspend and TThread.Resume are the RTL's.
--------------------------------------------------------------------------------
SFTP AND SNIP OVER SSH: A PACKET SENT INTO A WINDOW THE PEER KEEPS SHUT
================================================================================
96. FIXED - the SFTP client (TstSFTPClient, tSFTPTransport) and the SFTP
server (TstSFTPServerSubSystem) lost the end of a packet whose sending
the peer's SSH window held up for more than about a second and a half:
the client then waited for ever for the answer to that request - a
WRITE, a READ or any other - and the answers the server sent after a
cut one came out of frame
A channel's Send passes octets as far as the peer's window allows. When
the window shuts during the Send, it waits about a second and a half
(100 times 10 ms) for the peer to open a new one, then returns with the
rest unsent and says how many octets it passed (entry 76). A peer opens
a new window once it has taken in what arrived, so the window stays
shut while the peer does not read - a server busy with something else,
a client that has asked for several answers and takes its time over
them, as SFTP clients that read ahead do - and while what was sent into
it is still on its way over a slow link.
THE STEP THAT FAILED is sending the packet. tSFTPTransport sent every
request, in all 19 places it sends one, with a single Send and did not
look at what it returned, and the server subsystem sent every answer the
same way. A packet that fits in what is left of the peer's window is not
held up; one that runs past its end is, and SFTP packets are large:
TstSFTPClient.PutFile writes 128 KB at a time, GetFile asks for 128 KB,
and the server answers a READ with up to 64 KB. Our client and server
open a new window only once the whole window has been read, so between
them, at the default window of 1 MB, a WRITE runs past the end of the
server's window once in every 1 MB of WRITEs, and a DATA answer past the
end of the client's once in every 1 MB of answers.
WHAT IT LOOKED LIKE:
- A request whose end was not sent never reached the server whole, so
the server never answered it. The client waited for the answer for
ever: WriteFile, PutFile, GetFile and the others did not return.
- An answer whose end was not sent left the client a packet short. The
first octets of the next answer completed it, so the client took them
for the end of the earlier answer, and it could frame nothing after
that. Our client asks for one answer at a time, and waited for the rest
for ever instead. A client that asks ahead got a DATA answer that ended
in octets that were not the file's, then a stream it could not read.
NOW both send every packet with SendAllOnChannel (StreamSec.SSH.Transport),
which waits for the peer's window for as long as the channel is open and
sends all of it, as port forwarding does (entry 62).
WHAT EXISTING CODE SEES DIFFERENTLY:
- A client request that the server's window holds up waits until the
server opens the window, for as long as that takes, instead of about a
second and a half. Closing the channel, the SSH connection ending
(entry 84), closing the SSH client, or a TstSSHSocketServer in the
same program being deactivated with CloseAllOnDeactivate ends the wait:
the call then raises eSFTPClientError "Channel closed while sending an
SFTP packet". The same exception comes from a request made on a channel
that is no longer open, where the channel's Send used to raise
eSSHClientChannelError "... the channel has no broker ..." on a channel
whose close had completed.
- The server's subsystem thread waits with an answer the client's window
holds up, and reads no new requests meanwhile, as a server that has not
finished answering does. The client closing the channel, the connection
ending, or the server being stopped releases it: within 31 ms when the
client closed the channel, and at once in the other two cases.
THE DISCRIMINATING TEST: log in to a TstSSHSocketServer with a
DefaultWindowSize of 65,536 and an SFTP subsystem, make the subsystem
stop reading for three seconds after it has answered a REALPATH, and
call WriteFile with 100,000 octets straight after that REALPATH. An
affected release never returns from WriteFile, and the server never
gets the whole WRITE; this one returns True after about three seconds,
and the file holds the 100,000 octets.
Measured with Test\sftpinterop\SftpShutWindowTest, our client against
our server on 127.0.0.1, windows of 64 KB. The server not reading for
3 s: WriteFile of 100,000 octets, one WRITE larger than the window, and
PutFile of 300,000 octets never returned, and the server never received
the whole WRITE; now they return after 3.0 and 3.3 s with the files
right. A raw client not reading for 3 s: the DATA answer to a READ of
65,536 octets arrived 51 octets short, and the answer to the next READ
was framed as the end of it; of two READs of 40,000 octets asked
together, the second answer arrived 14,528 octets short, and nothing
after it could be framed; now all arrive whole and right. No peer
holding anything up, but a link between client and server that carries
32 KB a second: PutFile of 300,000 octets and GetFile of 200,000 octets
(a window of 64 KB at the client) never returned; now they return after
9.3 and 6.4 s with every octet right. Before, 12 of the test's 33 checks
failed, the same ones on Win32 and Win64 (a step that does not finish
skips its later checks); now all 40 pass on both. At the default windows
of 1 MB, measured once with the same program: through a link carrying
48 KB a second, PutFile of 2 MB never returned, the server having
received 917,504 octets - seven WRITEs, the eighth running past the end
of its window; through one carrying 32 KB a second, GetFile of 1,300,000
octets never returned either. Now they return after 42.9 and 40.0 s with
every octet right. A server sending into a window the client never reopens
is released as above, and closing the SSH client while WriteFile waits
to send returns within 15 ms and ends WriteFile with eSFTPClientError.
SftpEofRaceTest, SftpPutFileTest, SftpJailLinkTest, SftpSelfTest (on
Win32, where it is built), SshChannelSendCountTest,
SshChannelPacketTest and SshWindowAdjustTest pass as before.
PLATFORMS. Every platform: the same code runs on each. Measured on Win32
and Win64.
NOT INVOLVED: what a packet holds; the channel's Send and its count
(entry 76); the window and when it is opened (entries 40 and 69).
NOT CHANGED:
- tSFTPTransport.Send, the transport's iTransport.Send, still passes
straight to the channel's Send and returns its count.
- The legacy units stSFTPClient and stSFTPTransport, which no longer
ship, are not changed.
97. FIXED - snip over SSH (TsnipClient and TsnipServer, TsnipSSHClient and
TsnipSSHServer): a message that lay across the end of the receiving
end's SSH window never arrived, and the call waited for ever. So did
every message larger than the window. Snip messages follow one another
on the channel, so on a connection that carried more than one window's
worth of requests, or of answers, the first one to cross the end of a
window did this - with the default window of 1 MB, within the first MB
THE STEP THAT FAILED is taking the message off the channel. The snip
connection takes a message only once all of it has arrived, and it asked
the channel how much had: the channel's RecvLength. A channel takes in
no more than its window, and opens a new one only once the whole window
has been read. Of a message that ran past the end of the window, the part
inside it was never read, because the message was not all there; so the
window was never opened again, and the rest of the message never came.
THE SENDING END had the defect of entry 96 as well: RawSend sent a frame
with a single channel Send and SendMsgStream did not look at the count,
so a frame that the peer's window held up for more than about a second
and a half lost its end, and the peer waited for the rest for ever.
NOW:
- The SSH connection takes everything the channel holds into a buffer of
its own whenever it looks for a message, as the TLS connection does,
and counts what that buffer holds. The window opens again as soon as
its last octet has come in, and a message of any size arrives. The
buffer is wiped (ProtectClear) when the connection is freed.
- A frame is sent with SendAllOnChannel, waiting for the window for as
long as the channel is open.
- Close sends the close message with the channel's own Send, which waits
no longer than it did, and makes a frame still waiting for the window
on another thread give up: a peer that has stopped reading does not
keep this end from closing, and TsnipClient.Stop on another thread ends
a call that waits to send. With SendAllOnChannel alone, Stop waited as
long as the call did.
WHAT EXISTING CODE SEES DIFFERENTLY: a call whose request or answer
crosses the end of a window returns. A call whose request the peer's
window holds up waits for it, where the end of the request was lost
after about a second and a half, and TsnipClient.Stop ends that wait. Like a
connection over TLS, a connection over SSH holds a message in memory
whole until it is taken.
Measured with Test\snifssh\SnipShutWindowTest, a TsnipClient calling a
TsnipServer over SSH on 127.0.0.1 with windows of 64 KB. Of eight Takes
of 15,000 characters one after another, the fifth, the first to cross the
end of the server's window, never returned; so did the fifth of eight
Gives, whose answers cross the client's; now all eight return, and so
does one of 100,000 characters after them. At the default windows of
1 MB, the 70th Take and the 70th Give of 15,000 characters, the calls
that carry the stream past 1 MB, never returned; now all 81 return each
way. Over a link between client and server that carries 16 KB a second,
Takes and Gives of 100,000 characters: every one returns now, after 6.2 s
each; with the new buffering but a frame still sent with a single Send,
the first never returned - the window stayed shut for about four seconds
while a whole window of the frame was still on its way. Before, 4 of the
test's 21 checks failed, steps 2 to 5 each stopping at its first call
that did not return, on Win32 and Win64; now all 33 pass on both.
TsnipClient.Stop while a Take of 100,000 characters waits on a link that
passes nothing returns within 16 ms and ends the call.
SnipChannelOpenTimeoutTest, SnipConnectFailureTest,
SnipServerRestartTest, SshDeadConnectionTest, SshSubsystemTeardownTest
and SshClientCloseTest pass as before, and so do the Callback and
Mediator demos' SSH proofs (on Win32).
PLATFORMS. Every platform: the same code runs on each. Measured on Win32
and Win64.
NOT INVOLVED: snip over TLS, whose connection buffers what arrives
already; the Snif messages themselves; the SSH channel and its window.
NOT CHANGED: a peer that never opens its window, and never closes, keeps
a call that sends to it waiting until the program stops the client
(Stop); there is no timeout on a snip call, as before.
98. FIXED - the SSH Tunnel Client demo lost what it read from a TCP
connection when the SSH server's window stayed shut for more than about
a second and a half, in its -L relay loop, in its HTTP mode's first
request, and in the echo of its -R plugin SampleForwardDLL
Each sent what it had read with a single channel Send, as in entry 96,
and went on without the rest. NOW the relay loop keeps what the server's
window has no room for and sends it as room appears, relaying the other
way meanwhile and reading no more from the local socket until it has
gone; the HTTP request and the echo are sent with SendAllOnChannel.
Measured with Test\sshinterop\TunnelClientStallTest, which runs the
demo's tDirectListener and tForwardDLLHandler, with SampleForwardDLL.dll
built from the demo, against our SSH server on 127.0.0.1: a target that
did not read for 3 s got 1,572,864 of 4,194,304 octets through the relay
loop, the first wrong one at 262,144; an HTTP request of 24,000 octets,
through a link carrying 4 KB a second to a window of 8 KB, arrived as
its first 8,192; and 8,192 of 32,768 octets came back from the echo the
same way. On Win32 and Win64 alike, 3 of its 4 checks failed; now all
pass, with every octet right.
NOT CHANGED: a local socket that takes fewer octets than it is given, as
a TCP peer that reads slowly makes it do: entry 111.
--------------------------------------------------------------------------------
CMS: READING THE RC2 ITEMS OF A CORRESPONDENT'S SMIMECAPABILITIES
================================================================================
99. FIXED - tSMIMECapabilities.AssignStruct took every RC2 item of a
correspondent's smimeCapabilities as RC2 with a 64-bit key, whatever
key size the item gave, and raised instead of leaving out an RC2 item
whose parameter is no RC2 key size
AssignStruct (StreamSec.DSI.PkixCms) turns the smimeCapabilities
attribute of a correspondent's signature (RFC 8551, section 2.5.2) into
capability items, and with aIntersect True keeps the ones the list it is
called on holds itself. An RC2 item carries its key size in an INTEGER
parameter, which this library writes, and reads, as the RC2 parameter
version of RFC 2268, section 6 (entry 100).
THE STEP THAT FAILED is finding that parameter. A message loaded from
DER and not expanded - the way TstMPSignedData loads one to verify it -
decodes which alternative of an item's parameters it holds only when
that field is expanded. AssignStruct asked before that, was told none,
and took the item at the key size rc2-cbc has without a parameter,
8 octets. So RC2 at 40, 128, 192, 256 or 1024 bits came out as RC2 at
64 bits, and so did the three RC2 items OpenSSL writes (128, 64 and 40
bits); intersected with a list that holds RC2-64, as the list a
component fills in by itself does in a program that links stArc2, they
were kept. A message made ReadOnly and expanded with ExpandFull before
the call was read right, but there a parameter that is no RC2 key size
raised out of AssignStruct: eCipherError for a negative number, for one
over 1024 and for 189, which RFC 2268's table maps to 0 bits, and
eASN1DataError for an INTEGER too large for an Int64. RFC 3851, section
2.5.2, has a receiver handle a value it does not recognise "in a
graceful manner".
NOW AssignStruct expands an RC2 item's parameters before it looks at
them and reads the INTEGER as it is written, so an item this library
wrote reads back at the key size it was written with. An RC2 item whose
INTEGER is no RC2 key size, or one that is not a whole number of octets,
is left out, and the items after it are read as before. That leaves out
OpenSSL's three RC2 items (entry 100).
THE DISCRIMINATING TEST: sign with TstMPSignedData with one capability,
RC2 with KeyLength 16, load the message into a tContentInfo, and pass
its signer's smimeCapabilities to AssignStruct with aIntersect False. An
affected release gives an RC2 item of 8 octets; this one gives 16.
WHO. A program that calls AssignStruct on a correspondent's list and
acts on the RC2 items it gets, or that calls it on lists it does not
control. The components do not call AssignStruct themselves: the content
cipher of a TstMPEnvelopedData comes from its own SMIMECapabilities.
Measured with Test\tls13interop\PkixCmsSmimeCapWireTest (entry 93),
which now also signs RC2 items at 40, 64, 128, 192, 256 and 1024 bits,
compares what it wrote with RFC 2268's table, reads them back from the
message as loaded and as made ReadOnly and expanded, reads OpenSSL's
list, and reads lists of an RC2 item with 189, 1025, -1 or 2^64 followed
by AES-128-CBC. Before, 14 of its 94 checks failed on Win32, Win64 and
Linux64, every one of them reading: as loaded, five of the six RC2 items
came back as RC2-64, OpenSSL's three RC2 items were taken, and the four
odd ones were taken as RC2-64; expanded, the four odd ones raised. Now
all 94 pass on the three. PkixCmsSmimeCapTest, which builds its lists in
memory, passes its 37 checks on the three, as before.
PLATFORMS. Every platform: the same code reads the list on each.
Measured on Win32, Win64 and Linux64.
PACKAGES. StreamSec.DSI.PkixCms is in the StrSecIV packages already; no
package gains a unit. StrSecIV370 builds on Win32 and Win64.
NOT INVOLVED: what TstMPSignedData writes, which is unchanged; the
signature and its verification; the items of every cipher other than
RC2, which AssignStruct takes by their OID alone, before and after.
NOT CHANGED:
- An rc2-cbc item without parameters, or with NULL, is taken at 8
octets, as before.
- The legacy unit stMpCms, which no longer ships, reads the list with
code of its own and is not changed.
--------------------------------------------------------------------------------
DEPRECATED: RC2 IN S/MIME CAPABILITIES
================================================================================
100. DEPRECATED - RC2 items in S/MIME capabilities: tSMIMECapabilityItem
with CipherAlg caARC2, in the SMIMECapabilities of TstMPSignedData and
TstMPEnvelopedData and in tSMIMECapabilities.AssignStruct
An RC2 item works as it did. Deprecated means: do not rely on it, in a
list you advertise or in one you read. The declaration carries the word,
and what to use instead: AES-CBC (caRijndael).
WHY. RFC 3851, section 2.5.2.1, puts the effective key length in bits
in the parameter of an RC2 item, 128 for a 128-bit key, "NOT the
corresponding parameter version of 58", and OpenSSL writes that. This
library writes, and reads (entry 99), the RC2 parameter version of RFC
2268, section 6, as an EnvelopedData's rc2-cbc content encryption takes
it (RFC 3370, section 5.2). The two are the same number from 256 bits
up, and not below:
key written here RFC 3851, and OpenSSL
40 bits 02 02 00 A0 (160) 02 01 28 (40)
64 bits 02 01 78 (120) 02 01 40 (64)
128 bits 02 01 3A (58) 02 02 00 80 (128)
192 bits 02 01 16 (22) 02 02 00 C0 (192)
256 bits 02 02 01 00 (256) the same
So a correspondent that follows RFC 3851 reads another key size from an
RC2 item below 256 bits, and AssignStruct leaves out the RC2 items
OpenSSL writes. It is kept that way. RFC 5751, S/MIME 3.2, deleted
section 2.5.2.1 as one that "discussed deprecated RC2", and RFC 8551
keeps RC2/40 for decrypting existing mail only.
THE LIST FILLED IN BY DEFAULT. A component fills its SMIMECapabilities
with every CBC cipher the program has registered, so in a program that
links stArc2 it holds RC2 at every multiple of 8 octets from 8 to 128,
and every signature it makes advertises them. To leave RC2 out, delete
those items from SMIMECapabilities, or assign a list of your own. The
content cipher of a TstMPEnvelopedData is chosen from its own list as
before: among the items filled in by default it prefers AES-CBC with the
largest key.
NOT DEPRECATED HERE: the RC2 cipher itself (stArc2), and the parameter
version in an EnvelopedData's rc2-cbc content encryption, where RFC 3370
does want it.
--------------------------------------------------------------------------------
SSH PORT FORWARDING: AN EOF BEFORE THE FORWARDED CONNECTION IS UP
================================================================================
101. FIXED - on macOS, iOS, Linux and Android, TstSSHSenderControllerSocket
(-L, direct-tcpip) and TstSSHForwardingClientSocket (-R) ended a
forwarded connection instead of half-closing it when the SSH peer
sent SSH_MSG_CHANNEL_EOF while the TCP connect to the target was
still under way: the half-close they make for that EOF,
tAbstractSocket.ShutdownSend, stopped the connect, so the target never
saw the connection, and the channel closed with nothing on it
Both components connect to their target with tAbstractSocket.Open,
which on every platform but Windows starts the connect and returns
before it completes (entry 88), and the channel is confirmed at once.
When the peer sends SSH_MSG_CHANNEL_EOF, the component passes it on as a
half-close, ShutdownSend, so that the target reads the end of the stream
and can still answer. A shutdown made while the connect is under way
does not wait for it: macOS and Linux both take the connecting socket
straight to closed, sending neither a FIN nor any further SYN. The
target never heard of the connection, the component's next read said
end of stream (macOS) or ECONNRESET (Linux), and it closed the channel
about 100 ms after the EOF, with nothing sent on it.
A peer sends EOF before any data when it has nothing to send - the
client of a service that speaks first whose own input is already at its
end, or a TCP client of an -R listener that half-closes at once. The EOF
arrives while the connect is under way when the target is far away or
busy, and on macOS even for a target on 127.0.0.1, whose connect is not
complete when Open returns either. Data sent before the EOF was not
affected: its write waits for the connect, and the EOF follows it.
NOW a ShutdownSend made while the socket's own connect is under way is
held until the connect is up, and made by the first WaitForData,
WaitForWrite, Receive or Send on the socket that finds it up. The two
components wait on their socket every 100 ms, so the target reads the
end of the stream within 100 ms of the connection coming up. A connect
that fails is reported by the next read, as before.
WHO. A server with TstSSHSenderControllerSocket, and a client with
TstSSHForwardingClientSocket, built for macOS, iOS, Linux or Android.
Windows was not affected: there Open waits for the connect.
HOW IT WAS FOUND. On macOS, a copy of the socket unit that logged every
connect, send, shutdown and receive showed a shutdown made during the
connect succeed, the listener never see the connection, and the socket
then read end of stream. The two components make that shutdown when the
peer's EOF arrives.
THE DISCRIMINATING TEST: on macOS or Linux, Open a tAbstractSocket to a
listener on 127.0.0.1 whose accept queue is full, call ShutdownSend at
once, then let the listener accept. An affected release never delivers
the connection, and the socket reads end of stream (macOS) or fails with
error 104 (Linux) at once; this one delivers it, and the listener reads
the end of the stream.
PLATFORMS. New test SshFwdEarlyEofTest (battery rows Win32, Win64 and
Linux64) puts a target whose accept queue is full behind each component,
has the peer send EOF, with nothing before it, while the connect is
under way, and releases the queue 1.5 s later; it also shuts a bare
socket during its connect, and runs four controls - the EOF after the
connect, or behind one octet. An affected release fails 9 of its 35
checks on Linux64 and on macOS 26 on an Apple M1, the socket alone, -L
and -R each never reaching the target; this release passes all 35 on
both. On Win32 and Win64, where the queue is not filled and every case
is a control, its 23 checks pass before and after. Also passing as
before: on Linux64, every SSH row of the battery and entry 61's test; on
the M1, entry 61's test and the tests of entries 40, 44, 46, 70, 74, 78,
84 and 91. Run again on the M1 with entries 106 and 107: the test's 65
checks pass, and built without this entry it fails the same 9.
NOT INVOLVED: Windows; connections a server accepts - those of
TstSSHListenerControllerSocket - which are up when accepted; the SSH
protocol; data the peer sends before its EOF.
NOT CHANGED:
- Open still returns before the connect completes on every platform but
Windows (entry 88).
- A ShutdownSend held this way is made by the next call on that socket.
A program that shuts a connecting socket for sending and then waits
for something other than the socket sends its FIN only when it next
waits on, reads from or writes to the socket.
--------------------------------------------------------------------------------
SSH: A MESSAGE THE CLIENT OR THE SERVER DOES NOT RECOGNISE
================================================================================
102. FIXED - an SSH client and an SSH server never answered a message they
did not recognise: the SSH_MSG_UNIMPLEMENTED that RFC 4253 requires was
put together and not sent
RFC 4253 section 11.4: "An implementation MUST respond to all
unrecognized messages with an SSH_MSG_UNIMPLEMENTED message in the order
in which the messages were received." The answer carries the sequence
number of the packet it answers. Each end numbers the packets it
receives from 0, one more for each packet whatever it holds (section
6.4); under strict KEX, which both ends of this library offer, the
count starts again at 0 after each SSH_MSG_NEWKEYS.
THE STEP THAT FAILED is the last one, sending the answer. The SSH
transport under TstSSHSocketClient and TstSSHSocketServer (and
TstSSHClient and TstSSHServer) saw that a message was not one it knew,
put together SSH_MSG_UNIMPLEMENTED with a sequence number, and went on
without sending it. The message was then skipped, which RFC 4253 also
requires ("Such messages MUST be otherwise ignored"), so the peer was
never told, and neither end reported anything. That held for every
message the transport does not know, whichever end sent it and at
whatever point of the connection: before, during and after the key
exchange, during user authentication, and on an open connection.
WHO. Both ends: the SFTP client and server, snip over SSH and port
forwarding all run on this transport. A peer notices when it sends a
message of a protocol extension without first asking whether the other
end has it, and relies on SSH_MSG_UNIMPLEMENTED to learn that it does
not: it waited for an answer that never came. Measured against OpenSSH's
sshd (9.5, Windows): the one message it sent this client that the
transport did not recognise was its SSH_MSG_EXT_INFO, which the
transport now recognises (below); the rest, the global request
hostkeys-00@openssh.com included, it recognised already.
NOW the answer is sent, in the order the messages arrived, with the
sequence number of the message it answers; the message is otherwise
skipped, as before. Three more parts of the transport had to change for
the answer to be right, because until now it was never sent:
- THE SEQUENCE NUMBER. The transport took it from the cipher's count of
the packets it had decrypted. Under aes128-gcm@openssh.com and
aes256-gcm@openssh.com that count is the GCM invocation counter, which
starts from a number the key exchange gives it, not from 0: the answer
to the third packet after the key exchange would have carried
2235236387 in one measured connection. The transport now counts the
packets it receives itself, and starts again at 0 after the peer's
SSH_MSG_NEWKEYS under strict KEX. Under aes128-ctr with hmac-sha2-256,
and under chacha20-poly1305@openssh.com, the cipher's count gave the
right number in the connections measured.
- SSH_MSG_EXT_INFO. Both ends offer RFC 8308's extension negotiation
(ext-info-c, ext-info-s) in their first SSH_MSG_KEXINIT, and an end
that offers it "MUST be prepared to accept an SSH_MSG_EXT_INFO message
from the peer" (RFC 8308 section 2.2). OpenSSH's sshd sends one to
this client, and TstSSHServer sends one to every client that offers
ext-info-c, this library's own included. The transport did not
recognise it, so with the answer sent it would have answered each one.
Measured with the answer sent and SSH_MSG_EXT_INFO not recognised:
TstSSHServer ended the connection while this library's own client
logged in (Login raised eSSHIncomingDisconnect, reason 11), and
OpenSSH's sshd took the answer and went on. It is now recognised and
skipped. What it says is not used, as before.
- STRICT KEX (the Terrapin countermeasure, kex-strict-c-v00@openssh.com
and kex-strict-s-v00@openssh.com). When both ends offer it, a message
that is not the key exchange's own must end the connection if it
arrives during the initial key exchange (draft-miller-sshm-strict-kex
section 3.2), not be answered. The transport ended it for
SSH_MSG_IGNORE, SSH_MSG_DEBUG and SSH_MSG_UNIMPLEMENTED only. A message
it did not know it skipped, and with the answer sent it would have
answered it. And the server counted the initial key exchange as over
when it had sent its own SSH_MSG_NEWKEYS, not when it had read the
client's, so between the two it skipped even SSH_MSG_IGNORE. Now,
under strict KEX and until an end has read the peer's SSH_MSG_NEWKEYS,
every message other than the key exchange's own and SSH_MSG_DISCONNECT
ends the connection: this end sends SSH_MSG_DISCONNECT with reason 3
(SSH_DISCONNECT_KEY_EXCHANGE_FAILED) and raises eSSHOutgoingDisconnect.
Without strict KEX a message not recognised during the key exchange is
answered, which RFC 4253 section 7.1 allows.
THE DISCRIMINATING TEST: before any key exchange, send message 200 -
from the range RFC 4250 section 4.1.1 leaves to local extensions - as
an unencrypted packet right after the identification line, to a
TstSSHSocketServer, or from a listener a TstSSHSocketClient connects to.
An affected release sends its SSH_MSG_KEXINIT and nothing more, and goes
on waiting for the peer's SSH_MSG_KEXINIT; this one sends
SSH_MSG_KEXINIT and then SSH_MSG_UNIMPLEMENTED with sequence number 0.
After an SSH_MSG_IGNORE, message 200, an SSH_MSG_DEBUG and message 201,
the answers carry 1 and 3. On a logged-in connection between this
library's client and server, the answers carry the number of each
message counted where it was sent, under aes128-ctr, aes128-gcm and
chacha20-poly1305 alike; and against OpenSSH's sshd (9.5, Windows) the
client's count of its own packets agrees with the sequence number sshd
gives message 200 in its log ("dispatch_protocol_error: type 200 seq
2"), while sshd at LogLevel DEBUG3 logs no SSH_MSG_UNIMPLEMENTED from
the client.
PLATFORMS. Every platform: the same code runs on each. Measured on
Win32, Win64 and Linux64.
NOT INVOLVED: the ciphers, MACs and key exchange methods themselves, the
channels, SFTP, and how a message the transport does recognise is
handled.
NOT CHANGED:
- An SSH_MSG_UNIMPLEMENTED the peer sends: the component's
Unimplemented method is called with its sequence number and
eSSHUnimplemented is raised. On an open connection the thread that
reads the connection goes on; during the key exchange or user
authentication the exception still ends ConnectToHost or Login.
- Having skipped a message - one it does not know, SSH_MSG_IGNORE,
SSH_MSG_DEBUG or SSH_MSG_EXT_INFO - the transport waits for the next
one before it lets go of the connection, so this end can send nothing
meanwhile, and it ends the connection with
SSH_DISCONNECT_CONNECTION_LOST if the peer sends nothing more for
about six seconds. Measured with a lone SSH_MSG_IGNORE, before and
after this change alike: a client that then sent nothing for 5.5
seconds kept its connection to TstSSHSocketServer, one that sent
nothing for 6 seconds lost it; and TstSSHSocketClient, sent one by the
server, could not send a channel open half a second later, and lost
the connection. Entry 108 changes that.
- The legacy unit stSSHTransport, which no longer ships, has the same
defect and is not changed.
--------------------------------------------------------------------------------
SSH: STRICT KEX AT EVERY KEY EXCHANGE
================================================================================
103. FIXED - an SSH connection under strict KEX with aes128-ctr, aes-cbc or
any other cipher with a separate MAC ended at the first key exchange
the peer started after the initial one: the other end rejected the MAC
of the first packet after it. chacha20-poly1305@openssh.com failed the
same way right after the initial key exchange when the peer did not
offer strict KEX. And a packet the peer sent before its SSH_MSG_KEXINIT
was taken in where strict KEX requires the connection to end
Strict KEX is the Terrapin (CVE-2023-48795) countermeasure of
draft-miller-sshm-strict-kex-01. TstSSHSocketClient and TstSSHSocketServer
(and TstSSHClient and TstSSHServer) offer it in their first
SSH_MSG_KEXINIT, as kex-strict-c-v00@openssh.com and
kex-strict-s-v00@openssh.com; OpenSSH offers it too (measured: OpenSSH
9.5 for Windows, sshd and ssh). When both ends offer it, the draft says:
- section 3.1: the names "are valid only in the initial SSH_MSG_KEXINIT
message from each endpoint. Their presence or absence in subsequent
SSH_MSG_KEXINIT packets MUST be ignored by all parties."
- section 3.3: "both the client and server MUST reset their sequence
numbers at the conclusion of the initial KEX and for each subsequent
KEX."
- section 3.2: "implementations MUST verify that the SSH_MSG_KEXINIT was
the first message received from the peer."
Each end numbers the packets it sends and those it reads (RFC 4253
section 6.4), and does not send the number: the MAC of every cipher but
the two AEAD ones is computed over it, and it is the nonce of
chacha20-poly1305@openssh.com. The two ends have to agree on it for
every packet.
THE STEPS THAT FAILED:
- DECIDING STRICT KEX AT A LATER KEY EXCHANGE. The transport decided
anew at every SSH_MSG_KEXINIT whether strict KEX was in force, and at
a later one - which is not the first and carries no name - decided it
was not. So at that key exchange's SSH_MSG_NEWKEYS it did not set the
numbers back to 0, while a peer that follows the draft does. With a
cipher that has a separate MAC - aes128-ctr, aes192-ctr, aes256-ctr,
aes*-cbc and the rest, with any hmac-* - the first packet after that
SSH_MSG_NEWKEYS failed its MAC at the other end, and the connection
ended. chacha20-poly1305 and aes-gcm got through by accident: a new
chacha20-poly1305 cipher starts its count at 0 whatever the transport
does, which is what strict KEX asks for, and aes-gcm's nonce is a
counter of its own (RFC 5647).
- HANDING THE NUMBER TO A NEW CIPHER. The count lived in the cipher's
block padding, which the transport carries from one cipher to the
next, except for chacha20-poly1305, which has none: a new
chacha20-poly1305 cipher numbered from 0 at every SSH_MSG_NEWKEYS. With
strict KEX that happened to be right; without it the number should
have gone on (3 after the initial key exchange), so the first packet
after the initial key exchange failed at the other end.
- CHECKING WHAT CAME BEFORE THE PEER'S KEXINIT. Nothing did. An
SSH_MSG_IGNORE, an SSH_MSG_DEBUG or any other packet before it was
handled, and the key exchange went on under strict KEX.
WHAT IT LOOKED LIKE. Only a peer starts a key exchange after the
initial one: this library's ends start one of their own only after 2^31
packets one way. A peer does it by time or by the amount of data, as RFC
4253 section 9 recommends ("It is RECOMMENDED that the keys be changed
after each gigabyte of transmitted data or after each hour of connection
time"), or as configured, OpenSSH with RekeyLimit. Measured against
OpenSSH 9.5 (Windows) with RekeyLimit 1K, under aes128-ctr with
hmac-sha2-256:
- TstSSHSocketClient logged in to sshd: the connection ended at the first
key exchange after login. Whichever end read first gave up: sshd
logged "Corrupted MAC on input" and "message authentication code
incorrect", or the client closed the connection. A waiting
TstSFTPClient call raised eSFTPClientError "Channel closed while
awaiting an SFTP packet"; a GlobalRequest with a reply raised
eSSHClientChannelError, its reply never having come.
- OpenSSH's sftp against a TstSSHSocketServer with the SFTP subsystem:
sftp ended at the first key exchange with "Corrupted MAC on input" and
"message authentication code incorrect".
Under chacha20-poly1305@openssh.com and aes128-gcm@openssh.com the same
connections went on, through 61 key exchanges in 20 rounds of SFTP
traffic against sshd. The chacha20-
poly1305 failure without strict KEX needs a peer that does not offer it
- OpenSSH does - and was measured with a copy of this library's client
that did not offer it: sshd logged "Connection corrupted" at the client's
first encrypted packet. Between two ends of this library strict KEX is
always in force and neither end starts a key exchange of its own, so
none of this showed there.
NOW:
- Strict KEX is decided at the peer's first SSH_MSG_KEXINIT and holds for
the connection; a name in a later SSH_MSG_KEXINIT, or its absence, is
ignored. While it is in force the numbers go back to 0 after every
SSH_MSG_NEWKEYS: those of the packets sent after this end's, those of
the packets read after the peer's.
- The transport counts the packets each way itself and gives each
cipher it makes at SSH_MSG_NEWKEYS the number of the next packet: 0
under strict KEX, the running count without it. aes-gcm's own nonce
counter is left alone, as before.
- Under strict KEX, if the peer's SSH_MSG_KEXINIT is not the first packet
it sent, this end sends SSH_MSG_DISCONNECT with reason 3
(SSH_DISCONNECT_KEY_EXCHANGE_FAILED) when it reads the SSH_MSG_KEXINIT,
and ConnectToHost raises eSSHOutgoingDisconnect. What came before it is
handled as before - strict KEX is not known until the SSH_MSG_KEXINIT
has been read - so a message this end does not recognise is answered
with SSH_MSG_UNIMPLEMENTED first (entry 102). OpenSSH ends the connection
in the same place, with reason 2 and "strict KEX violation: KEXINIT was
not the first packet" (measured, sshd and ssh).
SECURITY. Neither step opened the Terrapin attack. The attack injects
packets before the key exchange ends and deletes as many after it, and
the numbers were set back to 0 at the initial key exchange's
SSH_MSG_NEWKEYS, in both directions, by every release that offers strict
KEX (4.1.1.349 and later), so an injected packet changed no number an
encrypted packet was checked against. The packets around a later key
exchange are encrypted and authenticated under the keys of the one
before. What failed was the connection. The missing check before the
peer's SSH_MSG_KEXINIT is a requirement of the draft that was not met,
and SSH.txt section 8 said that "any unexpected message before the first
KEX is rejected" and that the numbers "are reset at each NEWKEYS",
"reviewed and confirmed present": neither was so. Section 8 now says what
the transport does.
THE DISCRIMINATING TEST: run OpenSSH's sftp with -o RekeyLimit=1K -o
Ciphers=aes128-ctr -o MACs=hmac-sha2-256 against a TstSSHSocketServer
with the SFTP subsystem and upload 64 KB. An affected release ends
before the upload is done, sftp reporting "Corrupted MAC on input"; this
one completes it, and sftp -vvv logs "resetting send seqnr" and
"resetting read seqnr" at every key exchange. The same with
-o Ciphers=chacha20-poly1305@openssh.com completes with both.
PLATFORMS. Every platform: the same code runs on each. Measured on
Win32, Win64 and Linux64.
NOT INVOLVED: the ciphers and MACs themselves, the key exchange methods,
host keys, user authentication, the channels and SFTP.
NOT CHANGED:
- The standard names kex-strict-c and kex-strict-s are neither offered
nor recognised; with a peer that offers only those there is no strict
KEX, as before. The draft asks that an end offering both be able to
negotiate either ("SHOULD offer both").
- This library's ends still start no key exchange of their own before
2^31 packets one way.
- The legacy unit stSSHTransport, which no longer ships, is not changed.
--------------------------------------------------------------------------------
HTTP, OCSP, CRL, DNS AND SNIP-OVER-TLS CLIENTS: THE FIRST WRITE AFTER OPEN
================================================================================
104. FIXED - on macOS and iOS, and on Linux and Android for a server on
another machine, tHttpClient (and with it TsmAcmeClient), the OCSP,
CRL and time-stamp clients, tDnsTcpResolver and TsnipTLSClient never
sent their request: their first write, made while the TCP connect
was still under way, wrote nothing, and they took that for a broken
connection ("HTTP transport: send failed", "OCSP transport: send
failed", no DNS answer, EsnipClosed). A write larger than the socket
took at once failed the same way, part of it sent
Each of them opens its TCP connection with tAbstractSocket.Open, which
on every platform but Windows starts the connect and returns without
waiting for it (entries 88 and 101), and then writes its request at
once with one Send, taking a Send that wrote nothing for a failure. A
Send made while the connect is under way writes nothing: the system
answers "try again" (EAGAIN on Linux and Android, ENOTCONN on macOS and
iOS, which entry 88 reports the same way), and the caller is meant to
wait until the socket can be written and send again. These callers did
not wait:
- tHttpClient (Get, Head, Post, Execute) raised eHttpError "HTTP
transport: send failed" before the request - for an https URL, the
ClientHello - went out. TsmAcmeClient makes every request with it.
- The HTTP transport of StreamSec.DSI.AbstractOcsp raised eOcspError
"OCSP transport: send failed": TstOcsp and TsmOcsp got no answer
(LastError "OCSP transport error: OCSP transport: send failed"),
FetchCRL and FetchCACert returned False - TsmCustomTLSInternalServer
fetches a missing CRL and a missing issuer certificate with them - and
HttpPostExchange raised, so the RFC 3161 time-stamp client
(StreamSec.DSI.Tsp) got no time-stamp.
- tDnsTcpResolver got no answer and returned dsTempFail for every name:
TsmSMTPServer's default resolver had no SPF, DKIM or DMARC record to
check, and an MX lookup made with it found nothing.
- TsnipTLSClient and TsnipAdvancedTLSClient (Start, StartTransport)
raised EsnipClosed "snip/TLS: the connection dropped while sending the
1425 octet handshake flight" (the size varies with the settings).
The connect itself did not fail: a Windows build of the same program,
against the same server, sent its request. Measured, from Linux to a
server on another machine on the local network: tHttpClient.Get,
FetchCACert, HttpPostExchange and TsnipAdvancedTLSClient.StartTransport
10 times each, 40 failures in 40 calls, each within a millisecond and
the server never seeing a request; on macOS 26 on an Apple M1 to
127.0.0.1, tHttpClient, FetchCACert and HttpPostExchange 10 times each,
30 in 30. On macOS to 127.0.0.1 the snip client got through: making its
ClientHello takes longer than that connect.
A FULL SOCKET BUFFER answers "try again" too, on every platform once the
socket does not block: every socket off Windows, and a Windows one once
it has been waited on. On macOS, iOS, Linux and Android:
- tHttpClient and HttpPostExchange failed with the same messages when a
request body was larger than the socket took at once, part of it
already sent (measured: a 16 MB POST to 127.0.0.1 on Linux);
- a snip call over TLS whose message was larger than that went out cut
short (TsnipClientTLSOctetConnection), and the call waited for an
answer that never came - for ever, or until ReadTimeout (measured: a
call carrying 4,194,304 characters on Linux);
- TstOcspServer stopped writing an answer the socket did not take at
once, and closed the connection: the client got the start of it
(measured: 2,634,135 octets of a 24 MB answer on Linux). OCSP answers
of a few kilobytes, which the socket takes at once, were not affected.
On Windows none of these was seen: there each non-blocking send took the
whole buffer at once.
NOW they write with tAbstractSocket.SendAll, which waits until the
socket can be written and sends the rest:
- tHttpClient waits at most its Timeout without progress, the OCSP, CRL
and time-stamp clients the timeout they are given, tDnsTcpResolver
its Timeout, and TsnipTLSClient what is left of its HandshakeTimeout.
A connect that does not complete in that time ends the call with the
error it raised before ("send failed"; no DNS answer), the snip client
with EsnipTimeout "snip/TLS: the 1425 octet handshake flight could not
be sent within the 20000 ms HandshakeTimeout: the connection was not
established, or the server took none of it". HandshakeTimeout now
counts from before the ClientHello is made, since off Windows sending
it is also the wait for the connect.
- A refused connect still fails at once: EstSocketError "send failed
(111)" on Linux, "(61)" on macOS (entry 88), no answer from
tDnsTcpResolver; on Windows Open raises, as before.
- TsnipClientTLSOctetConnection waits as long as the server takes, as
snip over SSH does since entry 97; Stop ends the wait.
- TstOcspServer drops a client that takes none of its answer for
Timeout ms, as it drops one that sends its request too slowly; the
description of Timeout says so.
ADDED: tDnsTcpResolver.Port, the TCP port every server in Servers is
asked on, 53 unless set: for a resolver on another port, such as a
local forwarder, or a test responder that cannot bind a port below
1024.
WHO. A program built for macOS, iOS, Linux or Android that uses ACME
(TsmAcmeClient) or tHttpClient; OCSP checking with TstOcsp or TsmOcsp;
TsmCustomTLSInternalServer's automatic CRL and issuer-certificate
fetching; RFC 3161 time-stamps; TsmSMTPServer's SPF, DKIM and DMARC
checks with its default resolver, or tDnsTcpResolver elsewhere; snip
over TLS. The first write failed on Linux and Android only for a server
on another machine - one on the same machine is connected before Open
returns - and on macOS and iOS for any server; a write into a full
buffer, on all four for any server. A Windows program was not affected.
HOW IT WAS FOUND. Entry 88 left these callers as they were and named
them in its NOT CHANGED list. A reading of every library caller of Open
and Send then found the snip-over-TLS client and the two writers that
took a full buffer for a failure.
THE DISCRIMINATING TEST: on Linux, call tHttpClient.Get for a URL on
another machine, or on macOS for one on 127.0.0.1. An affected release
raises eHttpError "HTTP transport: send failed" within a millisecond,
and the server sees no request; this one gets the answer.
PLATFORMS. New test SendAfterOpenTest (battery rows Win32, Win64 and
Linux64) sends each client through a relay on 127.0.0.1 whose accept
queue is full for its first 300 ms, so the client's connect stays under
way until the relay makes room: tHttpClient.Get, FetchCACert,
HttpPostExchange, tDnsTcpResolver and TsnipAdvancedTLSClient with a
remoted call, each checking that the server got the request, the answer
came back and the client's connect was not made before the relay made
room. Then a connect that never completes, which must end each call
after its timeout; a refused connect (control); and the full buffer - a
16 MB POST through tHttpClient and HttpPostExchange to a server that
waits before reading, a snip call carrying 4,194,304 characters over
TLS, and TstOcspServer's 24 MB answer to a client that waits. On Linux64
(WSL, kernel 6.18) and on macOS 26 on an Apple M1 an affected release
fails 21 of its 25 checks, all but the four controls; this release
passes all 25, in 5 runs of 5 on each. On Win32 and Win64 its 22 checks
(Open waits there, so not the connect that never completes) pass before
and after. Also passing as before: OcspSelfTest,
OcspDelegatedResponderTest and the five mail rows on Win32;
SnipSharedEngineTest, RestSharedEngineTest, EngineLoadTest and
EngineRegistrantTest on Win32, Win64 and Linux64; SnipBoundTest and
SnipAdvancedTest on Win32.
NOT INVOLVED: Windows; the HTTP, OCSP, DNS and TLS protocols; the
connect itself; TsmTLSClient and TsmAdvancedTLSClient, the mail clients
and servers, the TLS chain probe and the SSH clients, which already
waited; the server end of snip over TLS, whose writes TsmAsyncTLSServer
queues.
NOT CHANGED:
- Open still returns before the connect completes on every platform but
Windows (entries 88 and 101), and a refused connect is still reported
by the first write or read, not by Open.
- Send still writes nothing and returns -1, with no error code, while a
connect is under way or the buffer is full. A caller of its own that
takes that for a failure still fails; SendAll, or WaitForWrite and the
same octets again, is the remedy (see tAbstractSocket.Send).
--------------------------------------------------------------------------------
SSH: A SERVER CHANNEL CLOSED ON ITS OWN THREAD WHILE ITS CONNECTION ENDS
================================================================================
105. FIXED - an SSH server channel that a thread of its own was closing
when its connection ended could finish its Close after the server had
freed the connection's channel broker: on Windows an access violation
on that thread, or a thread that never returned, and on Linux64 the
end of the server process
An SSH server (TstSSHServer, TstSSHSocketServer) keeps each connection's
channels on a channel broker, which runs on the connection's thread and
is freed when the connection ends: when the client disconnects, when the
server is deactivated, or when gGlobalCloseAll is raised. Before it goes,
the broker takes every channel still on it off. When the client closes a
channel, the server answers its CLOSE and leaves the channel in
csClosing for the channel's consumer, whose Close completes it to
csClosed and takes it off the broker. The server's port-forwarding
threads are such consumers - those of TstSSHSenderControllerSocket (-L,
direct-tcpip) and of TstSSHListenerControllerSocket (-R,
forwarded-tcpip) - and so is a thread of the program that closes a
session channel it holds. A client that closes its channels and then
disconnects, or a server deactivated meanwhile, makes the two meet. This
is the server's side of entry 94.
THE STEP THAT FAILED is the broker waiting for a channel that another
thread was taking off it. The channel's Close claimed the channel, ended
the channel's subsystem thread - a session channel has one from the
start, whether or not a subsystem ever runs on it - and then emptied its
slot in the broker's table under the broker's lock. The broker, freeing
itself, found the channel claimed, went on without waiting, and was
freed. The channel's Close then entered the freed broker's lock, or
called through the freed broker. On Win32 and Win64 that was an access
violation on the closing thread - in ntdll, entering the freed lock, or
reading through the freed broker - or the thread waited in that lock for
ever, and after a few connections had ended that way the server answered
no more logins. On Linux64 the call ran into freed memory and the process
ended, by an access violation no handler caught or by glibc's "corrupted
double-linked list" abort.
HOW OFTEN. For a session channel the window is as long as starting and
ending the channel's subsystem thread takes. Measured with
SshServerChannelCloseRaceTest: 48 session channels on one connection,
each with a thread that closes the server's end as soon as the client has
closed it, and the client closing all 48 and disconnecting 0 to 4 ms
later. In one run of 20 such rounds, 11 rounds failed on Win32 and 15 on
Win64, with 124 and 349 access violations and 123 and 131 closing threads
that never returned; on Linux64 the process ended in the first round. A
subclass that overrides InternalBeforeRemoveFromBroker runs its code
inside that window and widens it by as long as the code takes. With 0 to
2 ms there, 18 and 17 rounds of 20 failed on Win32 and Win64, and Linux64
ended in the first round; with gGlobalCloseAll raised instead of the
client disconnecting, 5 of 20 failed on Win32, the first 3 on Win64,
after which the server answered no more logins, and Linux64 ended in the
seventh. With 200 ms, every try failed, after the client's disconnect and
after the server's deactivation alike: on Windows the broker was freed 12
to 16 ms after the connection began to end and the removal ended some
200 ms after it, and the Linux64 process ended. For a port-forwarding
channel, which has no subsystem thread, the window ran from its claim to
the broker's lock: a few instructions, as in entry 94, or as long as the
broker held that lock to take other channels off (read in the code, not
measured).
NOW:
- A server channel's removal from its broker runs under the channel's
own lock from start to end. The first call takes the channel off - it
ends the subsystem thread and empties the slot - and a call that comes
meanwhile waits until the channel is off. The exception is the
channel's own subsystem thread, which a removal on another thread waits
for: it takes the channel off only when no other removal is under way,
and otherwise returns at once, as before. It needs no wait: the broker
is not freed while one of its subsystem threads is running (entry 50).
- The broker, freeing itself, takes the channels out of its table under
its lock - a channel a forwarded-port listener opens after that finds
no slot, as before - and then takes each off with its lock released.
It is freed only when every channel is off, so the end of a connection
waits for a Close that is taking a channel off on another thread: as
long as ending the channel's subsystem thread takes, and a subclass's
InternalBeforeRemoveFromBroker.
- The broker no longer holds its lock while it ends a channel's
subsystem thread. A subsystem that reopened its channel's window just
then needed that lock, and the two would have waited for each other
for ever (read in the code; none of the runs met it).
THE DISCRIMINATING TEST: subclass tSSHServerChannel, have its
InternalBeforeRemoveFromBroker sleep 200 ms after the inherited call on
a thread of your own, and register it in tSSHServerChannel's place with
RegisterAsMappedClass(True) - it keeps the name SSHServerChannel.session,
so the server makes its session channels from it. Have a client open a
session channel and close it; once the server's end is csClosing, call
that end's Close on your thread, and while it sleeps disconnect the
client or deactivate the server. An affected release frees the
connection's broker within milliseconds, and the Close then raises
EAccessViolation, never returns, or ends a Linux64 process; this one
frees the broker only after the 200 ms, and the Close returns without
raising.
WHO. A program with an SSH server whose channels are closed on threads
other than the connection's: the server's port forwarding, or a thread
of the program that closes a session channel. A subsystem that completes
its own channel's close on the channel's subsystem thread - SFTP, snip,
or a TstCustomSSHSubSystem of your own - was not affected: the server
already waited for that thread before freeing the connection (entry 50),
and the test's two steps for it pass before and after, on all three
platforms.
PLATFORMS. Every platform: the same code runs on each. Measured on
Win32, Win64 and Linux64; this release passed all 324 checks of
SshServerChannelCloseRaceTest on each, in eight runs of each, and the
other SSH, snip and SFTP tests pass as before.
NOT INVOLVED: the client's channels (entry 94); what a channel sends
when it closes, and the states it goes through; the transport, the key
exchange and the ciphers.
NOT CHANGED:
- A channel still on the broker when its connection ends is taken off
as before, in the state it was in.
- Send and SendEOF on a thread other than the channel's subsystem thread
do not wait for the end of the connection, nor it for them (read in the
code, not measured). [Measured and FIXED in entry 143, together with
Close; a Recv that reopens the window runs only on the broker's thread
or the subsystem thread and is already ordered.]
- The legacy unit stSSHServerChannel, which no longer ships, is not
changed.
--------------------------------------------------------------------------------
SSH PORT FORWARDING: AN -R CONNECTION THAT ENDS BEFORE THE CLIENT ANSWERS
================================================================================
106. FIXED - TstSSHListenerControllerSocket, the server's listener for remote
port forwarding (-R, forwarded-tcpip), lost the end of a TCP connection
it had taken when that end came before the SSH client had answered the
channel open: it sent no SSH_MSG_CHANNEL_EOF and never closed the
channel, so the target behind the client never read the end of the
stream, and the channel stayed open at both ends
For each TCP connection it takes, the listener opens a forwarded-tcpip
channel to the client and starts reading the connection at once. Until
the client answers the open with SSH_MSG_CHANNEL_OPEN_CONFIRMATION, the
channel has no recipient channel number, and its SendEOF and Close do
nothing. When the TCP connection's end - its half-close or close - came
in that time, the listener sent no EOF; by default (gSSHForwardHalfClose
not set) it also closed the TCP connection at once and let the channel
go without closing it. Once the client answered, the channel was open at
both ends with nothing behind it at the server: the target behind the
client never read the end of the stream, and the client's channel stayed
open for as long as the target kept its end open. With
gSSHForwardHalfClose set, what the target sent still reached the TCP
connection, but the EOF was lost the same way.
The client takes one round trip of the SSH connection to answer, plus
whatever it does first: TstSSHForwardingClientSocket starts its connect
to the target before it answers, and on Windows that connect is complete
before the answer goes, so there a slow target widens the time.
NOW, when the TCP connection's end comes before the client has answered,
the listener waits for the answer, as it already did for data, and then
sends the EOF and, by default, closes the channel and the TCP connection.
The wait also ends when the client refuses the open, when the channel is
closed from the SSH side, and when the server stops.
WHO. A server with TstSSHListenerControllerSocket whose clients forward
remote ports, on every platform.
HOW IT WAS FOUND. Reading the listener's code while measuring entry 101.
THE DISCRIMINATING TEST: give the client's BeforeCreateChannelThread a
handler that sleeps a second, and half-close a connection to the
server's -R listener meanwhile. An affected release never closes the
client's channel, and the target behind the client never reads the end
of the stream; this one closes both once the client has answered.
PLATFORMS. Cases 7 to A of entry 101's test SshFwdEarlyEofTest hold the
client's answer back for 1.5 s through BeforeCreateChannelThread and
half-close a connection to the server's listener meanwhile, with and
without gSSHForwardHalfClose, and, as controls, after the answer. An
affected release fails 4 of their 18 checks on Win32 and on Linux64: the
target reads no end of the stream, and the client's channel is still
open 3 s after the target gave up waiting for it. This release passes
all 18 on Win32, Win64 and Linux64; the test's battery rows now count
41, 41 and 53 checks. Also passing as before: the port-forwarding
self-test, entry 61's test and entry 80's test on Win32 and Linux64,
and entry 98's test on Win32 and Win64. On macOS 26 on an Apple M1 all
18 pass, and a build without this entry and entry 107 fails 8 of the
test's checks: these 4 and entry 107's 4. The port-forwarding self-test
and entry 61's test pass on the M1 as well; entry 80's test does not
finish there, with or without this entry, for another reason, which
this entry does not change.
NOT INVOLVED: data the TCP connection brought before its end, which
already waited for the answer; the SSH protocol.
NOT CHANGED:
- A TCP connection that fails - is reset - before the client has
answered: entry 107.
- The wait has no time limit of its own, as the wait for data never had:
a client that neither answers nor refuses the open holds the TCP
connection until the channel is closed from the SSH side or the server
stops.
107. FIXED - TstSSHListenerControllerSocket lost the reset of a TCP
connection it had taken when the reset came before the SSH client had
answered the -R channel open, as it lost a half-close or close before
entry 106: it never closed the channel, so the target behind the client
never saw its connection end, and the channel stayed open at both ends
When a TCP connection the listener had taken failed - its peer reset it
- while the forwarded-tcpip channel still waited for the client's answer,
the listener closed the TCP connection at once and closed the channel,
which does nothing before the answer. Once the client answered, the
channel was open at both ends with nothing behind it at the server: the
target behind the client never saw its connection end, and the client's
channel stayed open for as long as the target kept its end open.
gSSHForwardHalfClose made no difference.
NOW the listener waits for the answer on a failed connection too, as it
has done for a half-close or close since entry 106, and then closes the
channel; the client then closes its connection to the target. The wait
ends the same ways: on the answer, on a refused open, when the channel is
closed from the SSH side, and when the server stops.
WHO. A server with TstSSHListenerControllerSocket whose clients forward
remote ports, on every platform.
HOW IT WAS FOUND. Entry 106 listed this case as not changed, from
reading the code; measured, it showed the same loss.
THE DISCRIMINATING TEST: as entry 106's, with the TCP connection reset -
SO_LINGER with no time, then close - instead of half-closed. An affected
release never closes the client's channel, and the target never sees its
connection end; this one closes both once the client has answered.
PLATFORMS. Cases B to D of entry 101's test SshFwdEarlyEofTest reset a
connection to the server's listener while the client's answer is held
back, with and without gSSHForwardHalfClose, and, as a control, after
the answer. A release with entry 106 and not this one fails 4 of their
12 checks on Win32 and on Linux64, in three runs out of three: the
target's connection does not end, and the client's channel is still
open 3 s after the target gave up waiting. This release passes all 12 on
Win32, Win64 and Linux64; the test's battery rows now count 53, 53 and
65 checks. Also passing as before: the port-forwarding self-test on
Win32 and Linux64, entry 105's test on Win32, Win64 and Linux64,
entry 61's and entry 80's tests on Win32 and Linux64, and entry 98's
test on Win32 and Win64. On macOS 26 on an Apple M1 all 12 pass, and a
build with entry 106 and not this one fails the same 4; entry 105's
test passes there too, and entry 80's test does not finish there, as
entry 106 says.
NOT INVOLVED: data the TCP connection brought before it failed, which
already waited for the answer; the SSH protocol.
NOT CHANGED: the wait has no time limit of its own (entry 106).
--------------------------------------------------------------------------------
SSH: AFTER A MESSAGE THE TRANSPORT SKIPS
================================================================================
108. FIXED - after an SSH_MSG_IGNORE, an SSH_MSG_DEBUG or a message it does
not know, an SSH client or server could send nothing on that connection
until the peer sent again, and ended the connection when the peer sent
nothing for about 5 s
Each end of an SSH connection - a TstSSHSocketClient once it has logged
in, and a TstSSHSocketServer for each connection it accepts - reads what
arrives on a thread of its own, the channel broker, and holds the
connection's lock while it reads. Everything that end sends takes the
same lock: a channel's Send, opening and closing channels, window
adjusts, global requests.
THE STEP THAT FAILED is the broker's read after a message the transport
skips: SSH_MSG_IGNORE and SSH_MSG_DEBUG (RFC 4253 sections 11.2 and 11.3)
and a message number it does not know (section 11.4). The message itself
was skipped as it should be. But the read did not return then: it went
on waiting for the peer's next message, still holding the lock, and when
none came for about 5 s it sent SSH_MSG_DISCONNECT with reason 10
(connection lost) and closed the connection.
WHAT IT LOOKED LIKE, on Win32, Win64 and Linux64 alike:
- A Send on the end that had read the message waited until the peer sent
again. When the peer sent nothing more, the Send raised
eSSHTransportRawError "Cannot send: Socket is closed" about 5 s after
the message (4.95 s on Linux64, 5.8 s on Windows), and the connection
was gone.
- A client that sends SSH_MSG_IGNORE as a keepalive and is otherwise
idle lost its connection to a TstSSHSocketServer about 5 s after the
first keepalive: 6.0 s, measured with paramiko sending one IGNORE whose
data is a string. PuTTY's manual (section 4.27.1) says PuTTY sends its
keepalives as IGNORE messages.
- A TstSSHSocketServer whose OnBeforeSendIgnore sends IGNOREs held back
every Send of a TstSSHSocketClient for as long as they kept coming less
than 5 s apart, and the client ended the connection 5 s after the last
one: with an IGNORE every 0.2 s for 3.5 s, the client's first channel
Send raised after 8.2 to 9.0 s.
NOW the broker's read returns as soon as nothing more has arrived, after
a skipped message as after any other, and a Send gets the lock at once.
The brokers read with PollMessage, a new method of iSSHTransport: it
reads as ReadMessage does, but never waits for a message to arrive. A
class of your own that implements iSSHTransport must add the method:
what ReadMessage returns, and an empty result where it would wait.
NOT CHANGED:
- ReadMessage waits past the messages it skips for the one it was asked
for, and ends the connection when nothing arrives for about 5 s, as
before. The key exchange, the service request and user authentication
read with it: they need the peer's answer, and nothing else sends on
the connection while they wait.
- A key exchange the peer starts on a connection in use runs inside the
broker's read, with the lock held, as before: from its own
SSH_MSG_KEXINIT to its SSH_MSG_NEWKEYS an end may send only
key-exchange messages (RFC 4253 section 7.1).
- After the peer's SSH_MSG_UNIMPLEMENTED the broker's read already
returned at once.
- The legacy unit stSSHTransport, which no longer ships.
THE DISCRIMINATING TEST: log a TstSSHSocketClient in to a
TstSSHSocketServer and open a channel; have the server send one
SSH_MSG_IGNORE and nothing more, and 0.5 s later Send on the client's
channel. An affected release raises from that Send about 5 s later and
the connection is gone; this one returns at once and the data arrives.
From outside: paramiko, logged in to a TstSSHSocketServer, sending an
IGNORE whose data is a string and then nothing - an affected release
sends DISCONNECT reason 10 about 5 s later. Both are in Test\sshinterop:
SshIgnoreWaitTest, and the paramiko script ignore_paramiko.py.
NOT INVOLVED: the ciphers, the MACs, the key exchange, channel windows,
and noticing a connection that ends without a DISCONNECT (entry 74).
--------------------------------------------------------------------------------
SSH: AN IGNORE MESSAGE WHOSE DATA IS NOT A STRING
================================================================================
109. FIXED - an SSH_MSG_IGNORE whose data was not an SSH string ended the SSH
connection, at once or at the peer's next packet; paramiko's
Transport.send_ignore sends such an IGNORE
RFC 4253 section 11.2 lays SSH_MSG_IGNORE out as the message number
followed by a string, and says an end MUST ignore the message whenever
it arrives.
THE STEP THAT FAILED is reading that string, which the transport then
threw away: it took the 4 octets after the message number as the
string's length and read that many octets after them.
- paramiko's Transport.send_ignore, which paramiko offers as a
keep-alive, sends random octets - 10 to 41 of them unless told how
many - with no length in front. The length read from them was almost
always negative or larger than the transport accepts, and the end that
read the IGNORE, client or server, sent SSH_MSG_DISCONNECT with reason 2
(protocol error) and closed the connection: measured 0.05 to 0.09 s
after paramiko's IGNORE.
- An IGNORE with no data at all: the read went on into the next packet,
holding the connection's lock until one arrived, so meanwhile that end
could send nothing; then it took that packet as the IGNORE's data, and
the connection ended.
NOW the data of an IGNORE is not read: the rest of the packet is cleared
and dropped, whatever it holds. A well-formed IGNORE is dropped as
before.
NOT CHANGED:
- SSH_MSG_DEBUG is read as before.
- Under strict key exchange (kex-strict-c-v00@openssh.com and
kex-strict-s-v00@openssh.com), an IGNORE that arrives during the first
key exchange still ends the connection, as strict key exchange
requires.
- The legacy unit stSSHTransport, which no longer ships.
THE DISCRIMINATING TEST: log in to a TstSSHSocketServer with paramiko,
call Transport.send_ignore(), and send nothing more. An affected release
sends DISCONNECT reason 2 within a tenth of a second; this one keeps the
connection. Test\sshinterop\ignore_paramiko.py does this, and step 7 of
Test\sshinterop\SshIgnoreWaitTest sends both forms above from either end
of a connection between a TstSSHSocketClient and a TstSSHSocketServer.
Once its data is not read, such an IGNORE is skipped like any other, and
the end that read it can then send at once because of entry 108: that
step needs both.
NOT INVOLVED: the ciphers, the MACs, and the key exchange.
--------------------------------------------------------------------------------
SSH SERVER: THE LENGTH OnBeforeSendIgnore GIVES AN IGNORE
================================================================================
110. FIXED - an SSH server built the SSH_MSG_IGNORE that OnBeforeSendIgnore
asked for wrongly when the handler set aLength under 5 or over 260:
under 5 it wrote up to 4 octets past the end of the message's buffer
and sent a message too short for its length field, at 0 or less and
over 32768 it ended the connection, and over 260 the length field gave
the wrong number of octets
TstSSHServer and TstSSHSocketServer ask OnBeforeSendIgnore whether to
send an SSH_MSG_IGNORE on a connection that has nothing to read, and
propose its length in aLength, which the handler may change. aLength is
the length of the whole message: the message number, the length of its
data in 4 octets, and the data - a string, as RFC 4253 section 11.2 has
it and RFC 4251 section 5 lays it out. The server proposes 5 + 8k
octets, k from 0 to 31, and the IGNOREs it sends with those are right.
THE STEP THAT FAILED is building the message. The server made a buffer
of aLength octets and wrote the message number and the 4 octets of the
length into its first five whatever aLength was, the length as three
zeros and its low octet:
- aLength 1 to 4: the last 4 to 1 of those octets went past the end of
the buffer, into the heap memory after it, and the message sent was
the 1 to 4 octets of the buffer: too short to hold its length field.
The connection went on.
- aLength 0: there was no buffer, and the first write was an access
violation on the connection's thread; at -1 and less SetLength raised
ERangeError there. The server caught it, sent SSH_MSG_DISCONNECT with
reason 11 (by application) and ended the connection; nothing reached
the program.
- aLength 261 to 32768: the length field gave the length less 256, 512
and so on: 0 for 261, where 256 octets followed. A peer that reads the
data as the string takes the wrong number of octets (not measured with
any peer).
- aLength over 32768: the transport refused the message ("Too large
buffer": cMaximumPacketSize is the largest payload it sends), and the
connection ended as at 0.
The value is the program's own: aLength reaches the handler as the
server's proposal, and nothing a client sends enters it. What went past
the buffer was always zeros and the low octet of aLength - 5.
NOW the server writes the length in all 4 octets, takes a value under 5
as 5 (an IGNORE with no data) and one over 32768 as 32768: the largest
payload the transport sends, and the largest that RFC 4253 section 6.1
says every implementation must take. The description of
OnBeforeSendIgnore says what aLength counts and what the server does
with each value.
WHO. A program that assigns OnBeforeSendIgnore and sets aLength under 5
or over 260. One that leaves aLength as proposed, or sets it from 5 to
260, is not affected: its IGNOREs are the same octets as before. A
handler that set aLength to 0 to send nothing must set aSendIt to False
instead: the server now sends an IGNORE of 5 octets, where it ended the
connection before.
THE DISCRIMINATING TEST: set aLength to 261 in OnBeforeSendIgnore and
read the IGNORE whole at the client. An affected release gives its
length field as 0, with 256 octets after it; this one gives 256. Or set
it to 0: an affected release ends the connection with
SSH_MSG_DISCONNECT, reason 11; this one sends an IGNORE of 5 octets.
PLATFORMS. Every platform: the same code runs on each. The new test
SshIgnoreLengthTest sets aLength to 0, 3, 5, 260, 261, 300, 70000, -1,
1, 4, 32768 and 32769 in turn, and leaves it as proposed twice. For each
it reads the IGNORE whole at the client, holding the client's transport
lock, and checks its length, its length field, what the server's thread
raised, whether a heap block was written past its end (16 guard octets
after every block) and whether the connection goes on. An affected
release fails 28 of its 70 checks on Win32, Win64, Linux64 and macOS
(Apple Silicon), the same 28 on each, among them a block of 11 octets
(19 on 64-bit) written 2 octets past its end at aLength 3; this release
passes all 70 on the four, in four runs each on Win32, Win64 and Linux64
and in one on macOS.
NOT CHANGED:
- When the server asks, and what it does with aSendIt.
- The data of an IGNORE: zero octets.
- The legacy unit stSSHServerChannel, which no longer ships, is not
changed.
--------------------------------------------------------------------------------
THE SSH TUNNEL CLIENT DEMO: A LOCAL PROGRAM THAT READS SLOWLY
================================================================================
111. FIXED - the SSH Tunnel Client demo closed a forwarded -L connection
when the program at its local end read more slowly than the target
sent: that program lost the rest of the target's data
THE STEP THAT FAILED is the relay loop's write of what the SSH channel
brought to the local socket. It was a single Send, and the loop closed
the channel and the TCP connection when that Send took fewer octets than
it was given. The socket does not wait for room in its Send: the demo's
listener and the loop wait for data with WaitForData, which makes a
Windows socket non-blocking, and a socket accepted from that listener is
non-blocking from the start. So once the local program had stopped
reading and its buffers were full, the next Send took part of the
octets, or none with a "try again", and the connection ended - the
mistake entry 61 removed from the library's port-forwarding components.
NOW the loop keeps what the local socket has not taken and sends it as
room appears, relaying the other way meanwhile, and reads nothing more
from the channel until all of it has gone. The channel then gives the
SSH server no more room, and the server holds the rest back until the
local program reads again. This is what the other direction has done
since entry 98.
WHO. Anyone who ran the demo's -L forwarding (tDirectListener in
TunnelClientEngine, plain or in HTTP mode) to a target that sends more
than the local program reads at once.
HOW IT WAS FOUND. Entry 98 listed this case as not changed, from reading
the code; measured, it closed the connection as the code suggested.
THE DISCRIMINATING TEST: forward a local port to a target that sends
4 MB and keeps its connection open, and connect a TCP client to the
local port that reads nothing for 3 s, then everything. An affected demo
closes the client's connection after a few hundred kilobytes; this one
delivers every octet and keeps the connection open.
PLATFORMS. Measured on Win32 and Win64 with step 5 of entry 98's test,
Test\sshinterop\TunnelClientStallTest, which does that with the demo's
tDirectListener on our SSH client against our SSH server on 127.0.0.1.
Before, the TCP client got 212,992 or 262,144 of the 4,194,304 octets,
every one right, and then its connection was closed, in every run: 6 on
Win32 and 4 on Win64. Now it gets all 4,194,304 and the connection stays
open, in every run: 11 on Win32 and 9 on Win64. The test passes all 6 of
its checks on both; steps 1 to 4 pass as before.
NOT INVOLVED: the library and the SSH protocol; the demo's -R side.
NOT CHANGED: a local program that half-closes its connection (sends a
FIN) still ends the forwarded connection at once, with whatever the
target has still to send (read in the code, not measured).
--------------------------------------------------------------------------------
SSH SERVER: A SESSION CHANNEL WITH NO SUBSYSTEM, CLOSED BY THE CLIENT
================================================================================
112. FIXED - an SSH server kept a session channel that the client had
closed, with no subsystem attached to it - the client had asked for
none, or the server had refused the one it asked for - until the
connection ended. Each such channel held one of the connection's
MaxChannels channel slots, and once they held them all the server
refused every further channel open on that connection with
SSH_OPEN_RESOURCE_SHORTAGE ("Maximum number of channels is reached")
An SSH server (TstSSHServer, TstSSHSocketServer) keeps a connection's
channels in a table of MaxChannels slots, 16 by default, and refuses a
channel open that finds no free slot. When the client closes a channel,
the server answers with a CLOSE of its own and leaves the channel in
csClosing for the channel's consumer, whose Close completes it and frees
the slot (entry 105). A session channel's consumer is its subsystem:
TstSFTPServerSubSystem and TsnipSSHServer call Close once the client has
closed the channel. A session channel with no subsystem attached had no
consumer.
THE STEP THAT FAILED is the server's answer to the client's
SSH_MSG_CHANNEL_CLOSE on such a channel (tCustomSSHServerChannel.
DoDisconnected). It sent the answering CLOSE, so the client's channel
closed normally and the client saw nothing wrong, but it left the
server's channel in csClosing on the connection's channel broker for a
Close that nothing was there to call. The channel stayed until the
connection ended, holding its slot, its local window buffer
(DefaultWindowSize octets, 1 MB by default) and its subsystem thread,
which every session channel has from the start. A client that keeps one
connection for many channels and opens session channels on which no
subsystem runs - one that asks for a subsystem the server does not offer
or does not grant to the user, then closes the channel and tries another
- had its opens refused after MaxChannels of them. A client that ends
its connection after such a channel freed it with the connection.
Measured with the new Test\sshinterop\SshSessionSlotTest: a server with
MaxChannels 4, one connection, session channels opened and closed one
after another. With no request, with SSH_MSG_CHANNEL_EOF before the
CLOSE, and with a subsystem request the server refused, four channels
opened and the fifth open was refused with SSH_OPEN_RESOURCE_SHORTAGE;
each of the four server channels stayed csClosing on the broker with its
1,048,576-octet window and a subsystem thread that had not finished. On
Win32, Win64 and Linux64 alike, 6 of the test's 24 checks failed.
NOW the server completes the close of a channel that has no consumer
itself, as it answers the client's CLOSE: the channel ends csClosed and
leaves the broker, which ends its subsystem thread and frees its slot.
Both CLOSEs have then been sent, and RFC 4254 section 5.3 says that "The
channel is considered closed for a party when it has both sent and
received SSH_MSG_CHANNEL_CLOSE". A new virtual method,
tCustomSSHServerChannel.InternalHasConsumer, decides: it answers True
for every channel, as before, and a session channel (tSSHServerChannel)
answers whether a subsystem is attached. In the test all 12 channels now
open in each of those cases, and the server's end is off its broker at
most 16 ms after the client's channel has closed, on all three
platforms.
A SUBSYSTEM COMPLETES ITS CHANNEL'S CLOSE (owner ruling, 2026-10-06). It
calls aChannel.Close from ReadData once aChannel.PeerEOF is set or
aChannel.State is no longer csConnected; the server wakes the subsystem
thread for the client's EOF and for its CLOSE. A subsystem that never
calls Close keeps its channel until the connection ends, as before, and
the open after MaxChannels such channels is refused; the test checks
that too. SSH.txt now states this for every subsystem in section 7
(SESSION); it was written only for the SFTP server, in section 10.
BEHAVIOUR CHANGE for a program that holds a server session channel with
no subsystem attached - through a channel class of its own registered as
SSHServerChannel.session - and completes its close on a thread of its
own once the client has closed it, the thread entry 105 names. The
server may now complete that close first. The program's Close then does
nothing, as a Close of a closed channel always has, and the channel is
already off its broker; what the client sent before its CLOSE stays in
the channel's window for Recv (read in the code, not measured). A
program that needs the close for itself overrides InternalHasConsumer to
answer True, as the channel class of SshServerChannelCloseRaceTest now
does. Without that override that test still passed, but in its step 6
its own threads took 16 to 45 of the 48 channels off per round instead
of all 48; the server took the rest.
WHO. A program with an SSH server whose clients close session channels
that have no subsystem, on a connection they keep open. The server's
port-forwarding channels (direct-tcpip, forwarded-tcpip) are not
affected: their forwarding threads complete the close, and
InternalHasConsumer answers True for them as before.
THE DISCRIMINATING TEST: set the server's MaxChannels to 4. On one
connection, open a session channel, close it from the client without a
subsystem request, wait until the client's channel is csClosed, and open
the next. An affected release refuses the fifth open with
SSH_OPEN_RESOURCE_SHORTAGE; this one opens as many as you like. With a
subsystem that calls Close, such as SFTP, both open as many.
WHAT IT COSTS. The connection's thread ends the channel's subsystem
thread when the client's CLOSE arrives, where it did so when the
connection ended, and reads the connection's next message after that:
in the test the server's end was off its broker at most 16 ms after the
client's channel had closed.
PLATFORMS. Every platform: the same code runs on each. Measured on
Win32, Win64 and Linux64: SshSessionSlotTest passes all 24 checks on
each, SshServerChannelCloseRaceTest all 324, and the other SSH, snip and
SFTP tests of the battery pass as before.
NOT INVOLVED: the client's channels; what goes on the wire - the server
sends the same answering CLOSE as before, and a client sees no
difference but the slot; the transport, the key exchange and the
ciphers.
NOT CHANGED:
- A subsystem that never calls Close keeps its channel until the
connection ends (above).
- A channel the server closed first completes when the client's CLOSE
answers it, as before.
- The legacy unit stSSHServerChannel, which no longer ships, is not
changed.
113. FIXED - TstCustomSSHServer.Disconnect, and freeing an SSH server,
could wait for the lock of a connection whose own thread was ending
the session and freeing that lock: on Linux the Disconnect that
dropped a client then never returned, or the process's heap was
corrupted
Disconnect drops one client: it takes the connection off the server's
list and closes it under the lock of the connection's transport, the lock
the connection reads and sends under. Freeing the server does the same
for every connection still open (CloseAndJoinPeers). The connection's own
thread, when its session ends, also takes it off and closes it
(UnlockTransport) - and then freed the transport's lock.
THE STEP THAT FAILED is freeing that lock. Disconnect waits for the lock
for as long as the connection's thread holds it, and during a login that
thread holds it while it waits for the client's next authentication
request. When the thread let go, ended the session and freed the lock
before the waiting Disconnect had taken it, Disconnect was left waiting
on a critical section that no longer existed. On Linux64, with a client
dropped 1 s into an 8 s password prompt, Disconnect never returned in 4
of 10 runs; once a login also ended as soon as Disconnect asked (entry
110), the C library reported its heap corrupted and ended the process in
9 of 10 ("malloc(): smallbin double linked list corrupted"). On Windows,
in the same runs, nothing showed; the race is the same there.
NOW the transport's lock goes with the transport, when the last
reference to it does, and not when its session ends. Disconnect and the
server's destructor hold a reference to every connection they close, so
the lock they wait for is still there when they take it.
WHO. A server whose application drops clients with Disconnect, on any
platform; seen on Linux64. Freeing a server while clients are connected
takes each connection's lock the same way; that was not measured on its
own.
THE DISCRIMINATING TEST: on Linux, let a client pause 8 s before it sends
its password, call Disconnect for it 1 s into the pause, and repeat. An
affected release now and then does not return from Disconnect; this one
returns every time (after about 4 s without entry 114, at once with it).
PLATFORMS. Step 16 of the new SshLoginGraceTest (entry 114) meets the
race after the login: a custom service's handler holds the lock on the
connection's thread while Disconnect waits for it, then returns and ends
the session; ten rounds. Before this change it hung in its first round
on Linux64 in 3 of 3 runs - and so did a build of this release with only
the freeing of the lock in UnlockTransport put back; with the change, 3
of 3 passed, and on Win32 and Win64 all passed before and after. Steps
12 and 13 drop and deactivate during a login: with this change alone,
step 12 ran 10 times on Linux64 without a hang (before: 4 hangs in 10);
with entry 114 as well, steps 12 and 13 ran 10 times without a fault
(with entry 114 but not this one: 9 aborts in 10).
NOT CHANGED:
- UnlockTransport still takes the connection off the server's list and
closes it; it no longer frees the lock.
- The client's transport: its channel broker creates the lock and frees
it, as before.
- A thread that still holds a server transport after its session has
ended and sends on it now takes the lock and fails on the closed
connection (EstSocketError), where it raised eSSHTransportError 'No
lock created' before.
- NOT FIXED HERE: a Disconnect that comes while the connection's thread
is not waiting - in the key exchange, or between reading an
authentication request and answering it, which it does without the
lock - closes the connection under that thread. On Linux64, step 15 of
the test (the client's password request arrives while Disconnect waits
for the lock) failed in 10 of 10 runs with this change alone as before
it - the process aborted, hung, or was ended by SIGPIPE. With entry 114
the Disconnect of a client the server is waiting for ends the login
itself, and step 15 passed in 10 of 10; the windows named above
remain (entry 115 closes them).
114. FIXED - an SSH server ended a client's login when the client sent
nothing for about 5 s at any step of it (4.95 s on Linux, 5.7 to 5.8 s
on Windows): a person who took longer than that to accept the server's
host key in OpenSSH or PuTTY, or to type a password, was disconnected.
The server now waits for the client for as long as the whole login is
allowed to take, the new LoginGraceTime of TstCustomSSHServer (default
120000 ms, as in OpenSSH's sshd); 0 is no limit
Wherever the SSH transport needs the peer's next message - in a key
exchange, for a client the server's answers to its requests, for a server
each of the client's requests during the login - it waits for it in a
loop of sleeps that grow from 1 to 99 ms, and when the peer has sent
nothing by the end it sends SSH_MSG_DISCONNECT reason 10 (connection
lost) and closes the connection. The bound is there on purpose: a peer
that has gone quiet in the middle of a key exchange is dropped soon, and
a reader that holds the transport's lock - the channel brokers do, and so
does the server's user authentication - does not hold it for long.
THE STEP THAT FAILED is the server's wait during the login, where the
client may be waiting for a person: OpenSSH and PuTTY ask whether to
trust a host key they do not know before they send NEWKEYS, and ask for
the password after the server has answered the first authentication
request with the methods it accepts; an application may also ask for the
user name and password between TstSSHSocketClient.ConnectToHost and
Login. The server waited about 5 s for NEWKEYS, for the client's
SSH_MSG_SERVICE_REQUEST and for each SSH_MSG_USERAUTH_REQUEST alike, and
then disconnected. Measured with a TstSSHSocketClient that pauses at each
of those three points, six runs each, the server ended the connection
4.95 to 4.97 s into the pause on Linux64, 5.70 to 5.84 s on Win64 and
5.71 to 6.43 s on Win32. With OpenSSH 10.2p1's ssh on Linux, a host key
accepted after 3 s logged in; one accepted after 8 s did not (the server
had closed the connection: "Broken pipe"), and a password typed after 8 s
was answered with SSH_MSG_DISCONNECT reason 10.
NOW a server gives the client the whole login - version strings, key
exchange, service request and user authentication together -
LoginGraceTime milliseconds from the moment it takes the connection on,
and waits for the client's next message for as long as that allows.
Messages that are skipped, such as SSH_MSG_IGNORE, do not extend it. When
it runs out while the server is waiting, the server sends
SSH_MSG_DISCONNECT reason 10, as before. The wait for the client's
version string also ends then, unless its own limit - 30,000 sleeps of a
millisecond, about 33 s on Linux and, at Windows's default timer
resolution, about 8 minutes - has ended it first. Once the client has
logged in, the server waits about 5 s for each message again.
The server reads each authentication request holding the transport's
lock, so Disconnect and freeing the server now first end a login under
way (iSSHServerLogin.CancelLogin), which the login sees within about
0.1 s and ends with SSH_MSG_DISCONNECT reason 11, as Close does. Before,
Disconnect for a client in its password prompt waited until the 5 s wait
ran out (3.95 s on Linux64, 4.73 to 4.78 s on Windows, when called 1 s
into it); with only the longer wait it would have waited for the client
to send - 7.0 s in the test, up to the whole LoginGraceTime. It now
returns within 50 ms. Deactivating a TstSSHSocketServer with
CloseAllOnDeactivate ended such a login within about 0.1 s before and
does now. Ending the login sooner meets the race of entry 113 at once, so
entry 113 is part of this change.
WHO. Every server: a client that waited for a person during the login -
a first connection from OpenSSH or PuTTY, an interactive password, a
passphrase or PIN asked for between the requests - was disconnected
after about 5 s. The client side is not changed: TstSSHSocketClient waits
about 5 s for each of the server's answers, as before (a server that
sends its version string and nothing more makes ConnectToHost give up
after 4.96 s on Linux64 and 5.7 to 5.9 s on Windows, before and after).
NEW: TstCustomSSHServer.LoginGraceTime (published, milliseconds, default
cSSHLoginGraceTimeMSec = 120000, 0 = no limit), read when a connection is
taken on; the interface iSSHServerLogin (BeginLogin, EndLogin,
CancelLogin), which tSSHServerTransport implements and the server asks a
transport for with Supports. iSSHServerTransport is unchanged: a
transport of the application's own that implements it compiles as before
and, without iSSHServerLogin, is waited on during the login as before.
WHAT A DEPLOYMENT SHOULD WEIGH. Each connection runs on a thread of its
own until it ends, and nothing limits how many connections may be in
their login at once. A client that connects, sends its version string and
then says nothing now keeps its thread for up to LoginGraceTime, where it
kept it about 5 s before. One that sends nothing at all was already kept
for the version string's own limit - 33 s on Linux64 and 477 s on
Windows, measured - and is kept 33 s and 120 s now. A client that kept
sending SSH_MSG_IGNORE during the login was never dropped before, and is
dropped at LoginGraceTime now. Set LoginGraceTime lower where people do
not log in to the server by hand; OpenSSH's sshd also limits such
connections with MaxStartups (default 10:30:100), which this server does
not have.
THE DISCRIMINATING TEST: let a TstSSHSocketClient pause 8 s in
OnGetClientPassword. An affected server disconnects about 5 s into the
pause and the login fails; this one waits, and the login completes.
PLATFORMS. New test SshLoginGraceTest (battery rows Win32, Win64 and
Linux64, floor 56) pauses the client 8 s before its password request,
between ConnectToHost and Login, and in OnSetKey; with LoginGraceTime
3000 it checks that a pause of 5 s fails, that SSH_MSG_IGNOREs every
0.5 s do not extend the time, that raw clients silent after their version
string and silent altogether are closed 2.5 to 4.5 s after the connect,
that LoginGraceTime 0 waits, and that the limit ends with the login; it
also checks the client's own wait, Disconnect and deactivation during a
login, and Disconnect in rounds during and after a login (entry 113).
Before this change and entry 113, on each platform steps 2, 3, 4 and 12
fail (21 of 29 checks pass on Win32 and Win64 in steps 1 to 13, steps 5
to 10 not run there), and on Linux64 the process hangs or aborts in step
12, 15 or 16. With both, all checks pass on Win32, Win64 and Linux64 in
every run (55 in six runs on each before step 16 was added, 56 since, and
step 15 ten more times on Linux64). Eight single-change mutants of this
change and of entry 113 are each caught by a step of its own: the
freeing of the lock put back in UnlockTransport (step 16, on Linux64),
no CancelLogin (step 12:
Disconnect took 7.0 s), a limit per message instead of per login (step
6), no EndLogin (step 10), the version wait left out (step 8), 0 read as
"no time" (step 9), the client's waits made unbounded too (step 11), no
BeginLogin (steps 2 to 9 and 12). OpenSSH 10.2p1's ssh with this change:
a host key accepted after 8 s logged in, and so did a password typed
after 8 s and a host key and a password each answered after 15 s; with
LoginGraceTime 10000, a password typed after 15 s got SSH_MSG_DISCONNECT
reason 10.
NOT CHANGED:
- The client's waits, the server's waits after the login (in a later key
exchange), and the version string wait's own limit.
- keyboard-interactive is offered by neither the server nor the client
(SSH.txt section 6), so there is no wait for its responses.
- LoginGraceTime bounds each connection; it does not limit how many
connections may be logging in at once.
--------------------------------------------------------------------------------
SSH SERVER: DISCONNECT WHILE A CLIENT IS LOGGING IN
================================================================================
115. FIXED - an SSH server closed the connection of a client that was still
logging in from the thread of TstCustomSSHServer.Disconnect, or of the
server's destructor, while the connection's own thread was using it
without the transport's lock: the socket could be freed under that
thread's send or read, and both threads encrypted with the same
cipher. On Linux the process's heap was corrupted ("realloc(): invalid
next size") or the connection's thread never ended; on every platform
the client could read a packet it could not decrypt
While a server logs a client in, the connection's own thread does the
work: it exchanges the version strings, runs the key exchange, reads the
client's SSH_MSG_SERVICE_REQUEST and each SSH_MSG_USERAUTH_REQUEST,
checks the password or key and sends the answer. It holds the
transport's lock while it reads an authentication request and while it
sends USERAUTH_FAILURE, USERAUTH_PK_OK or a password change request; the
key exchange, the wait for the service request, the check of a request
and USERAUTH_SUCCESS it does without the lock. Disconnect, and the
server's destructor, close a connection from the caller's thread under
that lock: they send SSH_MSG_DISCONNECT, which encrypts with the
connection's cipher, and close the socket, which TstSSHSocketServer
frees there and then.
THE STEP THAT FAILED is that close, made while the connection's thread
was in one of the steps it takes without the lock. Nothing kept the two
threads apart then: the caller's thread freed the socket object while
the connection's thread was inside a send or a read on it, and encrypted
its SSH_MSG_DISCONNECT with the cipher the connection's thread was
encrypting with. On Linux64, with a client whose password request
arrived while Disconnect waited for the lock (step 15 of
SshLoginGraceTest, without the CancelLogin of entry 114), the process
aborted in 2 of 3 runs ("realloc(): invalid next size") and the
connection's thread hung in the third; under valgrind the connection's
thread sent its USERAUTH_SUCCESS through a socket, and wrote to the
critical section inside it, that Disconnect had freed. In 24 more runs
12 aborted and 12 hung, and gdb showed the two ways it hangs: the
connection's thread waiting, in that send, for the critical section of
the freed socket, which nothing would release, while the server's
destructor waited for that thread; or, after "Runtime error 232", a
thread that was ending meeting the corrupted heap. With entry 114
that client is ended by its own thread, but a Disconnect during the key
exchange, during the wait for the service request, while a password is
checked or while the answer is sent still closed the connection under
it. Windows showed no fault in that step; the race is the same there.
Where the caller's SSH_MSG_DISCONNECT overtook an answer the
connection's thread was sending, the client could not decrypt it - it
was encrypted as the packet after that answer - and its login failed
with eInternalRecvError ("An error occured while decoding an inbound
packet") instead of the disconnect.
NOW, until a client has logged in, its connection is only its own
thread's to send on and to close. Disconnect, the server's destructor
and a Close made during the login cancel the login and return at once,
without taking the transport's lock; the connection's thread sends
SSH_MSG_DISCONNECT reason 11 and closes the connection itself the next
time it reads or sends - at once while it waits for the client,
otherwise when the step under way is done (checking a password or a key,
or an event handler). A cancelled login sends the client nothing else,
so a password being checked when Disconnect came is not answered. The
login now begins when the server takes the connection on, before the
connection is on the server's list, so Disconnect cannot find one whose
login has not begun. After the login, Disconnect closes the connection
under the transport's lock from the caller's thread, as before.
WHO. Every server whose application drops a client with Disconnect while
it is logging in, or that is freed while clients are logging in, on
every platform; seen as a fault on Linux64. Without entry 114 a
Disconnect during the password prompt waited for the client's request
and then closed the connection while that request was checked and
answered: the case that aborted. A server that drops clients only after
they have logged in is not affected.
THE DISCRIMINATING TEST: wrap the server's raw events (override
InitTransport) and hold the connection's thread inside its send of
USERAUTH_SUCCESS while Disconnect is called. In an affected release the
caller's thread sends and closes while the connection's thread is still
inside that send, and the client cannot decode the next packet; in this
one every raw call on the connection is made by its own thread, and the
client reads the answer and then SSH_MSG_DISCONNECT.
PLATFORMS. New test SshLoginDisconnectTest (battery rows Win32, Win64
and Linux64, floor 41) records which thread makes each raw call on the
server's connection and holds its thread inside one: Disconnect lands in
the send of the answer to the password request (step 2), in a read while
the server waits for the client's NEWKEYS (3) and for its
SSH_MSG_SERVICE_REQUEST (4), 0.5 s into a password check that takes
1.5 s (5), and while the server waits for a guessed key exchange packet
that never comes (7); steps 1 and 6 are controls, a login and Disconnect
after a login. Before this change 9 of its 41 checks fail on Win32,
Win64 and Linux64 in every run, with entries 113 and 114 (three runs on
each) and without them (main before them, one run on each): in steps 2,
3, 4 and 7 the caller's thread sends and closes while the connection's
thread is inside a raw call, in step 5 during the check. With it, 41 of
41 on all three in every run (three on each). Three single-change
mutants, run on Win32, are each caught by a step of their own: no look
at the cancellation where a read finds nothing waiting (step 7: the
connection stays open), none in Send (step 5: the client logs in),
EndLogin not ending a cancelled login (step 2: the connection stays
open). SshLoginGraceTest (56 checks, its step 16 the pin of entry 113
after the login) and SshShortMessageTest (166) pass on all three with
this change.
NOT CHANGED:
- Disconnect of a client that has logged in: it closes the connection
under the transport's lock from the caller's thread, as before - the
connection's thread and every channel send under that lock then.
- iSSHServerLogin.CancelLogin (entry 114) is now a function: True when
the login was under way or had been cancelled, when the connection is
its own thread's to end.
- FOUND, NOT FIXED: while it waits for a guessed key exchange packet
(first_kex_packet_follows TRUE and the packet not yet sent) the server
polls the socket in a loop that never sleeps - 280,000 to 400,000
polls in 0.2 s in step 7, a whole core - until the packet comes, the
client closes the connection or LoginGraceTime (entry 114) runs out;
before entry 114, until the client closed it. The client transport has
the same loop. Entry 116 fixes both.
--------------------------------------------------------------------------------
SSH: THE WAIT FOR A GUESSED FIRST KEY EXCHANGE PACKET
================================================================================
116. FIXED - an SSH client or server whose peer's SSH_MSG_KEXINIT said
that a guessed key exchange packet followed, and which then did not
send it, waited for that packet in a loop that neither slept nor
looked at the clock: a whole processor core was busy until the packet
came, the connection was closed or, on a server, LoginGraceTime ran
out (entry 115; before it, LoginGraceTime did not end the wait)
An SSH_MSG_KEXINIT ends with first_kex_packet_follows and a reserved
uint32 (RFC 4253 section 7.1). TRUE says that the sender's guess at the
key exchange's first packet follows - for curve25519-sha256 and the
ecdh-sha2 methods, the client's SSH_MSG_KEX_ECDH_INIT - sent before it
has read the other end's KEXINIT. The other end uses that packet when
the guess was right and drops it when it was not. This library's own
KEXINIT always says FALSE.
THE STEP THAT FAILED is the wait for that packet in
tSSHTransport.ReadPeerKexInitAsServer and ReadPeerKexInitAsClient, when
it had not arrived with the KEXINIT. Everywhere else the transport waits
for the peer's next message with sleeps that grow from 1 to 99 ms, and
sends SSH_MSG_DISCONNECT reason 10 when nothing has come by the end
(entry 114: a server logging a client in, when LoginGraceTime runs out
instead). This wait asked the socket again and again, with neither.
WHAT IT LOOKED LIKE, with a raw client and a raw server that announce
the packet and do not send it, three runs on each of Win32, Win64 and
Linux64: the waiting end asked the socket how much had arrived 1.5 to
2.5 million times a second, and the process used a whole core (985 to
1016 ms of CPU in each second). A server with LoginGraceTime 3000 ended
the connection 3.00 s after the connect, busy until then; before entry
115 it still held it 8 s after. A TstSSHSocketClient's ConnectToHost
returned only when the raw server closed the connection, 12 s after its
KEXINIT, raising eSSHConnectionLost.
NOW the wait is the transport's wait for any message, the new protected
method tSSHTransport.WaitForPacket, which ReadNextMessage uses too: 26
to 28 looks at the socket in that second, and 0 to 47 ms of CPU. A
server logging a client in waits for the packet until LoginGraceTime
runs out and then sends SSH_MSG_DISCONNECT reason 10 (3.01 to 3.06 s
after the connect with LoginGraceTime 3000); the cancellation that
Disconnect and freeing the server make (entry 114) ends this wait as it
ends the login's other waits. A client, and a server in a later key
exchange, give up after about 5 s with SSH_MSG_DISCONNECT reason 10:
ConnectToHost raised eSSHOutgoingDisconnect 4.96 s after the KEXINIT on
Linux64 and 5.71 to 5.82 s after it on Windows. A packet that comes
during the wait is used, or dropped, as before.
WHO. Every TstSSHSocketServer and TstSSHSocketClient, on every
platform, whose peer announces a guessed packet and withholds it. For a
server that peer is any program that can connect: it needs no account,
and nothing limits how many such connections it may hold at once (entry
114, WHAT A DEPLOYMENT SHOULD WEIGH) - each kept one core busy until
LoginGraceTime ran out (default 120 s), and before entry 115 for as
long as the client kept it open. A peer that sends the packet right
after its KEXINIT was answered at once before, and is now.
THE DISCRIMINATING TEST: connect to a TstSSHSocketServer, send a version
string and a KEXINIT with first_kex_packet_follows TRUE and nothing
more, and read the process's CPU time over the next second. An affected
release uses a whole core; this one uses next to none. With
LoginGraceTime 3000 this one sends SSH_MSG_DISCONNECT reason 10 about
3 s after the connect; so does an affected release with entry 115,
busy until then, and without it keeps the connection until the client
closes it.
PLATFORMS. New test Test\sshinterop\SshKexGuessWaitTest (battery rows
Win32, Win64 and Linux64, floor 22; ports the system assigns on
127.0.0.1). A raw client sends a TstSSHSocketServer the guessed packet
at once (step 1, a control), 1.5 s late (step 2: at most 1000 looks at
the socket and a quarter of a core in 1 s of the wait, and the late
packet answered), never, with LoginGraceTime 3000 (step 3: DISCONNECT
reason 10 and the connection closed 2.5 to 4.5 s after the connect),
and 6.5 s late with the default LoginGraceTime (step 4: the server waits
past the ~5 s bound and answers). A raw server never sends it to a
TstSSHSocketClient (step 5: the same limits in 1 s of the wait, and
ConnectToHost giving up 3.5 to 9 s after the KEXINIT with DISCONNECT
reason 10), or sends 1.5 s late a guess the client must find wrong
(step 6, a control: the client drops it and then sends its own
SSH_MSG_KEX_ECDH_INIT). Before this change 6 of the 22 checks fail on
Win32, Win64 and Linux64 in every run (three on each), in steps 2 and 5;
step 3 passes, entry 115 ending the server's wait at LoginGraceTime.
Without entry 115 8 of 22 failed, step 3 too. With this change, 22 of
22 on all three in every run (three on each, with and without entry
115). Single-change mutants, run on Win32, are each caught by a step of
their own: the server's wait left as it was (step 2), the client's
(step 5), and the ~5 s bound applied during a server's login (step 4:
the server closed the connection 5.78 s after the KEXINIT). Leaving
LoginGraceTime out of WaitForPacket is caught by step 3 only without
entry 115, whose look at the login where a read finds nothing ends the
wait at the same moment.
NOT CHANGED:
- The waits of ReadNextMessage: the same code, moved into WaitForPacket.
- A guessed packet is still taken to be the next packet the peer sends,
whatever its message number, and used only when both ends name the
same key exchange method and the same host key algorithm first.
- FOUND, NOT FIXED: Recv, asked to wait (ReadDebug, ReadDisconnect,
ReadUnimplemented and ReadString do), polls the socket in the same way
when the message it reads ends where a field should begin, until the
next packet arrives - and then reads that packet as the rest of the
message. Measured with a raw client that sends a TstSSHSocketServer
its version string and one SSH_MSG_DEBUG, SSH_MSG_DISCONNECT or
SSH_MSG_UNIMPLEMENTED holding nothing but its message number, on Win32
and Linux64 with this change: 1.5 to 2.5 million looks at the socket
a second, a whole core, until LoginGraceTime ran out (3.0 to 3.5 s
after the connect with LoginGraceTime 3000, through entry 115's look at
the login where a read finds nothing; without entry 115 the connection
was still open 8 s after the connect). Entry 118 fixes it.
- The legacy unit stSSHTransport, which no longer ships, has the same
loop and is not changed.
NOT INVOLVED: the key exchange methods, the ciphers and the MACs.
--------------------------------------------------------------------------------
SSH: THE NUMBERS AND LENGTHS IN THE TRANSPORT'S OWN MESSAGES
================================================================================
117. FIXED - the SSH transport, at both ends of a connection, read a
four-octet number from the peer wrongly whenever its third octet was
not 0, as in every number from 256 to 65535: the reason code of
SSH_MSG_DISCONNECT, the sequence number of SSH_MSG_UNIMPLEMENTED, and
the length of a description or message of 256 octets or more, which
ended the connection as a protocol error or left it waiting
SSH sends a number as four octets. RFC 4251 section 5:
"uint32
Represents a 32-bit unsigned integer. Stored as four bytes in
the order of decreasing significance (network byte order)."
A string - a text, or data - goes as a uint32 holding its length,
followed by that many octets. RFC 4253 section 11 defines four messages
that "Either party may send ... at any time", and the transport of
TstSSHClient and TstSSHServer, and of every component built on them,
reads them itself:
byte SSH_MSG_DISCONNECT
uint32 reason code
string description in ISO-10646 UTF-8 encoding [RFC3629]
string language tag [RFC3066]
byte SSH_MSG_IGNORE
string data
byte SSH_MSG_DEBUG
boolean always_display
string message in ISO-10646 UTF-8 encoding [RFC3629]
string language tag [RFC3066]
byte SSH_MSG_UNIMPLEMENTED
uint32 packet sequence number of rejected message
THE STEP THAT FAILED is turning four octets into a number. The
transport weighted the third octet 2^16 instead of 2^8, so it read the
octets o1 o2 o3 o4 as o1 * 2^24 + (o2 + o3) * 2^16 + o4. With o3 = 0
that is the right number: every number below 256, and so every reason
code RFC 4253 defines (1 to 15). Otherwise it was wrong: 256 read as
65536, 300 as 65580, 1000 as 196840, $01020304 as $01050004. Three
things were read that way:
- THE REASON CODE of SSH_MSG_DISCONNECT, which eSSHIncomingDisconnect
passes on as ErrorCode. Only a code of 256 or more was affected - one
from the range that RFC 4250 section 4.2.3 leaves to private use, or
one assigned in future: $FE000102 read as $FE010002.
- THE SEQUENCE NUMBER of SSH_MSG_UNIMPLEMENTED, the number of the
packet of ours that the peer did not recognise. eSSHUnimplemented
passes it on as MsgNo, and the component's Unimplemented method
receives it. It was wrong for packets numbered 256 to 65535, and for
most above - numbers a connection reaches soon after it opens. During
a session the channel code catches eSSHUnimplemented and goes on, so
there the number reached only a descendant of the component that
overrides Unimplemented.
- THE LENGTH of every string in SSH_MSG_DISCONNECT and SSH_MSG_DEBUG, and
of the service name in SSH_MSG_SERVICE_REQUEST and
SSH_MSG_SERVICE_ACCEPT, which is short. A length of 256 to 512 came out
as 65536 to 131072, which the transport accepts: it took the rest of
the message as the string, and read the next string out of the next
message to arrive. A length of 513 to 65535 came out above 131072, and
the transport treated the message as a protocol error: it sent
SSH_MSG_DISCONNECT with reason 2, "Protocol error", closed the
connection, and raised eSSHOutgoingDisconnect with ErrorCode 2. It read
the data of SSH_MSG_IGNORE the same way; entry 109 changed the
transport so that it does not read that data at all.
WHAT A PROGRAM SAW, at either end - the client measured with
TstSSHSocketClient.ConnectToHost, the server with TstSSHSocketServer:
- A DISCONNECT from the peer with a description of 513 to 65535 octets
raised eSSHOutgoingDisconnect with ErrorCode 2 and the Description
"Protocol error", instead of eSSHIncomingDisconnect with the peer's
reason and description, and sent the peer a DISCONNECT of its own.
- A DISCONNECT with a description of 256 to 512 octets raised nothing
and did not end the connection. The transport waited for the language
tag in a message that a peer which has disconnected does not send, in
a loop that does not sleep: ConnectToHost did not return, and a server
given such a DISCONNECT by a client that then stayed connected kept
the connection open while the program used 1.5 to 2 seconds of
processor time in every 2 seconds - one processor core. When a message
did arrive, its first four octets, the message number first, read as
a length of 16777216 or more, and the connection ended as a protocol
error, as above. By the code, when the peer closes the connection
instead, the wait does not end at all; that was not measured. A client
can send such a DISCONNECT as soon as it has connected, before the key
exchange and before it authenticates.
- A DEBUG with a message of 256 to 512 octets never reached the
component's Debug method, and the connection ended as a protocol
error when the next message arrived. By the code, one of 513 octets
or more ended it at once.
- An IGNORE with 513 to 65535 octets of data ended the connection as a
protocol error, at once. RFC 4253 section 11.2 says of this message:
"All implementations MUST understand (and ignore) this message at any
time (after receiving the identification string)." By the code, 256 to
512 octets did no harm. Entry 109, not this one, ends that: the
transport no longer reads an IGNORE's data.
- A DISCONNECT with a reason code of 256 or more, and an UNIMPLEMENTED
about a packet numbered 256 or more, passed on a wrong number, as
above.
Which peers send such messages was not examined. The description,
message and data are the peer's to choose; RFC 4253 limits them only by
the size of a packet.
Now the transport weights the third octet 2^8, and reads the four
octets as the number RFC 4251 defines.
THE DISCRIMINATING TEST: a peer that sends SSH_MSG_DISCONNECT with reason
11 and a description of 1000 octets. An affected release raises
eSSHOutgoingDisconnect with ErrorCode 2 and the Description "Protocol
error"; this one raises eSSHIncomingDisconnect with ErrorCode 11 and the
1000 octets as its Description. A description of 255 octets or fewer
reads right on either release. Test\sshinterop\SshUint32DecodeTest runs
this and the other measured cases above over 127.0.0.1, against the
client and against the server, before any key exchange: without this
change 23 of its 56 checks fail - its two IGNORE steps pass there,
because of entry 109 - and with it all 56 pass.
PLATFORMS. Measured on Win32, Win64 and Linux64, with the same results
on each. The transport is the same code on every platform.
RELEASES. The transport has read numbers this way since it first
shipped, in 4.0 BETA 0.309 (2015): in stSSHTransport, and from
4.1.1.349 on in StreamSec.SSH.Transport as well, up to and including
4.1.4.360.
NOT INVOLVED: the key exchange, the ciphers and MACs, compression, the
channels and SFTP. The transport reads these four messages the same
way before and after the key exchange; only the decryption in front of
it differs. Every other number in a packet is read by other code, and
a search of the library's units for numbers put together from octets
found the mistake nowhere else.
NOT CHANGED: the transport's limit of 131072 octets for a string, and
what it does with each of the four messages once it has read them. The
legacy unit stSSHTransport, which no longer ships, has the same three
lines and is not changed.
--------------------------------------------------------------------------------
SSH: A MESSAGE WHOSE FIELDS RUN PAST THE END OF ITS PACKET
================================================================================
118. FIXED - an SSH client or server that read an SSH_MSG_DISCONNECT,
SSH_MSG_DEBUG, SSH_MSG_UNIMPLEMENTED, SSH_MSG_SERVICE_REQUEST or
SSH_MSG_SERVICE_ACCEPT whose fields ran past the end of its packet
waited for the peer's next packet in a loop that neither slept nor
looked at the clock - a whole processor core busy, on a server before
authentication - and then read that packet as the rest of the message
An SSH message is the payload of one binary packet (RFC 4253 section 6).
The transport itself reads five messages field by field:
SSH_MSG_DISCONNECT (reason code, description, language tag; section
11.1), SSH_MSG_DEBUG (always_display, message, language tag; section
11.3), SSH_MSG_UNIMPLEMENTED (the sequence number of the packet it
rejects; section 11.4), and the service name of SSH_MSG_SERVICE_REQUEST
and SSH_MSG_SERVICE_ACCEPT (section 10). Every other message is handed
on whole, in a buffer of exactly its length (entries 86 and 92 check the
reads from those).
THE STEP THAT FAILED is reading one of those fields when the packet had
fewer octets left than the field needs. The transport read each field
with Recv, asked to wait, which takes what is left of the current packet
and returns; and when nothing was left - the message ended where a field
should begin - it waited for the NEXT packet, asking the socket again
and again with no sleep and no time limit. When that packet came, its
payload, message number included, was taken as the rest of the field. A
field cut inside was filled up with zeros, and the field after it then
waited the same way.
WHAT IT LOOKED LIKE, three runs on each of Win32, Win64 and Linux64:
- A raw client sent a TstSSHSocketServer, before the key exchange, an
SSH_MSG_DEBUG, SSH_MSG_DISCONNECT or SSH_MSG_UNIMPLEMENTED holding
nothing but its message number, and then nothing more. The server
answered nothing, asked the socket how much had arrived 1.5 to 2.5
million times a second, and the process used a whole core (968 to
1032 ms of CPU in a second). That went on until LoginGraceTime (entry
114) ran out, which entry 115's look at the login where a read finds
nothing notices - with LoginGraceTime 3000, 3.0 to 3.5 s after the
connect, measured for entry 116 - and without entry 115 until the
client closed the connection. A bare SSH_MSG_SERVICE_REQUEST after the
key exchange did the same; its client gave up after about 5 s.
- After the login, the same message read by an end's channel broker:
the same loop, holding the transport's lock, which every Send on that
connection takes, until the peer sent its next packet or closed the
connection.
- A TstSSHSocketClient given such a message by a server: ConnectToHost
did not return until the server closed the connection (3.04 to 3.06 s
in the test, eSSHConnectionLost). A bare SSH_MSG_SERVICE_ACCEPT made
Login wait the same way for the server's next packet - in the test its
refusal of the service 2.5 s later - and take its first four octets as
the service name's length: SSH_MSG_DISCONNECT reason 2 after 2.50 to
2.51 s.
- A field cut inside - two octets of a uint32, a string longer than the
rest of the packet - read as zeros or cut short, and the next field
then waited as above. An SSH_MSG_UNIMPLEMENTED cut inside its sequence
number gave Unimplemented sequence number 0, and the connection ended
without a DISCONNECT.
NOW a field is read from its own packet only. A field that runs past the
end of the packet is a protocol error: the end that reads it sends
SSH_MSG_DISCONNECT reason 2 and raises eSSHOutgoingDisconnect, at once
(within 0.05 s in the test), and reads nothing more. ReadDebug,
ReadDisconnect, ReadUnimplemented and ReadString (which
ReadServiceRequest and ReadServiceAccept use) read with the new private
tSSHTransport.ReadField instead of Recv. Well-formed messages are read
as before.
WHO. Every TstSSHSocketServer and TstSSHSocketClient, on every platform.
For a server, the peer is any program that can connect: it needs no
account and no key exchange, and nothing limits how many connections
may be logging in at once (entry 114, WHAT A DEPLOYMENT SHOULD WEIGH) -
each such message kept one core busy for the rest of LoginGraceTime
(default 120 s), and before entry 115 for as long as the connection
stayed open. After the login, either end - a logged-in user, or the
server a client has logged in to - held the other end's lock and a core
for as long as it sent nothing more. A client: any server it connects
to, before the server's host key is checked.
THE DISCRIMINATING TEST: connect to a TstSSHSocketServer, send a version
string and one packet whose payload is the single octet 4 (SSH_MSG_DEBUG)
and nothing more, and read the process's CPU time over the next second.
An affected release sends nothing and uses a whole core; this one sends
SSH_MSG_DISCONNECT reason 2 at once and closes the connection.
PLATFORMS. New test Test\sshinterop\SshFieldPastPacketTest (battery rows
Win32, Win64 and Linux64, floor 86; ports the system assigns on
127.0.0.1). A raw client sends a TstSSHSocketServer, before the key
exchange, a well-formed SSH_MSG_DEBUG, UNIMPLEMENTED and DISCONNECT
(steps 1 to 3, controls: the fields reach Debug, Unimplemented and
eSSHIncomingDisconnect, and after the DEBUG the key exchange goes on);
the three with nothing after the message number (step 4: DISCONNECT 2
within 1.5 s and the connection closed, then at most 1000 looks at the
socket and a quarter of a core in a second); and seven cut elsewhere
(step 5). A TstSSHSocketClient sends a bare SSH_MSG_SERVICE_REQUEST
after the key exchange (step 6) and, after the login, a well-formed and
then a bare SSH_MSG_DEBUG to the server's channel broker (step 7). Steps
8 to 14 do the same with the ends swapped - a raw server, and a
TstSSHSocketServer whose OnUnauthenticatedServiceRequest sends a bare
SSH_MSG_SERVICE_ACCEPT (step 13). Step 15, a control, sends a bare
DISCONNECT from each end and resets the connection at once: the other
end ends it within 1.5 s, before and after. Before this change 58 of the
86 checks fail on Win32, Win64 and Linux64 in every run (three on each,
on main 7dd1962), in steps 4 to 7 and 11 to 14; with it, 86 of 86 in
every run (three on each). Three single-change mutants, run on Win32, are each
caught by steps of their own: ReadField without its check (no wait, but
the fields read as zeros and no protocol error: steps 4 to 7, 11, 12 and
14), the first field of DEBUG, DISCONNECT and UNIMPLEMENTED read with
Recv as before (steps 4, 5, 7, 11, 12 and 14), and ReadString as before
(steps 5, 6, 12 and 13).
NOT CHANGED:
- How the reason code, the sequence number and a string's length are
decoded (entry 117, whose misread length of a string of 256 to 512
octets led into this same wait).
- Data after a message's last field is dropped, as before. The data of
an SSH_MSG_IGNORE is not read at all (entry 109).
- tSSHTransport.Recv and Peek themselves: asked to wait, they still wait
for the next packet when the current one is used up. Nothing in the
library reads with them that way any more - Peek is called nowhere -
but an application that reads the transport through iTransport.Recv
would meet the same wait.
- When the peer resets the connection right after such a message, the
SSH_MSG_DISCONNECT this end sends may fail, and ConnectToHost then
raises EstSocketError (10054 on Windows; "send failed (32)" on Linux,
where no SIGPIPE is raised) instead of eSSHOutgoingDisconnect. Before
this change it raised EstSocketError or eSSHConnectionLost there,
depending on when the reset came (step 15).
- The legacy unit stSSHTransport, which no longer ships, reads these
fields the same way and is not changed.
NOT INVOLVED: the key exchange methods, the ciphers and the MACs.
119. REDACTED - this number was reserved during development for a change
that did not make it into this release - one found not to solve the
problem it was meant to, or superseded before it landed. The number
is kept, rather than closed up, so that the entries that follow keep
the numbers by which the test suite, the commit history and other
entries already refer to them.
120. REDACTED - as with entry 119, a number reserved for a change that did
not reach this release; it is kept so that the entries after it are
not renumbered.
--------------------------------------------------------------------------------
SSH: THE SERVER'S LISTENING SOCKET
================================================================================
121. FIXED - a TstSSHSocketServer closed its listening socket and listened
again whenever an accept took nothing, which on Windows happened each
time a connection the server had taken on ended: a client connecting
just then was reset before the server took it on, and its first send
failed with WSAECONNRESET (10054)
THE STEP THAT FAILED is the accept in tTCPDaemon.Execute, the loop of a
TstSSHSocketServer that takes connections on. It waits until the
listening socket is readable and accepts. When the accept returned no
socket, the loop closed the listening socket and listened again on the
same address and port, and the close reset every connection waiting in
the socket's queue: connected, and not yet taken on.
WHEN AN ACCEPT TAKES NOTHING. On Windows, before entry 132, each time a
connection the server had taken on ended, whichever end closed first. A
socket made by accept kept the listening socket's WSAEventSelect
association (FD_ACCEPT and FD_CLOSE, on the event tWinSocket.WaitForData
waits on), so the client's FIN signalled the listening socket's event,
and the accept that followed failed with WSAEWOULDBLOCK: for 20 of 20
connections that ended, in a probe with a loop of the same shape on
Win32 (10 closed first by the client, 10 by the server), and for none of
6 once the accepted socket's association was cancelled right after the
accept, as entry 132 now does. Anywhere, when the socket looks ready with
nothing to accept. On Linux, while the process is out of descriptors
(EMFILE) and a connection waits.
WHAT IT LOOKED LIKE. Found with a harness that opens ten connections
back to back, each ended by the server at once: about once in 25 to 120
runs on Win32 and Win64, never on Linux64, a raw client's first send -
its version string - failed with EstSocketError 10054. The connection
had never reached the server's RawAccept, and it was opened in the
millisecond in which the server closed the one before. With 8 clients
that connect, exchange version strings and close, again and again for
10 s on Win64, 59 of 1,204 connections were reset; with this change,
none of 8,118. On Linux a server that could not accept for lack of
descriptors reset every connection waiting: the close of the listening
socket freed a descriptor, and the new listening socket took it.
NOW an accept that takes nothing leaves the listening socket open, and
the loop waits for it again. When the socket is readable again at once -
a connection waits that accept cannot take, as when the process is out
of descriptors - the loop pauses 100 ms before the next try, as OpenSSH's
sshd does on EMFILE and ENFILE, rather than spin a core: 0 ms of CPU in
a second of it on Linux64, against 1000 ms without the pause. The
waiting connection is taken on once a descriptor is free.
WHO. Every TstSSHSocketServer on Windows that takes connections on while
others end, which is any server with more than one client: a client
whose connection arrived in the microseconds between the accept that
took nothing and the close was reset. Rare for a server with few
clients, routine under load: 2 to 5% of the connections in the bursts
above and below. On Linux, and wherever accept fails while a connection
waits, every TstSSHSocketServer that ran out of descriptors. A client
that was reset can connect again; nothing it sent reached the server.
THE DISCRIMINATING TEST: hold the lock of the server's listening socket
(tAbstractSocket.Lock, which Close takes) while a client's connection
ends and a second client connects; let the lock go and have the second
client send. On Windows an affected release resets the second client;
this one has taken it on already.
PLATFORMS. New test Test\sshinterop\SshListenerResetTest (battery rows
Win32, Win64 and Linux64, floors 16, 16 and 18; a port the system
assigns on 127.0.0.1). Holding the listening socket's lock, a connection
ends - the client closing first (step 2), or the server first, after the
client's SSH_MSG_DISCONNECT (step 3) - while a second client waits; on
Linux the process runs out of descriptors while that client waits (step
4: at most a quarter of a core for 1 s, and the client served once the
limit is restored); 8 clients connect and close again and again for 5 s
with no lock held (step 5); and on Windows the test signals the
listening socket's event with nothing to accept while the second client
waits (step 6, added with entry 132, after which a connection that ends
no longer wakes the loop). Without this change and entry 132, 7 of the
16 checks fail on Win32 and Win64, in steps 2, 3, 5 and 6 (11 to 33 of
438 to 803 connections of the burst reset, where counted), and 2 of 18
on Linux64, in step 4, in every run (three on each). With entry 132 and
without this change, step 6 alone fails on Win32 and Win64 (2 of 16), in
every run (three on each). With this change, 16, 16 and 18 pass in
every run, with entry 132 and without it (three on each; without it,
3,943 to 16,664 connections of the burst, none reset). Without the
pause, step 4 fails on Linux64 on the CPU time (1000 ms in 1000 ms) and
the Windows rows pass: the pause is for a connection that cannot be
taken.
NOT CHANGED:
- The listening socket is still created, bound and set listening in
tTCPDaemon.Create, so Active := True raises a bind failure. OnError
still fires when the daemon dies: when waiting on the listening socket
fails, and through the SSHDAEMONFAULT test hook (SshOnErrorTest, 4 of
4 on Win32).
- The wake: on Windows an accepted socket kept the listening socket's
WSAEventSelect association, so the loop woke once for each connection
that ended; with this change that cost one accept that took nothing.
Entry 132 removes the wake. The library's other accept loops on a
listening socket (the OCSP responder, the mail listeners, the SSH
remote-forward listener) already waited again after an accept that
took nothing.
- The legacy units stSSHSocketServer and stSocketServer, which no longer
ship, have the same loop and are not changed.
NOT INVOLVED: the SSH protocol, and the connection threads that read and
send on the connections the loop takes on.
--------------------------------------------------------------------------------
OBJECT IDENTIFIERS: READING, WRITING AND NAMING THEM
================================================================================
122. FIXED - an OBJECT IDENTIFIER whose first component is 2 and whose
second is 40 or more was read as another value - 2.999.3 as 26.39.3,
2.40 as 3.0 - and with assertions on it could be neither written nor
read: OIDToBytes failed an assertion on it
X.690 writes the first two components of an OID as one number,
40 * first + second. The first component is 0, 1 or 2, and only under 0
and 1 is the second limited to 39; under 2 it has no limit. So a first
number of 80 or more always means 2, and that number less 80 as the
second component.
THE STEPS THAT FAILED:
- Reading. InterpretBERToOID, which every decoder in the library uses for
an OID, split the first number by 40 whatever its size: 81 01 01
(2.49.1) came out as 3.9.1, 88 37 03 (2.999.3) as 26.39.3 and 81 80 4F
(2.16383) as 411.23. Nothing complained.
- Writing. OIDToBytes asserted that the second component is under 40
before it encoded it. With assertions off it wrote the right octets.
- A decoded field. tASN1ObjectIdentifier, the OID field of every typed
ASN.1 structure, checks each value it reads by encoding and decoding
it again, with an assertion. With assertions on, a certificate, CRL,
CMS message or OCSP response that carried such an OID in any OID field
failed that assertion as it was decoded; with assertions off the field
held the wrong value.
NOW InterpretBERToOID reads a first number of 80 or more as 2 and the
rest, and OIDToBytes takes a second component of any size under 2.
WHO. Programs that read or write OIDs under 2 with a second component of
40 or more, in data from elsewhere or their own. Assertions are on in a
Delphi Debug build unless the project turns them off.
THE DISCRIMINATING TEST: InterpretBERToOID of the octets 88 37 03 gives
26.39.3 in an affected release and 2.999.3 in this one. With assertions
on, OIDToBytes('2.999.3') fails its assertion in an affected release and
gives 88 37 03 in this one.
PLATFORMS. Every platform: the reading builds its text one way on Win32
and Linux64 and another on Win64, and both had the fault. The new test
OidCodecTest encodes and decodes 16 OIDs against the octets OpenSSL
3.5.7 writes for them, among them 2.40, 2.47, 2.48, 2.49.1, 2.999.3 and
2.16383, and decodes OpenSSL's ec_cert.der with the OID of its first
extension changed to 2.49.14. An affected release fails 13 of those
checks on Win32, Win64 and Linux64, the same 13 on each; this release
passes them all.
NOT CHANGED: a number above 4294967295 in an OID is still read wrongly.
The reading keeps its low 32 bits, so the octets of 2.25.4294967296 come
out as 2.25.0 (measured). OIDs made from a UUID, under 2.25, have numbers
that size.
123. BEHAVIOUR CHANGE - an OBJECT IDENTIFIER field whose content ends inside
a number - its last octet has bit 8 set - is refused as it is decoded,
with eASN1DataError. Content that ended in the octet 80 was read as the
shorter OID before it, 2A 80 as 1.2; other such content was read as no
OID at all, and in a field that is not optional, with assertions on,
that failed an assertion in ExtractSubIden
Each number in an OID is written in groups of 7 bits, one to an octet,
and bit 8 is set on every octet of a number but its last. Content whose
last octet has bit 8 set therefore stops in the middle of a number.
THE STEPS THAT FAILED:
- InterpretBERToOID decided whether the content ended inside a number
from the bits it had gathered, not from bit 8. An octet 80 carries no
bits, so 2A 80 was read as 1.2 and 2A 86 48 80 as 1.2.840. Any other
such content was read as '' (no OID), as it is now.
- tASN1ObjectIdentifier passed what it read to the check it makes on
every value: an assertion, which suits a value a program sets and not
octets someone else sent. With assertions on, a field that is not
optional, read as '', failed it - in ExtractSubIden, "StartPos out of
range". With assertions off the field held '' and decoding went on.
NOW InterpretBERToOID answers '' for any content whose last octet has bit
8 set, and a decoded OID field raises eASN1DataError before that check:
"<field>: the <n> content octets of this OBJECT IDENTIFIER encode no
value: a subidentifier ends inside them or starts with the octet 80"
(entry 128 is the second case), or, for a field that is not optional and
has no content at all, "<field>: this OBJECT IDENTIFIER is not optional
and its contents are empty". <field> is the field's name
in the structure, such as algorithm or extnId.
BEHAVIOUR CHANGE. Data with such content in an OID field used to load in
a build without assertions, with an empty or a shortened OID in the
field. It now raises eASN1DataError where the field is read, the class
the decoder raises for other content it cannot interpret.
WHO. Programs that decode certificates, CRLs, CMS, OCSP, PKCS#10 or
PKCS#12 data they did not make. Such content is malformed; a sound
encoder does not write it.
THE DISCRIMINATING TEST: decode a certificate with the content of its
first extension's OID changed to 55 1D 80. An affected release loads it
and reads that OID as 2.5.29; this one raises eASN1DataError.
PLATFORMS. Every platform. OidCodecTest reads six such contents with
InterpretBERToOID, and decodes OpenSSL's ec_cert.der with the content of
its first extension's OID changed to 55 1D 80, and with the last octet of
its signature algorithm OID changed to 82. An affected release fails 6
of those checks on Win32, Win64 and Linux64; this release passes them
all.
NOT CHANGED:
- InterpretBERToOID still answers '' and does not raise: code that calls
it directly sees '' as before.
- An optional OID field with no content at all is still read as no
value.
- A number written with a leading octet 80, in more octets than it
needs, is still read as its value: 2A 80 01 is 1.2.1 (measured).
124. FIXED - GetObjectName, and so the ContentAsString of every OID field,
gave an OID the name of an arc it is not under when its digits began
like that arc's - 1.2.840.10040.4.10 as { id-dsa }, 1.2.840.10045.4.10
as { ecdsa-with-SHA1 } - and raised EConvertError for others, or with
assertions on failed an assertion in ExtractSubIden: 1.3.1010,
1.3.1010.5, and every OID under id-ri, id-stc or id-swb
(1.3.6.1.5.5.7.16, .17 and .18) whose last arcs it has no name for
GetObjectName answers with the name of the deepest arc it knows that the
OID is under, followed by the numbers that remain: { id-swb 9 }. Its
answer is what tASN1ObjectIdentifier.ContentAsString returns, and so what
a certificate viewer or an ASN.1 dump shows.
THE STEPS THAT FAILED:
- 63 of its tests of whether an OID lies under an arc compared text: on
the arcs of X9.62 and X9.42, certicom, the Edwards curves, AES, DSA,
ML-KEM, Netscape and most certificate extensions. As text
1.2.840.10040.4.10 begins with 1.2.840.10040.4.1 (id-dsa) and is not
under it. After such a match it read the next arc from the character
after the arc and its dot: past the end of 1.3.1010 - an assertion in
ExtractSubIden with assertions on, a 0 and the wrong name with them
off - and from the middle of an arc in 1.3.1010.5, EConvertError.
- Under id-ri, id-stc and id-swb, for a leaf it has no name for, it
started the remaining numbers after the id-kp arc, which is one
character shorter, and so read from a dot: EConvertError, with
assertions on or off.
NOW every one of those tests is by arc: an OID lies under an arc when it
is the arc, or the arc followed by a dot and more. 1.2.840.10040.4.10 is
{ iso(1) member-body(2) us(840) 10040 4 10 }, and 1.3.6.1.5.5.7.18.9 is
{ id-swb 9 }. ExtractSubIden is unchanged: it fails its assertion when a
caller hands it a position past the end of the OID, and GetObjectName no
longer does.
WHO. Programs that show OIDs from data they did not make, through
ContentAsString, GetObjectName or a dump. The OIDs the library has names
for are named as before.
THE DISCRIMINATING TEST: GetObjectName('1.3.6.1.5.5.7.18.9') raises
EConvertError in an affected release and answers { id-swb 9 } in this
one.
PLATFORMS. Measured on Win32 with OidTest, which gains 27 checks: 15
OIDs whose digits begin like an arc they are not under must be named by
no such arc and must not raise; 5 under those arcs must keep their names;
7 under id-ri, id-stc, id-swb and pkcs-7 must be derived from their own
arc. An affected release fails 18 of the 27; this one passes all 119 of
OidTest's checks. The code is the same on every platform.
NOT CHANGED: a string that is not an OID - 1.3.6.1.5.5.7. with a dot at
the end - still fails ExtractSubIden's assertion when assertions are on.
That is the caller's error, and the assertion is there to say so.
125. FIXED - OIDToCipherClass failed an assertion in ExtractSubIden with
assertions on, or raised EConvertError, for the keyed-IV cipher arc
1.3.6.1.4.1.13085.1 itself and for OIDs that begin with its digits
without being under it, such as 1.3.6.1.4.1.13085.10
OIDToCipherClass (StreamSec.Mobile.StreamSecII) gives the cipher class
for a cipher OID. For StreamSec's deprecated keyed-IV ciphers it reads
the number after the arc 1.3.6.1.4.1.13085.1, and it recognised that arc
by its first 19 characters. So for 1.3.6.1.4.1.13085.1 itself and for
1.3.6.1.4.1.13085.10 it read past the end of the OID - the assertion, or
False with assertions off - and for 1.3.6.1.4.1.13085.10.3 it read '.3'
as a number: EConvertError.
NOW it reads that number only for an OID under the arc, and answers False
for the others.
WHO. Programs that call OIDToCipherClass themselves; nothing in the
library calls it.
THE DISCRIMINATING TEST: OIDToCipherClass('1.3.6.1.4.1.13085.10.3', ...)
raises EConvertError in an affected release and answers False in this
one.
PLATFORMS. OidCodecTest asks about the arc, the arc and its dot,
1.3.6.1.4.1.13085.10 and 1.3.6.1.4.1.13085.10.3, and about a keyed-IV
OID under the arc as a control. An affected release fails the first 4
on Win32, Win64 and Linux64; this one passes all 5.
126. FIXED - GetObjectName, and so the ContentAsString of a policy
qualifier's OID, named a user notice (id-qt-unotice, 1.3.6.1.5.5.7.2.2)
id-qt-cps, the name of the CPS pointer beside it
RFC 5280 section 4.2.1.4 gives a certificate policy two kinds of
qualifier: a CPS pointer, id-qt-cps (1.3.6.1.5.5.7.2.1), and a user
notice, id-qt-unotice (1.3.6.1.5.5.7.2.2). GetObjectName recognised the
user notice and then gave it the CPS pointer's name.
NOW 1.3.6.1.5.5.7.2.2 is named id-qt-unotice - the name stPkixExtension
registers for it, which the built-in name hid.
WHO. Programs that show the policy qualifiers of a certificate through
ContentAsString or GetObjectName. A program that looked for the text
id-qt-cps to find a CPS pointer would have taken a user notice for one.
Reading a qualifier through the stPkixExtension classes (Choice,
AsQtCps), which go by the OID itself, is not affected (read, not
measured).
THE DISCRIMINATING TEST: GetObjectName('1.3.6.1.5.5.7.2.2') answers
id-qt-cps in an affected release and id-qt-unotice in this one.
PLATFORMS. Measured on Win32 with OidTest, which gains 3 checks: the two
qualifier names and an unknown leaf under id-qt. An affected release
fails 1 of them; this one passes all 122 of OidTest's checks. The code
is the same on every platform.
127. FIXED - an arc of an OBJECT IDENTIFIER past 32 bits was read with its
high bits dropped - the UUID OID
2.25.329800735698586629295641978511506172918 as 2.25.3374214134 - and
one past 63 bits could be neither written nor named: OIDToBytes and
GetObjectName raised EConvertError on it
X.690 puts no upper bound on an arc. The arcs of UUID OIDs, under 2.25,
are 128-bit numbers.
THE STEPS THAT FAILED:
- Reading. InterpretBERToOID gathered each number in 32 bits and kept its
low 32: the octets of 2.25.4294967296 came out as 2.25.0, and those of
2.18446744073709551536 as 0.0.
- Writing. OIDToBytes read each arc as an Int64, and an arc past
9223372036854775807 raised EConvertError. So did a typed OID field
(tASN1ObjectIdentifier) given such an OID, with assertions on, since it
checks each value by encoding it.
- Naming. GetObjectName, GetRegistredOIDName and GetOIDDeclaration read
arcs as Int64 too - EConvertError past 63 bits - and GetObjectName put
the arc it compares with the ones it names into 32 bits:
1.3.6.1.5.5.7.3.4294967297 was named { id-kp-serverAuth 94967297 }.
- OIDToCipherClass put the keyed-IV leaf into 32 bits as well:
1.3.6.1.4.1.13085.1.4294967313 (2^32 + 17) answered the cipher of leaf
17.
NOW an arc of any size is read, written and named: up to 63 bits through
Int64 as before, past that in decimal. New in stDERUtils:
ExtractSubIdenText, which answers an arc as its digits, with the contract
of ExtractSubIden. ExtractSubIden itself is unchanged.
WHO. Programs that meet OIDs with large arcs - UUID OIDs under 2.25 above
all - in certificates or other data they read, or use such OIDs
themselves.
THE DISCRIMINATING TEST: InterpretBERToOID of the octets 69 90 80 80 80 00
(2.25.4294967296, as OpenSSL writes it) gives 2.25.0 in an affected
release and 2.25.4294967296 in this one.
PLATFORMS. Every platform. OidCodecTest gains 8 OpenSSL vectors, encoded
and decoded, a certificate policy holding the UUID OID, and keyed-IV
leaves past 32 and 64 bits: an affected release fails 18 of its 75 checks
on Win32, Win64 and Linux64, and this one passes all 75 on each. OidTest
gains 3 naming checks, all 3 failing before; it passes all 125.
NOT CHANGED: ExtractSubIden still answers an Int64 and raises
EConvertError for an arc past 63 bits; ExtractSubIdenText answers any
arc. (RegisterOID takes any arc too: entry 130.)
128. BEHAVIOUR CHANGE - an OBJECT IDENTIFIER field whose content has a
subidentifier that starts with the octet 80 is refused as it is
decoded, with eASN1DataError, as entry 123 refuses content that ends
inside one. It was read as if the octets 80 were not there: 2A 80 01 as
1.2.1
X.690 writes each subidentifier in the fewest octets it takes, so the
first octet of one is never 80: that octet adds nothing but a leading
group of zero bits. DER and BER alike forbid it, and OpenSSL shows such
content as BAD OBJECT.
THE STEP THAT FAILED: InterpretBERToOID read an octet 80 as a group of
zero bits and went on, so content no encoder writes read as an OID - 55
80 1D as 2.5.29 - and a decoded OID field took it.
NOW InterpretBERToOID answers '' for content in which a subidentifier
starts with 80, and a decoded OID field raises eASN1DataError with the
message entry 123 gives.
BEHAVIOUR CHANGE. Data with such content in an OID field used to load,
with the OID read as if the octets 80 were absent. It now raises
eASN1DataError where the field is read.
WHO. Programs that decode data they did not make. A sound encoder does
not write such content.
THE DISCRIMINATING TEST: InterpretBERToOID of the octets 2A 80 01 gives
1.2.1 in an affected release and '' in this one.
PLATFORMS. Every platform. OidCodecTest reads four such contents - OpenSSL
3.5.7 shows each as BAD OBJECT - and decodes OpenSSL's ec_cert.der with
the content of its first extension's OID changed to 55 80 1D. An affected
release fails 6 of those checks on Win32, Win64 and Linux64 (that
certificate loads, its extension read as 2.5.29); this one passes all 84
of OidCodecTest's checks on each.
129. FIXED - in a program built without assertions, OIDToBytes given an
empty OID wrote into a buffer of no octets - an access violation - and
given an OID of one arc, '1', encoded it as 1.0
Every OBJECT IDENTIFIER has at least two arcs, and a caller that hands
OIDToBytes fewer breaks its contract. With assertions on, the assertion
in ExtractSubIden says so, and that is unchanged. Without them nothing
stopped the encoding: for '' the result had no octets and the first
number was written into it ("Access violation ... Write of address
00000000"), and '1' came out as the content octet 28, the encoding of
1.0.
NOW, without assertions, OIDToBytes raises eInvalidDERData for a value
with no dot: "OIDToBytes: '<value>' is no OBJECT IDENTIFIER - it has
fewer than the two arcs every one has".
WHO. Programs built without assertions - a Delphi Release build - that
pass OIDToBytes an empty or one-arc value of their own, directly or as
the AlgorithmID of the X9.42 key agreement. An OID field of a typed
ASN.1 structure left empty does not reach OIDToBytes: it is written as
an OBJECT IDENTIFIER with no content.
THE DISCRIMINATING TEST: built without assertions, OIDToBytes('') raises
EAccessViolation in an affected release and eInvalidDERData in this one.
PLATFORMS. The code is the same on every platform. OidCodecTest gains
the two calls, which pass on EAssertionFailed or eInvalidDERData and
fail on an answer or any other exception. Built without assertions,
against an affected release they fail - EAccessViolation for '', the
octet 28 for '1' - and this release passes them with assertions on and
off. Measured on Win32.
NOT CHANGED: with assertions on, ExtractSubIden's assertion fires as
before; a value such as '1.', whose second arc is empty, raises
EConvertError, as a malformed number does.
130. FIXED - RegisterOID and RegisterOIDSimple raised EConvertError for an
OID with an arc past 63 bits - a UUID OID under 2.25, say - so no name
could be registered for one
RegisterOID keeps a tree of named arcs, which GetObjectName consults for
an OID the library has no name of its own for. It read each arc of the
OID it was given, and each number of a declaration it parsed (name
OBJECT IDENTIFIER ::= { 2 25 ... }), as an Int64.
NOW an arc of any size is registered, given in a dotted OID or as a
number in a declaration; GetObjectName then answers the registered name
for the OID, and an OID under it derives from that name.
WHO. Programs that register names for OIDs with an arc past
9223372036854775807 - UUID OIDs, which an application makes for itself,
above all.
THE DISCRIMINATING TEST:
RegisterOIDSimple('2.25.329800735698586629295641978511506172918', 'x')
raises EConvertError in an affected release; in this one GetObjectName
of that OID answers x.
PLATFORMS. The code is the same on every platform. OidTest gains 5
checks - the UUID OID registered by RegisterOIDSimple and named, an OID
under it, and a declaration with { 2 25 18446744073709551616 7 } - and
an affected release fails all 5 on Win32; this one passes all 130 of
OidTest's checks.
131. FIXED - OIDToCipherClass, asked about a keyed-IV cipher OID whose last
arc its table does not list, answered True with whatever cipher class
the caller's CipherClass held when it came in, and KeyedIV True
OIDToCipherClass (StreamSec.Mobile.StreamSecII) gives the cipher class,
key length and keyed-IV flag for a cipher OID; CipherClass is a var
parameter. Under the keyed-IV arc 1.3.6.1.4.1.13085.1 it looks the last
arc up in a table of ranges - 1 to 12, 16 to 24 and so on - and for a
number in none of them it left CipherClass as it was, worked a key length
out from it, and set KeyedIV. A caller that had a class in the variable
from an earlier call got True and that class back for an OID that names
no cipher.
NOW such an OID answers False with CipherClass nil and KeyedIV False, as
any OID the function does not know does.
WHO. Programs that call OIDToCipherClass themselves, with a CipherClass
variable that may hold a class; nothing in the library calls it.
THE DISCRIMINATING TEST: set CipherClass to tRijndael_CBC and call
OIDToCipherClass('1.3.6.1.4.1.13085.1.13', ...): an affected release
answers True with tRijndael_CBC; this one answers False with nil.
PLATFORMS. The code is the same on every platform. OidCodecTest asks
about leaves 13 and 55 with CipherClass set coming in, and about leaf 20
as a control: an affected release fails the first two on Win32; this one
passes all 89 of OidCodecTest's checks.
--------------------------------------------------------------------------------
SOCKETS: THE CONNECTIONS A LISTENING SOCKET TAKES ON
================================================================================
132. FIXED - on Windows, a socket accepted from a listening tWinSocket that
WaitForData had been called on kept the listening socket's event: when
its connection ended, a WaitForData waiting on the listening socket
returned True, and the accept that followed found nothing
THE STEP THAT FAILED is tWinSocket.Accept, which AcceptHandle calls. A
socket made by accept keeps the listening socket's WSAEventSelect
association: the same event, the one WaitForData waits on, and the same
events, FD_ACCEPT and FD_CLOSE. Accept left it in place, so the end of
any connection the listening socket had taken on - the peer's FIN,
whichever end closed first - signalled the listening socket's event,
unless a WaitForData on the accepted socket had replaced it.
WHAT IT LOOKED LIKE. A WaitForData on such a listening socket, waiting
on a thread of its own while connections it had accepted ended, returned
True for 5 of 5 connections the client closed first, about 300 ms into
the wait, when the client closed, and for 5 of 5 the server closed
first, when the client closed 0.1 s later; on Win32 and Win64, in every
run (three on each). Each such wake costs an accept that takes nothing
(WSAEWOULDBLOCK). Before entry 121 it cost a TstSSHSocketServer its
listening socket: the accept loop closed it and listened again,
resetting a client that connected just then.
NOW Accept cancels the association on the socket it makes, when the
listening socket has one - when WaitForData or DualWaitForData has
selected events on it: WSAEventSelect(socket, 0, 0). The accepted socket
stays non-blocking, as it was, from the listening socket, and its own
WaitForData associates it with its own event, as before. The accepted
sockets of a listening socket that WaitForData was never called on are
left alone: WSAEventSelect makes a socket non-blocking whatever events it
is given, so cancelling there would turn a blocking socket into a
non-blocking one (measured: recv then returned WSAEWOULDBLOCK at once).
WHO. On Windows, a server whose listening tWinSocket waits with
WaitForData and whose accepted sockets are not waited on with a
WaitForData of their own, which replaces the association:
TstSSHSocketServer, whose connections ask how much has arrived instead,
and application code that does the same. The OCSP responder
(TstOcspServer), the mail listeners and the SSH remote-forward listener
wait on each accepted socket at once; their listening sockets were woken
only by a connection that ended before that first wait. Off Windows an
accepted socket is not tied to its listening socket.
THE DISCRIMINATING TEST: accept a connection from a listening tWinSocket
that WaitForData has been called on, wait on it again with WaitForData
on another thread, and close the client. An affected release ends the
wait at once, True; this one waits out its time.
PLATFORMS. New test Test\acceptwake\AcceptWakeTest (battery rows Win32,
Win64 and Linux64, floors 11, 11 and 9; ports the system assigns on
127.0.0.1): no WaitForData on the listening socket may be woken by 5
connections that end, the client closing first (step 1) or the server
(step 2); a new connection wakes it (step 3); its accepted sockets are
non-blocking (step 4) and their own WaitForData sees data and the
client's close (step 5); and on Windows a listening socket never waited
on hands out blocking sockets (step 6). Before this change 2 of the 11
checks fail on Win32 and Win64, steps 1 and 2, all ten waits woken, in
every run (three on each); Linux64 passes 9 of 9 either way. With it,
11, 11 and 9. Cancelling on every accepted socket, also those of a
listening socket never waited on, fails step 6 on Win32 and Win64:
Receive returned at once.
Test\sshinterop\SshListenerResetTest (entry 121) gains step 6, which
signals the listening socket's event itself while a client waits, so that
its Windows rows still hold the accept loop to entry 121 now that a
connection that ends wakes nothing (floors 16, 16 and 18). Steps 2, 3
and 5 pass with either change: with this one and without entry 121,
step 6 alone fails on Win32 and Win64 (2 of 16, in every run, three on
each), and 8 clients connecting and closing for 5 s made 27,639 to
49,453 connections, none reset; with entry 121 and without this one,
3,943 to 16,664.
NOT CHANGED:
- A listening socket that WaitForData was never called on: its accepted
sockets are blocking, as before.
- tPosixSocket, whose accepted sockets have no tie to their listening
socket.
- The legacy units stSocketServer and stSSHForwardedListenerSocket, which
no longer ship, call tWinSocket.Accept directly and get the change
with it.
NOT INVOLVED: the asynchronous TLS server's Winsock listener
(StreamSec.Mobile.AsyncTLSListener.Winsock), which makes its own sockets
for the IOCP reactor and does not use tWinSocket.
--------------------------------------------------------------------------------
EXTENSIONS AND NAME ATTRIBUTES OF A TYPE THE LIBRARY DOES NOT LIST
================================================================================
133. FIXED - a program that set an extension's extnId, or a Name
attribute's type, to an OID the library has no type for, and then saved
it, failed an assertion in ExtractSubIden; built without assertions, it
wrote the extension without its extnID and the attribute without its
type
An extension's extnId picks the type of its extnValue from the table of
extensions the library knows (stPkixExtension), and a Name attribute's
type picks the type of its value from the table of attribute types
(stPkixName). Each table ends in an alternative that stands for every
OID it does not list. A program that sets extnId to such an OID - a
private extension, or one under a UUID OID - gets that alternative. When
the value was then reached, tASN1TypeIdentifier.Update (stASN1Base),
which keeps the identifier and the value's type in step, wrote that
alternative's identifier into the extnId; it has none, so it wrote an
empty OID. With assertions on, the extnId field refused it
("ExtractSubIden: StartPos out of range") and the save failed. Without
them it took it, and the extension was written with no extnID at all:
30 08 04 06 04 04 61 62 63 64 for a 2.25.1 extension holding the OCTET
STRING abcd, an Extension without the extnID RFC 5280 requires, with
extnId reading ''. A Name attribute of type 2.25.1 holding x failed the
same assertion as soon as its value was used, and without assertions it
was written as 30 03 14 01 78, with no type.
NOW the identifier stays as the program set it, and the extension or
attribute saves with it and with the value put into it, as OpenSSL
writes the same: 30 0C 06 02 69 01 04 06 04 04 61 62 63 64, and
30 07 06 02 69 01 14 01 78. Such an extension's value goes into its
alternative's primitive content with the tag set - 4 for an OCTET
STRING; such an attribute's value is a DirectoryString.
WHO. Programs that build a certificate, request or CRL with an extension
the library does not list, or a Name with an attribute type it does not
list, and save it. Reading such an extension from DER and saving it
again, and copying a decoded extension whole into a new one, did not
reach the fault.
THE DISCRIMINATING TEST: set a new extension's extnId to 2.25.1 and save
it. With assertions on, an affected release raises EAssertionFailed;
without them it writes 30 08 04 06 ... and extnId reads ''. This one
writes 30 0C 06 02 69 01 ... and extnId reads 2.25.1.
PLATFORMS. The code is the same on every platform. OidCodecTest gains 13
checks: the extensions 2.25.1 and one under the UUID OID, each holding
an OCTET STRING and compared with the octets OpenSSL 3.5.7 writes; 2.25.1
saved with no value; the Name attribute 2.25.1 holding x, compared with
OpenSSL's octets; and two controls - subjectKeyIdentifier saved with no
value, and OpenSSL's 2.25.1 extension read and saved again. An affected
release fails 7 of them on Win32, Win64 and Linux64, and 7 on Win32
built without assertions; this one passes all 102 of OidCodecTest's
checks on each.
NOT CHANGED:
- An extension of a type the library does not list, saved before any
value is put in it: its extnValue held 00 00 - the alternative's
content left empty, a tag 0 with no octets. Entry 134 refuses that
save with eASN1Error.
- tSetOfAttrValueInformationObject (StreamSec.DSI.Pkcs8: the attributes
of a PKCS#8 key and of a PKCS#12 bag) writes its alternative's
identifier in the same way, and its table also ends in such an
alternative. It is not changed here. The key tables of
tPublicKeyInformationObject and tPrivateKeyInformationObject list no
such alternative.
134. BEHAVIOUR CHANGE - a value of type ANY that a program never set - the
value of an extension the library has no type for, among others - is
refused when it is encoded, with eASN1Error, where it was written as
00 00
A field of type ANY (tASN1GenericContent, stASN1Types) takes the tag of
the value read into it or given to it. One that was never read and never
given a tag kept universal tag 0 and no content, and was written as
00 00: the end-of-contents marker of an indefinite length, which X.690
keeps for that use and DER never writes. An extension whose extnId the
library does not list, saved before a value was put in it (entry 133),
came out as 30 08 06 02 69 01 04 02 00 00, an extnValue with no value
in it.
NOW encoding such a value raises eASN1Error: "<name>: a value of type
ANY in it was never set - it has no tag, so there is nothing to encode",
where <name> is the nearest enclosing structure with a name - extensions,
for a certificate's extension. Nothing is written and the structure is
left as it was; once the value is set, it saves.
WHO. Programs that build an extension of a type the library does not
list, or another structure with a field of type ANY - in CMS (stCMS,
StreamSec.DSI.CMS) and PKCS#8 and PKCS#12 (StreamSec.DSI.Pkcs8) - and
encode it without setting that field. A value read from DER keeps the
tag it was read with, and a structure read and saved again unchanged
writes the octets it was read from.
THE DISCRIMINATING TEST: set a new extension's extnId to 2.25.1 and save
it without putting a value in it. An affected release writes
30 08 06 02 69 01 04 02 00 00; this one raises eASN1Error.
PLATFORMS. The code is the same on every platform. OidCodecTest's check
of that extension now requires the refusal, and then that the same
extension, given its value, saves as OpenSSL writes it (one more check):
an affected release fails the refusal on Win32, Win64 and Linux64, with
assertions and without; this one passes all 103 of OidCodecTest's
checks on each.
NOT CHANGED: a field of type ANY that a value was put in or read into is
written as before.
--------------------------------------------------------------------------------
SSH: AN OPTION FOR AN ALGORITHM THE PROGRAM DOES NOT LINK
================================================================================
135. FIXED - creating an SSH client or server component, or adding an
option to one of its option lists, read a string that had just been
freed when an option's algorithm was one the program has no class
for - in every program that does not link stTwoFish, for its twofish
ciphers and MACs
THE STEP THAT FAILED is the unregistration of such an option. Every SSH
client and server component creates its option lists - ciphers, MACs,
key exchanges and the rest - when it is created, and each list registers
its default options with stSecUtils.RegisterInitialization. An option
whose algorithm the program has no class for cannot be enabled, so the
registration lists are all that hold it, and
tCustomOption.WatchOutForGarbage (stCustomProtoComp) unregisters it as
soon as RegisterInitialization returns, handing
UnregisterInitialization the option's own Identifier field. Unregistering
released the lists' references, the last ones: the option was destroyed
during the call and the string freed with it, and UnregisterInitialization
went on comparing that string with the identifiers of the registrations
it had still to look at. Each comparison read the freed string's length,
and its characters when the lengths matched.
WHAT IT LOOKED LIKE. Nothing, on Windows: the memory manager leaves a
freed string's length and characters as they were, and every comparison
came out as it would have. On Linux64 the C library's allocator writes
its own bookkeeping into the first octets of a freed block, and there it
reaches a string's length, so every comparison after the free said
"different", and a registration of the same name further down the list
stayed registered. Measured with a
registration that cannot initialize, made under an option's name just
before AddOption adds that option: left registered in 20 of 20 rounds on
Linux64, removed in 20 of 20 on Win32. In the library the registrations
of the same names are StreamSec.SSH.BlockPadding's, of the twofish OMAC
MACs, which wait for a TwoFish class: on Linux64 they stayed after the
first SSH component was created, on Windows they were removed with the
MAC options of the same names. Nothing failed, and the components offered
the same options either way. valgrind reports the reads: "Invalid read of
size 4" in _UStrEqual called from UnregisterInitialization, "inside a
block of size 46 free'd" - 491 errors in 3 contexts for a program,
without stTwoFish, that creates two servers and two clients.
NOW WatchOutForGarbage holds a reference of its own to the identifier
for the length of the call, and the string is freed when the call has
returned.
WHO. Every program that creates an SSH client or server component and
does not link every algorithm its option lists name: any program without
stTwoFish, and programs that pass AddOption an algorithm they do not
link. The same path is taken by every tCustomOption that does not
replace WatchOutForGarbage, which includes the key stores' options of
the key managers.
THE DISCRIMINATING TEST: on Linux64, register an initialization that
cannot initialize (an iInitialization whose CanInit answers False) under
a name, then AddOption a cipher option of that name with an algorithm no
class implements (caRijndael in mode cmSSHChaCha). An affected release
leaves the first registration registered; this one removes it, as
Windows always did. Or run any program that creates an SSH component,
without stTwoFish, under valgrind: an affected release reports the reads
above, this one none.
PLATFORMS. The code is the same on every platform. New test
Test\optunreg\OptionUnregisterTest (battery rows Win32, Win64 and
Linux64, floor 25 on each) makes the read visible on all three: the
calls run inside a window of Test\optunreg\PageGuard.pas, a memory
manager for tests that gives every block allocated in the window pages
of its own and makes them inaccessible when the block is freed, so a
read of it raises EAccessViolation at once. A control step shows that it
does. With a registration of another name that cannot initialize made
first - so that one is always compared after the option is gone - step 2
adds a cipher option no class implements, and steps 3 and 4 create a
TstSSHSocketServer and a TstSSHSocketClient in a program without
stTwoFish. An affected release fails 3 of its 19 checks on Win32, Win64
and Linux64 (2.1, 3.1 and 4.1: EAccessViolation), in three runs of
three; this one passes all 25 on each, in three runs of three. Under
valgrind on Linux64 the program above reports no error at all, and step
1 of Test\sshinterop\SshLoginGraceTest, where the reads were first seen,
no invalid read or write. The ciphers and MACs offered are the same as
an affected release's on all three platforms.
NOT CHANGED:
- An option that cannot be enabled is still unregistered, and destroyed,
in the call that registered it: when the registration lists are all
that hold an option, WatchOutForGarbage takes it that nothing uses it.
So a class registered later (RegisterCipherClass) does not enable such
an option in a list created before it; a component created after it
registers its default options again and offers the option.
- UnregisterInitialization removes every registration of the name it is
given, not only the option's: the first SSH component created in a
program without stTwoFish removes the registrations of the twofish OMAC
MACs together with the MAC options of the same names - on Windows as
before, and now on Linux64 too.
- The key formats (stMPCustomKeyFormat, StreamSec.DSI.CustomKeyFormat)
replace WatchOutForGarbage with one that does nothing, and are not
unregistered this way.
NOT INVOLVED: the SSH protocol, the negotiation of algorithms with the
peer, and which options a component offers - the same before and after
on every platform.
--------------------------------------------------------------------------------
THE SSH TUNNEL CLIENT DEMO: DISCONNECT WHILE -L CONNECTIONS ARE OPEN
================================================================================
136. FIXED - the SSH Tunnel Client demo's Disconnect freed the SSH client
while the threads relaying its -L connections were still running: each
of them then wrote into freed memory, and one still waiting for an HTTP
request used the freed SSH client when the request came
THE STEP THAT FAILED is Disconnect's wait for the relays: there was none.
Each connection accepted on a -L listener (tDirectListener in
TunnelClientEngine) is relayed on a thread of its own, which keeps the
listener and the SSH client. The threads freed themselves when they
ended, and nothing waited for them. Disconnect freed the listeners, each
of which waited only for its own accept thread, and then the SSH client.
A relay still running at that moment then did two things it must not:
- when it ended, it counted itself out of the listener it came from,
which had been freed: a write of 4 octets into freed memory;
- until it ended, it went on using its channel of the SSH client, and a
relay in HTTP mode that was still waiting for the request naming its
target - it waits up to 5 s - opened a channel through the freed SSH
client when the request came. Entry 94: close the SSH client only once
the threads that send on its channels have stopped.
A relay whose local program had stopped reading kept running until that
program closed its connection.
NOW each listener keeps its relays, and frees a relay once its connection
has ended. When the listener is freed it stops every relay - each wait in
a relay, for data, for the channel to open and for room in the server's
window, ends when the relay is stopped - and waits until every relay's
thread has exited. So Disconnect frees the SSH client only after the
relays have stopped. It also returns sooner: a listener being freed no
longer waits up to 300 ms for its accept loop to notice.
WHO. Anyone who called Disconnect, or closed the demo, while -L
connections were open, plain or in HTTP mode. What followed depended on
what the freed memory held by then: nothing visible, a damaged heap, or
an access violation that the relay caught and did not report.
HOW IT WAS FOUND. Reading the code, then measured.
THE DISCRIMINATING TEST: open a -L forward in HTTP mode, connect a TCP
client to it that sends nothing, call Disconnect, and a second later
send an HTTP request on that connection. In an affected demo the relay
is still running when Disconnect returns, and opens a channel through
the freed SSH client when the request comes; in this one the relay has
ended and closed the connection before Disconnect returns.
PLATFORMS. Measured on Win32 and Win64 with
Test\sshinterop\TunnelClientDisconnectTest, which runs the demo's client
engine against the demo's server engine on 127.0.0.1, the server in a
second process, finds the relay threads and looks at them when
Disconnect returns: four -L forwards carrying data both ways, one whose
local program does not read, and one in HTTP mode whose request comes
after Disconnect. Before, every relay was still running when Disconnect
returned, in every run: 5 on Win32 and 6 on Win64. Built with a guard
memory manager, the test saw each relay write into its freed listener,
and the late HTTP request raised an access violation through the freed
SSH client, as it also did on Win32 without one. Now no relay is running
when Disconnect returns, and there is no access violation and no write
into freed memory, in every run: 8 on Win32 and 8 on Win64, half of them
with the guard memory manager. Entry 98's test,
Test\sshinterop\TunnelClientStallTest, passes all 6 of its checks on
both.
NOT INVOLVED: the library and the SSH protocol.
NOT CHANGED: what Disconnect does with the demo's -R forwards: entry
139.
--------------------------------------------------------------------------------
ATTRIBUTES READ BEFORE THEIR TYPE, OR OF A TYPE THE LIBRARY DOES NOT LIST
================================================================================
137. FIXED - a PKCS#8 or PKCS#12 attribute (StreamSec.DSI.Pkcs8) whose
value was reached before its type, or whose type is not one of the
four the library lists - Microsoft's CSP Name on a key bag, say - ended
in an access violation: the value's class was read from memory before
the attribute table, and called
An Attribute is a SEQUENCE of its type and a SET of values, and the type
picks the class of each value from a table that lists friendlyName,
localKeyId, the StreamSec key-usage attribute and keyUsage, and ends in
an alternative for every other type. tSetOfAttrValueInformationObject,
which keeps the two in step, failed in three ways:
- A value reached before the type - attribute.value[0] read before
attribute.typeId - found the type not yet joined to it, because an
attribute makes its fields as they are reached, so no alternative was
chosen for the value.
- A type the table does not list chose no alternative either: only an
exact match chose one, never the alternative for every other type.
- With no alternative chosen, the value's class was looked up at index
-1, before the table, and the code there called: "Access violation at
address 000104E4 ... Execution of address 000104E4" on Win32, a read of
address 0 on Linux64. Building such an attribute failed the same way
when its value was reached, and its value's alternative, once one was
chosen, would have written that alternative's empty identifier over
the type.
NOW the type's field is made when a value is reached first; a type the
table does not list chooses the alternative for every other type, whose
value is read and held as a value of type ANY (entry 134); the type is
written only from an alternative that has an identifier; and no class is
looked up for a value with no alternative.
WHO. Programs that read the attributes of a PKCS#8 key or of a PKCS#12
bag through iAttribute - an attribute the library does not list, which
a PKCS#12 file made by Windows, or by openssl pkcs12 -CSP, carries on its
key bag, or any attribute whose value is read before its type - and
programs that build an attribute of a type the library does not list.
The library's own PKCS#12 import does not reach it: ImportFromPFX of a
file that OpenSSL made with -CSP completes.
THE DISCRIMINATING TEST: read OpenSSL's friendlyName attribute,
30 11 06 09 2A 86 48 86 F7 0D 01 09 14 31 04 1E 02 00 78, into a new
tAttribute and ask for value[0]'s data before typeId. An affected release
raises EAccessViolation; this one answers a tASN1BMPString.
PLATFORMS. The code is the same on every platform; what the lookup at
index -1 found differed. OidCodecTest gains 7 checks against octets
OpenSSL 3.5.7 writes (asn1parse -genconf): friendlyName and Microsoft's
CSP Name, each read value first, the second saved again; an attribute of
type 2.25.1 built with an OCTET STRING value, and with none (refused, as
entry 134 says); and friendlyName built, as a control. An affected
release fails 5 of them on Win32, with assertions and without, and 4 on
Win64 and Linux64; this one passes all 114 of OidCodecTest's checks on
each.
NOT CHANGED here: tSetOfAttrValueInformationObject in stPkixExtension,
which keeps the attributes of a certificate's SubjectDirectoryAttributes
extension, had the same code; entry 138 fixes it.
138. BEHAVIOUR CHANGE - a value of an attribute in a certificate's
SubjectDirectoryAttributes extension (stPkixExtension) whose type the
library does not list is read and held as a value of type ANY (it was
a DirectoryString, which could not hold a value that is not a string -
RFC 3739's dateOfBirth, a GeneralizedTime); and reaching such an
attribute's value before its type no longer ends in an access violation
SubjectDirectoryAttributes holds attributes in the same form as a PKCS#8
one (entry 137): a SEQUENCE of a type and a SET of values, the type
picking each value's type from a table. tSetOfAttrValueInformationObject
in stPkixExtension picked it from the table of Name attribute types
(stPkixName), and failed in two ways.
THE ACCESS VIOLATION. A value reached before its type -
Items[0].attrValues[0] before Items[0].attrType - found the type not yet
joined to it, so no alternative was chosen; its class was then looked up
at index -1, before the table, and the code there called: "Access
violation at address 000104E4 ... Execution of address 000104E4" on
Win32, for commonName as for a type the table does not list. It was the
same defect, in the same code, as entry 137's.
THE VALUE TYPE. The table's last alternative, for every type it does not
list, was a DirectoryString: that suits a Name, whose attributes are
strings, but the attributes RFC 3739 defines for this extension include
dateOfBirth, a GeneralizedTime. Such an attribute could be neither read
("Field missing from st-PKIX-Extension.SetOfAttrValue", eASN1DataError)
nor built ("Cannot set Tag in class tASN1TeletexString",
eASN1NotSupported).
NOW the type's field is made when a value is reached first, and no class
is looked up for a value with no alternative; and the values of
SubjectDirectoryAttributes take a table of their own (tSdaAttrValue): the
Name attribute types as before, and for every other type a value of type
ANY - RFC 5280 defines AttributeValue as ANY. Such a value is read
whatever its tag, saved again as it was read, and built by giving its
content a tag (24 for a GeneralizedTime) and the content.
WHO. Programs that read or build a certificate's SubjectDirectoryAttributes
with an attribute of a type the Name table does not list - dateOfBirth,
placeOfBirth, gender, countryOfCitizenship and countryOfResidence among
them. Such an attribute that holds a string is now a value of type ANY
rather than a DirectoryString; its content is the same octets. Name
attributes (stPkixName) are not changed: there a type the table does not
list still takes a DirectoryString.
THE DISCRIMINATING TEST: read OpenSSL's SubjectDirectoryAttributes
extension holding dateOfBirth 19700101000000Z,
30 28 06 03 55 1D 09 04 21 30 1F 30 1D 06 08 2B 06 01 05 05 07 09 01
31 11 18 0F ..., and ask for its value: an affected release raises
eASN1DataError; this one answers a tASN1GenericChoice and saves the
extension again as OpenSSL wrote it. Asking for commonName's value before
its type, in
30 15 06 03 55 1D 09 04 0E 30 0C 30 0A 06 03 55 04 03 31 03 0C 01 78,
raised EAccessViolation on an affected release; this one answers a
tX520CommonName.
PLATFORMS. The code is the same on every platform. OidCodecTest covers
SubjectDirectoryAttributes with OpenSSL's extensions holding commonName
and a 2.25.1 attribute, each read value first and saved again, and
OpenSSL's dateOfBirth extension, read value first and saved again, built
through the library and compared with OpenSSL's octets. An affected
release raises on these; this one passes all 117 of OidCodecTest's checks
on Win32, Win64 and Linux64.
--------------------------------------------------------------------------------
SSH REMOTE FORWARDING: FREEING THE FORWARDING CLIENT
================================================================================
139. BEHAVIOUR CHANGE - freeing a TstSSHForwardingClient or a
TstSSHForwardingClientSocket ends the forwarded connections it is
serving and waits until the threads serving them are done with them.
Free returned at once and left them running, with the freed component
and, later, the SSH client being freed under them
A forwarding client (remote forwarding, -R) serves each connection that
the server forwards to it on a thread of its pool: OnChannelExecute runs
there, and a TstSSHForwardingClientSocket relays the channel to its
target there.
THE STEP THAT FAILED is Free. It ended the pool's idle threads, but it
neither stopped nor waited for one that was serving a connection, and the
component stayed in the SSH client's list of components to offer
forwarded connections to. After Free:
- OnChannelExecute, or the relay, went on until the connection's channel
closed - at the latest when the SSH client closed;
- a forwarded connection that the SSH client was handing over while Free
ran was handed to the freed component: an access violation on the
thread that reads the SSH connection;
- closing the SSH client released its reference to the freed component:
an access violation in System.@IntfClear on the thread that closed it;
- and a program that freed the SSH client next freed it under threads
still sending on its channels, which entry 94 says not to do.
A program that runs OnChannelExecute from a DLL and unloads the DLL once
the component is freed unloaded code that was still running: the SSH
Tunnel Client demo does, and closing it with such a connection open
ended the process with an access violation.
NOW Free refuses every forwarded connection from then on, waits for one
that is being handed over, ends each one in progress and waits until the
thread serving it is back in the pool; then it leaves the SSH client's
list, unless the SSH client has closed meanwhile and discarded it. A
connection is ended by closing its channel, which ends an
OnChannelExecute that returns once its channel leaves csConnected; a
TstSSHForwardingClientSocket closes its connection to the target, and
then the channel, once. Free sends nothing to the server: Close cancels
the remote listener, as before. Once Free returns, no thread runs
OnChannelExecute or uses the SSH client's channels for the component.
BEHAVIOUR CHANGE:
- a forwarded connection in progress ends when its component is freed;
it went on until the SSH connection ended;
- Free waits for OnChannelExecute to return, so a handler that does not
return once its channel has closed keeps Free waiting.
WHO. Programs that free a forwarding client while it has forwarded
connections - closing a program, or disconnecting, with a -R forward in
use.
THE DISCRIMINATING TEST: give a TstSSHForwardingClient an
OnChannelExecute that echoes what comes until its channel leaves
csConnected, open it, connect to the server's forwarded port and send,
and once the handler runs, Free the component. An affected release
returns from Free while the handler is still running, and closing the
SSH client afterwards raises an access violation; this one returns once
the handler has returned.
PLATFORMS. The code is the same on every platform. Measured with
Test\sshinterop\SshFwdFreeTest, which frees the component while
OnChannelExecute runs, while a TstSSHForwardingClientSocket relays
octets both ways, and while the SSH client is held for 1.5 s in handing
a new connection over (BeforeCreateChannelThread), and then frees the SSH
client. Before, those three were red on every platform: 5 of the 7
checks on Win32 and 6 on Win64, the access violations included, and all
3 on Linux64, where only the ordering is checked; built with a guard
memory manager, 6 of 11 on both. Now all pass, in every run: 3 runs of
each of the four Windows builds, and on Linux64. The demo, measured
with Test\sshinterop\TunnelClientDisconnectTest: before, its Disconnect
with a forwarded connection open to its DLL plug-in ended the process
in 5 runs of 5 on Win32 and on Win64; now it does not, and no thread of
a -R forward is running when Disconnect returns. The forwarding tests
that do not free the component in use pass as before: SshFwdEarlyEofTest,
SshFwdStallTest, SshGlobalRequestReplyTest, SshFwdSelf and
TunnelClientStallTest.
NOT INVOLVED: what is sent to the SSH server; the server's forwarding
components; local forwarding (-L).
NOT CHANGED:
- A thread that the program supplies through BeforeCreateChannelThread is
the program's: Free neither ends nor waits for its connection.
- Close cancels the remote listener and leaves the connections in
progress running, as before.
140. REDACTED - the change drafted under this number was folded into entry
138 (a value of a SubjectDirectoryAttributes attribute whose type the
library does not list is held as a value of type ANY). The number is
kept so that the entries that follow it keep their numbers.
--------------------------------------------------------------------------------
SSH SERVER: A REMOTE FORWARDING LISTENER THAT GOES WITH ITS CONNECTION
================================================================================
141. FIXED - an SSH server destroyed a remote forwarding (-R) listener twice
when the client's connection ended, or the server stopped, while the
forwarding was set up: the second time inside the first destructor, on
memory already freed
For each tcpip-forward request a client makes, a
TstSSHListenerControllerSocket makes a listener, which accepts TCP
connections and forwards each over the SSH connection. The listener is
reference counted - it is built on tObjectMapping - and the connection's
channel broker holds it. It goes when the client cancels the forwarding
(cancel-tcpip-forward), when the client's connection ends, or when the
server stops.
THE STEP THAT FAILED is the listener's destructor, which leaves its
broker and passes itself, as an interface, to do so; that takes a
reference to the listener and releases it. A tObjectMapping destroyed
itself whenever its reference count came back to 0, during its own
destruction as at any other time. So when the listener was destroyed
because its broker released it - the connection ended, or the server
stopped - the release in its destructor destroyed it a second time, and
the first destructor then went on over freed memory. With the default
memory manager the second free raised EInvalidPointer on the server's
thread for that connection; with a memory manager that fills freed
memory, an access violation. A cancel destroyed the listener once: the
broker holds a reference of its own while it hands the request over.
NOW a tObjectMapping marks itself as being destroyed before any of its
destructors runs (BeforeDestruction), as the RTL's TInterfacedObject
does, and a reference taken and released meanwhile does not bring its
count back to 0. This holds for every class built on tObjectMapping, not
only the listener.
WHO. SSH servers with a TstSSHListenerControllerSocket whose clients end
their connection, or that stop, while a remote forwarding is set up - a
session with ssh -R that ends without cancelling it, for one.
THE DISCRIMINATING TEST: give the server a TstSSHListenerControllerSocket
descendant that implements iSSHListenerController's GetListener again and
returns a tSSHForwardedListenerSocket descendant counting the calls of
its destructor; have a client set up a remote forwarding and close its
connection. An affected release calls the destructor twice; this one
once.
PLATFORMS. Measured with Test\sshinterop\SshFwdListenerTeardownTest,
which counts those calls when the client's connection ends with the
listener idle and with a forwarded connection in progress, when the
client cancels the forwarding in both cases (then sets up and cancels a
second one on the same connection), and when the server stops. Before,
the three steps without a cancel called the destructor twice on every
platform: 4 of the 26 checks red on Win32 and on Win64, 4 of 21 on
Linux64; built with a guard memory manager, they also raised an access
violation in System.@ClassDestroy reading freed memory and reported
freed memory written (10 of 31 on both). Now all pass, in every run: 3
runs of each of the four Windows builds, and 2 on Linux64. On macOS 26
on an Apple M1 all 21 pass, 3 runs in 3; built without this entry, the
test found a listener destroyed twice in step 1 and then ended in step
2, where macOS stopped the program for a corrupted heap, 2 runs in 2.
Entry 80's test, which did not finish on the M1 before (entry 106), ends
the same way without this entry and passes with it, 3 runs in 3,
including a step of its own that ends a connection while a forwarding
is open.
Step 2 - the connection ends while a forwarded connection carries
data - needs entry 143 as well: without it, its teardown hung now and
then on Windows (6 of 100 runs, four at a time), a defect of its own.
NOT INVOLVED: what the server sends; the client; the forwarded
connections themselves.
--------------------------------------------------------------------------------
RSA KEYS FROM FIPS 186 PROVABLE PRIMES
================================================================================
142. FIXED - RSAKeys with ifkgNIST and ifkgProvable raised eKeyGeneration
"Failure generating prime" for about one key of 2048 bits in a hundred;
and a provable prime's seed was hashed together with the memory after
it, so one seed did not give one prime
tNISTProvablePrimeGeneratorRSA (StreamSec.DSI.Arith) makes each prime by
the walk of FIPS 186-4 Appendix C.10: one candidate p - 1 = 2*t*p0 for
each of t, t + 1, t + 2 and so on, up to 5L of them (L the length of the
prime) before it gives up. A candidate whose p - 1 shares a factor with e
is rejected before any primality test, and after such a candidate the
generator did not go on to t + 1 - step 21, "t = t + 1", comes after the
test of step 19 whatever its result - but tested the same candidate
again, until the 5L were used up. With e = 65537 such a candidate is one
where 65537 divides t, which the walk meets before a prime about once in
185 primes of 1024 bits: RSAKeys failed for about one key of 2048 bits in
a hundred, and more often for 3072 and 4096 bits.
It also hashed 224 octets where the seed holds 28: the seed's length went
in bits to a parameter that takes octets, so the memory after the seed
went into every prime, and a seed given to the generator again gave a
different prime.
NOW the walk goes on to t + 1 after every candidate it rejects, and only
the seed's own octets are hashed - 28 for a prime of 1024 bits, 32 for
1536 and 48 for 2048: one seed gives one prime.
WHO. Programs that generate RSA keys with ifkgNIST and ifkgProvable:
TstRSAKey, whose default KeyGenerationKind includes both; the RSA keys
TstBasePKIXObjectGenerator makes for certificates; and the RSA part of
composite signature and composite KEM keys. Programs that give the
generator a Seed of their own got a prime that did not follow from it.
THE DISCRIMINATING TEST: generate a 2048-bit key with ifkgNIST and
ifkgProvable and E = 7 * 65537, which puts such a candidate at every
seventh t. An affected release raises eKeyGeneration "ifkgNIST,
ifkgProvable: Failure generating prime" for practically every key; this
one generates the key.
PLATFORMS. The code is the same on every platform. RsaGenTest gains 7
checks: three keys of 2048 bits with E = 7 * 65537, each generated, of
the right lengths, N = P * Q with that E and a raw RSA round trip; one
seed of 224 bits given three times with other memory around it, the
same prime of 1024 bits each time; and the prime of 1024 bits that one
seed gives with E = 65537, which a copy of the generator written
separately from this one, with the same two changes, gives too - two
implementations that agree, not a reference from outside. An affected
release fails 6 of them on Win32, Win64 and Linux64; this one passes all
85 of RsaGenTest's checks on each. 1000 pairs of 1024-bit primes with
e = 65537, as one key of 2048 bits takes them, on Win32: an affected
release fails 10 times (2 at the first prime, 8 at the second), this one
not at all.
NOT CHANGED:
- FIPS 186-4 C.6 and C.10 may still give up for a seed, rarely: by
estimate some 4 primes of 1024 bits in 100,000, at the Shawe-Taylor
levels of C.6. RSAKeys then raises eKeyGeneration, as before; it does
not try another seed.
- For a given seed the primes are not those FIPS 186-4 gives: C.6 step 14
asks for the prime one level down to have ceil(length / 2) + 1 bits,
where this one makes it floor(length / 2); C.10 step 17 forms
p = 2(t - 1)p0 + 1 from the t of step 15, where this one forms
2*t*p0 + 1 from the same t; and when the candidate passes 2^L, C.10
step 16 starts again from 2*p0 plus floor(sqrt(2) * 2^(L-1)), where
this one starts from 2^(L-1).
--------------------------------------------------------------------------------
SSH SERVER: A CHANNEL THAT SENDS ON ITS OWN THREAD WHILE ITS CONNECTION ENDS
================================================================================
143. FIXED - an SSH server channel whose Send, SendEOF or Close ran on a
thread of its own as the connection ended could call through the
connection's channel broker after the server had freed it: on Windows an
access violation on that thread or, for a Close, the connection's lock
left held by a thread that had ended, so that the server never
finished the connection and could not stop; on Linux64 a read of freed
memory that could end the server process. This is the send-side
residual that entry 105 listed as not changed.
An SSH server (TstSSHServer, TstSSHSocketServer) keeps each connection's
channels on a channel broker, a plain object the connection's own thread
frees when the connection ends - when the client disconnects, when the
server is deactivated, or when gGlobalCloseAll is raised (entry 105). The
server's port-forwarding threads send on their channel from a thread of
their own: those of TstSSHSenderControllerSocket (-L, direct-tcpip) and of
TstSSHListenerControllerSocket (-R, forwarded-tcpip) write what they read
from their TCP connection with the channel's Send, send its half-close with
SendEOF, and close it with Close; a thread of the program that holds a
session channel does the same. Entry 105 made the broker wait, before it is
freed, for a channel whose REMOVAL was under way on such a thread, and for
a channel's subsystem thread (entry 50); it did not make it wait for a
SEND in progress on one, and said so.
THE STEP THAT FAILED is a send ordering itself against the broker's end.
tCustomSSHServerChannel.Send took the broker reference into a local and
then called through it; SendEOF and Close read the field and called
through it; none waited, and the broker does not wait for them. A send that
had taken the reference when the connection ended called
tAbstractSSHServerChannelBroker.Send, .SendEOF or .Close on the freed
broker, which entered the freed transport's lock. On Win32 and Win64 that
was an access violation on the sending thread (a read through the freed
broker - the nil transport - at the lock); on Linux64 the call ran into
freed memory and, with no handler, the process ended.
A CLOSE COULD LEAVE THE CONNECTION'S LOCK HELD. The broker's Close
catches what its send raises. When the broker was freed while a Close was
inside the transport's lock - the -R port-forwarding thread closes its
channel as soon as a send fails, which is when the connection ends - its
release of the lock went through the nil transport, and the access
violation that raised was caught there: the thread ended owning the
transport's lock. The connection's own thread waited for that lock as it
finished, and so did the server's Free and Active := False
(CloseAndJoinPeers), without end. Measured on Win32 with
SshFwdListenerTeardownTest (entry 141), step 2 - a client ends its
connection while a forwarded connection carries data to it - run 100
times, four runs at a time on 127.0.0.1: 6 hung in the teardown, each
with the transport's lock owned by an -R port-forwarding thread that had
ended inside the broker's Close; with this entry, none of 100.
HOW OFTEN. The window runs from where the send takes the broker reference
to where it enters the transport's lock: a few instructions, as long as the
connection's thread needs to detect the end and free the broker. Measured
with the new SshServerChannelSendRaceTest, which holds a send in that
window on a thread of its own - the port-forwarding threads' situation -
while the client disconnects. On an affected release a held Send raised
EAccessViolation on Win32 and Win64 and on Linux64, and a held SendEOF
found the broker freed while it held it; with the default 20 rounds, 43 of
the test's 116 checks failed on each of the three platforms, the control
(no disconnect during the hold) passing.
NOW Send, SendEOF and Close take the broker reference and count the call in
together under the channel's own removal lock (the entry 105 lock), and
count it out when it returns. A removal nils the channel's broker reference
under the same lock as the connection ends, so a call started after it does
not begin; and the broker, freeing itself, waits after it has taken every
channel off - so no new call can start - for the calls still in progress,
before it is freed. A send on the channel's own subsystem thread is not
counted and does not take the lock: the broker already waits for that
thread (entry 50), and taking the lock there would deadlock a removal that
holds it while it ends the thread. The lock is released before the call, so
it is never held across the transport's lock (the entry 105 lock order,
removal lock then transport, is kept).
THE DISCRIMINATING TEST: subclass tSSHServerChannel and register it in its
place with RegisterAsMappedClass(True); open a session channel from a
client, and on a thread of your own call the server end's Send while you
hold that thread briefly between its taking the broker reference and its
use of it (SshServerChannelSendRaceTest does this with a build-only hook,
never compiled into a shipping build), and meanwhile disconnect the client.
An affected release frees the broker inside the hold and the send then
raises EAccessViolation or reads freed memory; this one holds the
connection's thread until the send returns and frees the broker only after.
WHO. A program with an SSH server whose clients forward ports (-L or -R),
or whose session channels are closed by a thread of the program: its
port-forwarding threads and that thread send, half-close and close their
channels, and a connection that ends under such a call was at risk. A
subsystem (SFTP, snip, or a TstCustomSSHSubSystem of your own) sends on its
channel's own subsystem thread, which the server already waited for
(entry 50), and was not affected. With -R forwarding on Windows, a
connection that ended while a forwarded connection carried data could
also leave the server unable to finish it, or to stop (above).
PLATFORMS. Every platform: the same code runs on each. Measured on Win32,
Win64 and Linux64; this release passes all 116 checks of
SshServerChannelSendRaceTest on each, in several runs of each, where an
affected release failed 43. Also passing as before, on the three platforms:
entry 105's SshServerChannelCloseRaceTest (324 checks), and the
port-forwarding tests SshFwdEarlyEofTest and SshFwdStallTest (Win32 and
Linux64). StrSecIV370 builds for Win32 and Win64. Not run on macOS (the
machine was off the network).
NOT INVOLVED: the client's channels (entry 94); the removal path and the
subsystem threads (entry 105); what a channel sends, and the states it goes
through; the transport, the key exchange and the ciphers.
NOT CHANGED:
- A Recv that reopens the channel's window calls through the broker too,
but only on the broker's own reading thread or on the channel's subsystem
thread, both of which the broker already waits for; it is left as it was.
- The broker's wait for a send in progress has no time limit of its own: it
lasts as long as the send does, bounded by the send's own timeout.
- The legacy unit stSSHServerChannel, which no longer ships, is not
changed.
--------------------------------------------------------------------------------
SSH: A CHANNEL THE SERVER CLOSES WHILE ITS OWN THREAD CLOSES IT
================================================================================
144. FIXED - a channel of an SSH client that the server closed, and that a
thread of the program closed at that moment, could send the server a
second SSH_MSG_CHANNEL_CLOSE; and when the program was closing the SSH
client just then, that thread's Close raised eSSHTransportRawError
"Cannot send: Socket is closed"
A TstSSHSocketClient answers the server's SSH_MSG_CHANNEL_CLOSE on its
channel broker's thread: the channel goes to csClosing, and the client's
own CLOSE goes back to the server (RFC 4254 section 5.3), once - a
channel's Close sends no CLOSE when one has been sent. The program then
completes the channel to csClosed with Close. A program that runs each
channel on a thread of its own, and closes it there as soon as it leaves
csConnected, calls that Close the moment the broker has made the channel
csClosing. The port-forwarding threads of TstSSHForwardingClientSocket do
this.
THE STEP THAT FAILED is the broker's answer to the server's CLOSE. It made
the channel csClosing first, and only then counted the client's CLOSE as
sent. A Close on another thread that came in between found csClosing and
no CLOSE counted, and sent one itself; the broker, which had looked
already and found none, sent its own as well.
- With the connection up, the server got two SSH_MSG_CHANNEL_CLOSE for
the channel. A TstSSHSocketServer ignores the second, the channel being
gone by then; other servers were not tried.
- When the program was closing the SSH client at that moment - the
connection was closed already - the Close raised eSSHTransportRawError
"Cannot send: Socket is closed" on the channel's thread. The channel
still ended csClosed, and closing the SSH client took it off the broker.
HOW OFTEN. Only the few instructions between the two steps are open, so
rarely. SshChannelCloseRaceTest's step 5 - 48 channels, each with a
thread that closes it the moment it leaves csConnected, the server
closing all 48 and the program closing the SSH client 0 to 4 ms later -
raised once on Linux64 in a run of 20 rounds, and not at all in 3000
rounds on Linux64 and 1000 each on Win32 and Win64 run afterwards. In a
build that held the broker between the two steps, every Close that came
in between sent a second CLOSE - 66, 117 and 331 of them in 10 rounds on
Linux64, Win32 and Win64 - and with the broker held until the program had
closed the SSH client, the Close raised in 8, 8 and 10 rounds of 10.
NOW:
- The broker counts the client's CLOSE as sent, and reads the broker it
is to go through, before it makes the channel csClosing. A Close that
finds csClosing finds the CLOSE counted and sends nothing; it may take
the channel off the broker meanwhile, and the broker's CLOSE still goes
out.
- The client's CLOSE is counted by an atomic compare-exchange everywhere
it is counted - in Close, in the answer to the server's CLOSE, and at
the end of the connection (entry 84) - and only the one that counts it
sends it. So one CLOSE goes out however those meet, also when the
program closes an open channel at the moment the broker handles the
server's CLOSE, where both could send one before. That case was not
measured; it follows from the compare-exchange.
- Close reads the channel's broker once. It read it twice, to see that
there was one and then to call it; the broker's thread, taking the
channel off in between when the server's CLOSE crossed the program's,
could leave it calling through nil. That was not seen in any run.
NEW: tSSHClientChannel.InternalAfterPeerClose, a protected virtual method
that does nothing. The broker's thread calls it when the server's CLOSE
has made an open channel csClosing, before the client's CLOSE goes back.
A subclass may override it, as it may InternalBeforeRemoveFromBroker.
THE DISCRIMINATING TEST: subclass tSSHClientChannel and have its
InternalAfterPeerClose, on the broker's thread, wait until
TThread.CheckTerminated - the SSH client is being closed and the
connection is closed - then let a thread of your own close the channel,
and wait until that Close has returned. Open such a channel on a
logged-in TstSSHSocketClient (Create on SSHClient.Broker, then Connect),
have the server close it, and call SSHClient.Close. The release before
this one has no InternalAfterPeerClose; built with it added where it made
the channel csClosing, and nothing else, the thread's Close raises
eSSHTransportRawError "Cannot send: Socket is closed" every time. In this
one it returns without raising, and the channel ends csClosed.
PLATFORMS. The code is the same on every platform. SshChannelCloseRaceTest
gains a step 7 doing the above three times, 15 checks, 330 in all. On
Win32, Win64 and Linux64 the release with only InternalAfterPeerClose
added fails 3 of them on each - each try's "the thread's Close returns
without an exception" - and this one passes all 330 on each.
NOT INVOLVED: the transport, the key exchange and the ciphers; taking a
channel off its broker (entry 94); and the end of the connection, which
already counted the CLOSE before it made a channel csClosing (entry 84).
NOT CHANGED:
- Close still raises when its CLOSE cannot be sent. A program that closes
an open channel on one thread while it closes the SSH client on another
can still get eSSHTransportRawError from that Close, as from Send,
SendEOF and RequestSubSystem (entry 94): close the SSH client once the
threads that use its channels have stopped.
- The SSH server's channels answer the client's CLOSE the same way round
- csClosing first, then the server's CLOSE counted as sent - and are
not changed here. That was not measured.
- The legacy unit stSSHClientChannel, which no longer ships, is not
changed.
--------------------------------------------------------------------------------
SSH: BOTH DIRECTIONS OF A CONNECTION AT ONCE
================================================================================
145. FIXED - an SSH connection between two ends built on this library
stopped when both ends sent faster than the other end read - an echo
through a forwarded port, a stream each way - and ended once a send had
waited SendTimeout (30 s by default)
Each send on an SSH connection of TstSSHSocketClient or TstSSHSocketServer
takes the connection's transport lock, encrypts the packet and writes it
to the socket whole, waiting for room while the peer catches up. The
thread that reads the connection - its channel broker's - takes the same
lock to read.
THE STEP THAT FAILED is reading while a send waits for room. When both
ends of a connection write faster than the other end reads, the socket in
each direction fills. Each end's send then waits for room holding its
lock, and each end's reader waits for that lock, so neither end reads
what the other has sent, and neither send finds room. The connection
stood still until a send had waited SendTimeout; that send then failed
(eExternalSendError) and the connection ended.
NOW a send that finds no room reads what the peer has sent meanwhile, as
it waits, and keeps it in order for the connection's reader, which reads
it as if it had stayed in the socket; nothing is decoded there. The
peer's send then finds room, its reader reads, and this end's send finds
room in turn. tAbstractSocket.SendAll has a new overload taking the
procedure to call each time a send finds no room (aOnStall), and then
waits for room 1 ms at a time; TstSSHSocketClient and TstSSHSocketServer
pass the transport's (StreamSec.SSH.Transport.SSHRawSendStall), which is
set while the transport sends a packet. Reading this way begins once the
peer's identification string has been read, and holds at most 32 MB of
what the peer sent; past that the send waits as before. A
TstSSHSocketClient's OnRawRecv is called for these reads too, on the
sending thread.
WHO. Programs where both ends of an SSH connection are this library and
both send on it at once, faster than the other end reads: a port forward
(-L or -R) to an echo service or to any protocol that sends both ways at
once, two channels carrying streams in opposite directions, an SFTP or
snip transfer each way at once. A peer that reads while it writes - as
OpenSSH does - always made room for this end's send in time (read in the
code, not measured).
THE DISCRIMINATING TEST: connect our SSH client to our SSH server, set up
a remote forwarding whose OnChannelExecute sends back what it reads, and
have a TCP client of the server's listener send 8 MB through it while it
reads the echo. An affected release on Windows stops within the first
megabyte, and the connection ends 30 s later; this one echoes all of it.
PLATFORMS. Measured with the new Test\sshinterop\SshFullDuplexTest: our
client and our server in one process, one remote forwarding, one
forwarded connection carrying 8 MB one way (a control), 8 MB echoed back,
and 8 MB each way at once, every octet checked. Before, on Win32 and
Win64, the echo and the two streams stopped with less than 1 MB of the
8 MB moved in either direction - nothing moved for 10 s - and freeing the
forwarding client after each raised (entry 146): 4 of the 9 checks red.
Now 9 of 9 in 3 runs of each of the four Windows builds (Win32, Win64,
each also with the guard memory manager HeapWatch, which reported no
heap fault). Linux64 passes before and after: there the sockets of a
loopback connection hold several megabytes and the readers keep up, so
no send waits for room even at 32 MB each way. The code is the same on
every platform, and over a link slower than the readers the sockets fill
on Linux too (not measured). While both directions wait for room the
transfer runs at about 1 MB/s each way on Windows in that test; one way
alone at 3.3 MB/s, as before.
NOT INVOLVED: what is sent and in what order; a send that finds room; the
key exchange and the ciphers.
NOT CHANGED:
- A send whose peer neither reads nor stops sending still fails once it
has waited SendTimeout.
- tAbstractSocket.SendAll without aOnStall waits as before, 100 ms at a
time; so does the RawSend of raw events of your own
(iSSHTransportRawEvents) unless it passes SSHRawSendStall to SendAll.
- The legacy units stSSHTransport, stSSHSocketClient and
stSSHSocketServer, which no longer ship, are not changed.
--------------------------------------------------------------------------------
SSH FORWARDING CLIENT: FREE AFTER THE CONNECTION FAILED
================================================================================
146. FIXED - freeing a TstSSHForwardingClient raised the SSH connection's
error, and returned while OnChannelExecute was still running, when the
connection's sends failed while a forwarded connection was being served
Since entry 139 Free ends each forwarded connection a thread of the
component serves by closing its channel, and waits until
OnChannelExecute has returned.
THE STEP THAT FAILED is that close. A client channel's Close raises when
its SSH_MSG_CHANNEL_CLOSE cannot be sent (and stays so - entry 144), and
Free let the exception out: it returned without waiting for the thread,
with the rest of the component's teardown not done. This happened when
the connection had failed - a send that ran out of SendTimeout, a
connection that ended - and the thread that reads it had not yet marked
its channels ended.
NOW Free catches the failure of that close. The channel is closing all
the same (Close makes it csClosing before it sends), which ends
OnChannelExecute, and Free waits for the thread and finishes as it does
otherwise.
WHO. Programs that free a TstSSHForwardingClient while OnChannelExecute
runs on a connection that has failed. TstSSHForwardingClientSocket ends
its forwarded connections by closing their TCP connection instead, and
was not affected.
THE DISCRIMINATING TEST: set up a remote forwarding with a
TstSSHForwardingClient whose OnChannelExecute waits while its channel is
csConnected; once it runs, have every send of the SSH client fail - an
OnRawSend that sets aResult to 0 does it - and free the component. An
affected release raises eExternalSendError from Free, and Free returns
with OnChannelExecute still running; this one returns once it has
returned, and raises nothing.
PLATFORMS. Measured with Test\sshinterop\SshFwdFreeTest, which gains that
step (5) and checks in every step that Free raises nothing. Before, step 5
failed both of its checks on Win32, Win64 and Linux64 (12 of 14 checks
passed on Windows, 7 of 9 on Linux64); now 14 of 14 on Win32 and Win64
(19 of 19 with HeapWatch) in 3 runs of each of the four Windows builds,
and 9 of 9 on Linux64. SshFullDuplexTest showed it first: before entry
145 its stalled connection made Free raise eSSHTransportError ("Transport
is not connected").
NOT INVOLVED: what is sent on the connection; the server.