Fix race between SendMessage and server-initiated key re-exchange
Fixes #1764
The race
Session.SendMessage checks _keyExchangeCompletedWaitHandle before acquiring _socketWriteLock. When the server initiates a key re-exchange in that window, the message loop thread resets the wait handle and sends the client's SSH_MSG_KEXINIT (under the same write lock). A data message that already passed the check then acquires the lock and goes out on the wire after our KEXINIT, violating RFC 4253 section 7.1 ("Once a party has sent a SSH_MSG_KEXINIT message ... it MUST NOT send any messages other than: Transport layer generic messages ...; Algorithm negotiation messages ...; Specific key exchange method messages").
Strict servers such as ProFTPD mod_sftp then fail the exchange or drop the connection, producing the two failure variants reported in #1764 (Message type 93 is not valid / connection drop with Key exchange failed).
The fix
SendMessage now re-checks the wait handle while holding the write lock and goes back to waiting when a re-exchange has started in the meantime. Re-checking under the lock is required: making the reset + KEXINIT send atomic is not sufficient, because a sender can already be blocked on the lock with a stale check result.
The packet is now also built entirely under the write lock, so a completing re-exchange can no longer swap _clientCipher/_clientMac/compression in the middle of building a packet.
The diff looks bigger than it is because the packet-building body moved unchanged into SendMessageWithinWriteLock — reviewing with whitespace changes hidden shows the actual change is the retry loop.
Why #1774 could not reproduce it
The repro attempt in #1774 ran against the OpenSSH test server. OpenSSH queues non-key-exchange output while a re-exchange is in progress and tolerates client data that slips in, so the race stays invisible there. ProFTPD mod_sftp does not tolerate it, so this PR adds an integration test running concurrent SFTP uploads against a ProFTPD container (alpine:3.24, ProFTPD 1.3.9c) configured to re-key every 1 MB (SFTPRekey required 3600 1), giving the race many trials per upload.
Evidence
Same environment (Docker Desktop/WSL2, net10.0), 4 concurrent uploads of 128 MB files, 3 attempts per run:
| Result | |
|---|---|
| Without the fix | 7 of 8 runs failed with SshConnectionException: Key exchange failed |
| With the fix | 4 of 4 runs passed |