From e932d0972e4a14f054442246b41b2f1a15a7b79b Mon Sep 17 00:00:00 2001 From: John Safranek Date: Wed, 18 Nov 2026 09:49:56 -0800 Subject: [PATCH 1/4] Count the keyboard-interactive request fields SendUserAuthRequest() writes the keyboard-interactive language tag and submethods without counting them in the payload size it reserves. The padding reserve hid the 8 bytes for 16-byte block ciphers; an 8-byte block cipher overruns the output buffer. - Add the two fields to payloadSz for ID_USERAUTH_KEYBOARD - Bound the AEAD tag write in BundlePacketPad() as the MAC write is --- src/internal.c | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/src/internal.c b/src/internal.c index 71c540ee5..10c209669 100644 --- a/src/internal.c +++ b/src/internal.c @@ -16103,14 +16103,17 @@ static int BundlePacketPad(WOLFSSH* ssh, word32 padBucket) else { #ifndef WOLFSSH_NO_AEAD idx += paddingSz; - ret = EncryptAead(ssh, - ssh->outputBuffer.buffer + ssh->packetStartIdx + LENGTH_SZ, - ssh->outputBuffer.buffer + ssh->packetStartIdx + LENGTH_SZ, - ssh->outputBuffer.length - ssh->packetStartIdx + paddingSz - - LENGTH_SZ, - output + idx, - ssh->outputBuffer.buffer + ssh->packetStartIdx, - LENGTH_SZ); + if (idx + ssh->macSz > ssh->outputBuffer.bufferSz) + ret = WS_BUFFER_E; + else + ret = EncryptAead(ssh, + output + ssh->packetStartIdx + LENGTH_SZ, + output + ssh->packetStartIdx + LENGTH_SZ, + ssh->outputBuffer.length - ssh->packetStartIdx + + paddingSz - LENGTH_SZ, + output + idx, + output + ssh->packetStartIdx, + LENGTH_SZ); idx += ssh->macSz; #else ret = WS_INVALID_ALGO_ID; @@ -23699,6 +23702,12 @@ int SendUserAuthRequest(WOLFSSH* ssh, byte authType, int addSig) ret = PrepareUserAuthRequestPublicKey(ssh, &payloadSz, &authData, keySig_ptr); } +#ifdef WOLFSSH_KEYBOARD_INTERACTIVE + else if (authId == ID_USERAUTH_KEYBOARD) { + /* language tag and submethods */ + payloadSz += LENGTH_SZ * 2; + } +#endif else if (authId != ID_NONE && #ifdef WOLFSSH_KEYBOARD_INTERACTIVE authId != ID_USERAUTH_KEYBOARD && From 71b440b3a277682cd5326bff40ddb35178aa2baa Mon Sep 17 00:00:00 2001 From: John Safranek Date: Fri, 20 Nov 2026 10:35:30 -0800 Subject: [PATCH 2/4] Count the X.509 ML-DSA certificate length PrepareUserAuthRequestMlDsaCert() leaves out the certificate length that BuildRFC6187Info() writes, so the userauth request reserves four bytes fewer than it sends. The padding reserve hides the shortfall today, with little to spare under an 8-byte block cipher. --- src/internal.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/internal.c b/src/internal.c index 10c209669..1516d6450 100644 --- a/src/internal.c +++ b/src/internal.c @@ -22960,6 +22960,7 @@ static int PrepareUserAuthRequestMlDsaCert(WOLFSSH* ssh, word32* payloadSz, if (ret == WS_SUCCESS) { *payloadSz += (LENGTH_SZ + authData->sf.publicKey.publicKeyTypeSz) + + LENGTH_SZ + /* certificate length */ (UINT32_SZ * 2); /* certificate and ocsp counts */ if (authData->sf.publicKey.hasSignature) { From ba1380a29007b333d46b811725a85082ecab1942 Mon Sep 17 00:00:00 2001 From: John Safranek Date: Mon, 16 Nov 2026 15:48:10 -0800 Subject: [PATCH 3/4] Add the chacha20-poly1305 cipher Implement chacha20-poly1305@openssh.com, also offered under the IETF name chacha20-poly1305, as OpenSSH's PROTOCOL.chacha20poly1305 defines it. It is first in the default cipher list. The packet length is encrypted with its own key, and the sequence number is the nonce. - Key a payload and a header ChaCha20, in a union with the Aes, from 64 bytes of KDF output; DoReceive() decrypts the length apart and checks the tag before decrypting the payload - WOLFSSH_NO_AEAD is set only when both AES-GCM and chacha20-poly1305 are disabled; a wolfSSL built with NO_AES is still refused - With strict KEX off on the CTX, the default list leaves chacha out; Terrapin tests needing an unauthenticated sequence number require GCM - Add a known-answer test, damaged-record and Terrapin tests, padding and keyboard request sizing tests, and an openssh-interop.test check --- README.md | 23 ++- scripts/openssh-interop.test | 74 ++++++++ src/internal.c | 336 +++++++++++++++++++++++++++++---- src/ssh.c | 8 + tests/api.c | 51 +++++ tests/regress.c | 265 +++++++++++++++++++++++--- tests/unit.c | 351 ++++++++++++++++++++++++++++++++--- wolfssh/internal.h | 45 ++++- wolfssh/ssh.h | 8 +- 9 files changed, 1069 insertions(+), 92 deletions(-) diff --git a/README.md b/README.md index d1a0d2776..5dcc3472e 100644 --- a/README.md +++ b/README.md @@ -834,17 +834,30 @@ attacker splicing packets into the unauthenticated initial exchange to shift the sequence numbers. A message that arrives out of turn ends the connection with SSH_MSG_DISCONNECT rather than being ignored. -Note that wolfSSH offers neither `chacha20-poly1305@openssh.com` nor the -`*-etm@openssh.com` MACs, the modes whose nonce comes from the sequence -number. The full silent-truncation form of Terrapin needs one of those, so it -was never reachable here; strict KEX closes the sequence-number shift the -attack is built on. +The full silent-truncation form of Terrapin needs a mode whose nonce comes +from the sequence number, such as chacha20-poly1305, which wolfSSH offers +first by default as both `chacha20-poly1305` and +`chacha20-poly1305@openssh.com`. Strict KEX is what stops it: it closes the +sequence-number shift the attack is built on. The AES modes carry chained +cipher state, so a deletion there breaks decryption instead. + +Strict KEX is only in force when both sides offer it. A chacha20-poly1305 +session without it can have the first packet after SSH_MSG_NEWKEYS deleted +unnoticed. That happens with a peer that never sends the marker, such as +OpenSSH before 9.6, and when the caller turns strict KEX off. An application +that has to talk to such peers can take chacha20-poly1305 out of the cipher +list: + + wolfSSH_CTX_SetAlgoListCipher(ctx, "aes256-gcm@openssh.com,aes256-ctr"); A caller that has to interoperate with a peer that mishandles the marker can turn it off on the context: wolfSSH_CTX_SetStrictKex(ctx, 0); +Sessions made from that context leave chacha20-poly1305 out of the default +cipher list. A cipher list the caller set is used as given. + Each session copies the setting when it is made, so the change affects only later sessions; to opt out one connection, turn it off, make that session, and turn it back on. Only the initial KEXINIT decides whether the mitigation diff --git a/scripts/openssh-interop.test b/scripts/openssh-interop.test index 92dc16b02..8a1bb8952 100755 --- a/scripts/openssh-interop.test +++ b/scripts/openssh-interop.test @@ -14,6 +14,10 @@ # ssh-agent through it, 1c checks that it forwards ports only with -F and # connects only to allowed destinations. # +# Parts 1 and 2 also check that chacha20-poly1305@openssh.com is the cipher +# negotiated. It is the AEAD whose tag covers the sequence number, so it is +# the one a counter disagreement fails on. +# # Part 3 has the wolfSSH client authenticate to sshd with an RSA key held # by OpenSSH's ssh-agent. The client has only the public half; the agent # makes the signature. @@ -184,6 +188,72 @@ esac mkdir -p "$work_dir" || exit 1 +# Whether this wolfSSH build has chacha20-poly1305; -E lists the algorithms +# without connecting. +wolfssh_chacha=0 +if ./examples/client/client -E -u x 2>&1 | \ + grep -q ': chacha20-poly1305@openssh.com$'; then + wolfssh_chacha=1 +fi + +# The cipher list one side proposed, from the OpenSSH debug log $1. $2 is +# local for OpenSSH's own proposal, peer for wolfSSH's. +cipher_proposal() { + grep -A 4 "$2 .* KEXINIT proposal" "$1" | grep -m 1 'ciphers ctos:' | \ + sed 's/.*ciphers ctos: //; s/ .*//' +} + +# Check the OpenSSH debug log $1 for chacha20-poly1305@openssh.com in both +# directions. $2 names the OpenSSH end for the messages, and $3 is the +# proposal the client made: local when OpenSSH is the client, peer when +# wolfSSH is. The client's first choice that the server offers is what the +# KEX picks, so chacha20-poly1305 is required only when that is it. wolfSSH +# lists it first; an OpenSSH under a crypto policy or a ssh_config may not. +check_chacha() { + [ $wolfssh_chacha -eq 1 ] || { + echo "this wolfSSH build has no chacha20-poly1305, not checking it" + return 0 + } + + cc_client=`cipher_proposal "$1" $3` + if [ "$3" = local ]; then + cc_server=`cipher_proposal "$1" peer` + else + cc_server=`cipher_proposal "$1" local` + fi + + case ",`cipher_proposal "$1" peer`," in + *,chacha20-poly1305@openssh.com,*) ;; + *) fail "wolfSSH didn't offer chacha20-poly1305@openssh.com" ;; + esac + + cc_expect= + for cc_alg in `echo "$cc_client" | tr ',' ' '`; do + case ",$cc_server," in + *,"$cc_alg",*) cc_expect=$cc_alg; break ;; + esac + done + + if [ "$cc_expect" != chacha20-poly1305@openssh.com ]; then + case "$3,$cc_server," in + peer,*chacha20-poly1305@openssh.com,*) fail \ + "wolfSSH preferred ${cc_expect:-no cipher} to chacha20-poly1305" + ;; + esac + echo "note: the $2 prefers ${cc_expect:-no shared cipher}," \ + "not checking chacha20-poly1305" + return 0 + fi + + for cc_dir in 'client->server' 'server->client'; do + if ! grep -q "kex: $cc_dir cipher: $cc_expect " "$1"; then + grep -E 'ciphers ctos:|kex: .* cipher:' "$1" + fail "the $2 didn't negotiate chacha20-poly1305 $cc_dir" + fi + done + echo "the $2 negotiated chacha20-poly1305@openssh.com" +} + # The echoserver is one shot, so start a new one per connection. It picks # an ephemeral port and writes it to the ready file. # @@ -299,6 +369,8 @@ fi echo "the OpenSSH client negotiated strict KEX with the echoserver" +check_chacha "$client_log" "OpenSSH client" local + # Part 1b forwards OpenSSH's ssh-agent through the echoserver. A local agent # client on the echoserver's side lists the forwarded key over the socket # the echoserver made for it, twice, so the second goes through a fresh @@ -757,6 +829,8 @@ fi echo "the wolfSSH client negotiated strict KEX with sshd" +check_chacha "$sshd_log" "sshd" peer + # Part 3 needs the client's agent support and OpenSSH's agent tools. if ! ./examples/client/client '-?' 2>&1 | grep -q 'SSH-AGENT'; then skip_rest "the example client has no agent support" "the agent half" diff --git a/src/internal.c b/src/internal.c index 1516d6450..1a3374e23 100644 --- a/src/internal.c +++ b/src/internal.c @@ -267,9 +267,12 @@ typedef char wolfSSH_channel_overhead_check[ WOLFSSH_NO_AES_GCM Set when AES or AES-GCM are disabled. Set to disable use of AES-GCM encryption. + WOLFSSH_NO_CHACHA20_POLY1305 + Set when ChaCha20 or Poly1305 are disabled. Set to disable use of + chacha20-poly1305 encryption. WOLFSSH_NO_AEAD - Set when AES-GCM is disabled. Set to disable use of AEAD ciphers for - encryption. Setting this will force all AEAD ciphers off. + Set when AES-GCM and ChaCha20/Poly1305 are disabled. Set to disable use of + AEAD ciphers for encryption. Setting this will force all AEAD ciphers off. WOLFSSH_NO_DH Set when all DH algorithms are disabled. Set to disable use of all DH algorithms for key agreement. Setting this will force all DH key agreement @@ -1389,7 +1392,18 @@ static const char cannedKeyAlgoNamesHostKey[] = #define cannedKeyAlgoNamesHostKey cannedKeyAlgoNames #endif /* WOLFSSH_OSSH_CERTS */ +#if !defined(WOLFSSH_NO_CHACHA20_POLY1305) + #define CANNED_CHACHA_NAMES \ + "chacha20-poly1305," \ + "chacha20-poly1305@openssh.com," +#else + #define CANNED_CHACHA_NAMES "" +#endif + +/* The chacha20-poly1305 names lead, so the list without them starts at + * cannedEncAlgoNamesNoChacha. */ static const char cannedEncAlgoNames[] = + CANNED_CHACHA_NAMES #if !defined(WOLFSSH_NO_AES_GCM) "aes256-gcm@openssh.com," "aes192-gcm@openssh.com," @@ -1407,6 +1421,9 @@ static const char cannedEncAlgoNames[] = #endif ""; +#define cannedEncAlgoNamesNoChacha \ + (cannedEncAlgoNames + sizeof(CANNED_CHACHA_NAMES) - 1) + static const char cannedMacAlgoNames[] = #if !defined(WOLFSSH_NO_HMAC_SHA2_256) "hmac-sha2-256," @@ -1652,7 +1669,7 @@ static void CipherClear(Ciphers* cipher) case ID_AES128_CBC: case ID_AES192_CBC: case ID_AES256_CBC: - wc_AesFree(&cipher->aes); + wc_AesFree(&cipher->cipher.aes); break; #endif @@ -1660,7 +1677,7 @@ static void CipherClear(Ciphers* cipher) case ID_AES128_CTR: case ID_AES192_CTR: case ID_AES256_CTR: - wc_AesFree(&cipher->aes); + wc_AesFree(&cipher->cipher.aes); break; #endif @@ -1668,7 +1685,15 @@ static void CipherClear(Ciphers* cipher) case ID_AES128_GCM: case ID_AES192_GCM: case ID_AES256_GCM: - wc_AesFree(&cipher->aes); + wc_AesFree(&cipher->cipher.aes); + break; +#endif + +#ifndef WOLFSSH_NO_CHACHA20_POLY1305 + case ID_CHACHA20_POLY1305: + case ID_CHACHA20_POLY1305_OPENSSH: + WS_FORCEZERO(&cipher->cipher.chacha, + sizeof(cipher->cipher.chacha)); break; #endif @@ -1715,12 +1740,14 @@ static int CipherSetKey(Ciphers* cipher, byte cryptId, int isEnc, WLOG(WS_LOG_DEBUG, "CSK:%s using cipher %s", isEnc ? "" : " peer", "aes-cbc"); if (iv != NULL) { - cryptErr = wc_AesInit(&cipher->aes, heap, INVALID_DEVID); + cryptErr = wc_AesInit(&cipher->cipher.aes, heap, + INVALID_DEVID); if (cryptErr == 0) { cipher->isInit = 1; cipher->cipherType = cryptId; - cryptErr = wc_AesSetKey(&cipher->aes, key, keySz, iv, - isEnc ? AES_ENCRYPTION : AES_DECRYPTION); + cryptErr = wc_AesSetKey(&cipher->cipher.aes, key, + keySz, iv, + isEnc ? AES_ENCRYPTION : AES_DECRYPTION); } } else { @@ -1736,12 +1763,13 @@ static int CipherSetKey(Ciphers* cipher, byte cryptId, int isEnc, WLOG(WS_LOG_DEBUG, "CSK:%s using cipher %s", isEnc ? "" : " peer", "aes-ctr"); if (iv != NULL) { - cryptErr = wc_AesInit(&cipher->aes, heap, INVALID_DEVID); + cryptErr = wc_AesInit(&cipher->cipher.aes, heap, + INVALID_DEVID); if (cryptErr == 0) { cipher->isInit = 1; cipher->cipherType = cryptId; - cryptErr = wc_AesSetKey(&cipher->aes, key, keySz, iv, - AES_ENCRYPTION); + cryptErr = wc_AesSetKey(&cipher->cipher.aes, key, + keySz, iv, AES_ENCRYPTION); } } else { @@ -1757,11 +1785,34 @@ static int CipherSetKey(Ciphers* cipher, byte cryptId, int isEnc, WOLFSSH_UNUSED(iv); WLOG(WS_LOG_DEBUG, "CSK:%s using cipher %s", isEnc ? "" : " peer", "aes-gcm"); - cryptErr = wc_AesInit(&cipher->aes, heap, INVALID_DEVID); + cryptErr = wc_AesInit(&cipher->cipher.aes, heap, INVALID_DEVID); if (cryptErr == 0) { cipher->isInit = 1; cipher->cipherType = cryptId; - cryptErr = wc_AesGcmSetKey(&cipher->aes, key, keySz); + cryptErr = wc_AesGcmSetKey(&cipher->cipher.aes, key, keySz); + } + break; +#endif + +#ifndef WOLFSSH_NO_CHACHA20_POLY1305 + case ID_CHACHA20_POLY1305: + case ID_CHACHA20_POLY1305_OPENSSH: + WOLFSSH_UNUSED(iv); + WLOG(WS_LOG_DEBUG, "CSK:%s using cipher %s", + isEnc ? "" : " peer", "chacha20-poly1305"); + if (keySz == CHACHA_POLY_KEY_SZ) { + cipher->isInit = 1; + cipher->cipherType = cryptId; + /* The first half keys the payload, the second half keys + * the packet length. */ + cryptErr = wc_Chacha_SetKey(&cipher->cipher.chacha.main, + key, CHACHA_MAX_KEY_SZ); + if (cryptErr == 0) + cryptErr = wc_Chacha_SetKey(&cipher->cipher.chacha.hdr, + key + CHACHA_MAX_KEY_SZ, CHACHA_MAX_KEY_SZ); + } + else { + ret = WS_BAD_ARGUMENT; } break; #endif @@ -1888,6 +1939,12 @@ WOLFSSH* SshInit(WOLFSSH* ssh, WOLFSSH_CTX* ctx) ssh->algoListKex = ctx->algoListKex; ssh->algoListKey = ctx->algoListKey; ssh->algoListCipher = ctx->algoListCipher; + /* Without strict KEX, chacha20-poly1305 is open to Terrapin's + * truncation, so the default list leaves it out. */ + if (!ssh->sendStrictKex && ssh->algoListCipher == cannedEncAlgoNames + && cannedEncAlgoNamesNoChacha[0] != '\0') { + ssh->algoListCipher = cannedEncAlgoNamesNoChacha; + } ssh->algoListMac = ctx->algoListMac; ssh->algoListKeyAccepted = ctx->algoListKeyAccepted; #ifdef WOLFSSH_SCP @@ -3998,6 +4055,11 @@ static const NameIdPair NameIdMap[] = { { ID_AES192_GCM, TYPE_CIPHER, "aes192-gcm@openssh.com" }, { ID_AES256_GCM, TYPE_CIPHER, "aes256-gcm@openssh.com" }, #endif +#ifndef WOLFSSH_NO_CHACHA20_POLY1305 + { ID_CHACHA20_POLY1305, TYPE_CIPHER, "chacha20-poly1305" }, + { ID_CHACHA20_POLY1305_OPENSSH, + TYPE_CIPHER, "chacha20-poly1305@openssh.com" }, +#endif /* Integrity IDs */ #ifndef WOLFSSH_NO_HMAC_SHA1 @@ -6429,6 +6491,11 @@ static INLINE byte BlockSzForId(byte id) case ID_AES192_GCM: case ID_AES256_GCM: return AES_BLOCK_SIZE; +#endif +#ifndef WOLFSSH_NO_CHACHA20_POLY1305 + case ID_CHACHA20_POLY1305: + case ID_CHACHA20_POLY1305_OPENSSH: + return MIN_BLOCK_SZ; #endif default: return 0; @@ -6454,6 +6521,17 @@ static INLINE byte MacSzForId(byte id) #ifndef WOLFSSH_NO_HMAC_SHA2_512 case ID_HMAC_SHA2_512: return WC_SHA512_DIGEST_SIZE; +#endif +#ifndef WOLFSSH_NO_AES_GCM + case ID_AES128_GCM: + case ID_AES192_GCM: + case ID_AES256_GCM: + return AES_BLOCK_SIZE; +#endif +#ifndef WOLFSSH_NO_CHACHA20_POLY1305 + case ID_CHACHA20_POLY1305: + case ID_CHACHA20_POLY1305_OPENSSH: + return POLY1305_DIGEST_SIZE; #endif default: return 0; @@ -6503,6 +6581,11 @@ static INLINE byte KeySzForId(byte id) return AES_192_KEY_SIZE; case ID_AES256_GCM: return AES_256_KEY_SIZE; +#endif +#ifndef WOLFSSH_NO_CHACHA20_POLY1305 + case ID_CHACHA20_POLY1305: + case ID_CHACHA20_POLY1305_OPENSSH: + return CHACHA_POLY_KEY_SZ; #endif default: return 0; @@ -6748,6 +6831,11 @@ static INLINE byte AeadModeForId(byte id) case ID_AES192_GCM: case ID_AES256_GCM: return 1; +#endif +#ifndef WOLFSSH_NO_CHACHA20_POLY1305 + case ID_CHACHA20_POLY1305: + case ID_CHACHA20_POLY1305_OPENSSH: + return 1; #endif default: return 0; @@ -6755,6 +6843,21 @@ static INLINE byte AeadModeForId(byte id) } +/* chacha20-poly1305 takes its nonce from the sequence number, not the KDF. */ +static INLINE byte AeadIvSzForId(byte id) +{ + switch (id) { +#ifndef WOLFSSH_NO_CHACHA20_POLY1305 + case ID_CHACHA20_POLY1305: + case ID_CHACHA20_POLY1305_OPENSSH: + return 0; +#endif + default: + return AEAD_NONCE_SZ; + } +} + + #ifndef WOLFSSH_NO_MLDSA static INLINE int KeyIdToMlDsaLevel(byte id) { @@ -6812,9 +6915,9 @@ static void SetLocalAlgoIds(HandshakeInfo* hs, hs->keys.macKeySz = KeySzForId(macId); } else { - hs->keys.ivSz = AEAD_NONCE_SZ; + hs->keys.ivSz = AeadIvSzForId(encId); hs->macId = ID_NONE; - hs->macSz = blkSz; + hs->macSz = MacSzForId(encId); hs->keys.macKeySz = 0; } } @@ -6835,9 +6938,9 @@ static void SetPeerAlgoIds(HandshakeInfo* hs, hs->peerKeys.macKeySz = KeySzForId(macId); } else { - hs->peerKeys.ivSz = AEAD_NONCE_SZ; + hs->peerKeys.ivSz = AeadIvSzForId(encId); hs->peerMacId = ID_NONE; - hs->peerMacSz = blkSz; + hs->peerMacSz = MacSzForId(encId); hs->peerKeys.macKeySz = 0; } } @@ -15071,8 +15174,9 @@ static INLINE int Encrypt(WOLFSSH* ssh, byte* cipher, const byte* input, case ID_AES128_CBC: case ID_AES192_CBC: case ID_AES256_CBC: - if (sz % AES_BLOCK_SIZE || wc_AesCbcEncrypt(&ssh->encryptCipher.aes, - cipher, input, sz) < 0) { + if (sz % AES_BLOCK_SIZE || + wc_AesCbcEncrypt(&ssh->encryptCipher.cipher.aes, + cipher, input, sz) < 0) { ret = WS_ENCRYPT_E; } @@ -15083,8 +15187,9 @@ static INLINE int Encrypt(WOLFSSH* ssh, byte* cipher, const byte* input, case ID_AES128_CTR: case ID_AES192_CTR: case ID_AES256_CTR: - if (sz % AES_BLOCK_SIZE || AESCTRHELPER(&ssh->encryptCipher.aes, - cipher, input, sz) < 0) { + if (sz % AES_BLOCK_SIZE || + AESCTRHELPER(&ssh->encryptCipher.cipher.aes, + cipher, input, sz) < 0) { ret = WS_ENCRYPT_E; } @@ -15119,8 +15224,9 @@ static INLINE int Decrypt(WOLFSSH* ssh, byte* plain, const byte* input, case ID_AES128_CBC: case ID_AES192_CBC: case ID_AES256_CBC: - if (sz % AES_BLOCK_SIZE || wc_AesCbcDecrypt(&ssh->decryptCipher.aes, - plain, input, sz) < 0) { + if (sz % AES_BLOCK_SIZE || + wc_AesCbcDecrypt(&ssh->decryptCipher.cipher.aes, + plain, input, sz) < 0) { ret = WS_DECRYPT_E; } @@ -15131,8 +15237,9 @@ static INLINE int Decrypt(WOLFSSH* ssh, byte* plain, const byte* input, case ID_AES128_CTR: case ID_AES192_CTR: case ID_AES256_CTR: - if (sz % AES_BLOCK_SIZE || AESCTRHELPER(&ssh->decryptCipher.aes, - plain, input, sz) < 0) { + if (sz % AES_BLOCK_SIZE || + AESCTRHELPER(&ssh->decryptCipher.cipher.aes, + plain, input, sz) < 0) { ret = WS_DECRYPT_E; } @@ -15346,7 +15453,7 @@ static INLINE int VerifyMac(WOLFSSH* ssh, const byte* in, word32 inSz, } -#ifndef WOLFSSH_NO_AEAD +#ifndef WOLFSSH_NO_AES_GCM /* Increment the explicit portion of the AEAD nonce. The carry runs the full * width with no early exit, so the timing doesn't depend on the counter, * which starts out as KDF output. */ @@ -15363,11 +15470,130 @@ static INLINE void AeadIncrementExpIv(byte* iv) carry = (sum >> 8) & 1u; } } +#endif /* WOLFSSH_NO_AES_GCM */ + + +#ifndef WOLFSSH_NO_CHACHA20_POLY1305 +/* chacha20-poly1305 as in OpenSSH's PROTOCOL.chacha20poly1305. Its 64-bit + * nonce is the sequence number with a 64-bit block counter. The 96-bit + * wolfCrypt nonce holds the counter's high word as zero, then the nonce. */ +static INLINE void ChachaPolySetNonce(byte* nonce, word32 seq) +{ + WMEMSET(nonce, 0, CHACHA_IV_BYTES); + c32toa(seq, nonce + CHACHA_IV_BYTES - UINT32_SZ); +} + + +/* The Poly1305 key is the first 32 bytes of the main keystream's block 0. The + * tag covers the encrypted length then the encrypted payload. */ +static int ChachaPolyTag(ChaCha* mainCtx, const byte* nonce, + const byte* len, word32 lenSz, const byte* data, word32 dataSz, + byte* tag) +{ + Poly1305 poly; + byte polyKey[CHACHA_CHUNK_BYTES]; + int ret; + + WMEMSET(polyKey, 0, sizeof(polyKey)); + ret = wc_Chacha_SetIV(mainCtx, nonce, 0); + if (ret == 0) + ret = wc_Chacha_Process(mainCtx, polyKey, polyKey, sizeof(polyKey)); + if (ret == 0) + ret = wc_Poly1305SetKey(&poly, polyKey, CHACHA_MAX_KEY_SZ); + if (ret == 0) + ret = wc_Poly1305Update(&poly, len, lenSz); + if (ret == 0) + ret = wc_Poly1305Update(&poly, data, dataSz); + if (ret == 0) + ret = wc_Poly1305Final(&poly, tag); + + WS_FORCEZERO(polyKey, sizeof(polyKey)); + WS_FORCEZERO(&poly, sizeof(poly)); + + return ret == 0 ? WS_SUCCESS : WS_CRYPTO_FAILED; +} + + +static int ChachaPolyEncrypt(Ciphers* cipher, word32 seq, byte* out, + const byte* in, word32 sz, byte* tag, byte* len, word32 lenSz) +{ + byte nonce[CHACHA_IV_BYTES]; + int ret; + + ChachaPolySetNonce(nonce, seq); + ret = wc_Chacha_SetIV(&cipher->cipher.chacha.hdr, nonce, 0); + if (ret == 0) + ret = wc_Chacha_Process(&cipher->cipher.chacha.hdr, len, len, lenSz); + if (ret == 0) + ret = wc_Chacha_SetIV(&cipher->cipher.chacha.main, nonce, 1); + if (ret == 0) + ret = wc_Chacha_Process(&cipher->cipher.chacha.main, out, in, sz); + if (ret == 0) + return ChachaPolyTag(&cipher->cipher.chacha.main, nonce, len, lenSz, + out, sz, tag); + + return WS_CRYPTO_FAILED; +} + + +/* Checks the tag before decrypting. The length stays encrypted in len. */ +static int ChachaPolyDecrypt(Ciphers* cipher, word32 seq, byte* out, + const byte* in, word32 sz, const byte* tag, + const byte* len, word32 lenSz) +{ + byte nonce[CHACHA_IV_BYTES]; + byte expected[POLY1305_DIGEST_SIZE]; + int ret; + + ChachaPolySetNonce(nonce, seq); + ret = ChachaPolyTag(&cipher->cipher.chacha.main, nonce, len, lenSz, + in, sz, expected); + if (ret == WS_SUCCESS && + WS_CONSTANTCOMPARE(expected, tag, sizeof(expected)) != 0) { + ret = WS_VERIFY_MAC_E; + } + if (ret == WS_SUCCESS) { + if (wc_Chacha_SetIV(&cipher->cipher.chacha.main, nonce, 1) != 0 || + wc_Chacha_Process(&cipher->cipher.chacha.main, out, in, + sz) != 0) { + ret = WS_CRYPTO_FAILED; + } + } + WS_FORCEZERO(expected, sizeof(expected)); + + return ret; +} +/* Decrypts the packet length into lenOut, leaving the input encrypted for + * the tag. */ +static int ChachaPolyGetLength(Ciphers* cipher, word32 seq, + const byte* in, word32* lenOut) +{ + byte nonce[CHACHA_IV_BYTES]; + byte len[UINT32_SZ]; + int ret = WS_SUCCESS; + + ChachaPolySetNonce(nonce, seq); + if (wc_Chacha_SetIV(&cipher->cipher.chacha.hdr, nonce, 0) != 0 || + wc_Chacha_Process(&cipher->cipher.chacha.hdr, len, in, + UINT32_SZ) != 0) { + ret = WS_CRYPTO_FAILED; + } + if (ret == WS_SUCCESS) + ato32(len, lenOut); + WS_FORCEZERO(len, sizeof(len)); + + return ret; +} +#endif /* WOLFSSH_NO_CHACHA20_POLY1305 */ + + +#ifndef WOLFSSH_NO_AEAD +/* chacha20-poly1305 encrypts auth, the packet length, in place. */ static INLINE int EncryptAead(WOLFSSH* ssh, byte* cipher, const byte* input, word32 sz, - byte* authTag, const byte* auth, + byte* authTag, byte* auth, word32 authSz) { int ret = WS_SUCCESS; @@ -15383,9 +15609,18 @@ static INLINE int EncryptAead(WOLFSSH* ssh, byte* cipher, case ID_AES128_GCM: case ID_AES192_GCM: case ID_AES256_GCM: - ret = wc_AesGcmEncrypt(&ssh->encryptCipher.aes, cipher, input, sz, + ret = wc_AesGcmEncrypt(&ssh->encryptCipher.cipher.aes, cipher, + input, sz, ssh->keys.iv, ssh->keys.ivSz, authTag, ssh->macSz, auth, authSz); + AeadIncrementExpIv(ssh->keys.iv); + break; +#endif +#ifndef WOLFSSH_NO_CHACHA20_POLY1305 + case ID_CHACHA20_POLY1305: + case ID_CHACHA20_POLY1305_OPENSSH: + ret = ChachaPolyEncrypt(&ssh->encryptCipher, ssh->seq, cipher, + input, sz, authTag, auth, authSz); break; #endif @@ -15393,7 +15628,6 @@ static INLINE int EncryptAead(WOLFSSH* ssh, byte* cipher, ret = WS_INVALID_ALGO_ID; } - AeadIncrementExpIv(ssh->keys.iv); ssh->txCount += sz; return ret; @@ -15418,9 +15652,18 @@ static INLINE int DecryptAead(WOLFSSH* ssh, byte* plain, case ID_AES128_GCM: case ID_AES192_GCM: case ID_AES256_GCM: - ret = wc_AesGcmDecrypt(&ssh->decryptCipher.aes, plain, input, sz, + ret = wc_AesGcmDecrypt(&ssh->decryptCipher.cipher.aes, plain, + input, sz, ssh->peerKeys.iv, ssh->peerKeys.ivSz, authTag, ssh->peerMacSz, auth, authSz); + AeadIncrementExpIv(ssh->peerKeys.iv); + break; +#endif +#ifndef WOLFSSH_NO_CHACHA20_POLY1305 + case ID_CHACHA20_POLY1305: + case ID_CHACHA20_POLY1305_OPENSSH: + ret = ChachaPolyDecrypt(&ssh->decryptCipher, ssh->peerSeq, plain, + input, sz, authTag, auth, authSz); break; #endif @@ -15428,7 +15671,6 @@ static INLINE int DecryptAead(WOLFSSH* ssh, byte* plain, ret = WS_INVALID_ALGO_ID; } - AeadIncrementExpIv(ssh->peerKeys.iv); ssh->rxCount += sz; return ret; @@ -15561,7 +15803,23 @@ int DoReceive(WOLFSSH* ssh) } /* Peek at the packet_length field. */ - ato32(ssh->inputBuffer.buffer + ssh->inputBuffer.idx, &ssh->curSz); +#ifndef WOLFSSH_NO_CHACHA20_POLY1305 + if (ssh->peerEncryptId == ID_CHACHA20_POLY1305 + || ssh->peerEncryptId == ID_CHACHA20_POLY1305_OPENSSH) { + ret = ChachaPolyGetLength(&ssh->decryptCipher, ssh->peerSeq, + ssh->inputBuffer.buffer + ssh->inputBuffer.idx, + &ssh->curSz); + if (ret != WS_SUCCESS) { + WLOG(WS_LOG_DEBUG, "PR: Length decrypt fail"); + return RejectPacket(ssh, peerBlockSz, ret); + } + } + else +#endif + { + ato32(ssh->inputBuffer.buffer + ssh->inputBuffer.idx, + &ssh->curSz); + } if (ssh->curSz > MAX_PACKET_SZ - (word32)peerMacSz - UINT32_SZ) { WLOG(WS_LOG_DEBUG, "Packet length overflow: size = %u", ssh->curSz); @@ -15570,7 +15828,8 @@ int DoReceive(WOLFSSH* ssh) /* RFC 4253 section 6 aligns packet_length through the padding * on the block size, or 8, whichever is larger. Under AES-GCM - * the length is AAD, so RFC 5647 section 7.2 aligns the body. */ + * the length is AAD, so RFC 5647 section 7.2 aligns the body; + * chacha20-poly1305 does the same. */ alignBlockSz = peerBlockSz < MIN_BLOCK_SZ ? MIN_BLOCK_SZ : peerBlockSz; alignSz = aeadMode ? ssh->curSz : UINT32_SZ + ssh->curSz; @@ -15649,6 +15908,9 @@ int DoReceive(WOLFSSH* ssh) ssh->msgHighwaterFlag = 1; return WS_FATAL_ERROR; } + /* chacha20-poly1305 left the length encrypted. */ + c32toa(ssh->curSz, + ssh->inputBuffer.buffer + ssh->inputBuffer.idx); #endif } } @@ -27600,16 +27862,18 @@ WOLFSSH_API int wolfSSH_TestBuildUserAuthRequestMlDsa(WOLFSSH* ssh, #endif /* !WOLFSSH_NO_MLDSA */ -#ifndef WOLFSSH_NO_AEAD - +#ifndef WOLFSSH_NO_AES_GCM void wolfSSH_TestAeadIncrementExpIv(byte* iv) { AeadIncrementExpIv(iv); } +#endif /* !WOLFSSH_NO_AES_GCM */ + +#ifndef WOLFSSH_NO_AEAD int wolfSSH_TestEncryptAead(WOLFSSH* ssh, byte* cipher, const byte* input, word32 sz, - byte* authTag, const byte* auth, word32 authSz) + byte* authTag, byte* auth, word32 authSz) { return EncryptAead(ssh, cipher, input, sz, authTag, auth, authSz); } diff --git a/src/ssh.c b/src/ssh.c index f42f3f15c..37fce1e6a 100644 --- a/src/ssh.c +++ b/src/ssh.c @@ -5722,6 +5722,10 @@ static const char* CipherNameForId(byte id) case ID_AES256_GCM: return "AES-256 GCM"; + + case ID_CHACHA20_POLY1305: + case ID_CHACHA20_POLY1305_OPENSSH: + return "ChaCha20-Poly1305"; } return ""; @@ -5754,6 +5758,10 @@ static const char* MacNameForId(byte macid, byte cipherid) case ID_AES256_GCM: return "AES256 GCM (in ETM mode)"; + + case ID_CHACHA20_POLY1305: + case ID_CHACHA20_POLY1305_OPENSSH: + return "Poly1305 (in ETM mode)"; } } diff --git a/tests/api.c b/tests/api.c index 58bfcb333..1bd0b87ae 100644 --- a/tests/api.c +++ b/tests/api.c @@ -10291,6 +10291,9 @@ static void test_wolfSSH_DefaultAlgoListsExcludeWeak(void) #ifndef WOLFSSH_NO_AES_GCM AssertIntEQ(AlgoListHas(cipher, "aes256-gcm@openssh.com"), 1); #endif +#ifndef WOLFSSH_NO_CHACHA20_POLY1305 + AssertIntEQ(AlgoListHas(cipher, "chacha20-poly1305@openssh.com"), 1); +#endif #ifndef WOLFSSH_NO_DH_GROUP14_SHA256 AssertIntEQ(AlgoListHas(kex, "diffie-hellman-group14-sha256"), 1); #endif @@ -10340,6 +10343,51 @@ static void test_wolfSSH_DefaultAlgoListsExcludeWeak(void) } +#ifndef WOLFSSH_NO_CHACHA20_POLY1305 +/* With strict KEX off on the context, a session given the default cipher + * list leaves chacha20-poly1305 out. A list the caller set is kept. */ +static void test_wolfSSH_DefaultCipherListStrictKex(void) +{ + static const char custom[] = "chacha20-poly1305@openssh.com"; + WOLFSSH_CTX* ctx; + WOLFSSH* ssh; + const char* cipher; + + ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL); + AssertNotNull(ctx); + + ssh = wolfSSH_new(ctx); + AssertNotNull(ssh); + cipher = wolfSSH_GetAlgoListCipher(ssh); + AssertIntEQ(AlgoListHas(cipher, "chacha20-poly1305"), 1); + AssertIntEQ(AlgoListHas(cipher, "chacha20-poly1305@openssh.com"), 1); + wolfSSH_free(ssh); + + AssertIntEQ(wolfSSH_CTX_SetStrictKex(ctx, 0), WS_SUCCESS); + ssh = wolfSSH_new(ctx); + AssertNotNull(ssh); + cipher = wolfSSH_GetAlgoListCipher(ssh); + AssertIntEQ(AlgoListHas(cipher, "chacha20-poly1305"), 0); + AssertIntEQ(AlgoListHas(cipher, "chacha20-poly1305@openssh.com"), 0); +#ifndef WOLFSSH_NO_AES_GCM + AssertIntEQ(AlgoListHas(cipher, "aes256-gcm@openssh.com"), 1); +#endif +#ifndef WOLFSSH_NO_AES_CTR + AssertIntEQ(AlgoListHas(cipher, "aes256-ctr"), 1); +#endif + wolfSSH_free(ssh); + + AssertIntEQ(wolfSSH_CTX_SetAlgoListCipher(ctx, custom), WS_SUCCESS); + ssh = wolfSSH_new(ctx); + AssertNotNull(ssh); + AssertPtrEq(wolfSSH_GetAlgoListCipher(ssh), custom); + wolfSSH_free(ssh); + + wolfSSH_CTX_free(ctx); +} +#endif + + /* Exercise CheckAlgoList()'s rejection paths through the public setters. */ static void test_wolfSSH_CheckAlgoList(void) { @@ -11058,6 +11106,9 @@ int wolfSSH_ApiTest(int argc, char** argv) test_wolfSSH_AlgoListKeyInSync(); test_wolfSSH_SetAlgoList(); test_wolfSSH_DefaultAlgoListsExcludeWeak(); +#ifndef WOLFSSH_NO_CHACHA20_POLY1305 + test_wolfSSH_DefaultCipherListStrictKex(); +#endif test_wolfSSH_CheckAlgoList(); #ifdef WOLFSSH_FWD test_wolfSSH_FwdRemote_badArgs(); diff --git a/tests/regress.c b/tests/regress.c index 6a03acdf9..e49a76022 100644 --- a/tests/regress.c +++ b/tests/regress.c @@ -1485,12 +1485,11 @@ static int FindPlainPacketOffset(const byte* packet, word32 packetSz, * * The published attack pairs that with deleting a packet after NEWKEYS to * put the counters back in step, silently truncating the stream. That step - * only works when the cipher takes its nonce from the sequence number -- - * chacha20-poly1305@openssh.com or the *-etm@openssh.com MACs. wolfSSH - * implements neither: its AES-GCM, CTR, and CBC modes all carry chained - * cipher state, so a deletion breaks decryption outright. The injection - * alone is what these tests exercise, and refusing it is what the - * mitigation has to do. */ + * only works when the cipher takes its nonce from the sequence number, + * as chacha20-poly1305@openssh.com does. wolfSSH's AES-GCM, CTR, and CBC + * modes carry chained cipher state, so a deletion breaks decryption + * outright. The injection alone is what these tests exercise, and refusing + * it is what the mitigation has to do. */ static void TerrapinInject(DuplexEndpoint* endpoint, const byte** output, word32* outputSz) { @@ -2948,17 +2947,19 @@ static void TestStrictKexResetsSequenceNumbers(void) * and finishes the handshake with its inbound counter one ahead of what * the server is sending against. Nothing notices, now or later -- the * harness negotiates aes256-gcm@openssh.com, and CreateMac()/VerifyMac() - * are reached only on the non-AEAD paths, so under an AEAD cipher the - * sequence number is not an authentication input at all. The counters - * simply stay apart. That undetected shift is what Terrapin is built on. - * Without GCM the harness negotiates an HMAC and the shift fails the MAC, - * so the test needs GCM. */ + * are reached only on the non-AEAD paths, so under AES-GCM the sequence + * number is not an authentication input at all. The counters simply stay + * apart. That undetected shift is what Terrapin is built on. + * The test requires aes256-gcm@openssh.com: an HMAC or chacha20-poly1305 + * would authenticate the sequence number and fail on the shift. */ static void TestTerrapinInjectionAcceptedWithoutStrictKex(void) { KexReplyHarness harness; KexReplyRunResult result; InitStrictKexHarness(&harness, MSGID_IGNORE, 0, 0); + AssertIntEQ(wolfSSH_SetAlgoListCipher(harness.client, + "aes256-gcm@openssh.com"), WS_SUCCESS); RunKexReplyHandshake(&harness, &result); AssertIntEQ(harness.mutator.injectedPackets, 1); @@ -2981,6 +2982,38 @@ static void TestTerrapinInjectionAcceptedWithoutStrictKex(void) } #endif /* !WOLFSSH_NO_AES_GCM */ +#ifndef WOLFSSH_NO_CHACHA20_POLY1305 +/* The same injection under chacha20-poly1305. The sequence number is the + * nonce, so the shift fails the first record after NEWKEYS. Only a matching + * deletion would put the counters back in step. The wrong nonce decrypts the + * length to noise, so the record is usually refused on its length before + * its tag is checked. */ +static void TestTerrapinInjectionBreaksChachaWithoutStrictKex(void) +{ + KexReplyHarness harness; + KexReplyRunResult result; + + InitStrictKexHarness(&harness, MSGID_IGNORE, 0, 0); + AssertIntEQ(wolfSSH_SetAlgoListCipher(harness.client, + "chacha20-poly1305@openssh.com"), WS_SUCCESS); + RunKexReplyHandshake(&harness, &result); + + AssertIntEQ(harness.mutator.injectedPackets, 1); + AssertIntEQ(harness.mutator.parseError, 0); + AssertIntEQ(harness.client->useStrictKex, 0); + AssertIntEQ(harness.client->encryptId, ID_CHACHA20_POLY1305_OPENSSH); + AssertIntEQ(harness.client->peerEncryptId, ID_CHACHA20_POLY1305_OPENSSH); + AssertIntEQ(harness.client->initialKexDone, 1); + + AssertFalse(result.clientSuccess); + AssertTrue(result.clientErr == WS_OVERFLOW_E || + result.clientErr == WS_BUFFER_E || + result.clientErr == WS_VERIFY_MAC_E); + + FreeKexReplyHarness(&harness); +} +#endif /* !WOLFSSH_NO_CHACHA20_POLY1305 */ + /* The same injection with strict KEX negotiated, for each message a man in * the middle could reach for. All of them are refused for as long as the * initial KEX is running, so the sequence number is never shifted and the @@ -3146,7 +3179,7 @@ static void TestPreKexInitInjectionRejectedWithStrictKex(void) } #ifndef WOLFSSH_NO_AES_GCM -/* Without strict KEX the same splice is accepted. Needs GCM, as +/* Without strict KEX the same splice is accepted. Requires GCM, as * TestTerrapinInjectionAcceptedWithoutStrictKex() does. */ static void TestPreKexInitInjectionAcceptedWithoutStrictKex(void) { @@ -3155,6 +3188,8 @@ static void TestPreKexInitInjectionAcceptedWithoutStrictKex(void) InitStrictKexHarnessMode(&harness, MSGID_IGNORE, 0, 0, REGRESS_MUTATE_TERRAPIN_PRE_KEXINIT); + AssertIntEQ(wolfSSH_SetAlgoListCipher(harness.client, + "aes256-gcm@openssh.com"), WS_SUCCESS); RunKexReplyHandshake(&harness, &result); AssertIntEQ(harness.mutator.injectedPackets, 1); @@ -5336,7 +5371,8 @@ static int PadSecretUserAuthCb(byte authType, WS_UserAuthData* authData, enum { PAD_XPORT_NONE = 0, /* null cipher, no MAC: a fresh session */ PAD_XPORT_CTR, /* aes256-ctr with hmac-sha2-256 */ - PAD_XPORT_GCM /* aes256-gcm, AEAD: length field in clear */ + PAD_XPORT_GCM, /* aes256-gcm, AEAD: length field in clear */ + PAD_XPORT_CHACHA /* chacha20-poly1305, AEAD, 8-byte block */ }; #if !defined(WOLFSSH_NO_AES_CTR) && !defined(WOLFSSH_NO_HMAC_SHA2_256) @@ -5345,6 +5381,12 @@ enum { #if !defined(WOLFSSH_NO_AES_GCM) && !defined(WOLFSSH_NO_AEAD) #define PAD_TEST_GCM #endif +#ifndef WOLFSSH_NO_CHACHA20_POLY1305 + #define PAD_TEST_CHACHA +#endif +#if defined(PAD_TEST_CTR) || defined(PAD_TEST_GCM) || defined(PAD_TEST_CHACHA) + #define PAD_TEST_KEYED +#endif #if defined(PAD_TEST_CTR) || defined(PAD_TEST_GCM) static const byte padTestKey[AES_256_KEY_SIZE] = { @@ -5365,18 +5407,50 @@ static const byte padTestMacKey[WC_SHA256_DIGEST_SIZE] = { 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B, 0x4B }; #endif +#endif /* PAD_TEST_CTR || PAD_TEST_GCM */ + +#ifdef PAD_TEST_KEYED +#ifdef PAD_TEST_CHACHA +/* The main key, then the header key. */ +static const byte padTestChachaKey[CHACHA_POLY_KEY_SZ] = { + 0x5A, 0x5A, 0x5A, 0x5A, 0x5A, 0x5A, 0x5A, 0x5A, + 0x5A, 0x5A, 0x5A, 0x5A, 0x5A, 0x5A, 0x5A, 0x5A, + 0x5A, 0x5A, 0x5A, 0x5A, 0x5A, 0x5A, 0x5A, 0x5A, + 0x5A, 0x5A, 0x5A, 0x5A, 0x5A, 0x5A, 0x5A, 0x5A, + 0xA5, 0xA5, 0xA5, 0xA5, 0xA5, 0xA5, 0xA5, 0xA5, + 0xA5, 0xA5, 0xA5, 0xA5, 0xA5, 0xA5, 0xA5, 0xA5, + 0xA5, 0xA5, 0xA5, 0xA5, 0xA5, 0xA5, 0xA5, 0xA5, + 0xA5, 0xA5, 0xA5, 0xA5, 0xA5, 0xA5, 0xA5, 0xA5 +}; +#endif /* Sets the session's outbound direction as key exchange would leave it. */ static void SetPadTestTransport(WOLFSSH* ssh, int xport) { - AssertIntEQ(wc_AesInit(&ssh->encryptCipher.aes, ssh->ctx->heap, - INVALID_DEVID), 0); ssh->encryptCipher.isInit = 1; +#ifdef PAD_TEST_CHACHA + if (xport == PAD_XPORT_CHACHA) { + ssh->encryptCipher.cipherType = ID_CHACHA20_POLY1305_OPENSSH; + AssertIntEQ(wc_Chacha_SetKey(&ssh->encryptCipher.cipher.chacha.main, + padTestChachaKey, CHACHA_MAX_KEY_SZ), 0); + AssertIntEQ(wc_Chacha_SetKey(&ssh->encryptCipher.cipher.chacha.hdr, + padTestChachaKey + CHACHA_MAX_KEY_SZ, + CHACHA_MAX_KEY_SZ), 0); + ssh->blockSz = MIN_BLOCK_SZ; + ssh->encryptId = ID_CHACHA20_POLY1305_OPENSSH; + ssh->aeadMode = 1; + ssh->macId = ID_NONE; + ssh->macSz = POLY1305_DIGEST_SIZE; + return; + } +#endif + AssertIntEQ(wc_AesInit(&ssh->encryptCipher.cipher.aes, ssh->ctx->heap, + INVALID_DEVID), 0); ssh->blockSz = AES_BLOCK_SIZE; #ifdef PAD_TEST_CTR if (xport == PAD_XPORT_CTR) { ssh->encryptCipher.cipherType = ID_AES256_CTR; - AssertIntEQ(wc_AesSetKey(&ssh->encryptCipher.aes, padTestKey, + AssertIntEQ(wc_AesSetKey(&ssh->encryptCipher.cipher.aes, padTestKey, sizeof(padTestKey), padTestIv, AES_ENCRYPTION), 0); ssh->encryptId = ID_AES256_CTR; ssh->aeadMode = 0; @@ -5389,7 +5463,7 @@ static void SetPadTestTransport(WOLFSSH* ssh, int xport) #ifdef PAD_TEST_GCM if (xport == PAD_XPORT_GCM) { ssh->encryptCipher.cipherType = ID_AES256_GCM; - AssertIntEQ(wc_AesGcmSetKey(&ssh->encryptCipher.aes, padTestKey, + AssertIntEQ(wc_AesGcmSetKey(&ssh->encryptCipher.cipher.aes, padTestKey, sizeof(padTestKey)), 0); ssh->encryptId = ID_AES256_GCM; ssh->aeadMode = 1; @@ -5460,12 +5534,55 @@ static word32 OpenPadTestPacket(int xport, word32 seq, const byte* out, out + UINT32_SZ + packetLen, AES_BLOCK_SIZE, out, UINT32_SZ), 0); } +#endif +#ifdef PAD_TEST_CHACHA + if (xport == PAD_XPORT_CHACHA) { + /* Opened with wolfCrypt directly, per PROTOCOL.chacha20poly1305. */ + ChaCha mainCtx, hdrCtx; + Poly1305 poly; + byte nonce[CHACHA_IV_BYTES]; + byte polyKey[CHACHA_CHUNK_BYTES]; + byte tag[POLY1305_DIGEST_SIZE]; + + AssertTrue(outSz > UINT32_SZ + POLY1305_DIGEST_SIZE); + WMEMSET(nonce, 0, sizeof(nonce)); + nonce[8] = (byte)(seq >> 24); + nonce[9] = (byte)(seq >> 16); + nonce[10] = (byte)(seq >> 8); + nonce[11] = (byte)seq; + AssertIntEQ(wc_Chacha_SetKey(&mainCtx, padTestChachaKey, + CHACHA_MAX_KEY_SZ), 0); + AssertIntEQ(wc_Chacha_SetKey(&hdrCtx, + padTestChachaKey + CHACHA_MAX_KEY_SZ, + CHACHA_MAX_KEY_SZ), 0); + + AssertIntEQ(wc_Chacha_SetIV(&hdrCtx, nonce, 0), 0); + AssertIntEQ(wc_Chacha_Process(&hdrCtx, plain, out, UINT32_SZ), 0); + packetLen = ReadUint32(plain); + AssertIntEQ(UINT32_SZ + packetLen + POLY1305_DIGEST_SIZE, outSz); + AssertTrue(UINT32_SZ + packetLen <= plainSz); + alignSz = packetLen; + + WMEMSET(polyKey, 0, sizeof(polyKey)); + AssertIntEQ(wc_Chacha_SetIV(&mainCtx, nonce, 0), 0); + AssertIntEQ(wc_Chacha_Process(&mainCtx, polyKey, polyKey, + sizeof(polyKey)), 0); + AssertIntEQ(wc_Poly1305SetKey(&poly, polyKey, CHACHA_MAX_KEY_SZ), 0); + AssertIntEQ(wc_Poly1305Update(&poly, out, UINT32_SZ + packetLen), 0); + AssertIntEQ(wc_Poly1305Final(&poly, tag), 0); + AssertIntEQ(WMEMCMP(tag, out + UINT32_SZ + packetLen, sizeof(tag)), + 0); + + AssertIntEQ(wc_Chacha_SetIV(&mainCtx, nonce, 1), 0); + AssertIntEQ(wc_Chacha_Process(&mainCtx, plain + UINT32_SZ, + out + UINT32_SZ, packetLen), 0); + } #endif wc_AesFree(&aes); (void)packetLen; return alignSz; } -#endif /* PAD_TEST_CTR || PAD_TEST_GCM */ +#endif /* PAD_TEST_KEYED */ /* Sends the client's password request, or its keyboard INFO_RESPONSE, with a * secret of secretSz bytes over the transport xport. With held, the packet is @@ -5485,7 +5602,7 @@ static word32 SecretPacketSz(int xport, int keyboard, word32 secretSz, wolfSSH_SetUserAuth(harness.ctx, PadSecretUserAuthCb); AssertIntEQ(wolfSSH_SetUsername(harness.ssh, "user"), WS_SUCCESS); padSecretSz = secretSz; -#if defined(PAD_TEST_CTR) || defined(PAD_TEST_GCM) +#ifdef PAD_TEST_KEYED if (xport != PAD_XPORT_NONE) SetPadTestTransport(harness.ssh, xport); #endif @@ -5538,7 +5655,7 @@ static word32 SecretPacketSz(int xport, int keyboard, word32 secretSz, sz = harness.io.outSz; } else { -#if defined(PAD_TEST_CTR) || defined(PAD_TEST_GCM) +#ifdef PAD_TEST_KEYED sz = OpenPadTestPacket(xport, seq, harness.io.out, harness.io.outSz, plain, (word32)sizeof(plain)); #else @@ -5577,7 +5694,7 @@ static void TestClientUserAuthSecretPadding(void) int keyboard, xport; word32 secretSz; - for (xport = PAD_XPORT_NONE; xport <= PAD_XPORT_GCM; xport++) { + for (xport = PAD_XPORT_NONE; xport <= PAD_XPORT_CHACHA; xport++) { #ifndef PAD_TEST_CTR if (xport == PAD_XPORT_CTR) continue; @@ -5585,6 +5702,10 @@ static void TestClientUserAuthSecretPadding(void) #ifndef PAD_TEST_GCM if (xport == PAD_XPORT_GCM) continue; +#endif +#ifndef PAD_TEST_CHACHA + if (xport == PAD_XPORT_CHACHA) + continue; #endif for (keyboard = 0; keyboard < 2; keyboard++) { #ifndef WOLFSSH_KEYBOARD_INTERACTIVE @@ -5606,6 +5727,50 @@ static void TestClientUserAuthSecretPadding(void) } } +#if defined(WOLFSSH_KEYBOARD_INTERACTIVE) && defined(PAD_TEST_CHACHA) +/* The keyboard-interactive request ends in an empty language tag and + * submethods. Under chacha20-poly1305's 8-byte block, the padding reserve + * no longer hides them if they go uncounted, so the request must frame for + * every username length across a block. */ +static void TestClientKbRequestSizing(void) +{ + static const char name[] = "abcdefghijklmnopqrstuvwx"; + ChannelOpenHarness harness; + byte plain[256]; + word32 nameSz, packetLen, payloadEnd; + byte padLen; + + for (nameSz = 1; nameSz < sizeof(name); nameSz++) { + char user[sizeof(name)]; + + WMEMCPY(user, name, nameSz); + user[nameSz] = 0; + InitChannelOpenHarnessClient(&harness, NULL, 0); + AssertIntEQ(wolfSSH_SetUsername(harness.ssh, user), WS_SUCCESS); + SetPadTestTransport(harness.ssh, PAD_XPORT_CHACHA); + + AssertIntEQ(SendUserAuthRequest(harness.ssh, + WOLFSSH_USERAUTH_KEYBOARD, 0), WS_SUCCESS); + OpenPadTestPacket(PAD_XPORT_CHACHA, harness.ssh->seq - 1, + harness.io.out, harness.io.outSz, plain, + (word32)sizeof(plain)); + + packetLen = ReadUint32(plain); + padLen = plain[UINT32_SZ]; + AssertIntEQ(plain[UINT32_SZ + PAD_LENGTH_SZ], + MSGID_USERAUTH_REQUEST); + payloadEnd = UINT32_SZ + packetLen - padLen; + AssertIntEQ(ReadUint32(plain + UINT32_SZ + PAD_LENGTH_SZ + MSG_ID_SZ), + nameSz); + /* language tag and submethods, both empty */ + AssertIntEQ(ReadUint32(plain + payloadEnd - LENGTH_SZ * 2), 0); + AssertIntEQ(ReadUint32(plain + payloadEnd - LENGTH_SZ), 0); + + FreeChannelOpenHarness(&harness); + } +} +#endif + /* Drive the whole receive path with a CHANNEL_OPEN sent from a pre-auth * connectState: no channel created, and the only thing sent back is the @@ -22802,6 +22967,58 @@ static void TestGenerateKeysSplit(void) wolfSSH_free(ssh); #endif /* !WOLFSSH_NO_AES_GCM */ +#ifndef WOLFSSH_NO_CHACHA20_POLY1305 + /* Sub-test E: chacha20-poly1305 both ways. It needs 64 bytes of key, more + * than one SHA-256 output, no IV, and no MAC key. */ + ssh = wolfSSH_new(ctx); + AssertNotNull(ssh); + AssertIntEQ(wolfSSH_SetAlgoListKex(ssh, FPF_KEX_GOOD), WS_SUCCESS); + AssertIntEQ(wolfSSH_SetAlgoListKey(ssh, FPF_KEY_GOOD), WS_SUCCESS); + AssertIntEQ(wolfSSH_SetAlgoListCipher(ssh, + "chacha20-poly1305@openssh.com"), WS_SUCCESS); + AssertIntEQ(wolfSSH_SetAlgoListMac(ssh, "hmac-sha1"), WS_SUCCESS); + idx = 0; + payloadSz = BuildKexInitPayloadFull( + FPF_KEX_GOOD, FPF_KEY_GOOD, + "chacha20-poly1305@openssh.com", + "chacha20-poly1305@openssh.com", + "hmac-sha1", + "hmac-sha1", + 0, payload, (word32)sizeof(payload)); + (void)wolfSSH_TestDoKexInit(ssh, payload, payloadSz, &idx); + AssertNotNull(ssh->handshake); + AssertIntEQ(ssh->handshake->encryptId, ID_CHACHA20_POLY1305_OPENSSH); + AssertIntEQ(ssh->handshake->peerEncryptId, ID_CHACHA20_POLY1305_OPENSSH); + AssertIntEQ(ssh->handshake->aeadMode, 1); + AssertIntEQ(ssh->handshake->peerAeadMode, 1); + AssertIntEQ(ssh->handshake->blockSz, MIN_BLOCK_SZ); + AssertIntEQ(ssh->handshake->macSz, POLY1305_DIGEST_SIZE); + AssertIntEQ(ssh->handshake->peerMacSz, POLY1305_DIGEST_SIZE); + + WMEMSET(ssh->k, 0xAA, WC_SHA256_DIGEST_SIZE); + ssh->kSz = WC_SHA256_DIGEST_SIZE; + WMEMSET(ssh->h, 0xBB, WC_SHA256_DIGEST_SIZE); + ssh->hSz = WC_SHA256_DIGEST_SIZE; + WMEMCPY(ssh->sessionId, ssh->h, ssh->hSz); + ssh->sessionIdSz = ssh->hSz; + + AssertIntEQ(wolfSSH_TestGenerateKeys(ssh, ssh->handshake->kexHashId), WS_SUCCESS); + + AssertIntEQ(ssh->handshake->keys.encKeySz, CHACHA_POLY_KEY_SZ); + AssertIntEQ(ssh->handshake->peerKeys.encKeySz, CHACHA_POLY_KEY_SZ); + AssertIntEQ(ssh->handshake->keys.ivSz, 0); + AssertIntEQ(ssh->handshake->peerKeys.ivSz, 0); + AssertIntEQ(ssh->handshake->keys.macKeySz, 0); + AssertIntEQ(ssh->handshake->peerKeys.macKeySz, 0); + /* The header key half was derived too. */ + AssertTrue(WMEMCMP(ssh->handshake->keys.encKey + CHACHA_MAX_KEY_SZ, + zeros, CHACHA_MAX_KEY_SZ) != 0); + AssertTrue(WMEMCMP(ssh->handshake->peerKeys.encKey + CHACHA_MAX_KEY_SZ, + zeros, CHACHA_MAX_KEY_SZ) != 0); + + wolfSSH_free(ssh); +#endif /* !WOLFSSH_NO_CHACHA20_POLY1305 */ + wolfSSH_CTX_free(ctx); } @@ -24446,6 +24663,9 @@ int main(int argc, char** argv) TestClientInfoRequestAfterHighwaterErrorAnswered(); #endif TestClientUserAuthSecretPadding(); +#if defined(WOLFSSH_KEYBOARD_INTERACTIVE) && defined(PAD_TEST_CHACHA) + TestClientKbRequestSizing(); +#endif TestClientBannerBehindServiceAccept(); TestChannelOpenRejectedBeforeKex(CONNECT_CLIENT_KEXINIT_SENT); TestChannelOpenRejectedBeforeKex(CONNECT_CLIENT_KEXDH_INIT_SENT); @@ -24935,6 +25155,9 @@ int main(int argc, char** argv) #ifndef WOLFSSH_NO_AES_GCM TestTerrapinInjectionAcceptedWithoutStrictKex(); #endif + #ifndef WOLFSSH_NO_CHACHA20_POLY1305 + TestTerrapinInjectionBreaksChachaWithoutStrictKex(); + #endif TestTerrapinInjectionRejectedWithStrictKex(); TestTerrapinInjectionRejectedByServer(); TestStrictKexTakesInjectedDisconnect(); diff --git a/tests/unit.c b/tests/unit.c index c1030509f..3b4ed5b76 100644 --- a/tests/unit.c +++ b/tests/unit.c @@ -1881,19 +1881,26 @@ static int test_DoPacket_UnimplementedConsumesPayload(void) #endif /* WOLFSSH_TEST_INTERNAL && !NO_WOLFSSH_SERVER */ -/* Returns 1 when all sz bytes at p are zero. */ -static WS_MAYBE_UNUSED int IsZeroed(const byte* p, word32 sz) +/* Returns 1 when all sz bytes at p are fill. */ +static WS_MAYBE_UNUSED int IsFilled(const byte* p, word32 sz, byte fill) { word32 i; for (i = 0; i < sz; i++) { - if (p[i] != 0) + if (p[i] != fill) return 0; } return 1; } +/* Returns 1 when all sz bytes at p are zero. */ +static WS_MAYBE_UNUSED int IsZeroed(const byte* p, word32 sz) +{ + return IsFilled(p, sz, 0); +} + + #if defined(WOLFSSH_TEST_INTERNAL) && \ (!defined(WOLFSSH_NO_HMAC_SHA1) || \ !defined(WOLFSSH_NO_HMAC_SHA1_96) || \ @@ -2098,7 +2105,7 @@ static int test_DoReceive_AeadTagFailure(void) /* Tamper with a ciphertext byte so the tag check must fail. */ record[UINT32_SZ] ^= 0x01; - if (wc_AesInit(&ssh->decryptCipher.aes, ssh->ctx->heap, + if (wc_AesInit(&ssh->decryptCipher.cipher.aes, ssh->ctx->heap, INVALID_DEVID) != 0) { result = -226; goto done; @@ -2107,7 +2114,8 @@ static int test_DoReceive_AeadTagFailure(void) * even if the key set fails */ ssh->decryptCipher.isInit = 1; ssh->decryptCipher.cipherType = ID_AES256_GCM; - if (wc_AesGcmSetKey(&ssh->decryptCipher.aes, key, sizeof(key)) != 0) { + if (wc_AesGcmSetKey(&ssh->decryptCipher.cipher.aes, key, + sizeof(key)) != 0) { result = -230; goto done; } @@ -2235,7 +2243,7 @@ static int test_DoReceive_FirstDecryptFailWipes(void) #endif /* WOLFSSH_TEST_INTERNAL */ -#if defined(WOLFSSH_TEST_INTERNAL) && !defined(WOLFSSH_NO_AEAD) +#if defined(WOLFSSH_TEST_INTERNAL) && !defined(WOLFSSH_NO_AES_GCM) /* The explicit half of the AES-GCM nonce (RFC 5647) is a big-endian counter * bumped after every record. The implicit half must never move. */ static int test_AeadIncrementExpIv(void) @@ -2280,7 +2288,7 @@ static int test_AeadIncrementExpIv(void) return 0; } -#endif /* WOLFSSH_TEST_INTERNAL && !WOLFSSH_NO_AEAD */ +#endif /* WOLFSSH_TEST_INTERNAL && !WOLFSSH_NO_AES_GCM */ #if defined(WOLFSSH_TEST_INTERNAL) && !defined(WOLFSSH_NO_AES_GCM) @@ -2294,7 +2302,7 @@ static int test_AeadNoncePerPacket(void) byte key[AES_256_KEY_SIZE]; byte iv[AEAD_NONCE_SZ]; byte expIv[AEAD_NONCE_SZ]; - const byte auth[UINT32_SZ] = { 0x00, 0x00, 0x00, 0x10 }; + byte auth[UINT32_SZ] = { 0x00, 0x00, 0x00, 0x10 }; byte plain[AES_BLOCK_SIZE]; byte first[AES_BLOCK_SIZE], second[AES_BLOCK_SIZE]; byte firstTag[AES_BLOCK_SIZE], secondTag[AES_BLOCK_SIZE]; @@ -2313,7 +2321,7 @@ static int test_AeadNoncePerPacket(void) WMEMSET(iv, 0x31, sizeof(iv)); WMEMSET(plain, 0x7E, sizeof(plain)); - if (wc_AesInit(&ssh->encryptCipher.aes, ssh->ctx->heap, + if (wc_AesInit(&ssh->encryptCipher.cipher.aes, ssh->ctx->heap, INVALID_DEVID) != 0) { result = -1022; goto done; @@ -2322,7 +2330,8 @@ static int test_AeadNoncePerPacket(void) * even if the key set fails */ ssh->encryptCipher.isInit = 1; ssh->encryptCipher.cipherType = ID_AES256_GCM; - if (wc_AesGcmSetKey(&ssh->encryptCipher.aes, key, sizeof(key)) != 0) { + if (wc_AesGcmSetKey(&ssh->encryptCipher.cipher.aes, key, + sizeof(key)) != 0) { result = -1022; goto done; } @@ -2358,14 +2367,15 @@ static int test_AeadNoncePerPacket(void) goto done; } - if (wc_AesInit(&ssh->decryptCipher.aes, ssh->ctx->heap, + if (wc_AesInit(&ssh->decryptCipher.cipher.aes, ssh->ctx->heap, INVALID_DEVID) != 0) { result = -1028; goto done; } ssh->decryptCipher.isInit = 1; ssh->decryptCipher.cipherType = ID_AES256_GCM; - if (wc_AesGcmSetKey(&ssh->decryptCipher.aes, key, sizeof(key)) != 0) { + if (wc_AesGcmSetKey(&ssh->decryptCipher.cipher.aes, key, + sizeof(key)) != 0) { result = -1028; goto done; } @@ -2404,6 +2414,290 @@ static int test_AeadNoncePerPacket(void) } #endif /* WOLFSSH_TEST_INTERNAL && !WOLFSSH_NO_AES_GCM */ +#if defined(WOLFSSH_TEST_INTERNAL) && !defined(WOLFSSH_NO_CHACHA20_POLY1305) +/* chacha20-poly1305 known answer: key bytes 0x00..0x3F, sequence number 7, + * length 16, payload bytes 0xA0..0xAF. The expected values come from the + * OpenSSL command line ChaCha20 and Poly1305. */ +static int test_ChachaPolyKat(void) +{ + WOLFSSH_CTX* ctx = NULL; + WOLFSSH* ssh = NULL; + int result = 0; + word32 i; + byte key[CHACHA_POLY_KEY_SZ]; + byte plain[16]; + byte len[UINT32_SZ] = { 0x00, 0x00, 0x00, 0x10 }; + byte cipher[sizeof(plain)]; + byte tag[POLY1305_DIGEST_SIZE]; + byte out[sizeof(plain)]; + const byte expLen[UINT32_SZ] = { 0xA3, 0x9A, 0xFC, 0xBA }; + const byte expCipher[sizeof(plain)] = { + 0x88, 0xE7, 0xB7, 0xE0, 0xEA, 0x26, 0x8C, 0xF9, + 0xC4, 0xC4, 0x11, 0x5B, 0x7B, 0x22, 0x7D, 0x83 + }; + const byte expTag[POLY1305_DIGEST_SIZE] = { + 0xFC, 0x12, 0xF6, 0x9E, 0x1D, 0x56, 0x80, 0xB8, + 0x25, 0x99, 0xD6, 0x80, 0x66, 0x7A, 0xAA, 0x32 + }; + + ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL); + if (ctx == NULL) + return -1040; + ssh = wolfSSH_new(ctx); + if (ssh == NULL) { + wolfSSH_CTX_free(ctx); + return -1041; + } + + for (i = 0; i < sizeof(key); i++) + key[i] = (byte)i; + for (i = 0; i < sizeof(plain); i++) + plain[i] = (byte)(0xA0 + i); + + ssh->encryptCipher.isInit = 1; + ssh->encryptCipher.cipherType = ID_CHACHA20_POLY1305_OPENSSH; + ssh->decryptCipher.isInit = 1; + ssh->decryptCipher.cipherType = ID_CHACHA20_POLY1305_OPENSSH; + if (wc_Chacha_SetKey(&ssh->encryptCipher.cipher.chacha.main, + key, CHACHA_MAX_KEY_SZ) != 0 + || wc_Chacha_SetKey(&ssh->encryptCipher.cipher.chacha.hdr, + key + CHACHA_MAX_KEY_SZ, CHACHA_MAX_KEY_SZ) != 0 + || wc_Chacha_SetKey(&ssh->decryptCipher.cipher.chacha.main, + key, CHACHA_MAX_KEY_SZ) != 0 + || wc_Chacha_SetKey(&ssh->decryptCipher.cipher.chacha.hdr, + key + CHACHA_MAX_KEY_SZ, CHACHA_MAX_KEY_SZ) != 0) { + result = -1042; + goto done; + } + ssh->encryptId = ID_CHACHA20_POLY1305_OPENSSH; + ssh->aeadMode = 1; + ssh->macSz = POLY1305_DIGEST_SIZE; + ssh->seq = 7; + ssh->peerEncryptId = ID_CHACHA20_POLY1305_OPENSSH; + ssh->peerAeadMode = 1; + ssh->peerMacSz = POLY1305_DIGEST_SIZE; + ssh->peerSeq = 7; + + if (wolfSSH_TestEncryptAead(ssh, cipher, plain, sizeof(plain), tag, + len, sizeof(len)) != WS_SUCCESS) { + result = -1043; + goto done; + } + if (WMEMCMP(len, expLen, sizeof(len)) != 0) { + result = -1044; + goto done; + } + if (WMEMCMP(cipher, expCipher, sizeof(cipher)) != 0) { + result = -1045; + goto done; + } + if (WMEMCMP(tag, expTag, sizeof(tag)) != 0) { + result = -1046; + goto done; + } + + if (wolfSSH_TestDecryptAead(ssh, out, cipher, sizeof(cipher), tag, + len, sizeof(len)) != WS_SUCCESS + || WMEMCMP(out, plain, sizeof(plain)) != 0) { + result = -1047; + goto done; + } + + /* Each rejected record leaves out untouched: the tag is checked + * before anything is decrypted. */ + + /* The sequence number is the nonce. */ + ssh->peerSeq = 8; + WMEMSET(out, 0xEE, sizeof(out)); + if (wolfSSH_TestDecryptAead(ssh, out, cipher, sizeof(cipher), tag, + len, sizeof(len)) != WS_VERIFY_MAC_E + || !IsFilled(out, sizeof(out), 0xEE)) { + result = -1048; + goto done; + } + ssh->peerSeq = 7; + + /* The tag covers the encrypted length. */ + len[0] ^= 0x01; + if (wolfSSH_TestDecryptAead(ssh, out, cipher, sizeof(cipher), tag, + len, sizeof(len)) != WS_VERIFY_MAC_E + || !IsFilled(out, sizeof(out), 0xEE)) { + result = -1049; + goto done; + } + len[0] ^= 0x01; + + cipher[sizeof(cipher) - 1] ^= 0x80; + if (wolfSSH_TestDecryptAead(ssh, out, cipher, sizeof(cipher), tag, + len, sizeof(len)) != WS_VERIFY_MAC_E + || !IsFilled(out, sizeof(out), 0xEE)) { + result = -1050; + goto done; + } + +done: + wolfSSH_free(ssh); + wolfSSH_CTX_free(ctx); + return result; +} + + +/* Ways test_DoReceive_ChachaPoly() damages its record. */ +enum { + CHACHA_RX_GOOD = 0, + CHACHA_RX_BODY, /* a ciphertext byte */ + CHACHA_RX_TAG, /* a tag byte */ + CHACHA_RX_LENGTH, /* the encrypted length's top bit */ + CHACHA_RX_MISALIGNED /* intact, but a 12-byte body */ +}; + +/* Verify DoReceive on a chacha20-poly1305 record: an intact one is taken, + * a tampered body or tag fails the tag and is wiped, and a length that + * decrypts oversize or misaligned is refused before the tag is read. */ +static int test_DoReceive_ChachaPoly(void) +{ + WOLFSSH_CTX* ctx = NULL; + WOLFSSH* ssh = NULL; + int ret; + int result = 0; + word32 i, c; + byte key[CHACHA_POLY_KEY_SZ]; + byte pkt[UINT32_SZ + 16]; + byte record[UINT32_SZ + 16 + POLY1305_DIGEST_SIZE]; + word32 prefixLen, payloadSz, totalLen; + const word32 seq = 3; + static const struct { + byte tamper; + byte bodySz; + int error; + } cases[] = { + { CHACHA_RX_GOOD, 16, WS_SUCCESS }, + { CHACHA_RX_BODY, 16, WS_VERIFY_MAC_E }, + { CHACHA_RX_TAG, 16, WS_VERIFY_MAC_E }, + { CHACHA_RX_LENGTH, 16, WS_OVERFLOW_E }, + { CHACHA_RX_MISALIGNED, 12, WS_BUFFER_E } + }; + + for (i = 0; i < sizeof(key); i++) + key[i] = (byte)(0x40 + i); + + /* The intact IGNORE must pass the message filter, which has no branch + * for a side that is compiled out. */ +#ifndef NO_WOLFSSH_CLIENT + ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL); +#else + ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL); +#endif + if (ctx == NULL) + return -1060; + + for (c = 0; c < sizeof(cases) / sizeof(cases[0]); c++) { + ssh = wolfSSH_new(ctx); + if (ssh == NULL) { + result = -1061; + goto done; + } + + /* MSGID_IGNORE carrying an empty string, then padding. */ + payloadSz = cases[c].bodySz; + prefixLen = UINT32_SZ + payloadSz; + WMEMSET(pkt, 0, sizeof(pkt)); + pkt[3] = (byte)payloadSz; + pkt[4] = (byte)(payloadSz - PAD_LENGTH_SZ - MSG_ID_SZ - UINT32_SZ); + pkt[5] = MSGID_IGNORE; + totalLen = prefixLen + POLY1305_DIGEST_SIZE; + + /* Both directions share the key, so the session seals its own + * record. */ + ssh->encryptCipher.isInit = 1; + ssh->encryptCipher.cipherType = ID_CHACHA20_POLY1305_OPENSSH; + ssh->decryptCipher.isInit = 1; + ssh->decryptCipher.cipherType = ID_CHACHA20_POLY1305_OPENSSH; + if (wc_Chacha_SetKey(&ssh->encryptCipher.cipher.chacha.main, + key, CHACHA_MAX_KEY_SZ) != 0 + || wc_Chacha_SetKey(&ssh->encryptCipher.cipher.chacha.hdr, + key + CHACHA_MAX_KEY_SZ, CHACHA_MAX_KEY_SZ) != 0 + || wc_Chacha_SetKey(&ssh->decryptCipher.cipher.chacha.main, + key, CHACHA_MAX_KEY_SZ) != 0 + || wc_Chacha_SetKey(&ssh->decryptCipher.cipher.chacha.hdr, + key + CHACHA_MAX_KEY_SZ, CHACHA_MAX_KEY_SZ) != 0) { + result = -1063; + goto done; + } + ssh->encryptId = ID_CHACHA20_POLY1305_OPENSSH; + ssh->aeadMode = 1; + ssh->macSz = POLY1305_DIGEST_SIZE; + ssh->seq = seq; + ssh->peerEncryptId = ID_CHACHA20_POLY1305_OPENSSH; + ssh->peerAeadMode = 1; + ssh->peerBlockSz = MIN_BLOCK_SZ; + ssh->peerMacSz = POLY1305_DIGEST_SIZE; + ssh->peerSeq = seq; + ssh->curSz = 0; + ssh->processReplyState = PROCESS_INIT; + ssh->error = 0; + + WMEMCPY(record, pkt, UINT32_SZ); + if (wolfSSH_TestEncryptAead(ssh, record + UINT32_SZ, + pkt + UINT32_SZ, payloadSz, record + prefixLen, + record, UINT32_SZ) != WS_SUCCESS) { + result = -1064; + goto done; + } + + if (cases[c].tamper == CHACHA_RX_BODY) + record[UINT32_SZ] ^= 0x01; + else if (cases[c].tamper == CHACHA_RX_TAG) + record[totalLen - 1] ^= 0x01; + else if (cases[c].tamper == CHACHA_RX_LENGTH) + record[0] ^= 0x80; + + ShrinkBuffer(&ssh->inputBuffer, 1); + if (GrowBuffer(&ssh->inputBuffer, totalLen) != WS_SUCCESS) { + result = -1065; + goto done; + } + WMEMCPY(ssh->inputBuffer.buffer, record, totalLen); + ssh->inputBuffer.length = totalLen; + ssh->inputBuffer.idx = 0; + + ret = wolfSSH_TestDoReceive(ssh); + if (cases[c].error == WS_SUCCESS) { + if (ret != WS_SUCCESS || ssh->peerSeq != seq + 1) { + result = -1066; + goto done; + } + } + else { + if (ret != WS_FATAL_ERROR || ssh->error != cases[c].error) { + result = -1067; + goto done; + } + if (!ssh->highwaterFlag || !ssh->msgHighwaterFlag) { + result = -1068; + goto done; + } + /* A failed tag wipes the packet; a refused length wipes the + * first block, all that was read. */ + if (!IsZeroed(ssh->inputBuffer.buffer + ssh->inputBuffer.idx, + cases[c].error == WS_VERIFY_MAC_E ? + prefixLen : MIN_BLOCK_SZ)) { + result = -1069; + goto done; + } + } + + wolfSSH_free(ssh); + ssh = NULL; + } + +done: + wolfSSH_free(ssh); + wolfSSH_CTX_free(ctx); + return result; +} +#endif /* WOLFSSH_TEST_INTERNAL && !WOLFSSH_NO_CHACHA20_POLY1305 */ + #ifdef WOLFSSH_TEST_INTERNAL /* Verify DoReceive rejects a binary packet whose padding_length is below the @@ -2672,9 +2966,10 @@ static int test_DoReceive_RejectsMisalignedCtr(void) goto done5; } - if (wc_AesInit(&ssh->decryptCipher.aes, ssh->ctx->heap, INVALID_DEVID) != 0 - || wc_AesSetKey(&ssh->decryptCipher.aes, key, sizeof(key), iv, - AES_ENCRYPTION) != 0) { + if (wc_AesInit(&ssh->decryptCipher.cipher.aes, ssh->ctx->heap, + INVALID_DEVID) != 0 + || wc_AesSetKey(&ssh->decryptCipher.cipher.aes, key, sizeof(key), + iv, AES_ENCRYPTION) != 0) { result = -805; goto done5; } @@ -2829,10 +3124,10 @@ static int test_DoReceive_CbcRejectDiscards(void) /* The MAC is zeros, which is wrong for any key. */ WMEMSET(record + sizeof(pkt), 0, WC_SHA256_DIGEST_SIZE); - if (wc_AesInit(&ssh->decryptCipher.aes, ssh->ctx->heap, + if (wc_AesInit(&ssh->decryptCipher.cipher.aes, ssh->ctx->heap, INVALID_DEVID) != 0 - || wc_AesSetKey(&ssh->decryptCipher.aes, key, sizeof(key), - iv, AES_DECRYPTION) != 0) { + || wc_AesSetKey(&ssh->decryptCipher.cipher.aes, key, + sizeof(key), iv, AES_DECRYPTION) != 0) { result = -844; goto done6; } @@ -3113,8 +3408,10 @@ static int test_DoReceive_RejectsMisalignedAead(void) } totalLen = UINT32_SZ + payloadSz + AES_BLOCK_SIZE; - if (wc_AesInit(&ssh->decryptCipher.aes, ssh->ctx->heap, INVALID_DEVID) != 0 - || wc_AesGcmSetKey(&ssh->decryptCipher.aes, key, sizeof(key)) != 0) { + if (wc_AesInit(&ssh->decryptCipher.cipher.aes, ssh->ctx->heap, + INVALID_DEVID) != 0 + || wc_AesGcmSetKey(&ssh->decryptCipher.cipher.aes, key, + sizeof(key)) != 0) { result = -786; goto done4; } @@ -29819,7 +30116,19 @@ int wolfSSH_UnitTest(int argc, char** argv) testResult = testResult || unitResult; #endif -#if defined(WOLFSSH_TEST_INTERNAL) && !defined(WOLFSSH_NO_AEAD) +#if defined(WOLFSSH_TEST_INTERNAL) && !defined(WOLFSSH_NO_CHACHA20_POLY1305) + unitResult = test_ChachaPolyKat(); + printf("ChachaPolyKat: %s\n", + (unitResult == 0 ? "SUCCESS" : "FAILED")); + testResult = testResult || unitResult; + + unitResult = test_DoReceive_ChachaPoly(); + printf("DoReceive_ChachaPoly: %s\n", + (unitResult == 0 ? "SUCCESS" : "FAILED")); + testResult = testResult || unitResult; +#endif + +#if defined(WOLFSSH_TEST_INTERNAL) && !defined(WOLFSSH_NO_AES_GCM) unitResult = test_AeadIncrementExpIv(); printf("AeadIncrementExpIv: %s\n", (unitResult == 0 ? "SUCCESS" : "FAILED")); diff --git a/wolfssh/internal.h b/wolfssh/internal.h index b8aeeb8f2..9dea91187 100644 --- a/wolfssh/internal.h +++ b/wolfssh/internal.h @@ -35,6 +35,8 @@ #include #include #include +#include +#include #include #include #include @@ -482,6 +484,8 @@ extern "C" { #ifdef WOLFSSH_NO_AEAD #undef WOLFSSH_NO_AES_GCM #define WOLFSSH_NO_AES_GCM + #undef WOLFSSH_NO_CHACHA20_POLY1305 + #define WOLFSSH_NO_CHACHA20_POLY1305 #endif #if defined(NO_AES) || !defined(HAVE_AES_CBC) @@ -496,21 +500,31 @@ extern "C" { #undef WOLFSSH_NO_AES_GCM #define WOLFSSH_NO_AES_GCM #endif +#if !defined(HAVE_POLY1305) || !defined(HAVE_CHACHA) + #undef WOLFSSH_NO_CHACHA20_POLY1305 + #define WOLFSSH_NO_CHACHA20_POLY1305 +#endif #if defined(WOLFSSH_NO_AES_CBC) && \ defined(WOLFSSH_NO_AES_CTR) && \ - defined(WOLFSSH_NO_AES_GCM) + defined(WOLFSSH_NO_AES_GCM) && \ + defined(WOLFSSH_NO_CHACHA20_POLY1305) #error "You need at least one encryption algorithm." #endif +/* The cipher state and transport buffers are sized from wolfCrypt's AES. */ +#if defined(NO_AES) + #error "wolfSSH needs AES in wolfSSL, even with only chacha20-poly1305." +#endif /* AES-CBC is the only soft-disabled cipher. */ #if defined(WOLFSSH_NO_AES_CTR) && \ defined(WOLFSSH_NO_AES_GCM) && \ + defined(WOLFSSH_NO_CHACHA20_POLY1305) && \ !defined(WOLFSSH_NO_AES_CBC_SOFT_DISABLE) #error "The only encryption algorithms left are soft-disabled. Define " \ "WOLFSSH_NO_AES_CBC_SOFT_DISABLE to offer them." #endif -#if defined(WOLFSSH_NO_AES_GCM) +#if defined(WOLFSSH_NO_AES_GCM) && defined(WOLFSSH_NO_CHACHA20_POLY1305) #undef WOLFSSH_NO_AEAD #define WOLFSSH_NO_AEAD #endif @@ -539,6 +553,8 @@ enum { ID_AES128_GCM, ID_AES192_GCM, ID_AES256_GCM, + ID_CHACHA20_POLY1305, + ID_CHACHA20_POLY1305_OPENSSH, /* Integrity IDs */ ID_HMAC_SHA1, @@ -663,6 +679,13 @@ enum NameIdType { #define MAX_KEY_EXCHANGE 2 #define MAX_PUBLIC_KEY 1 #define MIN_RSA_SIG_SZ 2 +#ifndef WOLFSSH_NO_CHACHA20_POLY1305 + /* chacha20-poly1305 keys a main and a header ChaCha20 instance. */ + #define CHACHA_POLY_KEY_SZ (CHACHA_MAX_KEY_SZ * 2) + #define MAX_ENC_KEY_SZ CHACHA_POLY_KEY_SZ +#else + #define MAX_ENC_KEY_SZ AES_256_KEY_SIZE +#endif #define MAX_HMAC_SZ WC_MAX_DIGEST_SIZE #define MIN_BLOCK_SZ 8 #define COOKIE_SZ 16 @@ -1049,7 +1072,15 @@ struct WOLFSSH_CTX { typedef struct Ciphers { - Aes aes; + union { + Aes aes; +#ifndef WOLFSSH_NO_CHACHA20_POLY1305 + struct { + ChaCha main; + ChaCha hdr; + } chacha; +#endif + } cipher; /* cipherType picks the member */ byte cipherType; byte isInit; } Ciphers; @@ -1058,7 +1089,7 @@ typedef struct Ciphers { typedef struct Keys { byte iv[AES_BLOCK_SIZE]; byte ivSz; - byte encKey[AES_256_KEY_SIZE]; + byte encKey[MAX_ENC_KEY_SZ]; byte encKeySz; byte macKey[MAX_HMAC_SZ]; byte macKeySz; @@ -2358,11 +2389,13 @@ enum WS_MessageIdLimits { WOLFSSH_API int wolfSSH_TestScpExtractFileName(const char* filePath, char* fileName, word32 fileNameSz); #endif /* WOLFSSH_SCP && !WOLFSSH_SCP_USER_CALLBACKS */ -#ifndef WOLFSSH_NO_AEAD +#ifndef WOLFSSH_NO_AES_GCM WOLFSSH_API void wolfSSH_TestAeadIncrementExpIv(byte* iv); +#endif +#ifndef WOLFSSH_NO_AEAD WOLFSSH_API int wolfSSH_TestEncryptAead(WOLFSSH* ssh, byte* cipher, const byte* input, word32 sz, - byte* authTag, const byte* auth, word32 authSz); + byte* authTag, byte* auth, word32 authSz); WOLFSSH_API int wolfSSH_TestDecryptAead(WOLFSSH* ssh, byte* plain, const byte* input, word32 sz, const byte* authTag, const byte* auth, word32 authSz); diff --git a/wolfssh/ssh.h b/wolfssh/ssh.h index 02341d3a3..cb03f0b2e 100644 --- a/wolfssh/ssh.h +++ b/wolfssh/ssh.h @@ -219,9 +219,11 @@ WOLFSSH_API int wolfSSH_CheckAlgoName(const char* name); /* Strict KEX (Terrapin mitigation, CVE-2023-48795), enabled by default. * wolfSSH_new() copies the CTX setting, so a change affects only later - * sessions. The CTX calls return WS_BAD_ARGUMENT on NULL, else the getter - * returns 1 or 0. wolfSSH_GetStrictKexNegotiated() returns 1 if the - * session negotiated strict KEX, else 0, or WS_SSH_NULL_E on NULL. */ + * sessions. With it off, a session given the default cipher list leaves + * chacha20-poly1305 out. The CTX calls return WS_BAD_ARGUMENT on NULL, + * else the getter returns 1 or 0. wolfSSH_GetStrictKexNegotiated() returns + * 1 if the session negotiated strict KEX, else 0, or WS_SSH_NULL_E on + * NULL. */ WOLFSSH_API int wolfSSH_CTX_SetStrictKex(WOLFSSH_CTX* ctx, byte enable); WOLFSSH_API int wolfSSH_CTX_GetStrictKex(WOLFSSH_CTX* ctx); WOLFSSH_API int wolfSSH_GetStrictKexNegotiated(WOLFSSH* ssh); From 26c057da20a7303a2bd1d1173c4ffd21a54c3111 Mon Sep 17 00:00:00 2001 From: John Safranek Date: Fri, 20 Nov 2026 11:01:20 -0800 Subject: [PATCH 4/4] Rekey at the highwater mark with a NULL callback wolfSSH_SetHighwaterCb() takes a NULL callback, and HighwaterCheck() then set the flag and did nothing, so the session never rekeyed. A NULL callback now falls back to the default, which starts a key exchange. - Add a regress test that a NULL callback still rekeys --- src/internal.c | 8 ++++++-- tests/regress.c | 35 +++++++++++++++++++++++++++++++++++ wolfssh/ssh.h | 3 ++- 3 files changed, 43 insertions(+), 3 deletions(-) diff --git a/src/internal.c b/src/internal.c index 1a3374e23..ebe3037de 100644 --- a/src/internal.c +++ b/src/internal.c @@ -712,8 +712,12 @@ static INLINE int HighwaterCheck(WOLFSSH* ssh, byte side) if (fire && ssh->disconnected) fire = 0; - if (fire && ssh->ctx->highwaterCb) - ret = ssh->ctx->highwaterCb(side, ssh->highwaterCtx); + if (fire) { + if (ssh->ctx->highwaterCb != NULL) + ret = ssh->ctx->highwaterCb(side, ssh->highwaterCtx); + else + ret = wsHighwater(side, ssh); + } return ret; } diff --git a/tests/regress.c b/tests/regress.c index e49a76022..1cbd1aedf 100644 --- a/tests/regress.c +++ b/tests/regress.c @@ -3595,6 +3595,40 @@ static void TestSecondHighwaterSendsNoKexInit(void) FreeKexReplyHarness(&harness); } +/* A NULL highwater callback still rekeys: the mark falls back to the + * default callback rather than firing into nothing. */ +static void TestNullHighwaterCbRekeys(void) +{ + KexReplyHarness harness; + KexReplyRunResult result; + WOLFSSH* ssh; + int clientErr, serverErr; + + InitKexReplyHarness(&harness, REGRESS_DEFAULT_KEY_ALGO, + REGRESS_DEFAULT_KEY_PATH, 0, NULL); + RunKexReplyHandshake(&harness, &result); + AssertTrue(result.clientSuccess); + AssertTrue(result.serverSuccess); + + ssh = harness.server; + wolfSSH_SetHighwaterCb(ssh->ctx, ssh->ctx->highwaterMark, NULL); + AssertIntEQ(ssh->isKeying, 0); + ssh->highwaterMark = ssh->txCount + 1; + + AssertIntEQ(wolfSSH_SendIgnore(ssh, NULL, 0), WS_SUCCESS); + AssertIntEQ(ssh->highwaterFlag, 1); + AssertTrue((ssh->isKeying & WOLFSSH_SELF_IS_KEYING) != 0); + + PumpDuplexPairNoAssert(&harness, &clientErr, &serverErr); + AssertIntEQ(clientErr, WS_SUCCESS); + AssertIntEQ(serverErr, WS_SUCCESS); + AssertIntEQ(harness.client->isKeying, 0); + AssertIntEQ(harness.server->isKeying, 0); + AssertIntEQ(ssh->highwaterFlag, 0); + + FreeKexReplyHarness(&harness); +} + /* SendNewKeys() clears the self-keying flag as soon as this side's NEWKEYS * goes out, while the peer's NEWKEYS is still to come and the handshake is * still live. A rekey request in that window must not send a KEXINIT or @@ -25141,6 +25175,7 @@ int main(int argc, char** argv) TestStrictKexResetsSequenceNumbersOnRekey(); TestSecondTriggerSendsNoKexInit(); TestSecondHighwaterSendsNoKexInit(); + TestNullHighwaterCbRekeys(); TestTriggerAfterNewKeysSendsNoKexInit(); TestRekeyHoldsNonTransport(); TestRekeyHoldCapped(); diff --git a/wolfssh/ssh.h b/wolfssh/ssh.h index cb03f0b2e..e972bc912 100644 --- a/wolfssh/ssh.h +++ b/wolfssh/ssh.h @@ -135,7 +135,8 @@ WOLFSSH_API WS_SOCKET_T wolfSSH_get_fd(const WOLFSSH* ssh); WOLFSSH_API int wolfSSH_SetFilesystemHandle(WOLFSSH* ssh, void* handle); WOLFSSH_API void* wolfSSH_GetFilesystemHandle(WOLFSSH* ssh); -/* data high water mark functions (RFC 4253 Sec 9) */ +/* data high water mark functions (RFC 4253 Sec 9). A NULL callback uses + * the default, which starts a key exchange. */ typedef int (*WS_CallbackHighwater)(byte side, void* ctx); WOLFSSH_API void wolfSSH_SetHighwaterCb(WOLFSSH_CTX* ctx, word32 level, WS_CallbackHighwater cb);