Commit Graph

581 Commits (master)

Author SHA1 Message Date
John Safranek f50dc81ca0 Keep highwater callback results out of counts
HighwaterCheck() hands the application callback's result back through
wolfSSH_SendPacket() into wolfSSH_stream_read(), which returns it as a
byte count. A positive result now comes back as WS_SUCCESS.

- sftp: check buffer_set_size() in SendReadPacket's remainder loop, so
  a count over the request ends the read instead of overrunning out
- tests: cover positive and negative callback results in ByteHighwater

Issue: CID-662152
2026-11-22 16:10:11 -06:00
John Safranek 49b90dc0a6 examples: match [host]:port known_hosts names
ClientPublicKeyCheck() takes a ClientHostCtx with the port as well as
the host. Off port 22 it looks up [host]:port, as OpenSSH writes it,
and takes a bare host line only when no [host]:port line has a key of
that type. The refusal prints the [host]:port line to add.

- a name field may be a comma list or a hashed |1|salt|hash name
- client, scpclient, sftpclient, portfwd and tpmcertclient pass the port
- client-hostkey.test covers port, fallback, comma and hashed names
2026-11-21 15:33:37 -06:00
John Safranek 970020a152 internal: check an x509v3 host key's format name
The plain host key parsers check the blob's name against the negotiated
algorithm; the certificate parsers skipped it. A server could then name
a certificate as a plain key, and a host key callback that reads the
name, as the example clients do, never checked it against the host.

- Test a misnamed chain in test_ParseECCPubKeyCert, and name the P-384
  curve mismatch case for P-384
2026-11-21 15:33:37 -06:00
John Safranek 021c29ee53 tpmcertclient: check the host certificate name
tpmcertclient links the example client's common code and registers its
host key check, with the -h host as the context. The library verifies
the chain to the -A CA; the check requires the leaf to name the host.

- Test the name check in testsuite.test with keys/ certificates
- Add a tpm-ssh job refusing the certificate when asked for localhost

Issue: F-10588
2026-11-21 15:33:37 -06:00
John Safranek 799b9f38ca examples: check host keys against known_hosts
The client, scpclient and sftpclient accept a plain host key only when
a "host type key" line of ~/.ssh/known_hosts holds it. An unknown or
changed key is refused, printing its fingerprint and the line to add.
-Y accepts any key, with a warning.

- Check that an x509v3 host certificate names the host by DNS or IP
  subjectAltName, or by common name without one; -X waives a mismatch
- Pass -Y in the tests and CI jobs that connect to a throwaway server
- Seed known_hosts for openssh-interop.test from sshd's host keys
- Add client-hostkey.test for unknown, known, stale and changed keys

Issue: F-7620
2026-11-21 15:33:37 -06:00
John Safranek b5e489f6c5 wolfssh: decide known hosts the way OpenSSH asks
ClientPublicKeyCheck() follows StrictHostKeyChecking=ask. A missing or
empty known_hosts has no entries and prompts, creating ~/.ssh with mode
0700 on yes; one it cannot read refuses, as does EOF at the prompt. A
line holding the key accepts wherever it is in the file.

- Size the base64 host key buffer from the blob, so ML-DSA keys fit
- Keep scanning past a stale same-type line for the host
- Check the certificate IP only once known_hosts accepts, and let the
  override waive only the IP mismatch
- Cover these in regress.test and sshclient.test

Issue: F-14635, F-15505, F-15508, F-15664
2026-11-19 14:41:59 -06:00
John Safranek adfb41e4d8 tests: check ancestor name constraints on chains
A leaf below a peer-supplied subordinate CA must still meet the name
constraints of the CAs above that CA. The test verifies a three-cert
chain under a constrained root as both server and client. It needs
wolfSSL 5.9.4 or later, but not cert generation.

- keys/nc-*.der: constrained root, CA excluding a subtree, CA, 3 leaves;
  gen-nameconstraints.sh regenerates them, configure links them
- leaf in the permitted subtree verifies; leaves outside it and in the
  excluded subtree are rejected, alone and within the chain
- wolfSSL must reject each bad leaf with ASN_NAME_INVALID_E, so a
  broken fixture cannot pass as a rejection
- add WOLFSSL_V5_9_4 to internal.h

Issue: F-13950
2026-11-19 09:17:54 -06:00
John Safranek ba8217fb98 echoserver: classify scp exec with the library
wsExecStartCb() now takes an exec request as a transfer only when
wolfSSH_ChannelCommandIsScp() does, the same test wolfSSH_accept()
diverts on. A command such as "scpbackup" is served as a session.

- tests: test_wolfSSH_SCP_ExecNotScp echoes data over a "scpbackup"
  exec channel

Issue: F-14206
2026-11-18 17:02:56 -06:00
John Safranek 9cd33e45e9 echoserver: one forward at a time, ports in range
wolfSSH_FwdDefaultActions() serves one forward per session. A
tcpip-forward or direct-tcpip setup that arrives while a listener or
connection is live is refused, and so is a port over 65535, before
anything narrows it to 16 bits. A cancel that lands while a forwarded
connection is open closes only the listener; closing that connection's
channel then frees the slot. server_worker() closes what is left.

- a direct forward whose target hung up may be replaced by a new one
- REMOTE_CLEANUP drops an accepted connection no channel carries yet,
  and refuses a cancel while a direct forward is still connecting
- a channel close closes the forwarded connection only once it is
  CONNECTED, so a late close of the slot's previous channel spares a
  connection still waiting for its own
- a closed forward goes to LISTEN with a listener, else to INIT
- a forwarded connection that ends frees originName; a remote forward
  keeps hostName
- a new setup frees stale hostName and originName and clears the
  slot's channel id
- server_worker() closes fwdCtx listenFd and appFd at teardown
- api: test_wolfSSH_FwdEchoserverSlot drives an in-process echoserver
  through the limit, the port bound, cancel, and a late close, and
  reaches the forward over IPv4 even under TEST_IPV6

Issue: F-16817, F-16818
2026-11-18 11:39:45 -06:00
John Safranek 5f27477b5e scp: Reset the sink chunk length per read
ReceiveScpFile clears scpFileBufferSz before it reads, so an empty file
hands the receive callback a zero-length chunk. A source run leaves the
buffer capacity in that field, and a later sink of an empty file on the
same session passed the whole stale buffer to the callback as data.

- ReceiveScpFile: zero scpFileBufferSz before the early return
- add wolfSSH_TestDoScpSink under WOLFSSH_TEST_INTERNAL
- unit: ScpSinkEmptyFileAfterSource checks the empty-file chunk size
2026-11-18 10:07:56 -06:00
John Safranek 73c5762559 scp: Wipe file data in the SCP transfer buffer
The sink wipes each received chunk once the receive callback has it,
and the source wipes the bytes it has sent. Freeing the buffer wipes
its full DEFAULT_SCP_BUFFER_SZ allocation, since scpFileBufferSz holds
only the last chunk length on the sink side and is zero by teardown.
ReceiveScpFile zeroes the buffer when it allocates it, as ScpSourceInit
does, so no stale heap bytes sit past the received chunk.

- DoScpSink: zero the chunk before resetting scpFileBufferSz
- DoScpSource: zero the sent span after compacting the buffer
- ScpSourceInit, SshResourceFree: zero the whole allocation
- add wolfSSH_TestDoScpSource under WOLFSSH_TEST_INTERNAL
- tests: check the buffer is clear after the SCP rekey transfers
- unit: ScpFileBuffer_zeroedOnFree reads the buffer back after
  SshResourceFree and after ScpSourceInit replaces it

Issue: F-8847, F-8844, F-10595
2026-11-18 10:07:56 -06:00
John Safranek 5fe8c84f06 scp: guard the remote path in the client command
As with OpenSSH scp, the client sends the remote path to the server's
shell as given, with "--" before a path starting with "-". A control
character in the path is refused with WS_BAD_ARGUMENT, since it would
end or split the command.

- wolfSSH_SCP_from works on a copy of dst, not the caller's const string
- wolfscp.h: the remote shell expands the path; callers quote it
- scpclient: test only for WS_FATAL_ERROR in the retry loop
- tests: add MakeScpCmd cases, parsed back off Windows, and check
  SCP_from leaves dst unchanged

Issue: F-12624, F-13319, F-12546
2026-11-17 09:40:16 -06:00
John Safranek d80696fb00 scp: warn on special files and 4 GiB files
The default send callback skips a FIFO, socket, device, or a file of
4 GiB or more with a warning. On WS_SCP_CONTINUE, DoScpSource sends a
warning record and asks a recursive walk for its next entry; a skipped
single file or recursive root ends the transfer. As in OpenSSH scp,
both sides fail a transfer after a warning, the source with exit 1.

- wFopenNoFollow opens non-blocking and refuses a non-regular file, so
  a single-file FIFO request cannot block
- a callback error goes out as a fatal (0x02) record and stays the
  session error; mid-file the transfer is dropped instead
- ReceiveScpMessage handles one record per call and keeps the rest of
  the read; a record cut off by EOF also fails the transfer
- the warning is cut to fit the sink's message buffer, and DoScpSource
  clears scpFileSz with the other per-file state
- tests: special files, a 4 GiB + 1 file, warning and error records,
  skips and unopenable sources on each side, mid-file skips

Issue: F-15503, F-15507
2026-11-17 09:40:16 -06:00
John Safranek 6525fef9c2 scp: fix server command and record parsing
ParseScpCommand stops looking for options once -t or -f has taken the
rest of the command as the path, and skips a "--" before it. A target
with no directory part names a file in the current directory, unless
it names an existing directory, which stays the target as in OpenSSH.

- ScpCheckForRename keeps a bare name whole and uses "." as its base,
  and leaves ".", "..", and an existing directory as they are
- GetScpFileMode checks the start index and the full mode field before
  reading
- DoScpRequest returns WS_SUCCESS when data follows a finished transfer
- tests: add ParseScpCommand cases, with directory targets and path
  checks skipped on Windows, and GetScpFileMode index cases
- scp.test: copy to and from "." in both directions

Issue: F-15504, F-15501, F-11655, F-13320
2026-11-17 09:40:16 -06:00
John Safranek b5f20a191c scp: fix no-filesystem callback file metadata
The built-in NO_FILESYSTEM SCP callbacks now start each file with fresh
state, abort a send whose file name cannot be extracted, and abort a
received file that does not fit the buffer.

- wsScpRecvCallback NEW_FILE terminates the name, sets nameSz and
  resets idx and fileSz
- wsScpRecvCallback aborts a file or part larger than the buffer
- wsScpSendCallback resets idx and aborts on an ExtractFileName error
  before the status callback and the name compare
- wsScpSendCallback documents that it reports mTime as aTime, since
  ScpBuffer has no access time and 0 would stamp the epoch
- tests: two files in one session, a bad peer file name, the reported
  times, a reused send buffer and oversize files

Issue: F-11667, F-13902, F-13906
2026-11-17 08:54:08 -06:00
John Safranek 3ecc542982 sftp: reply to a bad RMDIR path before logging it
RecvRMDIR answers a path GetAndCleanPath cannot resolve with FAILURE
straight away, as RecvMKDIR does, so the failure log never prints the
unfilled dir buffer.

- TestSftpFailedRequestsAnswered sends RMDIR an over-long path
2026-11-16 13:18:42 -06:00
John Safranek d741ce3c19 sftp: answer a malformed request with BAD_MESSAGE
A server handler that cannot parse its request, because a field runs
past the end of the packet, queues an SSH_FX_BAD_MESSAGE status for the
request id through SFTP_SendBadMessage instead of returning silently.

- Covers REALPATH, OPEN, OPENDIR, MKDIR, RMDIR, REMOVE, READ, WRITE,
  READDIR, STAT, LSTAT, FSTAT, SETSTAT, FSETSTAT and CLOSE
- The WRITE handle and RENAME path failures now say BAD_MESSAGE, not
  FAILURE
- CLOSE reads its handle length with GetSize
- TestSftpFailedRequestsAnswered sends truncated packets to each handler
2026-11-16 13:18:42 -06:00
John Safranek 8ae0df0d05 sftp: answer every failed server request
The SFTP server handlers queue an SSH_FXP_STATUS for a request they
refuse, so the client is never left waiting on its request id.
A request's attribute flag bits outside the v3 set are rejected, which
draft-ietf-secsh-filexfer-02 section 5 calls a protocol error; reply
parsing still ignores them.

- OPEN, OPENDIR, MKDIR, REALPATH and REMOVE answer FAILURE for a path
  that does not resolve, such as one of WOLFSSH_MAX_FILENAME bytes
- FSTAT and READDIR answer FAILURE for a wrong-size or unknown handle
- READ clamps a length over WOLFSSH_MAX_SFTP_RW to a short read, as
  OpenSSH's sftp-server does and filexfer-02 section 3 allows
- OPEN, MKDIR, SETSTAT and FSETSTAT answer BAD_MESSAGE for attributes
  that do not parse
- Add TestSftpFailedRequestsAnswered and a REALPATH test hook

Issue: F-17050, F-17051, F-17076, F-17077
2026-11-16 13:18:42 -06:00
John Safranek 74f3498044 echoserver: unwind all echoserver_test() failures
ES_ERROR now jumps to an echoserverFail label instead of returning, and
the label frees whatever is set up at that point: the listen socket,
unconsumed option lists, keyboard prompts, doneLock, pwMapList, the CTX,
the TPM host key and wolfSSH_Init(). The test harness keeps running
after echoserver_test() returns, so these were live-process leaks.

- pwMapList and kbAuthData are zeroed on entry; flags track doneLock
  and wolfSSH_Init(), each set only once its init succeeds
- usage errors take the same path and keep MY_EX_USAGE
- loop failures free their ssh and thread context before the jump
- drop the inline frees the cert-store and prompt paths now duplicate
- api.c: drive usage, algo-list and key-load failures for LSan; the
  key-load case is skipped on Zephyr and Nucleus, which lack -j

Issue: F-17053
2026-11-15 23:32:58 -06:00
John Safranek c4f6f8972e sftp: fix client state teardown and results
A failed automatic negotiation now frees only the VERSION receive
state, leaving the calling operation's state for it to clean up.
wolfSSH_SFTP_ClearState releases what LS, GET, and PUT hold across
calls.

- SFTP_STAT fails with WS_BUFFER_E on a malformed ATTRS reply
- RMDIR returns WS_PERMISSIONS on a permission failure and sets
  WS_SFTP_STATUS_NOT_OK for other statuses
- ClearState frees the LS name list and closes the local file of an
  interrupted GET or PUT
- tests: unit cases for each, with a guard allocator catching the
  write after free and the LS leak

Issue: F-17045, F-17049, F-17046, F-17048
2026-11-15 22:14:53 -06:00
John Safranek 1e36e591f7 tests: gate allocator hooks on wolfSSL memory
wolfSSL defines wolfSSL_SetAllocators() and wolfSSL_GetAllocators() only
under USE_WOLFSSL_MEMORY, so a wolfSSL built with NO_WOLFSSL_MEMORY or
XMALLOC_USER left unit.test and regress.test unable to link. The
capturing-allocator tests in unit.c and the SFTP allocation-failure
tests in regress.c now also require USE_WOLFSSL_MEMORY.
2026-11-15 14:39:38 -06:00
John Safranek 7a257c6ad5 agent: bound add-identity key type without wrap
DoAddIdentity() compares the key-type length against the bytes left
rather than adding it to the offset, so a length near UINT32_MAX can no
longer wrap past the check.

- api.c sends an ADD_IDENTITY reply with a 0xFFFFFFFF key-type length

Issue: F-11937
2026-11-15 14:39:38 -06:00
John Safranek 71918b0feb agent: free the reply SendFailure builds
SendFailure() wipes and frees the reply once it is bundled, as the
other senders do. wolfSSH_AGENT_SignRequest() gets one through
DoUnimplemented() for a reply id it does not handle, and dropped the
pointer at cleanup.

- api.c drives SignRequest with an EXTENSION_FAILURE reply and, under
  USE_WOLFSSL_MEMORY, counts allocations across the second exchange

Issue: F-16054
2026-11-15 14:39:38 -06:00
John Safranek f7166b7069 agent: wipe agent buffers before freeing them
AgentMsgFree() force-zeroes and releases agent->msg, which can hold
key blobs, comments, data to sign and signatures. Every site that freed
agent->msg now goes through it, and the context teardown wipes with
WS_FORCEZERO, which the compiler cannot drop before the free.

- AgentInit() failure path and wolfSSH_AGENT_free() use WS_FORCEZERO
  instead of WMEMSET
- api.c: a free hook checks the sign-request message and one left
  outstanding at wolfSSH_free() are wiped before release

Issue: F-13999, F-14000
2026-11-15 14:39:38 -06:00
John Safranek 6ada04294a internal: Cap the number of open channels
DoChannelOpen() refuses a peer CHANNEL_OPEN with OPEN_RESOURCE_SHORTAGE
once WOLFSSH_MAX_CHANNELS channels are open, before allocating anything.
Each channel holds a window-sized buffer, so uncapped forward or agent
opens could exhaust memory. The session stays up after a refusal.

- WOLFSSH_MAX_CHANNELS defaults to 64 and is overridable at build time
- regress test opens channels to the cap, checks the next is refused
  and that a close makes room again
- regress tests that open a second channel build only with a cap of at
  least 2; below that, TestSecondSessionChannelRejected expects
  OPEN_RESOURCE_SHORTAGE

Issue: F-12620
2026-11-13 13:45:08 -06:00
John Safranek 57dfc44c93 sftp: send the caller's attributes with MKDIR
wolfSSH_SFTP_MKDIR() encodes atr with SFTP_SetAttributes(), as the
other attribute-carrying requests do. A NULL atr requests permissions
0777, the request every MKDIR used to send.

- sftpclient: pass NULL instead of an uninitialized atr
- api: a 0700 request makes a 0700 directory on the echoserver

Issue: F-14634
2026-11-13 11:32:45 -06:00
John Safranek 8fd8f3fd15 Make wolfSSH_GetText output the same everywhere
wolfSSH_GetText() builds the text locally and copies it into str, so
str is always terminated and the return is the full text length,
whichever function WSNPRINTF maps to. A return of strSz or more means
truncation; an unknown id or unnegotiated KEX gives "" and 0.

- echoservers: test truncation with ret >= strSz
- api: empty, exact, truncated, and DH texts

Issue: F-17102
2026-11-13 11:32:45 -06:00
John Safranek 52014ac166 Ignore a NULL session in terminal resize setters
wolfSSH_SetTerminalResizeCb() and wolfSSH_SetTerminalResizeCtx() do
nothing for a NULL session, like the other session setters.

- api: NULL and valid session through both setters

Issue: F-17101
2026-11-13 11:32:45 -06:00
John Safranek d6ff22e140 Fill a caller buffer for ASN.1 public keys
DoAsn1Key() encodes a public key into the caller's *out when one is
supplied, as the private-key path already does, and returns WS_BUFFER_E
when *outSz is too small. It allocates only when *out is NULL.

- GetPubKeyOut() picks the buffer for every public-key encoder
- api: RSA, ECC, Ed25519 and ML-DSA-44 reads into a caller buffer, and
  one byte short

Issue: F-11652
2026-11-13 11:32:45 -06:00
John Safranek b256895f04 Send the caller's payload in wolfSSH_SendIgnore
wolfSSH_SendIgnore() carries buf in the SSH_MSG_IGNORE it sends. A
NULL buf with a zero bufSz still sends 128 zero bytes, and a NULL buf
with a nonzero size is WS_BAD_ARGUMENT. So is a payload whose packet,
with worst-case padding and MAC, would pass the peer's MAX_PACKET_SZ
check; this also keeps the PreparePacket() size sums from wrapping.

- internal: MAX_IGNORE_DATA_SZ bounds the payload like the peer check
- regress: check the payload and the NULL default on the wire
- regress: 0xFFFFFFFB and one over the bound fail cleanly
- regress: the largest payload reaches a peer, plain and keyed, with
  the byte highwater off so a low DEFAULT_HIGHWATER_MARK cannot rekey

Issue: F-7512
2026-11-13 11:32:45 -06:00
John Safranek 63cf1ff4e9 internal: wipe packets DoPacket refuses
DoReceive() wipes a packet that DoPacket() refuses before dispatch: a
message id the state does not allow, such as a USERAUTH_REQUEST after
auth, padding under the minimum, or a length that overflows. Only a
pending auth keeps its packet, since the next call dispatches it again.

- tests: a post-auth password request and a short-padding packet are
  wiped; a pending password request is kept until it completes

Issue: F-17105
2026-11-12 16:55:41 -06:00
John Safranek 9858b19269 internal: pad client userauth secrets to 64 bytes
The client pads a password USERAUTH_REQUEST and a keyboard-interactive
INFO_RESPONSE up to a multiple of 64 bytes, as OpenSSH does, so the
packet length no longer tracks the secret's length to the cipher block.

- BundlePacketPad() adds whole blocks of padding up to a bucket
- a packet held during our rekey keeps its bucket in keyingHold and is
  padded to it on release
- regress test checks 1 to 64 byte secrets over the none cipher,
  AES-CTR with HMAC, and AES-GCM, sent directly and after a hold

Issue: F-13390
2026-11-12 16:31:35 -06:00
John Safranek 7414925b98 internal: refuse secret auth over the none cipher
With WOLFSSH_ALLOW_NONE_CIPHER, a server whose NEWKEYS installed the
none cipher in either direction answers password and
keyboard-interactive requests, and an INFO_RESPONSE after a rekey to
none, with USERAUTH_FAILURE before the userauth callback sees a secret,
and leaves both methods out of the method list.

- DoNewKeys() and SendNewKeys() record a none cipher per direction
- a refused request or response clears authId, so a later INFO_RESPONSE
  is rejected
- unit tests drive both methods with each direction cleartext, and a
  rekey to none with a prompt outstanding

Issue: F-10578
2026-11-12 16:31:35 -06:00
John Safranek e1216a11dd internal: enforce accepted-key list in userauth
DoUserAuthRequestPublicKey() refuses a public key algorithm whose name
is not on algoListKeyAccepted, the list the server advertises in
server-sig-algs (RFC 8308 section 3.1). A NULL list leaves only the
compiled-in check.

- Match by name: the three OpenSSH RSA certificate names share one ID
- Bind an rsa-sha2-*-cert signature to its name's hash; the legacy
  ssh-rsa-cert-v01 takes any RSA hash, as OpenSSH's sshd does
- Advertise ssh-rsa-cert-v01 only where an ssh-rsa signature is accepted
- Pick the client's RSA certificate name from the certificate names in
  server-sig-algs
- Add TestUserAuthPkHonorsAcceptedList and two OpenSSH RSA certificate
  tests to the regress tests

Issue: F-16810
2026-11-11 21:57:43 -06:00
John Safranek e9deb96762 Anchor the key type checks in ReadKey_file
wolfSSH_ReadKey_file() now classifies a key file by comparing only its
first bytes against each SSH key type name and the OpenSSH and PEM
begin markers, rather than searching the whole file, which may be a
private key.

- match "ssh-mldsa" so composite ML-DSA public keys, such as
  ssh-mldsa44-es256@wolfssl.com, load as SSH format
- add test_wolfSSH_ReadKey_file_mldsaPub to api.c

Issue: F-14633, F-14666
2026-11-11 16:47:00 -06:00
John Safranek e2454ca67d tests: retry the drain peer's read on a timeout
The forked peer in RunDrainMidRekey() sets a 100 ms SO_RCVTIMEO and
retries its read. macOS can miss waking a read() that blocks just as
the other end half closes, leaving the peer asleep past the drain's
10 s deadline and failing DrainFailedRekey or DrainDisconnectMidRekey.
A missed wakeup now costs one timeout.
2026-11-11 14:12:41 -06:00
John Safranek d8d2140121 ssh: stop reading behind a large output backlog
wolfSSH_worker() and wolfSSH_stream_read() now flush before reading
once more than WOLFSSH_MAX_OUTPUT_BACKLOG bytes are queued, and return
WS_WANT_WRITE without reading if the flush leaves it over. A peer that
never reads can no longer grow outputBuffer one reply per packet.

- WOLFSSH_MAX_OUTPUT_BACKLOG defaults to two MAX_PACKET_SZ, overridable
- A smaller backlog still reads first, keeping the PR 856 order
- regress: unknown-id and GLOBAL_REQUEST floods with blocked sends stop
  at the cap and drain once the peer reads

Issue: F-16808
2026-11-11 12:35:23 -06:00
John Safranek b5e37bef91 ossh: keep decoder errors and the caller's heap
GetOpenSshKeyEd25519 now returns its parse errors as they are and
reports a wolfCrypt failure as WS_ED25519_E instead of WS_ECC_E. The
OpenSSH key decoders take the WS_KeySignature heap and initialize the
key with it, where they used NULL or the zeroed key's own heap field.

- tests: check the Ed25519 decoder errors and the heap of a decoded
  key

Issue: F-11653, F-11656
2026-11-10 14:58:50 -06:00
John Safranek 18dd82dd68 ossh: reject a misaligned OpenSSH private section
GetOpenSshKey checked the padding only when the private section was a
whole number of blocks, so a misaligned section, or one ending in junk,
loaded. It now rejects a section that is not a multiple of MIN_BLOCK_SZ,
as OpenSSH does, and compares every pad byte before deciding.

- tests: parse crafted Ed25519 keys with good, missing, junk and bad
  padding

Issue: F-12551, F-13925
2026-11-10 14:58:50 -06:00
John Safranek 2cc0d7d3f7 internal: keep rekey windows to transport only
RFC 4253 section 7.1 allows only transport messages from a party's
KEXINIT until its NEWKEYS. BundlePacket() holds anything else framed
in our window and SendNewKeys() sends it behind our NEWKEYS, and
IsMessageAllowed() refuses it from a peer in its window.
wolfSSH_OutputPending() does not count held output.

- Held: replies to requests in flight before our KEXINIT, and agent
  and forwarding channel opens, which still report success
- A hold past DEFAULT_KEYING_HOLD_SZ, or a failed release, sends
  DISCONNECT and ends the session
- wolfSSH_shutdown() runs the rekey until its held teardown goes out;
  HalfCloseAndDrain() runs it to the end unless the session is over
- The release reserves the output queue once, not once per packet
- regress, unit: cover both gates, delivery, the hold cap, a failed
  release, a channel open, the release allocations, and a shutdown and
  a drain mid-rekey

Issue: #1381
2026-11-10 14:34:09 -06:00
John Safranek ef7fbf5913 internal: refuse an unsolicited INFO_RESPONSE
The server takes a keyboard-interactive INFO_RESPONSE only while an
INFO_REQUEST is outstanding, and refuses any other as fatal, as it
does one outside keyboard-interactive auth. A response kept for
redispatch on WS_AUTH_PENDING keeps the exchange outstanding.

- DoUserAuthInfoResponse() requires kbSetupPending and clears it only
  once the response is consumed, not on WS_AUTH_PENDING
- SendUserAuthKeyboardRequest() arms it once the request is delivered,
  even if the highwater callback then fails; a blocked setup re-arms it
- unit: unsolicited responses after no request, a declined setup, and
  failed or partial rounds; would-block retries; a highwater failure
- regress: the INFO_RESPONSE harness marks the exchange outstanding

Issue: F-17085
2026-11-10 10:31:31 -06:00
John Safranek 505df91780 Free only the KEX keys that were initialized
SendKexDhReply and the ECDH and Curve25519 KeyAgree functions now
track which keys were initialized and free only those. A host-key
format with no loaded key, or a failed small-stack allocation, no
longer hands never-initialized storage to the wolfCrypt free.

- sigKeyBlockFull gains keyInit, set by SendKexGetSigningKey
- per-key Inited flags in the client and server KeyAgree functions
- regress: no matching host key frees nothing (WOLF_CRYPTO_CB_FREE)
- unit: server KeyAgree survives an allocation failure (small stack)

Issue: F-11675, F-11939
2026-11-08 22:12:25 -06:00
John Safranek fc5d2631f9 ssh, internal: send one KEXINIT per key exchange
RFC 4253 7.1 allows one KEXINIT from each side per key exchange.
wolfSSH_TriggerKeyExchange() is now a no-op returning WS_SUCCESS while
any keying is in progress, and SendKexInit() skips once this side's
KEXINIT is out, so the stored copy feeding the exchange hash stays put.

- covers the highwater callback, whose byte and message marks can both
  fire in one rekey
- covers the window after SendNewKeys() clears the self-keying flag
  while the peer's NEWKEYS is still due
- regress: second trigger, nested highwater and NEWKEYS-window tests

Issue: F-16775
2026-11-08 17:47:44 -06:00
John Safranek 77283a6f41 Verify RSA host key signatures by encoding
DoKexDhReply() now checks an RSA host key signature over H the same way
userauth does: it hashes H, encodes the DigestInfo, and compares whole
blocks with wolfSSH_RsaVerify() per RFC 8332 Section 5.3, in place of
wc_SignatureVerify(). This also restores ssh-rsa host keys on wolfSSL
5.9.2 and later, which refuse SHA-1 in wc_SignatureVerify().

- tests: ssh-rsa host key handshake, valid and corrupted signature
- tests: host key signature with a trailing byte is rejected

Issue: F-17075
2026-11-08 16:42:27 -06:00
John Safranek 880ace69ad Refuse RSA signatures longer than the key
wolfSSH_RsaVerify() now returns WS_RSA_E when the signature is longer
than the modulus, so trailing bytes after a valid signature no longer
verify. A shorter signature is still left-padded with zeros.

- tests: unit test with one byte appended to a valid signature
2026-11-08 16:42:27 -06:00
John Safranek 788a0c3279 Reject UINT32_MAX before size + 1 allocations
DoSshPubKey() and wolfSSH_SetUsernameRaw() allocate a word32 size plus
one for a null terminator. Both now return WS_BAD_ARGUMENT for a size
of UINT32_MAX, where that sum wraps to a zero-byte allocation.

- api.c: SetUsernameRaw and ReadKey_buffer reject UINT32_MAX

Issue: F-15662, F-15663
2026-11-08 14:47:53 -06:00
John Safranek fa1696714d io: map ECONNABORTED on send to a closed socket
wsEmbedSend() returns WS_CBIO_ERR_CONN_CLOSE for SOCKET_ECONNABORTED,
matching wsEmbedRecv(), so an aborted connection during a send sets
isClosed instead of being reported as a general error.

- unit: a send failing with ECONNABORTED closes the session

Issue: F-13903
2026-11-08 14:04:58 -06:00
John Safranek d50e1fabd5 Treat a 0 from the recv callback as a hang-up
GetInputData() now fails with WS_SOCKET_ERROR_E and marks the session
closed when the recv callback returns 0, as GetInputLine() already
does. A custom callback reporting an orderly shutdown no longer spins
DoReceive() forever.

- tests: DoReceive with a callback that always returns 0

Issue: F-14397
2026-11-08 14:04:58 -06:00
John Safranek 8e4bfc188a Wipe the client channel name before freeing it
The client keeps its exec command line, which can carry credentials,
in ssh->channelName. FreeChannelName() wipes and frees it, mirroring
FreeChannelCommand() on the server side.

- use it in SshResourceFree() and at the three wolfSSH_SetChannelType()
  release sites
- unit test reads back each freed name through a retaining allocator

Issue: F-14691
2026-11-08 13:40:28 -06:00
John Safranek c0a36ce31f internal: keep userauth verifier error codes
The public-key userauth verifiers now return the error from the step
that failed, and map only the wolfCrypt key decode itself to
WS_CRYPTO_FAILED. The X.509 ECDSA verifier checks the signature's
algorithm name like its siblings.

- EccCert and Ed25519: argument, allocation, parse and type errors
  keep their own codes
- Rsa and RsaCert: a hash with no OID, or a failed encode, is
  WS_CRYPTO_FAILED before the verify
- EccCert: accept the declared x509v3 name or RFC 6187's ecdsa-sha2
  name for the same curve; anything else is WS_INVALID_ALGO_ID
- unit: cover each case; add wolfSSH_TestDoUserAuthRequestEccCert

Issue: F-11654, F-12544, F-15665
2026-11-07 09:40:21 -06:00