wolfssh/tests/unit.c

31194 lines
1.1 MiB

/* unit.c
*
* Copyright (C) 2014-2026 wolfSSL Inc.
*
* This file is part of wolfSSH.
*
* wolfSSH is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* wolfSSH is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with wolfSSH. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#ifdef WOLFSSL_USER_SETTINGS
#include <wolfssl/wolfcrypt/settings.h>
#else
#include <wolfssl/options.h>
#endif
#include <stdio.h>
#include <wolfssh/ssh.h>
#include <wolfssh/keygen.h>
#include <wolfssh/error.h>
#include <wolfssh/internal.h>
#include <wolfssl/wolfcrypt/memory.h>
#include <wolfssl/wolfcrypt/random.h>
#include <wolfssl/wolfcrypt/integer.h>
#include <wolfssl/wolfcrypt/hmac.h>
#include <wolfssl/wolfcrypt/error-crypt.h>
#ifdef WOLFSSL_HAVE_MLKEM
#include <wolfssl/wolfcrypt/wc_mlkem.h>
#endif
#ifndef WOLFSSH_NO_RSA
#include <wolfssl/wolfcrypt/rsa.h>
#include <wolfssl/wolfcrypt/asn.h>
#endif
/* The Ed25519 key DER helpers arrive with asn.h, but that include is RSA-only
* and the Ed25519 tests do not need RSA. */
#include <wolfssl/wolfcrypt/asn_public.h>
#define WOLFSSH_TEST_HEX2BIN
/* The socket helpers, for the drain tests. A socketpair() found by configure
* says the platform has the rest of the sockets API they use, too. */
#ifdef HAVE_SOCKETPAIR
#define WOLFSSH_TEST_CLIENT
#include <sys/wait.h>
#endif
#include <wolfssh/test.h>
#include "unit.h"
/* Regression coverage for non-CA intermediate promotion. The test bodies use
* only public API, but keep WOLFSSH_TEST_INTERNAL: it limits them to the
* autotools test builds, which run with the ./keys certs the tests hard-load.
* Also needs the cert manager, runtime cert generation to forge the attack
* cert, ECDSA (the test certs are ECC), and a filesystem for the certs. */
#if defined(WOLFSSH_TEST_INTERNAL) && defined(WOLFSSH_CERTS) && \
defined(WOLFSSL_CERT_GEN) && !defined(WOLFSSH_NO_ECDSA) && \
!defined(NO_FILESYSTEM)
#define WOLFSSH_TEST_CERTMAN_PROMOTE
#include <wolfssl/wolfcrypt/ecc.h>
#include <wolfssl/wolfcrypt/asn.h>
#endif
/* Cert manager tests that read a test cert off disk. A superset of the
* WOLFSSH_TEST_CERTMAN_PROMOTE conditions above. */
#if defined(WOLFSSH_CERTS) && !defined(WOLFSSH_NO_ECDSA) && \
!defined(NO_FILESYSTEM)
#define WOLFSSH_TEST_CERTMAN_ROOTCA
/* The certman helpers use malloc/free and LONG_MAX; pull these in here so
* the tests build even when the SCP block below is not compiled.
* certman.h itself comes from the WOLFSSH_CERTS block below. */
#include <limits.h>
#include <stdlib.h>
#endif
/* wolfSSH_SetCertManager() is an unconditional WS_NOT_COMPILED stub before
* wolfSSL 4.6.0, which is where wolfSSL_CertManager_up_ref() landed. Skip the
* test there rather than failing on behaviour that is by design. */
#if defined(WOLFSSH_CERTS) && (LIBWOLFSSL_VERSION_HEX >= WOLFSSL_V4_6_0)
#define WOLFSSH_TEST_SET_CERTMAN
#endif
#ifdef WOLFSSH_CERTS
#include <wolfssh/certman.h>
#include <wolfssl/ssl.h>
#endif
#ifdef WOLFSSH_WINDOWS_CERT_STORE
#include <windows.h>
#include <wincrypt.h>
#include <wchar.h>
#ifndef CERT_SYSTEM_STORE_CURRENT_USER
#define CERT_SYSTEM_STORE_CURRENT_USER 0x00010000
#endif
#ifndef CERT_SYSTEM_STORE_LOCAL_MACHINE
#define CERT_SYSTEM_STORE_LOCAL_MACHINE 0x00020000
#endif
#ifndef CERT_SYSTEM_STORE_USERS
#define CERT_SYSTEM_STORE_USERS 0x00060000
#endif
#ifndef CERT_SYSTEM_STORE_CURRENT_SERVICE
#define CERT_SYSTEM_STORE_CURRENT_SERVICE 0x00040000
#endif
#ifndef CERT_SYSTEM_STORE_SERVICES
#define CERT_SYSTEM_STORE_SERVICES 0x00050000
#endif
#ifndef CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY
#define CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY 0x00070000
#endif
#ifndef CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY
#define CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY 0x00080000
#endif
#ifndef CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE
#define CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE 0x00090000
#endif
#endif
#ifdef WOLFSSH_SFTP
#include <wolfssh/wolfsftp.h>
#endif
#if defined(WOLFSSH_SCP) && !defined(WOLFSSH_SCP_USER_CALLBACKS) && \
!defined(NO_FILESYSTEM) && !defined(WOLFSSL_NUCLEUS) && \
!defined(_WIN32) && !defined(WOLFSSH_ZEPHYR)
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
/* Needs a server build that does file transfers and an off_t wide enough for
* a 4 GiB offset. A narrower one takes a reject path no 64-bit build hits. */
#if !defined(NO_FILESYSTEM) && !defined(USE_WINDOWS_API) && \
!defined(WOLFSSL_NUCLEUS) && !defined(WOLFSSH_ZEPHYR) && \
!defined(FREESCALE_MQX) && !defined(MICROCHIP_MPLAB_HARMONY) && \
!defined(WOLFSSH_USER_FILESYSTEM) && !defined(WOLFSSH_FATFS) && \
(defined(WOLFSSH_SFTP) || defined(WOLFSSH_SCP)) && \
!defined(NO_WOLFSSH_SERVER) && defined(SIZEOF_OFF_T) && SIZEOF_OFF_T == 8
#include <stdlib.h>
#include <errno.h>
#include <sys/stat.h>
#include <unistd.h>
#define WOLFSSH_TEST_PREAD_PWRITE
#endif
/* The SFTP put regression drives a client session over a scratch file, so it
* needs mkstemp() and a mounted filesystem. */
#if defined(WOLFSSH_SFTP) && !defined(NO_WOLFSSH_CLIENT) && \
!defined(NO_FILESYSTEM) && !defined(USE_WINDOWS_API) && \
!defined(WOLFSSL_NUCLEUS) && !defined(WOLFSSH_ZEPHYR) && \
!defined(FREESCALE_MQX) && !defined(MICROCHIP_MPLAB_HARMONY) && \
!defined(WOLFSSH_USER_FILESYSTEM) && !defined(WOLFSSH_FATFS)
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <errno.h>
#define WOLFSSH_TEST_SFTP_PUT
#endif
/* A port whose seek type cannot reach 4 GiB rejects the offset instead of
* truncating it. Needs a mounted filesystem for the scratch file. */
#if defined(WOLFSSH_ZEPHYR) && !defined(NO_FILESYSTEM) && \
(defined(WOLFSSH_SFTP) || defined(WOLFSSH_SCP)) && \
!defined(NO_WOLFSSH_SERVER) && defined(CONFIG_WOLFSSH_SFTP_DEFAULT_DIR) && \
defined(SIZEOF_OFF_T) && SIZEOF_OFF_T == 4
#define WOLFSSH_TEST_PREAD_PWRITE_CEILING
#endif
/* wResolveOffset() is defined whenever a port that does file transfers is
* built, so testing it directly needs no filesystem. */
#if (defined(WOLFSSH_SFTP) || defined(WOLFSSH_SCP) || \
defined(WOLFSSH_SSHD)) && \
!(defined(NO_WOLFSSH_SERVER) && defined(NO_WOLFSSH_CLIENT)) && \
(!defined(NO_FILESYSTEM) || defined(WOLFSSH_FATFS))
#define WOLFSSH_TEST_RESOLVE_OFFSET
#endif
/* SendChannelTerminalRequest() reads the terminal settings of stdin, so the
* no-tty case needs POSIX file descriptors to point stdin at /dev/null. */
#if defined(WOLFSSH_TEST_INTERNAL) && defined(WOLFSSH_TERM) && \
!defined(NO_FILESYSTEM) && !defined(NO_WOLFSSH_CLIENT) && \
!defined(USE_WINDOWS_API) && !defined(MICROCHIP_PIC32) && \
!defined(NO_TERMIOS) && !defined(WOLFSSL_NUCLEUS) && \
!defined(WOLFSSH_ZEPHYR) && !defined(_WIN32)
#define TEST_TERM_REQUEST_NO_TTY
/* the test pins TERM and juggles descriptors, so it needs malloc/free
* and the environment calls even when the blocks above are not built */
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#endif
#ifdef WOLFSSH_TEST_INTERNAL
typedef struct {
const char* name;
const char* proto;
int ioError;
int expected;
int side; /* WOLFSSH_ENDPOINT_CLIENT or WOLFSSH_ENDPOINT_SERVER */
} ProtoIdTestVector;
typedef struct {
const ProtoIdTestVector* tv;
word32 offset;
} ProtoIdTestState;
static const ProtoIdTestVector protoIdTestVectors[] = {
/* Pre-version banner lines (RFC 4253 Section 4.2). DoProtoId on the
* client skips informational lines before the version string. */
{ "banner lines LF before version",
"this is a test\n"
"more test line\n"
"SSH-2.0-wolfSSHv" LIBWOLFSSH_VERSION_STRING "\n",
0, WS_SUCCESS, WOLFSSH_ENDPOINT_CLIENT },
{ "banner lines CRLF before version",
"this is a test\r\n"
"more test line\r\n"
"SSH-2.0-wolfSSHv" LIBWOLFSSH_VERSION_STRING "\r\n",
0, WS_SUCCESS, WOLFSSH_ENDPOINT_CLIENT },
/* Valid version strings with no banner. */
{ "version with comment CRLF",
"SSH-2.0-wolfSSHv" LIBWOLFSSH_VERSION_STRING " some comment\r\n",
0, WS_SUCCESS, WOLFSSH_ENDPOINT_CLIENT },
{ "version CRLF no comment",
"SSH-2.0-wolfSSHv" LIBWOLFSSH_VERSION_STRING "\r\n",
0, WS_SUCCESS, WOLFSSH_ENDPOINT_CLIENT },
{ "version LF only",
"SSH-2.0-wolfSSHv" LIBWOLFSSH_VERSION_STRING "\n",
0, WS_SUCCESS, WOLFSSH_ENDPOINT_CLIENT },
/* Case rejection. DoProtoId uses WSTRNCMP. */
{ "lowercase ssh prefix",
"ssh-2.0-wolfSSHv" LIBWOLFSSH_VERSION_STRING "\r\n",
0, WS_SOCKET_ERROR_E, WOLFSSH_ENDPOINT_CLIENT },
{ "mixed case SSH prefix",
"Ssh-2.0-wolfSSHv" LIBWOLFSSH_VERSION_STRING "\r\n",
0, WS_SOCKET_ERROR_E, WOLFSSH_ENDPOINT_CLIENT },
/* Case rejection. DoProtoId uses WSTRNCMP. */
{ "lowercase ssh prefix",
"ssh-2.0-wolfSSHv" LIBWOLFSSH_VERSION_STRING "\r\n",
0, WS_VERSION_E, WOLFSSH_ENDPOINT_SERVER },
{ "mixed case SSH prefix",
"Ssh-2.0-wolfSSHv" LIBWOLFSSH_VERSION_STRING "\r\n",
0, WS_VERSION_E, WOLFSSH_ENDPOINT_SERVER },
/* OpenSSH peer identification. */
{ "OpenSSH version string",
"SSH-2.0-OpenSSH_8.9\r\n",
0, WS_SUCCESS, WOLFSSH_ENDPOINT_CLIENT },
/* Wrong SSH versions. */
{ "SSH-1.99 version",
"SSH-1.99-server\r\n",
0, WS_VERSION_E, WOLFSSH_ENDPOINT_CLIENT },
{ "SSH-1.0 version",
"SSH-1.0-old\r\n",
0, WS_VERSION_E, WOLFSSH_ENDPOINT_CLIENT },
{ "SSH-3.0 future version",
"SSH-3.0-future\r\n",
0, WS_VERSION_E, WOLFSSH_ENDPOINT_CLIENT },
/* Malformed or missing version strings. Cases where the peer sends
* incomplete data and then closes the connection map to
* WS_SOCKET_ERROR_E because GetInputLine treats a 0-byte recv as EOF. */
{ "no newline terminator",
"SSH-2.0-wolfSSHv" LIBWOLFSSH_VERSION_STRING,
0, WS_SOCKET_ERROR_E, WOLFSSH_ENDPOINT_CLIENT },
{ "empty line only",
"\r\n",
0, WS_SOCKET_ERROR_E, WOLFSSH_ENDPOINT_CLIENT },
{ "bare newline",
"\n",
0, WS_SOCKET_ERROR_E, WOLFSSH_ENDPOINT_CLIENT },
{ "not SSH at all",
"HTTP/1.1 200 OK\r\n",
0, WS_SOCKET_ERROR_E, WOLFSSH_ENDPOINT_CLIENT },
{ "SSH- prefix but truncated",
"SSH-\r\n",
0, WS_VERSION_E, WOLFSSH_ENDPOINT_CLIENT },
/* Line longer than the 255-byte per-line cap (RFC 4253 4.2). */
{ "overlong line before version",
"01234567890123456789012345678901234567890123456789"
"01234567890123456789012345678901234567890123456789"
"01234567890123456789012345678901234567890123456789"
"01234567890123456789012345678901234567890123456789"
"01234567890123456789012345678901234567890123456789"
"01234567890123456789012345678901234567890123456789"
"SSH-2.0-wolfSSHv" LIBWOLFSSH_VERSION_STRING "\r\n",
0, WS_VERSION_E, WOLFSSH_ENDPOINT_CLIENT },
/* Banner line of exactly 255 bytes including CRLF (253 chars + CRLF).
* The cap is inclusive so this line should be accepted. */
{ "banner exactly 255 bytes",
"01234567890123456789012345678901234567890123456789"
"01234567890123456789012345678901234567890123456789"
"01234567890123456789012345678901234567890123456789"
"01234567890123456789012345678901234567890123456789"
"01234567890123456789012345678901234567890123456789"
"012\r\n"
"SSH-2.0-wolfSSHv" LIBWOLFSSH_VERSION_STRING "\r\n",
0, WS_SUCCESS, WOLFSSH_ENDPOINT_CLIENT },
/* Banner consumed, then peer closes mid-version-line. Exercises a
* second GetInputLine call returning WS_SOCKET_ERROR_E after a prior
* call succeeded. */
{ "banner then truncated SSH line",
"banner line\nSSH-2.0-",
0, WS_SOCKET_ERROR_E, WOLFSSH_ENDPOINT_CLIENT },
/* More than WOLFSSH_MAX_BANNER_LINES (default 10) banner lines before
* the version string. The 11th banner line trips the cap. */
{ "too many banner lines",
"b1\nb2\nb3\nb4\nb5\nb6\nb7\nb8\nb9\nb10\nb11\n"
"SSH-2.0-wolfSSHv" LIBWOLFSSH_VERSION_STRING "\r\n",
0, WS_VERSION_E, WOLFSSH_ENDPOINT_CLIENT },
/* IO error cases. The IO callback returns WS_CBIO_ERR_* values.
* ReceiveData maps WS_CBIO_ERR_GENERAL to -1, and GetInputLine
* returns WS_SOCKET_ERROR_E for that. WS_CBIO_ERR_WANT_READ is
* mapped to WS_WANT_READ by ReceiveData and GetInputLine. */
{ "IO recv general error",
"", WS_CBIO_ERR_GENERAL, WS_SOCKET_ERROR_E, WOLFSSH_ENDPOINT_CLIENT },
{ "IO recv want read",
"", WS_CBIO_ERR_WANT_READ, WS_WANT_READ, WOLFSSH_ENDPOINT_CLIENT },
/* Server-side: a wolfSSH server reading the client's identification
* string MUST reject any non-"SSH-" line. The client is required to
* send the version string first per RFC 4253 4.2. */
{ "server accepts SSH- line",
"SSH-2.0-OpenSSH_8.9\r\n",
0, WS_SUCCESS, WOLFSSH_ENDPOINT_SERVER },
{ "server rejects banner before SSH-",
"client banner\r\n"
"SSH-2.0-OpenSSH_8.9\r\n",
0, WS_VERSION_E, WOLFSSH_ENDPOINT_SERVER },
{ "server rejects non-SSH protocol",
"GET / HTTP/1.1\r\n",
0, WS_VERSION_E, WOLFSSH_ENDPOINT_SERVER },
/* Protoversion is exactly "2.0" plus a '-'. A 7 byte compare lets
* "SSH-2.01-..." pass. (RFC 4253 4.2) */
{ "protoversion 2.01 rejected",
"SSH-2.01-Test\r\n",
0, WS_VERSION_E, WOLFSSH_ENDPOINT_CLIENT },
{ "server rejects protoversion 2.01",
"SSH-2.01-Test\r\n",
0, WS_VERSION_E, WOLFSSH_ENDPOINT_SERVER },
/* Protoversion runs into the terminator, no delimiter. */
{ "protoversion with no delimiter CRLF",
"SSH-2.0\r\n",
0, WS_VERSION_E, WOLFSSH_ENDPOINT_CLIENT },
{ "protoversion with no delimiter LF",
"SSH-2.0\n",
0, WS_VERSION_E, WOLFSSH_ENDPOINT_CLIENT },
/* Controls. */
{ "protoversion 2.0 accepted",
"SSH-2.0-Test\r\n",
0, WS_SUCCESS, WOLFSSH_ENDPOINT_CLIENT },
{ "server accepts protoversion 2.0",
"SSH-2.0-Test\r\n",
0, WS_SUCCESS, WOLFSSH_ENDPOINT_SERVER },
};
static int RecvFromPtr(WOLFSSH* ssh, void* data, word32 sz, void* ctx)
{
ProtoIdTestState* state;
const ProtoIdTestVector* tv;
word32 protoSz;
word32 remaining;
WOLFSSH_UNUSED(ssh);
state = (ProtoIdTestState*)ctx;
tv = state->tv;
if (tv->ioError)
return tv->ioError;
protoSz = (word32)WSTRLEN(tv->proto);
if (state->offset >= protoSz) {
/* Simulate the peer closing the connection after sending all the
* data in the test vector. */
return 0;
}
remaining = protoSz - state->offset;
if (remaining < sz)
sz = remaining;
WMEMCPY(data, tv->proto + state->offset, sz);
state->offset += sz;
return sz;
}
/* Scripted IO mock for testing non-blocking control flow. A script is a
* sequence of steps. Each step either delivers a chunk of bytes or signals
* a single WS_CBIO_ERR_WANT_READ to the caller. After the script is
* exhausted the mock returns 0 (clean EOF). Long byte chunks are delivered
* across multiple IO callback invocations as needed. */
typedef struct {
const char* bytes; /* NULL means "return WS_CBIO_ERR_WANT_READ" */
word32 sz; /* 0 means strlen(bytes) */
} ProtoIdScriptStep;
typedef struct {
const ProtoIdScriptStep* steps;
word32 stepCount;
word32 stepIdx;
word32 stepOffset;
} ProtoIdScriptState;
typedef struct {
const char* name;
const ProtoIdScriptStep* steps;
word32 stepCount;
int side;
int expected;
} ProtoIdScriptVector;
static int RecvFromScript(WOLFSSH* ssh, void* data, word32 sz, void* ctx)
{
ProtoIdScriptState* s;
const ProtoIdScriptStep* step;
word32 stepSz;
word32 remaining;
WOLFSSH_UNUSED(ssh);
s = (ProtoIdScriptState*)ctx;
while (s->stepIdx < s->stepCount) {
step = &s->steps[s->stepIdx];
if (step->bytes == NULL) {
/* WANT_READ marker; consume the step exactly once. */
s->stepIdx++;
s->stepOffset = 0;
return WS_CBIO_ERR_WANT_READ;
}
stepSz = step->sz ? step->sz : (word32)WSTRLEN(step->bytes);
if (s->stepOffset >= stepSz) {
s->stepIdx++;
s->stepOffset = 0;
continue;
}
remaining = stepSz - s->stepOffset;
if (remaining < sz)
sz = remaining;
WMEMCPY(data, step->bytes + s->stepOffset, sz);
s->stepOffset += sz;
if (s->stepOffset == stepSz) {
s->stepIdx++;
s->stepOffset = 0;
}
return (int)sz;
}
/* Script exhausted: simulate peer closing the connection. */
return 0;
}
/* WANT_READ delivered partway through a banner line. Driver retries and
* the partial line is completed cleanly. */
static const ProtoIdScriptStep wantReadMidBannerSteps[] = {
{ "this is a part", 0 },
{ NULL, 0 },
{ "ial banner\n"
"SSH-2.0-wolfSSHv" LIBWOLFSSH_VERSION_STRING "\r\n", 0 },
};
/* WANT_READ delivered partway through the SSH version line itself. */
static const ProtoIdScriptStep wantReadMidVersionSteps[] = {
{ "SSH-2.0-wolf", 0 },
{ NULL, 0 },
{ "SSHv" LIBWOLFSSH_VERSION_STRING "\r\n", 0 },
};
/* Eleven banner lines, each followed by WS_WANT_READ. WOLFSSH_MAX_BANNER_LINES
* defaults to 10, so the eleventh line must trip the cap. This is a
* regression guard: an earlier version kept the banner counter as a
* DoProtoId stack local, which got reset on every WS_WANT_READ retry and
* effectively bypassed the cap. */
static const ProtoIdScriptStep manyBannersWantReadSteps[] = {
{ "b1\n", 0 }, { NULL, 0 },
{ "b2\n", 0 }, { NULL, 0 },
{ "b3\n", 0 }, { NULL, 0 },
{ "b4\n", 0 }, { NULL, 0 },
{ "b5\n", 0 }, { NULL, 0 },
{ "b6\n", 0 }, { NULL, 0 },
{ "b7\n", 0 }, { NULL, 0 },
{ "b8\n", 0 }, { NULL, 0 },
{ "b9\n", 0 }, { NULL, 0 },
{ "b10\n", 0 }, { NULL, 0 },
{ "b11\n", 0 },
};
#define SCRIPT_LEN(s) (word32)(sizeof(s)/sizeof((s)[0]))
static const ProtoIdScriptVector protoIdScriptVectors[] = {
{ "WANT_READ mid-banner resumes",
wantReadMidBannerSteps, SCRIPT_LEN(wantReadMidBannerSteps),
WOLFSSH_ENDPOINT_CLIENT, WS_SUCCESS },
{ "WANT_READ mid-SSH-version resumes",
wantReadMidVersionSteps, SCRIPT_LEN(wantReadMidVersionSteps),
WOLFSSH_ENDPOINT_CLIENT, WS_SUCCESS },
{ "banners across WANT_READ still trip cap",
manyBannersWantReadSteps, SCRIPT_LEN(manyBannersWantReadSteps),
WOLFSSH_ENDPOINT_CLIENT, WS_VERSION_E },
};
/* Capture-to-buffer send callback for the SendProtoId() vectors. The
* proto ID is the first thing on the wire, so everything the callback
* sees is the ID line itself. */
typedef struct ProtoIdSendState {
byte buf[WOLFSSH_PROTOID_LIMIT + 1];
word32 len;
} ProtoIdSendState;
static int ProtoIdCaptureSend(WOLFSSH* ssh, void* buf, word32 sz, void* ctx)
{
ProtoIdSendState* s = (ProtoIdSendState*)ctx;
WOLFSSH_UNUSED(ssh);
if (sz > sizeof(s->buf) - s->len)
return WS_CBIO_ERR_GENERAL;
WMEMCPY(s->buf + s->len, buf, sz);
s->len += sz;
return (int)sz;
}
/* DoProtoId() Unit Test */
static int test_DoProtoId(void)
{
WOLFSSH_CTX* clientCtx;
WOLFSSH_CTX* serverCtx;
WOLFSSH_CTX* ctx;
WOLFSSH* ssh;
const ProtoIdTestVector* tv;
int tc = (int)(sizeof(protoIdTestVectors)/sizeof(protoIdTestVectors[0]));
int i;
int ret;
int failures = 0;
clientCtx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (clientCtx == NULL)
return -100;
serverCtx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (serverCtx == NULL) {
wolfSSH_CTX_free(clientCtx);
return -101;
}
wolfSSH_SetIORecv(clientCtx, RecvFromPtr);
wolfSSH_SetIORecv(serverCtx, RecvFromPtr);
for (i = 0, tv = protoIdTestVectors; i < tc; i++, tv++) {
ProtoIdTestState state;
state.tv = tv;
state.offset = 0;
ctx = (tv->side == WOLFSSH_ENDPOINT_SERVER) ? serverCtx : clientCtx;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
fprintf(stderr, "\t[%d] \"%s\" FAIL: wolfSSH_new returned NULL\n",
i, tv->name);
failures++;
continue;
}
wolfSSH_SetIOReadCtx(ssh, &state);
ret = wolfSSH_TestDoProtoId(ssh);
if (ret != tv->expected) {
fprintf(stderr, "\t[%d] \"%s\" FAIL: got %d, expected %d\n",
i, tv->name, ret, tv->expected);
failures++;
}
wolfSSH_free(ssh);
}
/* Scripted-IO vectors: exercise non-blocking flow where ReceiveData
* returns WS_WANT_READ partway through a line. The driver re-enters
* DoProtoId until it returns something other than WS_WANT_READ. */
wolfSSH_SetIORecv(clientCtx, RecvFromScript);
wolfSSH_SetIORecv(serverCtx, RecvFromScript);
{
const ProtoIdScriptVector* sv;
int sc = (int)(sizeof(protoIdScriptVectors)
/ sizeof(protoIdScriptVectors[0]));
for (i = 0, sv = protoIdScriptVectors; i < sc; i++, sv++) {
ProtoIdScriptState scriptState;
scriptState.steps = sv->steps;
scriptState.stepCount = sv->stepCount;
scriptState.stepIdx = 0;
scriptState.stepOffset = 0;
ctx = (sv->side == WOLFSSH_ENDPOINT_SERVER)
? serverCtx : clientCtx;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
fprintf(stderr,
"\t[script %d] \"%s\" FAIL: wolfSSH_new returned NULL\n",
i, sv->name);
failures++;
continue;
}
wolfSSH_SetIOReadCtx(ssh, &scriptState);
do {
ret = wolfSSH_TestDoProtoId(ssh);
} while (ret == WS_WANT_READ);
if (ret != sv->expected) {
fprintf(stderr,
"\t[script %d] \"%s\" FAIL: got %d, expected %d\n",
i, sv->name, ret, sv->expected);
failures++;
}
wolfSSH_free(ssh);
}
}
{
static char tooLongProtoId[WOLFSSH_PROTOID_LIMIT + 2];
static char justRightProtoId[WOLFSSH_PROTOID_LIMIT + 1];
/* Ensure a malformed local protoId cannot be loaded. */
{
static const struct {
const char* name;
const char* id;
int expectSuccess;
} protoIds[] = {
{ "conforming custom ID", "SSH-2.0-this_is_my_app\r\n", 1 },
{ "shortest valid Id", "SSH-2.0-t\r\n", 1 },
{ "exact len custom ID", justRightProtoId, 1 },
/* Pin the printable-ASCII range as inclusive at both ends: an
* interior 0x20 (the RFC 4253 "SP comments" suffix) and a
* 0x7e must both be accepted. */
{ "body w/ SP comments", "SSH-2.0-app comment\r\n", 1 },
{ "body w/ tilde", "SSH-2.0-app~1\r\n", 1 },
/* RFC 4253 section 4.2 bars '-' only from softwareversion. */
{ "comments w/ minus", "SSH-2.0-app my-comment\r\n", 1 },
{ "comments are minus", "SSH-2.0-app -\r\n", 1 },
/* Failing Tests */
{ "wrong version prefix", "SSH-2-this_is_my_app\r\n", 0 },
{ "bad casing prefix", "sSH-2.0-this_is_my_app\r\n", 0 },
{ "LF terminator only", "SSH-2.0-this_is_my_app\n", 0 },
{ "CR terminator only", "SSH-2.0-this_is_my_app\r", 0 },
{ "empty string", "", 0 },
{ "prefix with no body", "SSH-2.0-\r\n", 0 },
{ "missing prefix", "hello-this-is\r\n", 0 },
{ "non ascii char", "SSH-2.0-\x90s\r\n", 0 },
{ "Body End in CR", "SSH-2.0-s\r\r\n", 0 },
{ "Body End in TAB", "SSH-2.0-s\t\r\n", 0 },
{ "body starts w/ space", "SSH-2.0-\x20-a-b\r\n", 0 },
{ "body has embedded TAB", "SSH-2.0-\x7e" "a\t\r\n", 0 },
{ "swversion w/ minus", "SSH-2.0-my-app\r\n", 0 },
{ "swversion is minus", "SSH-2.0--\r\n", 0 },
{ "minus before comments", "SSH-2.0-app- comment\r\n", 0 },
{ "too long id", tooLongProtoId, 0 },
{ "null pointer", NULL, 0 },
};
int pc = (int)(sizeof(protoIds) / sizeof(protoIds[0]));
WMEMSET(tooLongProtoId, 'a', sizeof(tooLongProtoId));
WMEMCPY(tooLongProtoId, "SSH-2.0-", sizeof("SSH-2.0-") - 1);
tooLongProtoId[sizeof(tooLongProtoId) - 1] = '\0';
tooLongProtoId[sizeof(tooLongProtoId) - 2] = '\n';
tooLongProtoId[sizeof(tooLongProtoId) - 3] = '\r';
WMEMSET(justRightProtoId, 'a', sizeof(justRightProtoId));
WMEMCPY(justRightProtoId, "SSH-2.0-", sizeof("SSH-2.0-") - 1);
justRightProtoId[sizeof(justRightProtoId) - 1] = '\0';
justRightProtoId[sizeof(justRightProtoId) - 2] = '\n';
justRightProtoId[sizeof(justRightProtoId) - 3] = '\r';
for (i = 0; i < pc; i++) {
const char* prevId = clientCtx->sshProtoIdStr;
ret = wolfSSH_CTX_SetSshProtoIdStr(clientCtx, protoIds[i].id);
if ((ret == WS_SUCCESS) != protoIds[i].expectSuccess) {
fprintf(stderr,
"\t[protoId %d] \"%s\" FAIL: got %d, expected %s\n",
i, protoIds[i].name, ret,
protoIds[i].expectSuccess ? "WS_SUCCESS"
: "WS_BAD_ARGUMENT");
failures++;
}
if (!protoIds[i].expectSuccess &&
clientCtx->sshProtoIdStr != prevId) {
fprintf(stderr,
"\t[protoId %d] \"%s\" FAIL: invalid proto id "
"was stored\n",
i, protoIds[i].name);
failures++;
}
if (clientCtx->sshProtoIdStrSz !=
(word32)WSTRLEN(clientCtx->sshProtoIdStr)) {
fprintf(stderr,
"\t[protoId %d] \"%s\" FAIL: stored sshProtoIdStrSz "
"was not retained\n",
i, protoIds[i].name);
failures++;
}
}
}
/* A configured proto ID must reach the wire byte for byte. */
{
static const char* const sendIds[] = {
"SSH-2.0-this_is_my_app\r\n",
"SSH-2.0-t\r\n",
"SSH-2.0-app comment\r\n",
justRightProtoId,
};
int sc = (int)(sizeof(sendIds) / sizeof(sendIds[0]));
wolfSSH_SetIOSend(clientCtx, ProtoIdCaptureSend);
for (i = 0; i < sc; i++) {
ProtoIdSendState sendState;
word32 expectSz = (word32)WSTRLEN(sendIds[i]);
ret = wolfSSH_CTX_SetSshProtoIdStr(clientCtx, sendIds[i]);
if (ret != WS_SUCCESS) {
fprintf(stderr,
"\t[send %d] FAIL: set proto id returned %d\n",
i, ret);
failures++;
continue;
}
ssh = wolfSSH_new(clientCtx);
if (ssh == NULL) {
fprintf(stderr,
"\t[send %d] FAIL: wolfSSH_new returned NULL\n", i);
failures++;
continue;
}
WMEMSET(&sendState, 0, sizeof(sendState));
wolfSSH_SetIOWriteCtx(ssh, &sendState);
ret = wolfSSH_TestSendProtoId(ssh);
if (ret != WS_SUCCESS) {
fprintf(stderr,
"\t[send %d] FAIL: SendProtoId returned %d\n",
i, ret);
failures++;
}
else if (sendState.len != expectSz ||
WMEMCMP(sendState.buf, sendIds[i], expectSz) != 0) {
fprintf(stderr,
"\t[send %d] FAIL: wrote %u bytes, expected the "
"%u byte proto id back verbatim\n",
i, sendState.len, expectSz);
failures++;
}
wolfSSH_free(ssh);
}
}
}
wolfSSH_CTX_free(serverCtx);
wolfSSH_CTX_free(clientCtx);
return failures;
}
/* GetMpint() Unit Test */
typedef struct {
const char* name;
const byte* input;
word32 inputSz;
int expected; /* expected return value */
word32 expectedSz; /* expected mpint size on success */
} GetMpintTestVector;
static const byte mpintPositive[] = { 0, 0, 0, 4, 0x12, 0x34, 0x56, 0x78 };
static const byte mpintLeadZero[] = { 0, 0, 0, 3, 0x00, 0x80, 0x01 };
static const byte mpintZeroLen[] = { 0, 0, 0, 0 };
static const byte mpintNegative[] = { 0, 0, 0, 2, 0x80, 0x01 };
static const byte mpintNegOne[] = { 0, 0, 0, 1, 0xFF };
static const byte mpintShort[] = { 0, 0, 0, 5, 0x01, 0x02 };
static const GetMpintTestVector getMpintTestVectors[] = {
{ "positive", mpintPositive, sizeof(mpintPositive), WS_SUCCESS, 4 },
{ "canonical leading zero", mpintLeadZero, sizeof(mpintLeadZero),
WS_SUCCESS, 3 },
{ "zero length", mpintZeroLen, sizeof(mpintZeroLen), WS_SUCCESS, 0 },
{ "negative", mpintNegative, sizeof(mpintNegative), WS_PARSE_E, 0 },
{ "negative one", mpintNegOne, sizeof(mpintNegOne), WS_PARSE_E, 0 },
{ "length past end of buffer", mpintShort, sizeof(mpintShort),
WS_BUFFER_E, 0 },
};
static int test_GetMpint(void)
{
const GetMpintTestVector* tv;
int tc = (int)(sizeof(getMpintTestVectors)/sizeof(getMpintTestVectors[0]));
int i;
int ret;
int failures = 0;
for (i = 0, tv = getMpintTestVectors; i < tc; i++, tv++) {
const byte* mpint = NULL;
word32 mpintSz = 0;
word32 idx = 0;
ret = GetMpint(&mpintSz, &mpint, tv->input, tv->inputSz, &idx);
if (ret != tv->expected) {
fprintf(stderr, "\t[%d] \"%s\" FAIL: got %d, expected %d\n",
i, tv->name, ret, tv->expected);
failures++;
continue;
}
if (ret == WS_SUCCESS) {
const byte* expectedPtr =
(tv->expectedSz > 0) ? tv->input + LENGTH_SZ : NULL;
if (mpintSz != tv->expectedSz) {
fprintf(stderr,
"\t[%d] \"%s\" FAIL: size %u, expected %u\n",
i, tv->name, mpintSz, tv->expectedSz);
failures++;
}
else if (mpint != expectedPtr || idx != LENGTH_SZ + mpintSz) {
fprintf(stderr,
"\t[%d] \"%s\" FAIL: bad pointer or index\n",
i, tv->name);
failures++;
}
}
}
return failures;
}
#endif /* WOLFSSH_TEST_INTERNAL */
/* Key Derivation Function (KDF) Unit Test */
typedef struct {
byte hashId;
byte keyId;
const char* k;
const char* h;
const char* sessionId;
const char* expectedKey;
} KdfTestVector;
#ifndef NO_SHA
/** Test Vector Set #1: SHA-1 **/
const char kdfTvSet1k[] =
"35618FD3AABF980A5F766408961600D4933C60DD7B22D69EEB4D7A987C938F6F"
"7BB2E60E0F638BB4289297B588E6109057325F010D021DF60EBF8BE67AD9C3E2"
"6376A326A16210C7AF07B3FE562B8DD1DCBECB17AA7BFAF38708B0136120B2FC"
"723E93EF4237AC3737BAE3A16EC03F605C7EEABFD526B38C826B506BBAECD2F7"
"9932F1371AEABFBEB4F8222313506677330C714A2A6FDC70CB859B581AA18625"
"ECCB6BA9DDEEAECF0E41D9E5076B899B477112E59DDADC4B4D9C13E9F07E1107"
"B560FEFDC146B8ED3E73441D05345031C35F9E6911B00319481D80015855BE4D"
"1C7D7ACC8579B1CC2E5F714109C0882C3B57529ABDA1F2255D2B27C4A83AE11E";
const char kdfTvSet1h[] = "40555741F6DE70CDC4E740104A97E75473F49064";
const char kdfTvSet1sid[] = "40555741F6DE70CDC4E740104A97E75473F49064";
const char kdfTvSet1a[] = "B2EC4CF6943632C39972EE2801DC7393";
const char kdfTvSet1b[] = "BC92238B6FA69ECC10B2B013C2FC9785";
const char kdfTvSet1c[] = "9EF0E2053F66C56F3E4503DA1C2FBD6B";
const char kdfTvSet1d[] = "47C8395B08277020A0645DA3959FA1A9";
const char kdfTvSet1e[] = "EE436BFDABF9B0313224EC800E7390445E2F575E";
const char kdfTvSet1f[] = "FB9FDEEC78B0FB258F1A4F47F6BCE166680994BB";
/** Test Vector Set #2: SHA-1 **/
const char kdfTvSet2k[] =
"19FA2B7C7F4FE7DE61CDE17468C792CCEAB0E3F2CE37CDE2DAA0974BCDFFEDD4"
"A29415CDB330FA6A97ECA742359DC1223B581D8AC61B43CFFDF66D20952840B0"
"2593B48354E352E2A396BDF7F1C9D414FD31C2BF47E6EED306069C4F4F5F66C3"
"003A90E85412A1FBE89CDFB457CDA0D832E8DA701627366ADEC95B70E8A8B7BF"
"3F85775CCF36E40631B83B32CF643088F01A82C97C5C3A820EB4149F551CAF8C"
"C98EE6B3065E6152FF877823F7C618C1CD93CE26DB9FAAFED222F1C93E8F4068"
"BFDA4480432E14F98FFC821F05647693040B07D71DC273121D53866294434D46"
"0E95CFA4AB4414705BF1F8224655F907A418A6A893F2A71019225869CB7FE988";
const char kdfTvSet2h[] = "DFB748905CC8647684C3E0B7F26A3E8E7414AC51";
const char kdfTvSet2sid[] = "DFB748905CC8647684C3E0B7F26A3E8E7414AC51";
const char kdfTvSet2a[] = "52EDBFD5E414A3CC6C7F7A0F4EA60503";
const char kdfTvSet2b[] = "926C6987696C5FFCC6511BFE34557878";
const char kdfTvSet2c[] = "CB6D56EC5B9AFECD326D544DA2D22DED";
const char kdfTvSet2d[] = "F712F6451F1BD6CE9BAA597AC87C5A24";
const char kdfTvSet2e[] = "E42FC62C76B76B37818F78292D3C2226D0264760";
const char kdfTvSet2f[] = "D14BE4DD0093A3E759580233C80BB8399CE4C4E7";
#endif
/** Test Vector Set #3: SHA-256 **/
const char kdfTvSet3k[] =
"6AC382EAACA093E125E25C24BEBC84640C11987507344B5C739CEB84A9E0B222"
"B9A8B51C839E5EBE49CFADBFB39599764ED522099DC912751950DC7DC97FBDC0"
"6328B68F22781FD315AF568009A5509E5B87A11BF527C056DAFFD82AB6CBC25C"
"CA37143459E7BC63BCDE52757ADEB7DF01CF12173F1FEF8102EC5AB142C213DD"
"9D30696278A8D8BC32DDE9592D28C078C6D92B947D825ACAAB6494846A49DE24"
"B9623F4889E8ADC38E8C669EFFEF176040AD945E90A7D3EEC15EFEEE78AE7104"
"3C96511103A16BA7CAF0ACD0642EFDBE809934FAA1A5F1BD11043649B25CCD1F"
"EE2E38815D4D5F5FC6B4102969F21C22AE1B0E7D3603A556A13262FF628DE222";
const char kdfTvSet3h[] =
"7B7001185E256D4493445F39A55FB905E6321F4B5DD8BBF3100D51BA0BDA3D2D";
const char kdfTvSet3sid[] =
"7B7001185E256D4493445F39A55FB905E6321F4B5DD8BBF3100D51BA0BDA3D2D";
const char kdfTvSet3a[] = "81F0330EF6F05361B3823BFDED6E1DE9";
const char kdfTvSet3b[] = "3F6FD2065EEB2B0B1D93195A1FED48A5";
const char kdfTvSet3c[] = "C35471034E6FD6547613178E23435F21";
const char kdfTvSet3d[] = "7E9D79032090D99F98B015634DD9F462";
const char kdfTvSet3e[] =
"24EE559AD7CE712B685D0B2271E443C17AB1D1DCEB5A360569D25D5DC243002F";
const char kdfTvSet3f[] =
"C3419C2B966235869D714BA5AC48DDB7D9E35C8C19AAC73422337A373453607E";
/** Test Vector Set #4: SHA-256 **/
const char kdfTvSet4k[] =
"44708C76616F700BD31B0C155EF74E36390EEB39BC5C32CDC90E21922B0ED930"
"B5B519C8AFEBEF0F4E4FB5B41B81D649D2127506620B594E9899F7F0D442ECDD"
"D68308307B82F00065E9D75220A5A6F5641795772132215A236064EA965C6493"
"C21F89879730EBBC3C20A22D8F5BFD07B525B194323B22D8A49944D1AA58502E"
"756101EF1E8A91C9310E71F6DB65A3AD0A542CFA751F83721A99E89F1DBE5497"
"1A3620ECFFC967AA55EED1A42D6E7A138B853557AC84689889F6D0C8553575FB"
"89B4E13EAB5537DA72EF16F0D72F5E8505D97F110745193D550FA315FE88F672"
"DB90D73843E97BA1F3D087BA8EB39025BBFFAD37589A6199227303D9D8E7F1E3";
const char kdfTvSet4h[] =
"FE3727FD99A5AC7987C2CFBE062129E3027BF5E10310C6BCCDE9C916C8329DC2";
const char kdfTvSet4sid[] =
"FFFA598BC0AD2AE84DC8DC05B1F72C5B0134025AE7EDF8A2E8DB11472E18E1FC";
const char kdfTvSet4a[] = "36730BAE8DE5CB98898D6B4A00B37058";
const char kdfTvSet4b[] = "5DFE446A83F40E8358D28CB97DF8F340";
const char kdfTvSet4c[] = "495B7AFED0872B761437728E9E94E2B8";
const char kdfTvSet4d[] = "C1474B3925BEC36F0B7F6CC698E949C8";
const char kdfTvSet4e[] =
"B730F8DF6A0697645BE261169486C32A11612229276CBAC5D8B3669AFB2E4262";
const char kdfTvSet4f[] =
"14A5EA98245FB058978B82A3CB092B1CCA7CE0109A4F98C16E1529579D58B819";
#define HASH_SHA WC_HASH_TYPE_SHA
#define HASH_SHA256 WC_HASH_TYPE_SHA256
static const KdfTestVector kdfTestVectors[] = {
#ifndef NO_SHA
{HASH_SHA, 'A', kdfTvSet1k, kdfTvSet1h, kdfTvSet1sid, kdfTvSet1a},
{HASH_SHA, 'B', kdfTvSet1k, kdfTvSet1h, kdfTvSet1sid, kdfTvSet1b},
{HASH_SHA, 'C', kdfTvSet1k, kdfTvSet1h, kdfTvSet1sid, kdfTvSet1c},
{HASH_SHA, 'D', kdfTvSet1k, kdfTvSet1h, kdfTvSet1sid, kdfTvSet1d},
{HASH_SHA, 'E', kdfTvSet1k, kdfTvSet1h, kdfTvSet1sid, kdfTvSet1e},
{HASH_SHA, 'F', kdfTvSet1k, kdfTvSet1h, kdfTvSet1sid, kdfTvSet1f},
{HASH_SHA, 'A', kdfTvSet2k, kdfTvSet2h, kdfTvSet2sid, kdfTvSet2a},
{HASH_SHA, 'B', kdfTvSet2k, kdfTvSet2h, kdfTvSet2sid, kdfTvSet2b},
{HASH_SHA, 'C', kdfTvSet2k, kdfTvSet2h, kdfTvSet2sid, kdfTvSet2c},
{HASH_SHA, 'D', kdfTvSet2k, kdfTvSet2h, kdfTvSet2sid, kdfTvSet2d},
{HASH_SHA, 'E', kdfTvSet2k, kdfTvSet2h, kdfTvSet2sid, kdfTvSet2e},
{HASH_SHA, 'F', kdfTvSet2k, kdfTvSet2h, kdfTvSet2sid, kdfTvSet2f},
#endif
{HASH_SHA256, 'A', kdfTvSet3k, kdfTvSet3h, kdfTvSet3sid, kdfTvSet3a},
{HASH_SHA256, 'B', kdfTvSet3k, kdfTvSet3h, kdfTvSet3sid, kdfTvSet3b},
{HASH_SHA256, 'C', kdfTvSet3k, kdfTvSet3h, kdfTvSet3sid, kdfTvSet3c},
{HASH_SHA256, 'D', kdfTvSet3k, kdfTvSet3h, kdfTvSet3sid, kdfTvSet3d},
{HASH_SHA256, 'E', kdfTvSet3k, kdfTvSet3h, kdfTvSet3sid, kdfTvSet3e},
{HASH_SHA256, 'F', kdfTvSet3k, kdfTvSet3h, kdfTvSet3sid, kdfTvSet3f},
{HASH_SHA256, 'A', kdfTvSet4k, kdfTvSet4h, kdfTvSet4sid, kdfTvSet4a},
{HASH_SHA256, 'B', kdfTvSet4k, kdfTvSet4h, kdfTvSet4sid, kdfTvSet4b},
{HASH_SHA256, 'C', kdfTvSet4k, kdfTvSet4h, kdfTvSet4sid, kdfTvSet4c},
{HASH_SHA256, 'D', kdfTvSet4k, kdfTvSet4h, kdfTvSet4sid, kdfTvSet4d},
{HASH_SHA256, 'E', kdfTvSet4k, kdfTvSet4h, kdfTvSet4sid, kdfTvSet4e},
{HASH_SHA256, 'F', kdfTvSet4k, kdfTvSet4h, kdfTvSet4sid, kdfTvSet4f}
};
static int test_KDF(void)
{
int result = 0;
word32 i;
word32 tc = sizeof(kdfTestVectors)/sizeof(KdfTestVector);
const KdfTestVector* tv = NULL;
byte* k = NULL;
byte* h = NULL;
byte* sId = NULL;
byte* eKey = NULL;
word32 kSz = 0, hSz = 0, sIdSz = 0, eKeySz = 0;
byte cKey[32]; /* Greater of SHA256_DIGEST_SIZE and AES_BLOCK_SIZE */
/* sId - Session ID, eKey - Expected Key, cKey - Calculated Key */
for (i = 0, tv = kdfTestVectors; i < tc; i++, tv++) {
result = ConvertHexToBin(tv->k, &k, &kSz,
tv->h, &h, &hSz,
tv->sessionId, &sId, &sIdSz,
tv->expectedKey, &eKey, &eKeySz);
if (result != 0 || eKey == NULL) {
printf("KDF: Could not convert test vector %u.\n", i);
result = -100;
}
if (result == 0) {
result = wolfSSH_KDF(tv->hashId, tv->keyId, cKey, eKeySz,
k, kSz, h, hSz, sId, sIdSz);
if (result != 0) {
printf("KDF: Could not derive key.\n");
result = -101;
}
}
if (result == 0) {
if (memcmp(cKey, eKey, eKeySz) != 0) {
printf("KDF: Calculated Key does not match Expected Key.\n");
result = -102;
}
}
FreeBins(k, h, sId, eKey);
k = NULL;
h = NULL;
sId = NULL;
eKey = NULL;
if (result != 0) break;
}
return result;
}
/* Checks the internal.h derivation directly, independent of any API. */
#if defined(WOLFSSH_NO_MLDSA44) && defined(WOLFSSH_NO_MLDSA65) && \
defined(WOLFSSH_NO_MLDSA87) && !defined(WOLFSSH_NO_MLDSA)
#error "WOLFSSH_NO_MLDSA must follow from all three levels being off"
#endif
/* Key Generation Unit Test */
#ifdef WOLFSSH_KEYGEN
#ifndef WOLFSSH_NO_RSA
static int test_RsaKeyGen(void)
{
int result = 0;
byte der[1200];
int derSz;
derSz = wolfSSH_MakeRsaKey(der, sizeof(der),
WOLFSSH_RSAKEY_DEFAULT_SZ,
WOLFSSH_RSAKEY_DEFAULT_E);
if (derSz < 0) {
printf("RsaKeyGen: MakeRsaKey failed\n");
result = -103;
}
return result;
}
#endif
#ifndef WOLFSSH_NO_ECDSA
static int test_EcdsaKeyGen(void)
{
int result = 0;
byte der[1200];
int derSz;
derSz = wolfSSH_MakeEcdsaKey(der, sizeof(der),
WOLFSSH_ECDSAKEY_PRIME256);
if (derSz < 0) {
printf("EcdsaKeyGen: MakeEcdsaKey failed\n");
result = -104;
}
return result;
}
#endif
#if !defined(WOLFSSH_NO_ED25519) && defined(HAVE_ED25519) && \
defined(HAVE_ED25519_MAKE_KEY) && defined(HAVE_ED25519_KEY_EXPORT)
static int test_Ed25519KeyGen(void)
{
int result = 0;
byte der[1200];
int derSz;
derSz = wolfSSH_MakeEd25519Key(der, sizeof(der), WOLFSSH_ED25519KEY);
if (derSz < 0) {
printf("Ed25519KeyGen: MakeEd25519Key failed\n");
result = -105;
}
return result;
}
#endif
#ifndef WOLFSSH_NO_MLDSA
static int test_MlDsaKeyGen(void)
{
static const struct {
word32 level;
word32 derSz;
const char* name;
} params[] = {
#ifndef WOLFSSH_NO_MLDSA44
{ WOLFSSH_MLDSAKEY_44, WC_MLDSA_44_BOTH_KEY_DER_SIZE, "44" },
#endif
#ifndef WOLFSSH_NO_MLDSA65
{ WOLFSSH_MLDSAKEY_65, WC_MLDSA_65_BOTH_KEY_DER_SIZE, "65" },
#endif
#ifndef WOLFSSH_NO_MLDSA87
{ WOLFSSH_MLDSAKEY_87, WC_MLDSA_87_BOTH_KEY_DER_SIZE, "87" },
#endif
};
word32 i;
int result = 0;
for (i = 0; i < (word32)(sizeof(params) / sizeof(params[0])); i++) {
byte* der;
int sz;
der = (byte*)WMALLOC(params[i].derSz, NULL, DYNTYPE_BUFFER);
if (der == NULL) {
printf("MlDsaKeyGen: alloc failed for level %s\n", params[i].name);
result = -106;
break;
}
sz = wolfSSH_MakeMlDsaKey(der, params[i].derSz, params[i].level);
if (sz < 0) {
printf("MlDsaKeyGen: MakeMlDsaKey level %s failed (%d)\n",
params[i].name, sz);
WFREE(der, NULL, DYNTYPE_BUFFER);
result = -107;
break;
}
/* Confirm exact DER size for boundary check. */
if ((word32)sz != params[i].derSz) {
printf("MlDsaKeyGen: level %s DER size %d != constant %u\n",
params[i].name, sz, params[i].derSz);
WFREE(der, NULL, DYNTYPE_BUFFER);
result = -108;
break;
}
sz = wolfSSH_MakeMlDsaKey(der, params[i].derSz - 1, params[i].level);
if (sz != WS_CRYPTO_FAILED) {
printf("MlDsaKeyGen: undersized buffer wrong result %d, level %s\n",
sz, params[i].name);
WFREE(der, NULL, DYNTYPE_BUFFER);
result = -109;
break;
}
WFREE(der, NULL, DYNTYPE_BUFFER);
}
if (result == 0) {
int sz = wolfSSH_MakeMlDsaKey(NULL, 0, 9999);
if (sz != WS_BAD_ARGUMENT) {
printf("MlDsaKeyGen: invalid level wrong result %d\n", sz);
result = -110;
}
}
return result;
}
/* Round-trip test for ML-DSA composite keys. */
#ifndef WOLFSSH_NO_MLDSA_COMPOSITES
static int test_MlDsaCompositeKeyGen(void)
{
/* NULL-terminated sentinel bounds the loop. */
static const struct {
word32 level;
word32 tradType;
const char* name;
} params[] = {
#ifndef WOLFSSH_NO_MLDSA44_ED25519
{ WOLFSSH_MLDSAKEY_44, WOLFSSH_COMPOSITE_TRAD_ED25519, "44+Ed25519" },
#endif
#ifndef WOLFSSH_NO_MLDSA44_ES256
{ WOLFSSH_MLDSAKEY_44, WOLFSSH_COMPOSITE_TRAD_ECDSA, "44+ES256" },
#endif
#ifndef WOLFSSH_NO_MLDSA65_ED25519
{ WOLFSSH_MLDSAKEY_65, WOLFSSH_COMPOSITE_TRAD_ED25519, "65+Ed25519" },
#endif
#ifndef WOLFSSH_NO_MLDSA65_ES256
{ WOLFSSH_MLDSAKEY_65, WOLFSSH_COMPOSITE_TRAD_ECDSA, "65+ES256" },
#endif
#ifndef WOLFSSH_NO_MLDSA87_ED448
{ WOLFSSH_MLDSAKEY_87, WOLFSSH_COMPOSITE_TRAD_ED448, "87+Ed448" },
#endif
#ifndef WOLFSSH_NO_MLDSA87_ES384
{ WOLFSSH_MLDSAKEY_87, WOLFSSH_COMPOSITE_TRAD_ECDSA, "87+ES384" },
#endif
{ 0, 0, NULL }
};
const word32 bufSz = 8192;
word32 i;
word32 firstLevel = 0;
word32 firstTradType = 0;
word32 firstSz = 0;
int result = 0;
for (i = 0; i < (word32)(sizeof(params) / sizeof(params[0])) &&
params[i].name != NULL; i++) {
WOLFSSH_CTX* ctx;
byte* buf;
int sz;
buf = (byte*)WMALLOC(bufSz, NULL, DYNTYPE_BUFFER);
if (buf == NULL) {
printf("MlDsaCompositeKeyGen: alloc failed for %s\n",
params[i].name);
result = -120;
break;
}
sz = wolfSSH_MakeMlDsaCompositeKey(buf, bufSz, params[i].level,
params[i].tradType);
if (sz <= 0) {
printf("MlDsaCompositeKeyGen: MakeMlDsaCompositeKey %s "
"failed (%d)\n", params[i].name, sz);
WFREE(buf, NULL, DYNTYPE_BUFFER);
result = -121;
break;
}
if (i == 0) {
firstLevel = params[i].level;
firstTradType = params[i].tradType;
firstSz = (word32)sz;
}
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL) {
printf("MlDsaCompositeKeyGen: CTX_new failed for %s\n",
params[i].name);
WFREE(buf, NULL, DYNTYPE_BUFFER);
result = -122;
break;
}
if (wolfSSH_CTX_UsePrivateKey_buffer(ctx, buf, (word32)sz,
WOLFSSH_FORMAT_OPENSSH) != WS_SUCCESS) {
printf("MlDsaCompositeKeyGen: round-trip parse failed for %s\n",
params[i].name);
result = -123;
}
wolfSSH_CTX_free(ctx);
WFREE(buf, NULL, DYNTYPE_BUFFER);
if (result != 0) {
break;
}
}
if (result == 0 && firstSz > 0) {
/* out == NULL is a size query for a valid (level, tradType): it
* should return the required buffer size, not an error. */
int sz = wolfSSH_MakeMlDsaCompositeKey(NULL, 0, firstLevel,
firstTradType);
if (sz <= 0 || (word32)sz != firstSz) {
printf("MlDsaCompositeKeyGen: NULL out size query wrong "
"result %d (expected %u)\n", sz, firstSz);
result = -124;
}
}
if (result == 0) {
byte dummy[1];
int sz = wolfSSH_MakeMlDsaCompositeKey(dummy, sizeof(dummy), 9999,
9999);
if (sz != WS_BAD_ARGUMENT) {
printf("MlDsaCompositeKeyGen: invalid level/tradType wrong "
"result %d\n", sz);
result = -125;
}
}
if (result == 0) {
byte dummy[1];
int sz = wolfSSH_MakeMlDsaCompositeKey(dummy, sizeof(dummy),
WOLFSSH_MLDSAKEY_87, WOLFSSH_COMPOSITE_TRAD_ED25519);
if (sz != WS_BAD_ARGUMENT) {
printf("MlDsaCompositeKeyGen: mismatched level/tradType wrong "
"result %d\n", sz);
result = -127;
}
}
/* A gated-off pair must report WS_NOT_COMPILED, not WS_BAD_ARGUMENT. */
#if defined(WOLFSSH_NO_MLDSA44_ES256) && !defined(WOLFSSH_NO_MLDSA44) && \
!defined(WOLFSSH_NO_ECDSA_SHA2_NISTP256)
if (result == 0) {
byte dummy[1];
int sz = wolfSSH_MakeMlDsaCompositeKey(dummy, sizeof(dummy),
WOLFSSH_MLDSAKEY_44, WOLFSSH_COMPOSITE_TRAD_ECDSA);
if (sz != WS_NOT_COMPILED) {
printf("MlDsaCompositeKeyGen: gated-off composite wrong "
"result %d\n", sz);
result = -129;
}
}
#endif
/* Same, for a derived gate rather than a user-set one. */
#if defined(WOLFSSH_NO_MLDSA87_ED448) && !defined(WOLFSSH_NO_MLDSA87)
if (result == 0) {
byte dummy[1];
int sz = wolfSSH_MakeMlDsaCompositeKey(dummy, sizeof(dummy),
WOLFSSH_MLDSAKEY_87, WOLFSSH_COMPOSITE_TRAD_ED448);
if (sz != WS_NOT_COMPILED) {
printf("MlDsaCompositeKeyGen: derived gated-off composite wrong "
"result %d\n", sz);
result = -130;
}
}
#endif
if (result == 0 && firstSz > 0) {
byte* buf = (byte*)WMALLOC(firstSz, NULL, DYNTYPE_BUFFER);
if (buf == NULL) {
printf("MlDsaCompositeKeyGen: alloc failed for undersized "
"buffer test\n");
result = -126;
}
else {
int sz = wolfSSH_MakeMlDsaCompositeKey(buf, firstSz - 1,
firstLevel, firstTradType);
if (sz != WS_BUFFER_E) {
printf("MlDsaCompositeKeyGen: undersized buffer wrong "
"result %d\n", sz);
result = -128;
}
WFREE(buf, NULL, DYNTYPE_BUFFER);
}
}
return result;
}
#endif /* WOLFSSH_NO_MLDSA_COMPOSITES */
/* With every composite off the entry point stays compiled: a valid pair must
* report WS_NOT_COMPILED, a bad one still WS_BAD_ARGUMENT. */
#if defined(WOLFSSH_NO_MLDSA_COMPOSITES) && !defined(WOLFSSH_NO_MLDSA)
static int test_MlDsaCompositesDisabled(void)
{
byte dummy[1];
int result = 0;
int sz;
sz = wolfSSH_MakeMlDsaCompositeKey(dummy, sizeof(dummy),
WOLFSSH_MLDSAKEY_44, WOLFSSH_COMPOSITE_TRAD_ECDSA);
if (sz != WS_NOT_COMPILED) {
printf("MlDsaCompositesDisabled: valid pair wrong result %d\n", sz);
result = -131;
}
if (result == 0) {
sz = wolfSSH_MakeMlDsaCompositeKey(dummy, sizeof(dummy), 9999, 9999);
if (sz != WS_BAD_ARGUMENT) {
printf("MlDsaCompositesDisabled: invalid pair wrong result %d\n",
sz);
result = -132;
}
}
return result;
}
#endif
#endif /* WOLFSSH_NO_MLDSA */
/* API behaviour with ML-DSA off; the #error above covers the derivation. */
#ifdef WOLFSSH_NO_MLDSA
static int test_MlDsaLevelsDisabled(void)
{
byte dummy[1];
int result = 0;
int sz;
sz = wolfSSH_MakeMlDsaKey(dummy, sizeof(dummy), WOLFSSH_MLDSAKEY_44);
if (sz != WS_NOT_COMPILED) {
printf("MlDsaLevelsDisabled: MakeMlDsaKey wrong result %d\n", sz);
result = -133;
}
return result;
}
#endif
#endif /* WOLFSSH_KEYGEN */
/* Exercises the malformed-input error paths of the WOLFSSH_FORMAT_OPENSSH
* PEM stripping added to wolfSSH_ProcessBuffer() (via the public
* wolfSSH_CTX_UsePrivateKey_buffer() entry point): a header that doesn't
* match "-----BEGIN OPENSSH PRIVATE KEY-----", a missing footer, and a
* corrupt/non-Base64 body. Each should fail with WS_BAD_FILE_E rather than
* crash or leak. */
static int test_OpenSshPemNegative(void)
{
static const char badHeader[] =
"-----BEGIN OPENSSH PUBLIC KEY-----\n"
"AAAA\n"
"-----END OPENSSH PRIVATE KEY-----\n";
static const char noFooter[] =
"-----BEGIN OPENSSH PRIVATE KEY-----\n"
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n";
static const char badBase64[] =
"-----BEGIN OPENSSH PRIVATE KEY-----\n"
"not valid base64 !!!\n"
"-----END OPENSSH PRIVATE KEY-----\n";
static const struct {
const char* pem;
word32 pemSz;
const char* name;
} cases[] = {
{ badHeader, (word32)sizeof(badHeader) - 1, "bad header" },
{ noFooter, (word32)sizeof(noFooter) - 1, "missing footer" },
{ badBase64, (word32)sizeof(badBase64) - 1, "bad base64" },
};
word32 i;
int result = 0;
for (i = 0; i < (word32)(sizeof(cases) / sizeof(cases[0])); i++) {
WOLFSSH_CTX* ctx;
int ret;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL) {
printf("OpenSshPemNegative: CTX_new failed for %s\n",
cases[i].name);
result = -116;
break;
}
ret = wolfSSH_CTX_UsePrivateKey_buffer(ctx,
(const byte*)cases[i].pem, cases[i].pemSz,
WOLFSSH_FORMAT_OPENSSH);
if (ret != WS_BAD_FILE_E) {
printf("OpenSshPemNegative: %s wrong result %d\n",
cases[i].name, ret);
result = -117;
}
wolfSSH_CTX_free(ctx);
if (result != 0) {
break;
}
}
return result;
}
#ifndef WOLFSSH_NO_ECDSA_SHA2_NISTP256
/* A well-formed OpenSSH-format key that isn't a composite type must be
* rejected, not stored as an envelope no non-composite parser can walk. */
static int test_OpenSshFormatNonCompositeRejected(void)
{
static const char ecdsaOpenSsh[] =
"-----BEGIN OPENSSH PRIVATE KEY-----\n"
"b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAaAAAABNlY2RzYS\n"
"1zaGEyLW5pc3RwMjU2AAAACG5pc3RwMjU2AAAAQQTAqdBgCp8bYSq2kQQ48/Ud8Iy6Mjnb\n"
"/fpB3LfSE/1kx9VaaE4FL3i9Gg2vDV0eLGM3PWksFNPhULxtcYJyjaBjAAAAqJAeleSQHp\n"
"XkAAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBMCp0GAKnxthKraR\n"
"BDjz9R3wjLoyOdv9+kHct9IT/WTH1VpoTgUveL0aDa8NXR4sYzc9aSwU0+FQvG1xgnKNoG\n"
"MAAAAgPrOgktioNqad/wHNC/rt/zVrpNqDnOwg9tNDFMOTwo8AAAANYm9iQGxvY2FsaG9z\n"
"dAECAw==\n"
"-----END OPENSSH PRIVATE KEY-----\n";
WOLFSSH_CTX* ctx;
int ret;
int result = 0;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL) {
printf("OpenSshFormatNonCompositeRejected: CTX_new failed\n");
return -118;
}
ret = wolfSSH_CTX_UsePrivateKey_buffer(ctx,
(const byte*)ecdsaOpenSsh, (word32)sizeof(ecdsaOpenSsh) - 1,
WOLFSSH_FORMAT_OPENSSH);
if (ret != WS_UNIMPLEMENTED_E) {
printf("OpenSshFormatNonCompositeRejected: wrong result %d\n", ret);
result = -119;
}
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* !WOLFSSH_NO_ECDSA_SHA2_NISTP256 */
#ifdef WOLFSSH_TEST_INTERNAL
/* An OpenSSH private key whose key-type name wolfSSH does not know is
* WS_UNIMPLEMENTED_E, straight from GetOpenSshKey(). */
static int test_IdentifyOpenSshKeyUnknownName(void)
{
static const byte blob[] = {
'o', 'p', 'e', 'n', 's', 's', 'h', '-', 'k', 'e', 'y', '-',
'v', '1', 0x00,
0x00, 0x00, 0x00, 0x04, 'n', 'o', 'n', 'e', /* ciphername */
0x00, 0x00, 0x00, 0x04, 'n', 'o', 'n', 'e', /* kdfname */
0x00, 0x00, 0x00, 0x00, /* kdfoptions */
0x00, 0x00, 0x00, 0x01, /* key count */
0x00, 0x00, 0x00, 0x00, /* public key */
0x00, 0x00, 0x00, 0x13, /* private list */
0x01, 0x02, 0x03, 0x04, 0x01, 0x02, 0x03, 0x04, /* checkints */
0x00, 0x00, 0x00, 0x07, 's', 's', 'h', '-', 'f', 'o', 'o'
};
int ret;
ret = IdentifyOpenSshKey(blob, (word32)sizeof(blob), NULL);
if (ret != WS_UNIMPLEMENTED_E) {
printf("IdentifyOpenSshKeyUnknownName: wrong result %d\n", ret);
return -120;
}
return 0;
}
#endif /* WOLFSSH_TEST_INTERNAL */
#if defined(WOLFSSH_TEST_INTERNAL) && !defined(WOLFSSH_NO_ED25519)
static word32 OsshTest_PutString(byte* out, const byte* s, word32 sSz)
{
out[0] = (byte)(sSz >> 24);
out[1] = (byte)(sSz >> 16);
out[2] = (byte)(sSz >> 8);
out[3] = (byte)sSz;
if (sSz > 0)
WMEMCPY(out + UINT32_SZ, s, sSz);
return UINT32_SZ + sSz;
}
/* Build an unencrypted openssh-key-v1 Ed25519 key. The private section
* is the checkints, the key and an empty comment (131 bytes) followed by
* tail, so the caller controls the padding. privSz shortens the k||ENC(A)
* string. Returns the blob size. */
static word32 OsshTest_Ed25519Blob(byte* out, const byte* pub,
const byte* seed, word32 privSz, const byte* tail, word32 tailSz)
{
static const char magic[] = "openssh-key-v1";
static const char none[] = "none";
static const char name[] = "ssh-ed25519";
byte priv[ED25519_KEY_SIZE + ED25519_PUB_KEY_SIZE];
byte pubBlob[UINT32_SZ + sizeof(name) - 1 + UINT32_SZ
+ ED25519_PUB_KEY_SIZE];
byte sect[256];
word32 sectSz = 0, pubBlobSz = 0, sz = 0;
WMEMCPY(priv, seed, ED25519_KEY_SIZE);
WMEMCPY(priv + ED25519_KEY_SIZE, pub, ED25519_PUB_KEY_SIZE);
pubBlobSz += OsshTest_PutString(pubBlob, (const byte*)name,
sizeof(name) - 1);
pubBlobSz += OsshTest_PutString(pubBlob + pubBlobSz, pub,
ED25519_PUB_KEY_SIZE);
WMEMSET(sect, 0x5A, 2 * UINT32_SZ); /* checkint1 == checkint2 */
sectSz = 2 * UINT32_SZ;
sectSz += OsshTest_PutString(sect + sectSz, (const byte*)name,
sizeof(name) - 1);
sectSz += OsshTest_PutString(sect + sectSz, pub, ED25519_PUB_KEY_SIZE);
sectSz += OsshTest_PutString(sect + sectSz, priv, privSz);
sectSz += OsshTest_PutString(sect + sectSz, NULL, 0); /* comment */
if (tailSz > 0)
WMEMCPY(sect + sectSz, tail, tailSz);
sectSz += tailSz;
WMEMCPY(out, magic, sizeof(magic));
sz = sizeof(magic);
sz += OsshTest_PutString(out + sz, (const byte*)none, sizeof(none) - 1);
sz += OsshTest_PutString(out + sz, (const byte*)none, sizeof(none) - 1);
sz += OsshTest_PutString(out + sz, NULL, 0); /* kdfoptions */
out[sz++] = 0; out[sz++] = 0; out[sz++] = 0; out[sz++] = 1;
sz += OsshTest_PutString(out + sz, pubBlob, pubBlobSz);
sz += OsshTest_PutString(out + sz, sect, sectSz);
return sz;
}
/* GetOpenSshKey on Ed25519 keys: the private section must be a whole
* number of blocks ending in the 1, 2, 3, ... padding, a malformed key
* reports WS_KEY_FORMAT_E, and the key is set up on the caller's heap. */
static int test_OpenSshKeyEd25519Parse(void)
{
static const byte seed[ED25519_KEY_SIZE] = {
0x9d, 0x61, 0xb1, 0x9d, 0xef, 0xfd, 0x5a, 0x60,
0xba, 0x84, 0x4a, 0xf4, 0x92, 0xec, 0x2c, 0xc4,
0x44, 0x49, 0xc5, 0x69, 0x7b, 0x32, 0x69, 0x19,
0x70, 0x3b, 0xac, 0x03, 0x1c, 0xae, 0x7f, 0x60
};
static const byte padGood[] = { 1, 2, 3, 4, 5 };
static const byte padLong[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 };
static const byte padBad2[] = { 1, 9, 3, 4, 5 };
static const byte padBad5[] = { 1, 2, 3, 4, 9 };
static const byte junk3[] = { 0xFF, 0xFF, 0xFF };
static const struct {
const char* name;
const byte* tail;
word32 tailSz;
word32 privSz;
int expect;
} cases[] = {
{ "aligned, good pad", padGood, sizeof(padGood),
ED25519_KEY_SIZE + ED25519_PUB_KEY_SIZE, WS_SUCCESS },
{ "aligned, an extra block of pad", padLong, sizeof(padLong),
ED25519_KEY_SIZE + ED25519_PUB_KEY_SIZE, WS_SUCCESS },
{ "misaligned, no pad", NULL, 0,
ED25519_KEY_SIZE + ED25519_PUB_KEY_SIZE, WS_KEY_FORMAT_E },
{ "misaligned, junk tail", junk3, sizeof(junk3),
ED25519_KEY_SIZE + ED25519_PUB_KEY_SIZE, WS_KEY_FORMAT_E },
{ "aligned, bad second pad byte", padBad2, sizeof(padBad2),
ED25519_KEY_SIZE + ED25519_PUB_KEY_SIZE, WS_KEY_FORMAT_E },
{ "aligned, bad last pad byte", padBad5, sizeof(padBad5),
ED25519_KEY_SIZE + ED25519_PUB_KEY_SIZE, WS_KEY_FORMAT_E },
/* 131 - 48 + 5 = 88 is aligned, so only privSz < pubSz fails */
{ "private string shorter than public", padGood, sizeof(padGood),
ED25519_KEY_SIZE + ED25519_PUB_KEY_SIZE - 48, WS_KEY_FORMAT_E },
/* 131 - 8 + 5 = 128 is aligned; wolfCrypt rejects a 24-byte k */
{ "private key the wrong size", padGood, sizeof(padGood),
ED25519_KEY_SIZE + ED25519_PUB_KEY_SIZE - 8, WS_ED25519_E },
};
ed25519_key edKey;
byte pub[ED25519_PUB_KEY_SIZE];
byte blob[512];
WS_KeySignature keySig;
#ifndef WOLFSSL_STATIC_MEMORY
/* Any non-NULL marker; a static-memory heap hint must be real. */
int heapMark = 0;
void* heap = &heapMark;
#else
void* heap = NULL;
#endif
word32 blobSz, idx, i;
int ret, result = 0;
if (wc_ed25519_init(&edKey) != 0)
return -1720;
ret = wc_ed25519_import_private_only(seed, sizeof(seed), &edKey);
if (ret == 0)
ret = wc_ed25519_make_public(&edKey, pub, sizeof(pub));
wc_ed25519_free(&edKey);
if (ret != 0)
return -1721;
for (i = 0; i < (word32)(sizeof(cases) / sizeof(cases[0])); i++) {
blobSz = OsshTest_Ed25519Blob(blob, pub, seed, cases[i].privSz,
cases[i].tail, cases[i].tailSz);
WMEMSET(&keySig, 0, sizeof(keySig));
keySig.heap = heap;
keySig.keyId = ID_NONE;
idx = 0;
ret = GetOpenSshKey(&keySig, blob, blobSz, &idx);
if (ret != cases[i].expect) {
printf("OpenSshKeyEd25519Parse: %s: ret %d, expected %d\n",
cases[i].name, ret, cases[i].expect);
result = -1722;
}
else if (ret == WS_SUCCESS
&& (keySig.keyId != ID_ED25519
|| keySig.ks.ed25519.key.heap != keySig.heap)) {
printf("OpenSshKeyEd25519Parse: %s: keyId %d, key heap is %s\n",
cases[i].name, keySig.keyId,
keySig.ks.ed25519.key.heap == keySig.heap ?
"the caller's" : "not the caller's");
result = -1723;
}
wolfSSH_KEY_clean(&keySig);
}
/* Cut the 131-byte private section to 100 bytes, inside the k||ENC(A)
* string, so reading that string runs out of buffer. */
blobSz = OsshTest_Ed25519Blob(blob, pub, seed,
ED25519_KEY_SIZE + ED25519_PUB_KEY_SIZE, NULL, 0);
blobSz -= 131 - 100;
blob[blobSz - 100 - 4] = 0;
blob[blobSz - 100 - 3] = 0;
blob[blobSz - 100 - 2] = 0;
blob[blobSz - 100 - 1] = 100;
WMEMSET(&keySig, 0, sizeof(keySig));
keySig.heap = heap;
keySig.keyId = ID_NONE;
idx = 0;
ret = GetOpenSshKey(&keySig, blob, blobSz, &idx);
if (ret != WS_BUFFER_E) {
printf("OpenSshKeyEd25519Parse: truncated private string: ret %d, "
"expected %d\n", ret, WS_BUFFER_E);
result = -1724;
}
wolfSSH_KEY_clean(&keySig);
return result;
}
#endif /* WOLFSSH_TEST_INTERNAL && !WOLFSSH_NO_ED25519 */
#if defined(WOLFSSH_TEST_INTERNAL) && \
(!defined(WOLFSSH_NO_HMAC_SHA1) || \
!defined(WOLFSSH_NO_HMAC_SHA1_96) || \
!defined(WOLFSSH_NO_HMAC_SHA2_256) || \
!defined(WOLFSSH_NO_HMAC_SHA2_512) || \
!defined(WOLFSSH_NO_AES_GCM))
/* Minimal SSH binary packet: uint32 length, padding_length, msgId, padding.
* The caller picks padLen to get the alignment it wants. */
static word32 BuildMacTestPacketPrefix(byte msgId, byte padLen,
byte* out, word32 outSz)
{
word32 packetLen = (word32)(1 + 1 + padLen);
word32 need = UINT32_SZ + packetLen;
if (outSz < need)
return 0;
out[0] = (byte)(packetLen >> 24);
out[1] = (byte)(packetLen >> 16);
out[2] = (byte)(packetLen >> 8);
out[3] = (byte)(packetLen);
out[4] = padLen;
out[5] = msgId;
WMEMSET(out + 6, 0, padLen);
return need;
}
#endif
/* The test below drives a server-side session. With NO_WOLFSSH_SERVER the
* message filter has no server branch, so every message on such a session is
* refused and the test cannot run. */
#if defined(WOLFSSH_TEST_INTERNAL) && !defined(NO_WOLFSSH_SERVER)
/* Swallow the SSH_MSG_UNIMPLEMENTED that DoPacket sends back, so its send
* does not decide the result of the test. */
static int SinkIoSendUnimplemented(WOLFSSH* ssh, void* buf, word32 sz,
void* ctx)
{
(void)ssh; (void)buf; (void)ctx;
return (int)sz;
}
/* Two back-to-back packets in one buffer. DoPacket() is driven directly:
* DoReceive() force-frees the buffer after every packet, zeroing the cursor
* under test. */
static const byte s_unimplStream[] = {
/* unimplemented message, 8 bytes of payload that no handler reads */
0x00, 0x00, 0x00, 0x10, /* packetSz = 16 */
0x06, /* padSz = 6 */
0x0A, /* msgId = 10 */
0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, /* payload */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* padding */
/* MSGID_IGNORE carrying a zero-length string */
0x00, 0x00, 0x00, 0x0C, /* packetSz = 12 */
0x06, /* padSz = 6 */
0x02, /* msgId = IGNORE */
0x00, 0x00, 0x00, 0x00, /* string, len 0 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00 /* padding */
};
/* Message ID 10 is unassigned and always allowed, so it reaches DoPacket's
* default case, which reads none of its 8 payload bytes. DoPacket must step
* over them itself. Checked by the cursor it leaves, and by the length peeked
* there being the next packet's. Framing from payloadIdx lands 8 short. */
static int test_DoPacket_UnimplementedConsumesPayload(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
int result = 0;
int ret;
int i;
/* packetSz of each packet in s_unimplStream, in order */
static const word32 pktSizes[] = { 16, 12 };
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -220;
wolfSSH_SetIOSend(ctx, SinkIoSendUnimplemented);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -221; goto done; }
/* Past user auth, so the connection-layer message IDs are allowed. */
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ssh->peerEncryptId = ID_NONE;
ssh->peerMacId = ID_NONE;
ssh->peerAeadMode = 0;
ssh->peerBlockSz = MIN_BLOCK_SZ;
ssh->peerMacSz = 0;
ssh->peerSeq = 0;
ssh->error = 0;
/* Both packets in the buffer at once. */
ShrinkBuffer(&ssh->inputBuffer, 1);
if (GrowBuffer(&ssh->inputBuffer, (word32)sizeof(s_unimplStream))
!= WS_SUCCESS) {
result = -222;
goto done;
}
WMEMCPY(ssh->inputBuffer.buffer, s_unimplStream, sizeof(s_unimplStream));
ssh->inputBuffer.length = (word32)sizeof(s_unimplStream);
ssh->inputBuffer.idx = 0;
for (i = 0; i < (int)(sizeof(pktSizes) / sizeof(pktSizes[0])); i++) {
word32 pktStart = ssh->inputBuffer.idx;
const byte* lenField = ssh->inputBuffer.buffer + pktStart;
word32 curSz;
byte bufferConsumed = 0;
/* The peek DoReceive does; a short cursor reads leftover payload. */
curSz = ((word32)lenField[0] << 24) | ((word32)lenField[1] << 16)
| ((word32)lenField[2] << 8) | (word32)lenField[3];
if (curSz != pktSizes[i]) {
printf("DoPacket[%d]: packetSz=%u at cursor %u, expected %u\n",
i, curSz, pktStart, pktSizes[i]);
result = -223;
goto done;
}
ssh->curSz = curSz;
ret = wolfSSH_TestDoPacket(ssh, &bufferConsumed);
if (ret != WS_SUCCESS) {
printf("DoPacket[%d]: ret=%d, error=%d\n", i, ret, ssh->error);
result = -224;
goto done;
}
if (!bufferConsumed) {
printf("DoPacket[%d]: packet not consumed\n", i);
result = -225;
goto done;
}
/* The whole packet, no more and no less. */
if (ssh->inputBuffer.idx != pktStart + UINT32_SZ + curSz) {
printf("DoPacket[%d]: cursor at %u, expected %u\n", i,
ssh->inputBuffer.idx, pktStart + UINT32_SZ + curSz);
result = -226;
goto done;
}
if (ssh->peerSeq != (word32)(i + 1)) {
printf("DoPacket[%d]: peerSeq=%u, expected %d\n", i,
ssh->peerSeq, i + 1);
result = -227;
goto done;
}
}
/* Buffer exactly spent. */
if (ssh->inputBuffer.idx != (word32)sizeof(s_unimplStream)) {
printf("DoPacket: %u of %u bytes consumed\n", ssh->inputBuffer.idx,
(word32)sizeof(s_unimplStream));
result = -228;
goto done;
}
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#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)
{
word32 i;
for (i = 0; i < sz; i++) {
if (p[i] != 0)
return 0;
}
return 1;
}
#if defined(WOLFSSH_TEST_INTERNAL) && \
(!defined(WOLFSSH_NO_HMAC_SHA1) || \
!defined(WOLFSSH_NO_HMAC_SHA1_96) || \
!defined(WOLFSSH_NO_HMAC_SHA2_256) || \
!defined(WOLFSSH_NO_HMAC_SHA2_512))
static int test_DoReceive_VerifyMacFailure(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
int ret = WS_SUCCESS;
int result = 0;
byte flatSeq[LENGTH_SZ];
byte macKey[MAX_HMAC_SZ];
Hmac hmac;
word32 prefixLen;
word32 totalLen;
byte pkt[UINT32_SZ + 12 + MAX_HMAC_SZ];
int i;
struct {
byte macId;
int hmacType;
byte macSz;
byte keySz;
} cases[] = {
#ifndef WOLFSSH_NO_HMAC_SHA1
{ ID_HMAC_SHA1, WC_SHA, WC_SHA_DIGEST_SIZE, WC_SHA_DIGEST_SIZE },
#endif
#ifndef WOLFSSH_NO_HMAC_SHA1_96
{ ID_HMAC_SHA1_96, WC_SHA, SHA1_96_SZ, WC_SHA_DIGEST_SIZE },
#endif
#ifndef WOLFSSH_NO_HMAC_SHA2_256
{ ID_HMAC_SHA2_256, WC_SHA256, WC_SHA256_DIGEST_SIZE,
WC_SHA256_DIGEST_SIZE },
#endif
#ifndef WOLFSSH_NO_HMAC_SHA2_512
{ ID_HMAC_SHA2_512, WC_SHA512, WC_SHA512_DIGEST_SIZE,
WC_SHA512_DIGEST_SIZE },
#endif
};
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -200;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return -201;
}
WMEMSET(macKey, 0xA5, sizeof(macKey));
for (i = 0; i < (int)(sizeof(cases) / sizeof(cases[0])); i++) {
prefixLen = BuildMacTestPacketPrefix(MSGID_IGNORE, 10,
pkt, sizeof(pkt));
if (prefixLen == 0) {
result = -202;
goto done;
}
totalLen = prefixLen + cases[i].macSz;
ssh->peerEncryptId = ID_NONE;
ssh->peerAeadMode = 0;
ssh->peerBlockSz = MIN_BLOCK_SZ;
ssh->peerMacId = cases[i].macId;
ssh->peerMacSz = cases[i].macSz;
WMEMCPY(ssh->peerKeys.macKey, macKey, cases[i].keySz);
ssh->peerKeys.macKeySz = cases[i].keySz;
ssh->peerSeq = 0;
ssh->curSz = 0;
ssh->processReplyState = PROCESS_INIT;
ssh->error = 0;
ssh->highwaterFlag = 0;
ssh->msgHighwaterFlag = 0;
flatSeq[0] = (byte)(ssh->peerSeq >> 24);
flatSeq[1] = (byte)(ssh->peerSeq >> 16);
flatSeq[2] = (byte)(ssh->peerSeq >> 8);
flatSeq[3] = (byte)(ssh->peerSeq);
ret = wc_HmacInit(&hmac, ssh->ctx->heap, INVALID_DEVID);
if (ret != WS_SUCCESS) {
result = -203;
goto done;
}
{
byte digest[WC_MAX_DIGEST_SIZE];
ret = wc_HmacSetKey(&hmac, cases[i].hmacType,
ssh->peerKeys.macKey, ssh->peerKeys.macKeySz);
if (ret == WS_SUCCESS)
ret = wc_HmacUpdate(&hmac, flatSeq, sizeof(flatSeq));
if (ret == WS_SUCCESS)
ret = wc_HmacUpdate(&hmac, pkt, prefixLen);
if (ret == WS_SUCCESS)
ret = wc_HmacFinal(&hmac, digest);
wc_HmacFree(&hmac);
if (ret == WS_SUCCESS)
WMEMCPY(pkt + prefixLen, digest, cases[i].macSz);
}
if (ret != WS_SUCCESS) {
result = -204;
goto done;
}
pkt[prefixLen] ^= 0x01;
ShrinkBuffer(&ssh->inputBuffer, 1);
ret = GrowBuffer(&ssh->inputBuffer, totalLen);
if (ret != WS_SUCCESS) {
result = -205;
goto done;
}
WMEMCPY(ssh->inputBuffer.buffer, pkt, totalLen);
ssh->inputBuffer.length = totalLen;
ssh->inputBuffer.idx = 0;
ret = wolfSSH_TestDoReceive(ssh);
if (ret != WS_FATAL_ERROR) {
result = -206;
goto done;
}
if (ssh->error != WS_VERIFY_MAC_E) {
result = -207;
goto done;
}
if (!ssh->highwaterFlag || !ssh->msgHighwaterFlag) {
result = -209;
goto done;
}
/* The rejected packet does not wait for wolfSSH_free(). */
if (!IsZeroed(ssh->inputBuffer.buffer + ssh->inputBuffer.idx,
totalLen)) {
result = -210;
goto done;
}
}
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* WOLFSSH_TEST_INTERNAL && any HMAC SHA variant enabled */
#if defined(WOLFSSH_TEST_INTERNAL) && !defined(WOLFSSH_NO_AES_GCM)
/* Verify DoReceive rejects an AES-GCM record whose ciphertext has been
* tampered with, so the AEAD tag check fails and the connection is torn down.
* Mirrors test_DoReceive_VerifyMacFailure for the AEAD path. */
static int test_DoReceive_AeadTagFailure(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
Aes encAes;
int ret;
int result = 0;
int aesInited = 0;
byte key[AES_256_KEY_SIZE];
byte iv[GCM_NONCE_MID_SZ];
byte pkt[UINT32_SZ + 16];
byte record[UINT32_SZ + 16 + AES_BLOCK_SIZE];
word32 prefixLen, payloadSz, totalLen;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -220;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return -221;
}
WMEMSET(key, 0x5A, sizeof(key));
WMEMSET(iv, 0x31, sizeof(iv));
prefixLen = BuildMacTestPacketPrefix(MSGID_IGNORE, 14,
pkt, sizeof(pkt));
if (prefixLen == 0) {
result = -222;
goto done;
}
payloadSz = prefixLen - UINT32_SZ;
ret = wc_AesInit(&encAes, NULL, INVALID_DEVID);
if (ret != 0) {
result = -223;
goto done;
}
aesInited = 1;
if (wc_AesGcmSetKey(&encAes, key, sizeof(key)) != 0) {
result = -224;
goto done;
}
WMEMCPY(record, pkt, UINT32_SZ);
if (wc_AesGcmEncrypt(&encAes, record + UINT32_SZ, pkt + UINT32_SZ,
payloadSz, iv, sizeof(iv), record + UINT32_SZ + payloadSz,
AES_BLOCK_SIZE, record, UINT32_SZ) != 0) {
result = -225;
goto done;
}
totalLen = UINT32_SZ + payloadSz + AES_BLOCK_SIZE;
/* Tamper with a ciphertext byte so the tag check must fail. */
record[UINT32_SZ] ^= 0x01;
if (wc_AesInit(&ssh->decryptCipher.aes, ssh->ctx->heap,
INVALID_DEVID) != 0) {
result = -226;
goto done;
}
/* claim the context before setting the key so wolfSSH_free frees it
* 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) {
result = -230;
goto done;
}
ssh->peerEncryptId = ID_AES256_GCM;
ssh->peerAeadMode = 1;
ssh->peerBlockSz = AES_BLOCK_SIZE;
ssh->peerMacSz = AES_BLOCK_SIZE;
WMEMCPY(ssh->peerKeys.iv, iv, sizeof(iv));
ssh->peerKeys.ivSz = sizeof(iv);
ssh->curSz = 0;
ssh->processReplyState = PROCESS_INIT;
ssh->error = 0;
ShrinkBuffer(&ssh->inputBuffer, 1);
if (GrowBuffer(&ssh->inputBuffer, totalLen) != WS_SUCCESS) {
result = -227;
goto done;
}
WMEMCPY(ssh->inputBuffer.buffer, record, totalLen);
ssh->inputBuffer.length = totalLen;
ssh->inputBuffer.idx = 0;
ret = wolfSSH_TestDoReceive(ssh);
if (ret != WS_FATAL_ERROR) {
result = -228;
goto done;
}
if (ssh->error != AES_GCM_AUTH_E) {
result = -229;
goto done;
}
if (!ssh->highwaterFlag || !ssh->msgHighwaterFlag) {
result = -230;
goto done;
}
/* The packet that failed its tag is wiped. */
if (!IsZeroed(ssh->inputBuffer.buffer + ssh->inputBuffer.idx,
UINT32_SZ + ssh->curSz)) {
result = -231;
goto done;
}
done:
if (aesInited)
wc_AesFree(&encAes);
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* WOLFSSH_TEST_INTERNAL && !WOLFSSH_NO_AES_GCM */
#ifdef WOLFSSH_TEST_INTERNAL
/* A first block that fails to decrypt is wiped, and nothing around it. */
static int test_DoReceive_FirstDecryptFailWipes(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
int ret;
int result = 0;
word32 i;
const word32 lead = 5;
const word32 recordSz = 2 * AES_BLOCK_SIZE;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -232;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
result = -233;
goto done;
}
/* Decrypt() has no case for ID_UNKNOWN, so the first block fails. */
ssh->peerEncryptId = ID_UNKNOWN;
ssh->peerAeadMode = 0;
ssh->peerBlockSz = AES_BLOCK_SIZE;
ssh->peerMacSz = 0;
ssh->curSz = 0;
ssh->processReplyState = PROCESS_INIT;
ssh->error = 0;
ShrinkBuffer(&ssh->inputBuffer, 1);
if (GrowBuffer(&ssh->inputBuffer, lead + recordSz) != WS_SUCCESS) {
result = -234;
goto done;
}
WMEMSET(ssh->inputBuffer.buffer, 0xEE, lead);
WMEMSET(ssh->inputBuffer.buffer + lead, 0x5A, recordSz);
ssh->inputBuffer.length = lead + recordSz;
ssh->inputBuffer.idx = lead;
ret = wolfSSH_TestDoReceive(ssh);
if (ret != WS_FATAL_ERROR || ssh->error != WS_INVALID_ALGO_ID) {
result = -235;
goto done;
}
if (ssh->inputBuffer.idx != lead) {
result = -236;
goto done;
}
if (!IsZeroed(ssh->inputBuffer.buffer + lead, AES_BLOCK_SIZE)) {
result = -237;
goto done;
}
/* Only the block it read is wiped. */
for (i = 0; i < lead; i++) {
if (ssh->inputBuffer.buffer[i] != 0xEE) {
result = -238;
goto done;
}
}
for (i = lead + AES_BLOCK_SIZE; i < lead + recordSz; i++) {
if (ssh->inputBuffer.buffer[i] != 0x5A) {
result = -239;
goto done;
}
}
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* WOLFSSH_TEST_INTERNAL */
#if defined(WOLFSSH_TEST_INTERNAL) && !defined(WOLFSSH_NO_AEAD)
/* 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)
{
const byte impIv[AEAD_IMP_IV_SZ] = { 0xDE, 0xAD, 0xBE, 0xEF };
byte iv[AEAD_NONCE_SZ];
int i;
WMEMCPY(iv, impIv, AEAD_IMP_IV_SZ);
WMEMSET(iv + AEAD_IMP_IV_SZ, 0, AEAD_EXP_IV_SZ);
wolfSSH_TestAeadIncrementExpIv(iv);
if (WMEMCMP(iv, impIv, AEAD_IMP_IV_SZ) != 0)
return -1010;
for (i = 0; i < AEAD_EXP_IV_SZ - 1; i++) {
if (iv[AEAD_IMP_IV_SZ + i] != 0)
return -1011;
}
if (iv[AEAD_NONCE_SZ - 1] != 1)
return -1012;
wolfSSH_TestAeadIncrementExpIv(iv);
if (iv[AEAD_NONCE_SZ - 1] != 2)
return -1013;
/* carry out of the low byte */
iv[AEAD_NONCE_SZ - 1] = 0xFF;
wolfSSH_TestAeadIncrementExpIv(iv);
if (iv[AEAD_NONCE_SZ - 1] != 0 || iv[AEAD_NONCE_SZ - 2] != 1)
return -1014;
/* carry through every explicit byte wraps to zero and leaves the
* implicit half alone */
WMEMSET(iv + AEAD_IMP_IV_SZ, 0xFF, AEAD_EXP_IV_SZ);
wolfSSH_TestAeadIncrementExpIv(iv);
if (WMEMCMP(iv, impIv, AEAD_IMP_IV_SZ) != 0)
return -1015;
for (i = 0; i < AEAD_EXP_IV_SZ; i++) {
if (iv[AEAD_IMP_IV_SZ + i] != 0)
return -1016;
}
return 0;
}
#endif /* WOLFSSH_TEST_INTERNAL && !WOLFSSH_NO_AEAD */
#if defined(WOLFSSH_TEST_INTERNAL) && !defined(WOLFSSH_NO_AES_GCM)
/* Every packet gets a fresh nonce: the same plaintext must not encrypt to the
* same record, and the receive side must advance in step. */
static int test_AeadNoncePerPacket(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
int result = 0;
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 plain[AES_BLOCK_SIZE];
byte first[AES_BLOCK_SIZE], second[AES_BLOCK_SIZE];
byte firstTag[AES_BLOCK_SIZE], secondTag[AES_BLOCK_SIZE];
byte out[AES_BLOCK_SIZE];
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -1020;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return -1021;
}
WMEMSET(key, 0x5A, sizeof(key));
WMEMSET(iv, 0x31, sizeof(iv));
WMEMSET(plain, 0x7E, sizeof(plain));
if (wc_AesInit(&ssh->encryptCipher.aes, ssh->ctx->heap,
INVALID_DEVID) != 0) {
result = -1022;
goto done;
}
/* claim the context before setting the key so wolfSSH_free frees it
* 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) {
result = -1022;
goto done;
}
ssh->encryptId = ID_AES256_GCM;
ssh->aeadMode = 1;
ssh->macSz = AES_BLOCK_SIZE;
WMEMCPY(ssh->keys.iv, iv, sizeof(iv));
ssh->keys.ivSz = sizeof(iv);
if (wolfSSH_TestEncryptAead(ssh, first, plain, sizeof(plain), firstTag,
auth, sizeof(auth)) != WS_SUCCESS) {
result = -1023;
goto done;
}
if (wolfSSH_TestEncryptAead(ssh, second, plain, sizeof(plain), secondTag,
auth, sizeof(auth)) != WS_SUCCESS) {
result = -1024;
goto done;
}
if (WMEMCMP(first, second, sizeof(first)) == 0) {
result = -1025;
goto done;
}
if (WMEMCMP(firstTag, secondTag, sizeof(firstTag)) == 0) {
result = -1026;
goto done;
}
WMEMCPY(expIv, iv, sizeof(expIv));
expIv[AEAD_NONCE_SZ - 1] = (byte)(iv[AEAD_NONCE_SZ - 1] + 2);
if (WMEMCMP(ssh->keys.iv, expIv, sizeof(expIv)) != 0) {
result = -1027;
goto done;
}
if (wc_AesInit(&ssh->decryptCipher.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) {
result = -1028;
goto done;
}
ssh->peerEncryptId = ID_AES256_GCM;
ssh->peerAeadMode = 1;
ssh->peerMacSz = AES_BLOCK_SIZE;
WMEMCPY(ssh->peerKeys.iv, iv, sizeof(iv));
ssh->peerKeys.ivSz = sizeof(iv);
if (wolfSSH_TestDecryptAead(ssh, out, first, sizeof(first), firstTag,
auth, sizeof(auth)) != WS_SUCCESS
|| WMEMCMP(out, plain, sizeof(plain)) != 0) {
result = -1029;
goto done;
}
if (wolfSSH_TestDecryptAead(ssh, out, second, sizeof(second), secondTag,
auth, sizeof(auth)) != WS_SUCCESS
|| WMEMCMP(out, plain, sizeof(plain)) != 0) {
result = -1030;
goto done;
}
/* rewind the receive counter: the second record must no longer
* authenticate */
WMEMCPY(ssh->peerKeys.iv, iv, sizeof(iv));
if (wolfSSH_TestDecryptAead(ssh, out, second, sizeof(second), secondTag,
auth, sizeof(auth)) == WS_SUCCESS) {
result = -1031;
goto done;
}
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* WOLFSSH_TEST_INTERNAL && !WOLFSSH_NO_AES_GCM */
#ifdef WOLFSSH_TEST_INTERNAL
/* Verify DoReceive rejects a binary packet whose padding_length is below the
* RFC 4253 section 6 minimum of four bytes, returning WS_BUFFER_E. The packet
* is delivered in the clear (no cipher, no MAC), matching the pre-key-exchange
* transport, so DoPacket's padding check is what rejects it. */
static int test_DoReceive_RejectsShortPadding(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
int ret;
int result = 0;
/* A well-formed MSGID_IGNORE packet carrying an empty string, but with
* padding_length = 1 (below MIN_PAD_LENGTH). The 16-byte total keeps the
* packet block aligned so the padding check is the only thing that can
* reject it. Layout: uint32 packet_length=12, padding_length=1, msgId,
* uint32 string_len=0, 6 pad bytes => 16 bytes total. */
byte pkt[16];
word32 totalLen = (word32)sizeof(pkt);
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -760;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return -761;
}
WMEMSET(pkt, 0, sizeof(pkt));
pkt[3] = 12; /* packet_length */
pkt[4] = 1; /* padding_length, below MIN_PAD_LENGTH (4) */
pkt[5] = MSGID_IGNORE;
/* string_len = 0, then padding, both zero */
ssh->peerEncryptId = ID_NONE;
ssh->peerAeadMode = 0;
ssh->peerBlockSz = MIN_BLOCK_SZ;
ssh->peerMacId = ID_NONE;
ssh->peerMacSz = 0;
ssh->peerSeq = 0;
ssh->curSz = 0;
ssh->processReplyState = PROCESS_INIT;
ssh->error = 0;
ShrinkBuffer(&ssh->inputBuffer, 1);
ret = GrowBuffer(&ssh->inputBuffer, totalLen);
if (ret != WS_SUCCESS) {
result = -762;
goto done2;
}
WMEMCPY(ssh->inputBuffer.buffer, pkt, totalLen);
ssh->inputBuffer.length = totalLen;
ssh->inputBuffer.idx = 0;
ret = wolfSSH_TestDoReceive(ssh);
if (ret != WS_FATAL_ERROR) {
result = -763;
goto done2;
}
if (ssh->error != WS_BUFFER_E) {
result = -764;
goto done2;
}
if (!ssh->highwaterFlag || !ssh->msgHighwaterFlag) {
result = -765;
goto done2;
}
done2:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* Verify DoReceive rejects a cleartext packet whose padding_length leaves no
* room for the message id, returning WS_OVERFLOW_E, and stops the highwater
* callback. Layout: packet_length=4, padding_length=4 => 8 bytes total. */
static int test_DoReceive_RejectsPaddingUnderflow(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
int ret;
int result = 0;
byte pkt[8];
word32 totalLen = (word32)sizeof(pkt);
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -766;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return -767;
}
WMEMSET(pkt, 0, sizeof(pkt));
pkt[3] = 4; /* packet_length */
pkt[4] = MIN_PAD_LENGTH;
ShrinkBuffer(&ssh->inputBuffer, 1);
ret = GrowBuffer(&ssh->inputBuffer, totalLen);
if (ret != WS_SUCCESS) {
result = -768;
goto done;
}
WMEMCPY(ssh->inputBuffer.buffer, pkt, totalLen);
ssh->inputBuffer.length = totalLen;
ssh->inputBuffer.idx = 0;
ret = wolfSSH_TestDoReceive(ssh);
if (ret != WS_FATAL_ERROR || ssh->error != WS_OVERFLOW_E) {
result = -769;
goto done;
}
if (!ssh->highwaterFlag || !ssh->msgHighwaterFlag) {
result = -793;
goto done;
}
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* Verify DoReceive rejects a cleartext binary packet whose length field is
* not block aligned. The packet is valid in every other respect, so the
* RFC 4253 section 6 alignment check is the only thing that can reject it. */
static int test_DoReceive_RejectsMisalignedPacket(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
int ret;
int result = 0;
/* Layout: uint32 packet_length=10, padding_length=4, msgId,
* uint32 string_len=0, 4 pad bytes => 14 bytes total. 14 is not a
* multiple of the 8-byte minimum block size. */
byte pkt[14];
word32 totalLen = (word32)sizeof(pkt);
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -770;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return -771;
}
WMEMSET(pkt, 0, sizeof(pkt));
pkt[3] = 10; /* packet_length */
pkt[4] = MIN_PAD_LENGTH;
pkt[5] = MSGID_IGNORE;
/* string_len = 0, then padding, both zero */
ssh->peerEncryptId = ID_NONE;
ssh->peerAeadMode = 0;
ssh->peerBlockSz = MIN_BLOCK_SZ;
ssh->peerMacId = ID_NONE;
ssh->peerMacSz = 0;
ssh->peerSeq = 0;
ssh->curSz = 0;
ssh->processReplyState = PROCESS_INIT;
ssh->error = 0;
ShrinkBuffer(&ssh->inputBuffer, 1);
ret = GrowBuffer(&ssh->inputBuffer, totalLen);
if (ret != WS_SUCCESS) {
result = -772;
goto done3;
}
WMEMCPY(ssh->inputBuffer.buffer, pkt, totalLen);
ssh->inputBuffer.length = totalLen;
ssh->inputBuffer.idx = 0;
ret = wolfSSH_TestDoReceive(ssh);
if (ret != WS_FATAL_ERROR) {
result = -773;
goto done3;
}
if (ssh->error != WS_BUFFER_E) {
result = -774;
goto done3;
}
if (!ssh->highwaterFlag || !ssh->msgHighwaterFlag) {
result = -794;
goto done3;
}
done3:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* WOLFSSH_TEST_INTERNAL */
#if defined(WOLFSSH_TEST_INTERNAL) && !defined(WOLFSSH_NO_AES_CTR)
/* Counts receive calls. */
static int CountRecv(WOLFSSH* ssh, void* buf, word32 sz, void* ctx)
{
WOLFSSH_UNUSED(ssh);
WOLFSSH_UNUSED(buf);
WOLFSSH_UNUSED(sz);
(*(word32*)ctx)++;
return WS_CBIO_ERR_WANT_READ;
}
/* Verify DoReceive rejects an AES-CTR packet aligned as a body alone but
* misaligned with the length field counted. RFC 4253 section 6 covers
* packet_length too, so a packet_length of 16 is a 20-byte total. It fails
* at once, with no CBC-style discard. */
static int test_DoReceive_RejectsMisalignedCtr(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
Aes encAes;
int ret;
int result = 0;
int aesInited = 0;
byte key[AES_256_KEY_SIZE];
byte iv[AES_BLOCK_SIZE];
/* Layout: uint32 packet_length=16, padding_length=10, msgId,
* uint32 string_len=0, 10 pad bytes => 20 bytes total, which is not a
* multiple of AES_BLOCK_SIZE. Valid in every other respect. */
byte pkt[UINT32_SZ + 16];
byte record[UINT32_SZ + 16];
word32 totalLen = (word32)sizeof(record);
word32 recvCalls = 0;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -800;
wolfSSH_SetIORecv(ctx, CountRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return -801;
}
wolfSSH_SetIOReadCtx(ssh, &recvCalls);
WMEMSET(key, 0x4B, sizeof(key));
WMEMSET(iv, 0x27, sizeof(iv));
WMEMSET(pkt, 0, sizeof(pkt));
pkt[3] = 16; /* packet_length */
pkt[4] = 10; /* padding_length */
pkt[5] = MSGID_IGNORE;
/* string_len = 0, then padding, both zero */
ret = wc_AesInit(&encAes, NULL, INVALID_DEVID);
if (ret != 0) {
result = -802;
goto done5;
}
aesInited = 1;
if (wc_AesSetKey(&encAes, key, sizeof(key), iv, AES_ENCRYPTION) != 0) {
result = -803;
goto done5;
}
if (wc_AesCtrEncrypt(&encAes, record, pkt, totalLen) != 0) {
result = -804;
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) {
result = -805;
goto done5;
}
ssh->decryptCipher.isInit = 1;
ssh->decryptCipher.cipherType = ID_AES256_CTR;
ssh->peerEncryptId = ID_AES256_CTR;
ssh->peerAeadMode = 0;
ssh->peerBlockSz = AES_BLOCK_SIZE;
ssh->peerMacId = ID_NONE;
ssh->peerMacSz = 0;
ssh->peerSeq = 0;
ssh->curSz = 0;
ssh->processReplyState = PROCESS_INIT;
ssh->error = 0;
ShrinkBuffer(&ssh->inputBuffer, 1);
if (GrowBuffer(&ssh->inputBuffer, totalLen) != WS_SUCCESS) {
result = -806;
goto done5;
}
WMEMCPY(ssh->inputBuffer.buffer, record, totalLen);
ssh->inputBuffer.length = totalLen;
ssh->inputBuffer.idx = 0;
ret = wolfSSH_TestDoReceive(ssh);
if (ret != WS_FATAL_ERROR) {
result = -807;
goto done5;
}
if (ssh->error != WS_BUFFER_E) {
result = -808;
goto done5;
}
if (recvCalls != 0) {
result = -809;
goto done5;
}
done5:
if (aesInited)
wc_AesFree(&encAes);
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* WOLFSSH_TEST_INTERNAL && !WOLFSSH_NO_AES_CTR */
#if defined(WOLFSSH_TEST_INTERNAL) && !defined(WOLFSSH_NO_AES_CBC) && \
!defined(WOLFSSH_NO_HMAC_SHA2_256)
typedef struct {
word32 fed;
word32 calls;
word32 closeAt;
} CbcDiscardIo;
/* Feeds filler in short reads, with a WS_WANT_READ before each one. Closes
* the connection once closeAt bytes are fed, if closeAt is set. */
static int CbcDiscardRecv(WOLFSSH* ssh, void* buf, word32 sz, void* ctx)
{
CbcDiscardIo* io = (CbcDiscardIo*)ctx;
WOLFSSH_UNUSED(ssh);
if (io->closeAt != 0 && io->fed >= io->closeAt)
return WS_CBIO_ERR_CONN_CLOSE;
if ((io->calls++ & 1) == 0)
return WS_CBIO_ERR_WANT_READ;
if (sz > 1000)
sz = 1000;
WMEMSET(buf, 0x5A, sz);
io->fed += sz;
return (int)sz;
}
/* Verify a rejected AES-CBC packet is read out to MAX_PACKET_SZ bytes
* before DoReceive fails, whether the length check or the MAC rejects it,
* so the failure point does not reveal the decrypted length. A discard cut
* short by the peer closing still reports the rejection, and calling again
* after the discard reads nothing more. */
static int test_DoReceive_CbcRejectDiscards(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
Aes encAes;
CbcDiscardIo io;
int ret;
int result = 0;
int aesInited = 0;
int i;
word32 step;
word32 fed;
byte key[AES_128_KEY_SIZE];
byte iv[AES_BLOCK_SIZE];
/* Two blocks of packet then a MAC: packet_length=28, padding_length=22,
* msgId, uint32 string_len=0, 22 pad bytes. */
byte pkt[2 * AES_BLOCK_SIZE];
byte record[2 * AES_BLOCK_SIZE + WC_SHA256_DIGEST_SIZE];
struct {
word32 packetLen;
word32 readSz;
int error;
word32 lead; /* bytes ahead of the packet in inputBuffer */
word32 closeAt; /* peer closes after this many filler bytes */
} cases[] = {
{ 20, AES_BLOCK_SIZE, WS_BUFFER_E, 0, 0 }, /* misaligned */
{ 0x7FFFFFF0, AES_BLOCK_SIZE, WS_OVERFLOW_E, 0, 0 }, /* too long */
{ 28, (word32)sizeof(record), WS_VERIFY_MAC_E, 0, 0 }, /* bad MAC */
{ 20, AES_BLOCK_SIZE, WS_BUFFER_E, 7, 0 }, /* offset start */
{ 28, (word32)sizeof(record), WS_VERIFY_MAC_E, 0, 5000 } /* closed */
};
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -840;
wolfSSH_SetIORecv(ctx, CbcDiscardRecv);
ret = wc_AesInit(&encAes, NULL, INVALID_DEVID);
if (ret != 0) {
result = -841;
goto done6;
}
aesInited = 1;
WMEMSET(key, 0x3C, sizeof(key));
WMEMSET(iv, 0x61, sizeof(iv));
for (i = 0; i < (int)(sizeof(cases) / sizeof(cases[0])); i++) {
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
result = -842;
goto done6;
}
WMEMSET(&io, 0, sizeof(io));
io.closeAt = cases[i].closeAt;
wolfSSH_SetIOReadCtx(ssh, &io);
WMEMSET(pkt, 0, sizeof(pkt));
pkt[0] = (byte)(cases[i].packetLen >> 24);
pkt[1] = (byte)(cases[i].packetLen >> 16);
pkt[2] = (byte)(cases[i].packetLen >> 8);
pkt[3] = (byte)(cases[i].packetLen);
pkt[4] = 22; /* padding_length */
pkt[5] = MSGID_IGNORE;
WMEMSET(pkt + 10, 0x5A, 22);
if (wc_AesSetKey(&encAes, key, sizeof(key), iv,
AES_ENCRYPTION) != 0
|| wc_AesCbcEncrypt(&encAes, record, pkt,
sizeof(pkt)) != 0) {
result = -843;
goto done6;
}
/* 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,
INVALID_DEVID) != 0
|| wc_AesSetKey(&ssh->decryptCipher.aes, key, sizeof(key),
iv, AES_DECRYPTION) != 0) {
result = -844;
goto done6;
}
ssh->decryptCipher.isInit = 1;
ssh->decryptCipher.cipherType = ID_AES128_CBC;
ssh->peerEncryptId = ID_AES128_CBC;
ssh->peerAeadMode = 0;
ssh->peerBlockSz = AES_BLOCK_SIZE;
ssh->peerMacId = ID_HMAC_SHA2_256;
ssh->peerMacSz = WC_SHA256_DIGEST_SIZE;
WMEMSET(ssh->peerKeys.macKey, 0xA5, WC_SHA256_DIGEST_SIZE);
ssh->peerKeys.macKeySz = WC_SHA256_DIGEST_SIZE;
ssh->peerSeq = 0;
ssh->curSz = 0;
ssh->processReplyState = PROCESS_INIT;
ssh->error = 0;
/* Preload what DoReceive reads before it rejects the packet. */
ShrinkBuffer(&ssh->inputBuffer, 1);
if (GrowBuffer(&ssh->inputBuffer, cases[i].lead + cases[i].readSz)
!= WS_SUCCESS) {
result = -845;
goto done6;
}
WMEMSET(ssh->inputBuffer.buffer, 0xEE, cases[i].lead);
WMEMCPY(ssh->inputBuffer.buffer + cases[i].lead, record,
cases[i].readSz);
ssh->inputBuffer.length = cases[i].lead + cases[i].readSz;
ssh->inputBuffer.idx = cases[i].lead;
step = 0;
do {
ret = wolfSSH_TestDoReceive(ssh);
} while (ret == WS_FATAL_ERROR && ssh->error == WS_WANT_READ
&& ++step < 1000);
if (ret != WS_FATAL_ERROR) {
result = -846;
goto done6;
}
if (ssh->error != cases[i].error) {
result = -847;
goto done6;
}
fed = cases[i].closeAt != 0 ?
cases[i].closeAt : MAX_PACKET_SZ - cases[i].readSz;
if (io.fed != fed) {
result = -848;
goto done6;
}
/* The bytes decrypted before the rejection are wiped. */
if (!IsZeroed(ssh->inputBuffer.buffer + ssh->inputBuffer.idx,
cases[i].readSz)) {
result = -851;
goto done6;
}
/* Again after the discard: same error, nothing more read. */
if (ssh->processReplyState != PROCESS_DISCARD) {
result = -849;
goto done6;
}
ret = wolfSSH_TestDoReceive(ssh);
if (ret != WS_FATAL_ERROR || ssh->error != cases[i].error
|| io.fed != fed) {
result = -850;
goto done6;
}
wolfSSH_free(ssh);
ssh = NULL;
}
done6:
if (aesInited)
wc_AesFree(&encAes);
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* WOLFSSH_TEST_INTERNAL && !WOLFSSH_NO_AES_CBC && HMAC-SHA2-256 */
#ifdef WOLFSSH_TEST_INTERNAL
/* Gives up after this many calls, so an unfixed reader that keeps
* retrying a 0 return still terminates. */
#define RECV_ZERO_CALL_CAP 100
static int RecvZeroCalls;
static int RecvAlwaysZero(WOLFSSH* ssh, void* data, word32 sz, void* ctx)
{
WOLFSSH_UNUSED(ssh);
WOLFSSH_UNUSED(data);
WOLFSSH_UNUSED(sz);
WOLFSSH_UNUSED(ctx);
if (++RecvZeroCalls > RECV_ZERO_CALL_CAP)
return WS_CBIO_ERR_GENERAL;
return 0;
}
/* Verify DoReceive treats a 0 from the recv callback as the peer closing
* the connection: it fails after one call and marks the session closed,
* instead of calling the callback again. */
static int test_DoReceive_RecvZeroIsClose(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
int ret;
int result = 0;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -794;
wolfSSH_SetIORecv(ctx, RecvAlwaysZero);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return -795;
}
RecvZeroCalls = 0;
ret = wolfSSH_TestDoReceive(ssh);
if (ret != WS_FATAL_ERROR || ssh->error != WS_SOCKET_ERROR_E) {
result = -796;
goto done;
}
if (RecvZeroCalls != 1) {
result = -797;
goto done;
}
if (!ssh->isClosed) {
result = -798;
goto done;
}
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* WOLFSSH_TEST_INTERNAL */
#if defined(WOLFSSH_TEST_INTERNAL) && !defined(WOLFSSH_USER_IO) && \
!defined(WOLFSSH_TEST_BLOCK) && !defined(WOLFSSH_LWIP) && \
(defined(__linux__) || defined(__APPLE__))
#include <errno.h>
#include <sys/socket.h>
/* No socket can be made to fail a send() with ECONNABORTED on demand, so
* this test replaces send() for the whole program. The library is linked in
* statically, so wsEmbedSend() binds to this definition. A send() on the
* marked descriptor fails with the chosen errno; any other passes through
* to sendto(), which is send() on a connected socket. */
#define SEND_ERRNO_FD 0x5e4d
static int sendErrnoInject = 0;
static int sendErrnoCalls = 0;
ssize_t send(int sd, const void* buf, size_t len, int flags)
{
if (sd == SEND_ERRNO_FD && sendErrnoInject != 0) {
sendErrnoCalls++;
errno = sendErrnoInject;
return -1;
}
return sendto(sd, buf, len, flags, NULL, 0);
}
/* Verify wsEmbedSend maps ECONNABORTED to a closed connection, and that
* the packet send path then marks the session closed. */
static int test_EmbedSend_ConnAbortedIsClose(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
byte data[1] = { 0 };
int ret;
int result = 0;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -799;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return -800;
}
wolfSSH_set_fd(ssh, SEND_ERRNO_FD);
sendErrnoInject = ECONNABORTED;
sendErrnoCalls = 0;
ret = wsEmbedSend(ssh, data, (word32)sizeof(data), ssh->ioWriteCtx);
if (sendErrnoCalls != 1 || ret != WS_CBIO_ERR_CONN_CLOSE) {
result = -801;
goto done;
}
/* Not keyed yet, so strict KEX would refuse the IGNORE outright. */
ssh->sendStrictKex = 0;
ret = wolfSSH_SendIgnore(ssh, NULL, 0);
if (ret != WS_SOCKET_ERROR_E || ssh->error != WS_SOCKET_ERROR_E) {
result = -802;
goto done;
}
if (!ssh->isClosed) {
result = -803;
goto done;
}
done:
sendErrnoInject = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* WOLFSSH_TEST_INTERNAL && !WOLFSSH_USER_IO && (linux || apple) */
#if defined(WOLFSSH_TEST_INTERNAL) && !defined(WOLFSSH_NO_AES_GCM)
/* Verify DoReceive rejects an AES-GCM record whose length field is not a
* multiple of the cipher block size. RFC 5647 aligns the body alone, so a
* 12-byte body is misaligned even though the tag over it is valid. */
static int test_DoReceive_RejectsMisalignedAead(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
Aes encAes;
int ret;
int result = 0;
int aesInited = 0;
byte key[AES_256_KEY_SIZE];
byte iv[GCM_NONCE_MID_SZ];
/* Layout: uint32 packet_length=12, padding_length=6, msgId,
* uint32 string_len=0, 6 pad bytes => a 12-byte body, which is not a
* multiple of AES_BLOCK_SIZE. Valid in every other respect. */
byte pkt[UINT32_SZ + 12];
byte record[UINT32_SZ + 12 + AES_BLOCK_SIZE];
word32 prefixLen, payloadSz, totalLen;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -780;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return -781;
}
WMEMSET(key, 0x5A, sizeof(key));
WMEMSET(iv, 0x31, sizeof(iv));
WMEMSET(pkt, 0, sizeof(pkt));
pkt[3] = 12; /* packet_length */
pkt[4] = 6; /* padding_length */
pkt[5] = MSGID_IGNORE;
/* string_len = 0, then padding, both zero */
prefixLen = (word32)sizeof(pkt);
payloadSz = prefixLen - UINT32_SZ;
ret = wc_AesInit(&encAes, NULL, INVALID_DEVID);
if (ret != 0) {
result = -783;
goto done4;
}
aesInited = 1;
if (wc_AesGcmSetKey(&encAes, key, sizeof(key)) != 0) {
result = -784;
goto done4;
}
WMEMCPY(record, pkt, UINT32_SZ);
if (wc_AesGcmEncrypt(&encAes, record + UINT32_SZ, pkt + UINT32_SZ,
payloadSz, iv, sizeof(iv), record + UINT32_SZ + payloadSz,
AES_BLOCK_SIZE, record, UINT32_SZ) != 0) {
result = -785;
goto done4;
}
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) {
result = -786;
goto done4;
}
ssh->decryptCipher.isInit = 1;
ssh->decryptCipher.cipherType = ID_AES256_GCM;
ssh->peerEncryptId = ID_AES256_GCM;
ssh->peerAeadMode = 1;
ssh->peerBlockSz = AES_BLOCK_SIZE;
ssh->peerMacSz = AES_BLOCK_SIZE;
WMEMCPY(ssh->peerKeys.iv, iv, sizeof(iv));
ssh->peerKeys.ivSz = sizeof(iv);
ssh->curSz = 0;
ssh->processReplyState = PROCESS_INIT;
ssh->error = 0;
ShrinkBuffer(&ssh->inputBuffer, 1);
if (GrowBuffer(&ssh->inputBuffer, totalLen) != WS_SUCCESS) {
result = -787;
goto done4;
}
WMEMCPY(ssh->inputBuffer.buffer, record, totalLen);
ssh->inputBuffer.length = totalLen;
ssh->inputBuffer.idx = 0;
ret = wolfSSH_TestDoReceive(ssh);
if (ret != WS_FATAL_ERROR) {
result = -788;
goto done4;
}
if (ssh->error != WS_BUFFER_E) {
result = -789;
goto done4;
}
done4:
if (aesInited)
wc_AesFree(&encAes);
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* WOLFSSH_TEST_INTERNAL && !WOLFSSH_NO_AES_GCM */
#ifdef WOLFSSH_TEST_INTERNAL
/* Send sink, so a test can run a real send path (build the packet, drain it)
* without a live transport. */
static int UnitIoSendSink(WOLFSSH* ssh, void* buf, word32 sz, void* ctx)
{
(void)ssh;
(void)buf;
(void)ctx;
return (int)sz;
}
/* Write a big-endian uint32 without the internal-only c32toa(). */
static void PutU32BE(byte* out, word32 v)
{
out[0] = (byte)(v >> 24);
out[1] = (byte)(v >> 16);
out[2] = (byte)(v >> 8);
out[3] = (byte)(v);
}
#endif /* WOLFSSH_TEST_INTERNAL */
#if defined(WOLFSSH_TEST_INTERNAL) && !defined(WOLFSSH_NO_DH_GEX_SHA256)
typedef struct {
const char* candidate;
const char* generator;
word32 minBits;
word32 maxBits;
int expectedResult;
} PrimeTestVector;
static const PrimeTestVector primeTestVectors[] = {
{
/*
* For testing the ValidateKexDhGexGroup() function, we need to
* verify that the function detects unsafe primes. The following
* unsafe prime is the prime used with GOST-ECC. (RFC 7836) It is
* prime and fine for its application. It isn't safe for DH, as
* q = (p-1)/2 is not prime.
*/
"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdc7",
"02",
512, 8192, WS_CRYPTO_FAILED
},
{
/*
* We need to verify that the function detects safe primes. The
* following safePrime is the MODP 2048-bit group from RFC 3526.
*/
"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74"
"020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f1437"
"4fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7ed"
"ee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf05"
"98da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb"
"9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3b"
"e39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf695581718"
"3995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff",
"02",
2048, 8192, WS_SUCCESS
},
{
/*
* This checks for g = p - 1.
*/
"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74"
"020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f1437"
"4fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7ed"
"ee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf05"
"98da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb"
"9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3b"
"e39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf695581718"
"3995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff",
"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74"
"020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f1437"
"4fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7ed"
"ee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf05"
"98da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb"
"9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3b"
"e39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf695581718"
"3995497cea956ae515d2261898fa051015728e5a8aacaa68fffffffffffffffe",
2048, 8192, WS_CRYPTO_FAILED
},
{
/*
* This checks for g = 1.
*/
"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74"
"020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f1437"
"4fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7ed"
"ee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf05"
"98da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb"
"9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3b"
"e39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf695581718"
"3995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff",
"01",
2048, 8192, WS_CRYPTO_FAILED
},
{
/*
* This checks prime size less than minBits.
*/
"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74"
"020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f1437"
"4fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7ed"
"ee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf05"
"98da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb"
"9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3b"
"e39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf695581718"
"3995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff",
"02",
3072, 8192, WS_DH_SIZE_E
},
{
/*
* This checks prime size greater than maxBits.
*/
"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74"
"020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f1437"
"4fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7ed"
"ee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf05"
"98da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb"
"9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3b"
"e39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf695581718"
"3995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff",
"02",
512, 1024, WS_DH_SIZE_E
},
{
/*
* This checks for even p.
*/
"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74"
"020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f1437"
"4fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7ed"
"ee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf05"
"98da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb"
"9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3b"
"e39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf695581718"
"3995497cea956ae515d2261898fa051015728e5a8aacaa68fffffffffffffffe",
"02",
2048, 8192, WS_CRYPTO_FAILED
},
{
/*
* A well known composite number that breaks some MR implementations.
* This is calculated by wolfCrypt for one of its prime tests.
*/
"000000000088cbf655be37a612fa535b4a9b81d394854ecbedfe1a4afbecdc7b"
"a6a263549dd3c17882b054329384962576e7c5aa281e04ab5a0e7245584ad324"
"9c7ac4de7caf5663bae95f6bb9e8bec4124e04d82eac54a246bda49a5c5c2a1b"
"366ef8c085fc7c5f87478a55832d1b2184154c24260df67561d17c4359724403",
"02",
512, 8192, WS_CRYPTO_FAILED
},
};
static int test_DhGexGroupValidate(void)
{
WC_RNG rng;
const PrimeTestVector* tv;
byte* candidate;
byte* generator;
word32 candidateSz;
word32 generatorSz;
int tc = (int)(sizeof(primeTestVectors)/sizeof(primeTestVectors[0]));
int result = 0, ret, i;
if (wc_InitRng(&rng) != 0) {
printf("DhGexGroupValidate: wc_InitRng failed\n");
return -110;
}
for (i = 0, tv = primeTestVectors; i < tc && !result; i++, tv++) {
candidate = NULL;
candidateSz = 0;
generator = NULL;
generatorSz = 0;
ret = ConvertHexToBin(tv->candidate, &candidate, &candidateSz,
tv->generator, &generator, &generatorSz,
NULL, NULL, NULL, NULL, NULL, NULL);
if (ret != 0) {
result = -113;
break;
}
ret = wolfSSH_TestValidateKexDhGexGroup(candidate, candidateSz,
generator, generatorSz, tv->minBits, tv->maxBits, &rng);
if (ret != tv->expectedResult) {
printf("DhGexGroupValidate: validator returned %d, expected %d\n",
ret, tv->expectedResult);
result = -121;
}
FreeBins(candidate, generator, NULL, NULL);
}
wc_FreeRng(&rng);
return result;
}
#if WOLFSSH_DH_GEX_MIN_BITS == 2048
/* Assert the selector returns a group of exactly expectSz bytes, and that the
* bytes really are a built-in DH prime: every one of RFC 2409/3526 group 1,
* 14, and 16 begins and ends with 0xFF. Checking the pointer and not just the
* size keeps a mispaired (group, sizeof) entry in candidates[] from passing.
* Returns 0, or code on mismatch. */
static int DhGexExpectGroup(word32 minBits, word32 prefBits, word32 maxBits,
word32 expectSz, int code, const char* what)
{
const byte* group = NULL;
word32 groupSz = 0;
int ret;
ret = wolfSSH_TestSelectKexDhGexGroup(minBits, prefBits, maxBits,
&group, &groupSz);
if (ret != WS_SUCCESS || groupSz != expectSz || group == NULL) {
printf("DhGexGroupSelect: %s got ret %d sz %u want %u\n",
what, ret, groupSz, expectSz);
return code;
}
if (group[0] != 0xFF || group[groupSz - 1] != 0xFF) {
printf("DhGexGroupSelect: %s group is not a built-in prime\n", what);
return code;
}
return 0;
}
#endif /* WOLFSSH_DH_GEX_MIN_BITS == 2048 */
/* The selector must reject the window rather than serve a group outside it. */
static int DhGexExpectReject(word32 minBits, word32 prefBits, word32 maxBits,
int code, const char* what)
{
const byte* group = NULL;
word32 groupSz = 0;
int ret;
ret = wolfSSH_TestSelectKexDhGexGroup(minBits, prefBits, maxBits,
&group, &groupSz);
if (ret != WS_DH_SIZE_E) {
printf("DhGexGroupSelect: %s got ret %d sz %u\n", what, ret, groupSz);
return code;
}
return 0;
}
/* Server-side group selection for DH GEX. Confirms the server honors the
* client's requested min/preferred/max window instead of always handing back
* the 2048-bit group 14, and rejects windows no built-in group can satisfy.
* The concrete group sizes below are only meaningful at the default 2048-bit
* floor; a build that overrides WOLFSSH_DH_GEX_MIN_BITS gets the
* floor-relative checks instead. */
static int test_DhGexGroupSelect(void)
{
int ret;
#if WOLFSSH_DH_GEX_MIN_BITS == 2048
/* NULL out-params are rejected before anything else. */
if (wolfSSH_TestSelectKexDhGexGroup(2048, 2048, 8192, NULL, NULL)
!= WS_BAD_ARGUMENT) {
printf("DhGexGroupSelect: NULL out-params not rejected\n");
return -199;
}
/* Default-ish window. RFC 4419 sec. 3: return the smallest group at or
* above the client's preferred size. With group 16 that is 4096 (512
* bytes) for a preferred of 3072; without it -- or when a reduced
* MAX_KEX_KEY_SZ / KEX_F_SIZE caps the selector's maxBits below 4096 --
* nothing reaches 3072 and the largest in-window group, 2048 (256 bytes),
* is returned instead. Guard on the same buffer sizes SelectKexDhGexGroup
* caps against, matching test_DhGexGroup16KeyAgree. */
#if !defined(WOLFSSH_NO_DH_GROUP16_SHA512) && \
(MAX_KEX_KEY_SZ * 8) >= 4096 && ((KEX_F_SIZE - 1) * 8) >= 4096
ret = DhGexExpectGroup(1024, 3072, 8192, 512, -200, "default window");
#else
ret = DhGexExpectGroup(1024, 3072, 8192, 256, -200, "default window");
#endif
if (ret != 0)
return ret;
/* A preferred size that a group matches exactly takes that group: the
* comparison is >=, not the RFC's literal "larger than". */
ret = DhGexExpectGroup(2048, 2048, 8192, 256, -201, "exact-preferred");
if (ret != 0)
return ret;
/* A max below 4096 must cap the choice even when preferred is huge. */
ret = DhGexExpectGroup(1024, 8192, 2048, 256, -202, "max-cap window");
if (ret != 0)
return ret;
/* A window no built-in group falls inside must be rejected, not silently
* served a group outside it. */
ret = DhGexExpectReject(3000, 3000, 3500, -203, "impossible window");
if (ret != 0)
return ret;
#if !defined(WOLFSSH_NO_DH_GROUP16_SHA512) && \
(MAX_KEX_KEY_SZ * 8) >= 4096 && ((KEX_F_SIZE - 1) * 8) >= 4096
/* A client demanding a 4096-bit minimum gets the 4096-bit group (512
* bytes), never a silent downgrade to 2048. */
ret = DhGexExpectGroup(4096, 4096, 8192, 512, -204, "4096 min");
#else
/* Without group 16 -- or when the selector's buffers cap maxBits below
* 4096 -- there is nothing >= 4096, so the request is rejected rather than
* downgraded. */
ret = DhGexExpectReject(4096, 4096, 8192, -204, "4096 min (no group16)");
#endif
if (ret != 0)
return ret;
/* A sub-2048 window must be rejected, not downgraded to the 1024-bit group
* 1, even when group 1 is compiled in for direct group1-sha1: the GEX path
* enforces the WOLFSSH_DH_GEX_MIN_BITS (2048) floor from RFC 8270. The
* client's max (1536) is below the floor, so no candidate fits. */
ret = DhGexExpectReject(1024, 1024, 1536, -205, "sub-2048 window");
if (ret != 0)
return ret;
/* A window whose minimum is below the floor but whose max admits 2048 must
* clamp up to the 2048-bit group (256 bytes), never the 1024-bit group.
* The low preferred size keeps the choice at 2048 rather than 4096. */
ret = DhGexExpectGroup(1024, 1024, 4096, 256, -206, "floor-clamp window");
if (ret != 0)
return ret;
#else
/* No built-in group lies in [3000, 3500] at any floor: either the window
* is empty on its own, or the clamped min exceeds the max. */
ret = DhGexExpectReject(3000, 3000, 3500, -207, "impossible window");
if (ret != 0)
return ret;
/* A window topping out below the floor is rejected, never downgraded.
* Guarded so a zero floor cannot underflow the max into 0xFFFFFFFF. */
#if WOLFSSH_DH_GEX_MIN_BITS >= 2
ret = DhGexExpectReject(1, 1, WOLFSSH_DH_GEX_MIN_BITS - 1, -209,
"sub-floor window");
if (ret != 0)
return ret;
#endif
/* A wide-open window never selects a group below the floor. */
{
const byte* group = NULL;
word32 groupSz = 0;
ret = wolfSSH_TestSelectKexDhGexGroup(1, 1, 8192, &group, &groupSz);
if (ret == WS_SUCCESS &&
(groupSz * 8) < (word32)WOLFSSH_DH_GEX_MIN_BITS) {
printf("DhGexGroupSelect: floor %d violated, sz %u\n",
WOLFSSH_DH_GEX_MIN_BITS, groupSz);
return -208;
}
}
#endif /* WOLFSSH_DH_GEX_MIN_BITS == 2048 */
(void)ret;
return 0;
}
/* One send/hash consistency case. Runs the real server request path for the
* given client window, then confirms GetDHPrimeGroup hands the exchange-hash
* and key-agreement path the exact group SendKexDhGexGroup cached and put on
* the wire. A zero expectSz skips the size assertion. Failure codes are
* offset from base so each caller reports distinctly. */
static int DhGexSendHashConsistencyCase(word32 minBits, word32 prefBits,
word32 maxBits, word32 expectSz, int base)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
byte request[UINT32_SZ * 3];
word32 idx = 0;
const byte* hashGroup = NULL;
word32 hashGroupSz = 0;
const byte* generator = NULL;
word32 generatorSz = 0;
int ret;
int result = 0;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return base;
wolfSSH_SetIOSend(ctx, UnitIoSendSink);
ssh = wolfSSH_new(ctx);
if (ssh == NULL || ssh->handshake == NULL) {
result = base - 1;
goto out;
}
ssh->handshake->kexId = ID_DH_GEX_SHA256;
PutU32BE(request, minBits);
PutU32BE(request + UINT32_SZ, prefBits);
PutU32BE(request + UINT32_SZ * 2, maxBits);
/* Real server entry point: parse the window, select the group, send it on
* the wire, and cache it on the handshake. */
ret = wolfSSH_TestDoKexDhGexRequest(ssh, request, sizeof(request), &idx);
if (ret != WS_SUCCESS) {
printf("DhGexSendHashConsistency: request ret %d\n", ret);
result = base - 2;
goto out;
}
if (ssh->handshake->primeGroup == NULL ||
(expectSz != 0 && ssh->handshake->primeGroupSz != expectSz)) {
printf("DhGexSendHashConsistency: wire group sz %u want %u\n",
ssh->handshake->primeGroupSz, expectSz);
result = base - 3;
goto out;
}
/* The exchange-hash / key-agreement path must hand back the identical group
* -- same pointer, same size -- not an independently re-selected one. */
ret = wolfSSH_TestGetDHPrimeGroup(ssh, &hashGroup, &hashGroupSz,
&generator, &generatorSz);
if (ret != WS_SUCCESS) {
printf("DhGexSendHashConsistency: hash group ret %d\n", ret);
result = base - 4;
goto out;
}
if (hashGroup != ssh->handshake->primeGroup ||
hashGroupSz != ssh->handshake->primeGroupSz) {
printf("DhGexSendHashConsistency: hash group sz %u != wire %u\n",
hashGroupSz, ssh->handshake->primeGroupSz);
result = base - 5;
goto out;
}
out:
if (ssh != NULL)
wolfSSH_free(ssh);
if (ctx != NULL)
wolfSSH_CTX_free(ctx);
return result;
}
/* End-to-end consistency check for DH GEX server group selection: the group
* SendKexDhGexGroup puts on the wire must be the exact group GetDHPrimeGroup
* hands the exchange hash. */
static int test_DhGexGroupSendHashConsistency(void)
{
int ret;
/* Default client window. Covers the cache plumbing on every build,
* including group14-only ones. A floor raised above the largest built-in
* group leaves nothing to select, and this case reports that. */
ret = DhGexSendHashConsistencyCase(WOLFSSH_DEFAULT_GEXDH_MIN,
WOLFSSH_DEFAULT_GEXDH_PREFERRED, WOLFSSH_DEFAULT_GEXDH_MAX,
0, -210);
if (ret != 0)
return ret;
#if !defined(WOLFSSH_NO_DH_GROUP16_SHA512) && \
WOLFSSH_DH_GEX_MIN_BITS == 2048 && \
(MAX_KEX_KEY_SZ * 8) >= 4096 && ((KEX_F_SIZE - 1) * 8) >= 4096
/* Force the 4096-bit group 16 (512 bytes) so a send/hash divergence can't
* hide behind both paths independently landing on the default group 14. */
ret = DhGexSendHashConsistencyCase(4096, 4096, 8192, 512, -230);
if (ret != 0)
return ret;
#endif
return 0;
}
/* Exercise the GetDHPrimeGroup cache-miss fallback: with the cached group
* cleared, it must re-select the same group from the client window (and set a
* generator), not desync from the wire. */
static int test_DhGexGroupCacheMissFallback(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
byte request[UINT32_SZ * 3];
word32 idx = 0;
const byte* group = NULL;
word32 groupSz = 0;
const byte* generator = NULL;
word32 generatorSz = 0;
word32 wireSz = 0;
int ret;
int result = 0;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -240;
wolfSSH_SetIOSend(ctx, UnitIoSendSink);
ssh = wolfSSH_new(ctx);
if (ssh == NULL || ssh->handshake == NULL) {
result = -241;
goto out;
}
ssh->handshake->kexId = ID_DH_GEX_SHA256;
PutU32BE(request, WOLFSSH_DEFAULT_GEXDH_MIN);
PutU32BE(request + UINT32_SZ, WOLFSSH_DEFAULT_GEXDH_PREFERRED);
PutU32BE(request + UINT32_SZ * 2, WOLFSSH_DEFAULT_GEXDH_MAX);
ret = wolfSSH_TestDoKexDhGexRequest(ssh, request, sizeof(request), &idx);
if (ret != WS_SUCCESS || ssh->handshake->primeGroup == NULL) {
printf("DhGexGroupCacheMissFallback: request ret %d\n", ret);
result = -242;
goto out;
}
wireSz = ssh->handshake->primeGroupSz;
/* Drop the cache to force the fallback branch. primeGroup is a WMALLOC'd
* copy; the fallback returns a pointer into static group data. */
WFREE(ssh->handshake->primeGroup, ssh->ctx->heap, DYNTYPE_MPINT);
ssh->handshake->primeGroup = NULL;
ret = wolfSSH_TestGetDHPrimeGroup(ssh, &group, &groupSz,
&generator, &generatorSz);
if (ret != WS_SUCCESS) {
printf("DhGexGroupCacheMissFallback: fallback ret %d\n", ret);
result = -243;
goto out;
}
/* Must re-select the group the wire used, with a non-NULL generator. */
if (group == NULL || groupSz != wireSz || generator == NULL ||
generatorSz == 0) {
printf("DhGexGroupCacheMissFallback: group sz %u wire %u gen %p\n",
groupSz, wireSz, (const void*)generator);
result = -244;
goto out;
}
out:
if (ssh != NULL)
wolfSSH_free(ssh);
if (ctx != NULL)
wolfSSH_CTX_free(ctx);
return result;
}
/* Drive the real server request path with a client window no built-in group
* satisfies (3000..3500, and no group exists between 2048 and 4096). The server
* must return WS_DH_SIZE_E and leave no group cached, rather than emit a
* KEXDH_GEX_GROUP with a NULL prime. The window is impossible at any floor, so
* this is not gated on WOLFSSH_DH_GEX_MIN_BITS. */
static int test_DhGexServerRejectsUnsatisfiableWindow(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
byte request[UINT32_SZ * 3];
word32 idx = 0;
int ret;
int result = 0;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -280;
wolfSSH_SetIOSend(ctx, UnitIoSendSink);
ssh = wolfSSH_new(ctx);
if (ssh == NULL || ssh->handshake == NULL) {
result = -281;
goto out;
}
ssh->handshake->kexId = ID_DH_GEX_SHA256;
PutU32BE(request, 3000);
PutU32BE(request + UINT32_SZ, 3000);
PutU32BE(request + UINT32_SZ * 2, 3500);
ret = wolfSSH_TestDoKexDhGexRequest(ssh, request, sizeof(request), &idx);
if (ret != WS_DH_SIZE_E) {
printf("DhGexServerRejectsUnsatisfiableWindow: ret %d want %d\n",
ret, WS_DH_SIZE_E);
result = -282;
goto out;
}
/* A rejected selection must not leave a half-cached group behind. */
if (ssh->handshake->primeGroup != NULL ||
ssh->handshake->primeGroupSz != 0) {
printf("DhGexServerRejectsUnsatisfiableWindow: stale cache %p sz %u\n",
(const void*)ssh->handshake->primeGroup,
ssh->handshake->primeGroupSz);
result = -283;
goto out;
}
out:
if (ssh != NULL)
wolfSSH_free(ssh);
if (ctx != NULL)
wolfSSH_CTX_free(ctx);
return result;
}
/* Drive SendKexDhGexRequest with the window preset on the handshake. The send
* sink swallows the packet; the caller inspects the window it advertised. */
static int DhGexRequestCase(word32 minBits, word32 prefBits, word32 maxBits,
int expectRet, WOLFSSH_CTX* ctx, WOLFSSH** sshOut)
{
WOLFSSH* ssh = wolfSSH_new(ctx);
*sshOut = ssh;
if (ssh == NULL || ssh->handshake == NULL)
return -1;
ssh->handshake->kexId = ID_DH_GEX_SHA256;
ssh->handshake->dhGexMinSz = minBits;
ssh->handshake->dhGexPreferredSz = prefBits;
ssh->handshake->dhGexMaxSz = maxBits;
return (wolfSSH_TestSendKexDhGexRequest(ssh) == expectRet) ? 0 : -1;
}
/* The client must advertise the same minimum DoKexDhGexGroup enforces on the
* reply. Otherwise a lowered WOLFSSH_DEFAULT_GEXDH_MIN asks for a group that
* the accept path then rejects. */
static int test_DhGexRequestFloorClamp(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
/* Window edges expressed relative to the floor so the clamp is exercised at
* any WOLFSSH_DH_GEX_MIN_BITS, not just the 2048-bit default. */
word32 subFloor = WOLFSSH_DH_GEX_MIN_BITS / 2;
word32 prefAbove = WOLFSSH_DH_GEX_MIN_BITS + (WOLFSSH_DH_GEX_MIN_BITS / 2);
word32 maxHigh = WOLFSSH_DH_GEX_MIN_BITS * 4;
int result = 0;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -290;
wolfSSH_SetIOSend(ctx, UnitIoSendSink);
/* A sub-floor min is raised to the floor, and the preferred size rides up
* with it so the advertised triple stays min <= preferred. */
if (DhGexRequestCase(subFloor, subFloor, maxHigh, WS_SUCCESS, ctx, &ssh)
!= 0) {
result = -291;
goto out;
}
if (ssh->handshake->dhGexMinSz != WOLFSSH_DH_GEX_MIN_BITS ||
ssh->handshake->dhGexPreferredSz != WOLFSSH_DH_GEX_MIN_BITS) {
printf("DhGexRequestFloorClamp: min %u pref %u want %u\n",
ssh->handshake->dhGexMinSz, ssh->handshake->dhGexPreferredSz,
(word32)WOLFSSH_DH_GEX_MIN_BITS);
result = -292;
goto out;
}
wolfSSH_free(ssh);
ssh = NULL;
/* A window topping out below the floor has nothing to ask for. Reject it
* here rather than emit a request whose reply we would refuse. */
if (DhGexRequestCase(subFloor, subFloor, WOLFSSH_DH_GEX_MIN_BITS - 1,
WS_DH_SIZE_E, ctx, &ssh) != 0) {
result = -293;
goto out;
}
wolfSSH_free(ssh);
ssh = NULL;
/* A window already at or above the floor is advertised untouched. */
if (DhGexRequestCase(WOLFSSH_DH_GEX_MIN_BITS, prefAbove, maxHigh, WS_SUCCESS,
ctx, &ssh) != 0) {
result = -294;
goto out;
}
if (ssh->handshake->dhGexMinSz != WOLFSSH_DH_GEX_MIN_BITS ||
ssh->handshake->dhGexPreferredSz != prefAbove ||
ssh->handshake->dhGexMaxSz != maxHigh) {
result = -295;
goto out;
}
wolfSSH_free(ssh);
ssh = NULL;
/* A preferred size above the max is clamped down to the max, so the
* advertised triple keeps min <= preferred <= max (RFC 4419 sec. 3). */
if (DhGexRequestCase(WOLFSSH_DH_GEX_MIN_BITS, prefAbove,
WOLFSSH_DH_GEX_MIN_BITS, WS_SUCCESS, ctx, &ssh) != 0) {
result = -296;
goto out;
}
if (ssh->handshake->dhGexPreferredSz != WOLFSSH_DH_GEX_MIN_BITS ||
ssh->handshake->dhGexMaxSz != WOLFSSH_DH_GEX_MIN_BITS) {
printf("DhGexRequestFloorClamp: pref %u max %u want %u\n",
ssh->handshake->dhGexPreferredSz, ssh->handshake->dhGexMaxSz,
(word32)WOLFSSH_DH_GEX_MIN_BITS);
result = -297;
goto out;
}
out:
if (ssh != NULL)
wolfSSH_free(ssh);
if (ctx != NULL)
wolfSSH_CTX_free(ctx);
return result;
}
/* Mirror of test_DhGexRequestFloorClamp for the accept side: even when the
* client advertised a sub-floor min, DoKexDhGexGroup must clamp the accept
* minimum up to WOLFSSH_DH_GEX_MIN_BITS and reject a below-floor group the
* server sent anyway (RFC 8270). Without the clamp, a 1024-bit prime paired
* with dhGexMinSz == 1024 would pass. The size check runs before primality,
* so an arbitrary 1024-bit value is a sufficient fixture. */
static int test_DhGexGroupAcceptFloor(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
/* A prime half the floor's bit length: below the floor at any
* WOLFSSH_DH_GEX_MIN_BITS, so the accept-side clamp must reject it. */
word32 magBytes = WOLFSSH_DH_GEX_MIN_BITS / 16;
byte group[UINT32_SZ + 1 + (WOLFSSH_DH_GEX_MIN_BITS / 16)
+ UINT32_SZ + 1];
word32 gIdx = 0;
word32 idx = 0;
int ret;
int result = 0;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -270;
ssh = wolfSSH_new(ctx);
if (ssh == NULL || ssh->handshake == NULL) {
result = -271;
goto out;
}
ssh->handshake->kexId = ID_DH_GEX_SHA256;
/* Sub-floor min: the accept-side clamp, not this value, must govern. */
ssh->handshake->dhGexMinSz = WOLFSSH_DH_GEX_MIN_BITS / 2;
ssh->handshake->dhGexMaxSz = WOLFSSH_DH_GEX_MIN_BITS * 4;
/* mpint prime: a canonical (floor/2)-bit value (0x00 sign pad, then a 0x80
* top byte so GetMpint accepts it), followed by mpint generator 2. The
* size check runs before primality, so an arbitrary value is sufficient. */
PutU32BE(group + gIdx, 1 + magBytes);
gIdx += UINT32_SZ;
group[gIdx++] = 0x00;
group[gIdx++] = 0x80;
WMEMSET(group + gIdx, 0xFF, magBytes - 1);
gIdx += magBytes - 1;
PutU32BE(group + gIdx, 1);
gIdx += UINT32_SZ;
group[gIdx++] = 0x02;
ret = wolfSSH_TestDoKexDhGexGroup(ssh, group, gIdx, &idx);
if (ret != WS_DH_SIZE_E) {
printf("DhGexGroupAcceptFloor: ret %d want %d\n", ret, WS_DH_SIZE_E);
result = -272;
goto out;
}
out:
if (ssh != NULL)
wolfSSH_free(ssh);
if (ctx != NULL)
wolfSSH_CTX_free(ctx);
return result;
}
/* Drive a real 4096-bit GEX key agreement on the server. Selecting group 16 is
* now the ordinary outcome for a stock client window (preferred 3072), so the
* 512-byte modulus has to survive KeyAgreeDh_server's f buffer (KEX_F_SIZE)
* and shared-secret buffer (ssh->k). Confirms the server's f and k are a real
* DH pair by recomputing the secret from the client side. */
static int test_DhGexGroup16KeyAgree(void)
{
#if !defined(WOLFSSH_NO_DH_GROUP16_SHA512) && \
WOLFSSH_DH_GEX_MIN_BITS == 2048 && \
(MAX_KEX_KEY_SZ * 8) >= 4096 && ((KEX_F_SIZE - 1) * 8) >= 4096
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
byte request[UINT32_SZ * 3];
word32 idx = 0;
const byte* group = NULL;
word32 groupSz = 0;
const byte* generator = NULL;
word32 generatorSz = 0;
DhKey clientKey;
int keyInited = 0;
byte f[KEX_F_SIZE];
word32 fSz = (word32)sizeof(f);
byte cPriv[MAX_KEX_KEY_SZ];
word32 cPrivSz = (word32)sizeof(cPriv);
byte cPub[KEX_F_SIZE];
word32 cPubSz = (word32)sizeof(cPub);
byte cSecret[MAX_KEX_KEY_SZ];
word32 cSecretSz = (word32)sizeof(cSecret);
int ret;
int result = 0;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -250;
wolfSSH_SetIOSend(ctx, UnitIoSendSink);
ssh = wolfSSH_new(ctx);
if (ssh == NULL || ssh->handshake == NULL) {
result = -251;
goto out;
}
ssh->handshake->kexId = ID_DH_GEX_SHA256;
/* Window that resolves to group 16 under the RFC 4419 rule. */
PutU32BE(request, 2048);
PutU32BE(request + UINT32_SZ, 4096);
PutU32BE(request + UINT32_SZ * 2, 8192);
ret = wolfSSH_TestDoKexDhGexRequest(ssh, request, sizeof(request), &idx);
if (ret != WS_SUCCESS || ssh->handshake->primeGroupSz != 512) {
printf("DhGexGroup16KeyAgree: request ret %d sz %u\n",
ret, ssh->handshake->primeGroupSz);
result = -252;
goto out;
}
/* Build a client key pair over the very group the server put on the wire. */
ret = wolfSSH_TestGetDHPrimeGroup(ssh, &group, &groupSz,
&generator, &generatorSz);
if (ret != WS_SUCCESS) {
result = -253;
goto out;
}
if (wc_InitDhKey(&clientKey) != 0) {
result = -254;
goto out;
}
keyInited = 1;
if (wc_DhSetKey(&clientKey, group, groupSz, generator, generatorSz) != 0) {
result = -255;
goto out;
}
PRIVATE_KEY_UNLOCK();
ret = wc_DhGenerateKeyPair(&clientKey, ssh->rng, cPriv, &cPrivSz,
cPub, &cPubSz);
PRIVATE_KEY_LOCK();
if (ret != 0) {
result = -256;
goto out;
}
/* Hand the client's public value to the server as the mpint
* SendKexDhInit() would send, and run the agreement. */
ssh->handshake->eSz = 0;
if (cPub[0] & 0x80)
ssh->handshake->e[ssh->handshake->eSz++] = 0;
WMEMCPY(ssh->handshake->e + ssh->handshake->eSz, cPub, cPubSz);
ssh->handshake->eSz += cPubSz;
ssh->kSz = MAX_KEX_KEY_SZ;
ret = wolfSSH_TestKeyAgreeDh_server(ssh, WC_HASH_TYPE_SHA256, f, &fSz);
if (ret != WS_SUCCESS || fSz == 0 || fSz > 512) {
printf("DhGexGroup16KeyAgree: agree ret %d fSz %u\n", ret, fSz);
result = -257;
goto out;
}
if (ssh->primeGroupSz != 512 || ssh->kSz == 0) {
printf("DhGexGroup16KeyAgree: primeGroupSz %u kSz %u\n",
ssh->primeGroupSz, ssh->kSz);
result = -258;
goto out;
}
/* The server's k must be the shared secret the client derives from f. */
PRIVATE_KEY_UNLOCK();
ret = wc_DhAgree(&clientKey, cSecret, &cSecretSz, cPriv, cPrivSz,
f, fSz);
PRIVATE_KEY_LOCK();
if (ret != 0) {
result = -259;
goto out;
}
if (cSecretSz != ssh->kSz ||
WMEMCMP(cSecret, ssh->k, cSecretSz) != 0) {
printf("DhGexGroup16KeyAgree: secret mismatch, client %u server %u\n",
cSecretSz, ssh->kSz);
result = -260;
goto out;
}
out:
if (keyInited)
wc_FreeDhKey(&clientKey);
if (ssh != NULL)
wolfSSH_free(ssh);
if (ctx != NULL)
wolfSSH_CTX_free(ctx);
return result;
#else
return 0;
#endif
}
/* Drive a successful client-side GEX GROUP accept and confirm the client honors
* a peer's non-default generator (g != 2). DoKexDhGexGroup caches the wire prime
* and generator on the handshake, then GetDHPrimeGroup must hand both back to
* key agreement -- the generator-honoring branch that only the client reaches.
* The server-side tests always leave handshake->generator NULL, so without this
* that branch has zero positive coverage. Mirrors how test_DhGexGroup16KeyAgree
* sources a real safe prime, but exercises the accept side instead of select. */
static int test_DhGexGroupAcceptHonorsGenerator(void)
{
#if WOLFSSH_DH_GEX_MIN_BITS <= 2048
WOLFSSH_CTX* sctx = NULL; /* server: source a genuine 2048-bit safe prime */
WOLFSSH* sssh = NULL;
WOLFSSH_CTX* cctx = NULL; /* client: drive the accept under test */
WOLFSSH* cssh = NULL;
byte request[UINT32_SZ * 3];
const byte* srcGroup = NULL;
word32 srcGroupSz = 0;
const byte* srcGen = NULL;
word32 srcGenSz = 0;
byte wire[UINT32_SZ + 1 + 512 + UINT32_SZ + 1];
word32 wIdx = 0;
word32 idx = 0;
const byte* group = NULL;
word32 groupSz = 0;
const byte* generator = NULL;
word32 generatorSz = 0;
byte pad;
int ret;
int result = 0;
/* Select group 14 on a server so we have a real 2048-bit safe prime to put
* on the wire; a window pinned to 2048 leaves group 14 the only fit. */
sctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (sctx == NULL)
return -300;
wolfSSH_SetIOSend(sctx, UnitIoSendSink);
sssh = wolfSSH_new(sctx);
if (sssh == NULL || sssh->handshake == NULL) {
result = -301;
goto out;
}
sssh->handshake->kexId = ID_DH_GEX_SHA256;
PutU32BE(request, 2048);
PutU32BE(request + UINT32_SZ, 2048);
PutU32BE(request + UINT32_SZ * 2, 2048);
ret = wolfSSH_TestDoKexDhGexRequest(sssh, request, sizeof(request), &idx);
if (ret != WS_SUCCESS) {
printf("DhGexGroupAcceptHonorsGenerator: request ret %d\n", ret);
result = -302;
goto out;
}
ret = wolfSSH_TestGetDHPrimeGroup(sssh, &srcGroup, &srcGroupSz,
&srcGen, &srcGenSz);
if (ret != WS_SUCCESS || srcGroup == NULL || srcGroupSz == 0) {
result = -303;
goto out;
}
/* Build a GROUP message: mpint prime (0x00 sign pad when the top bit is
* set), then mpint generator 5 -- deliberately not the built-in 2, so a
* passing accept can only come from caching and honoring the wire value. */
pad = (srcGroup[0] & 0x80) ? 1 : 0;
if ((word32)(UINT32_SZ + pad + srcGroupSz + UINT32_SZ + 1) > sizeof(wire)) {
result = -304;
goto out;
}
PutU32BE(wire + wIdx, srcGroupSz + pad);
wIdx += UINT32_SZ;
if (pad)
wire[wIdx++] = 0x00;
WMEMCPY(wire + wIdx, srcGroup, srcGroupSz);
wIdx += srcGroupSz;
PutU32BE(wire + wIdx, 1);
wIdx += UINT32_SZ;
wire[wIdx++] = 0x05;
cctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (cctx == NULL) {
result = -305;
goto out;
}
wolfSSH_SetIOSend(cctx, UnitIoSendSink);
cssh = wolfSSH_new(cctx);
if (cssh == NULL || cssh->handshake == NULL) {
result = -306;
goto out;
}
cssh->handshake->kexId = ID_DH_GEX_SHA256;
cssh->handshake->dhGexMinSz = 2048;
cssh->handshake->dhGexMaxSz = 8192;
idx = 0;
ret = wolfSSH_TestDoKexDhGexGroup(cssh, wire, wIdx, &idx);
if (ret != WS_SUCCESS) {
printf("DhGexGroupAcceptHonorsGenerator: accept ret %d\n", ret);
result = -307;
goto out;
}
/* The accept must have cached the wire generator, not defaulted to g = 2. */
if (cssh->handshake->generator == NULL ||
cssh->handshake->generatorSz != 1 ||
cssh->handshake->generator[0] != 0x05) {
result = -308;
goto out;
}
/* GetDHPrimeGroup must return the cached prime AND the cached non-default
* generator -- same pointers -- so key agreement runs over the peer's g. */
ret = wolfSSH_TestGetDHPrimeGroup(cssh, &group, &groupSz,
&generator, &generatorSz);
if (ret != WS_SUCCESS) {
result = -309;
goto out;
}
if (group != cssh->handshake->primeGroup ||
groupSz != cssh->handshake->primeGroupSz) {
result = -310;
goto out;
}
if (generator != cssh->handshake->generator ||
generatorSz != 1 || generator[0] != 0x05) {
printf("DhGexGroupAcceptHonorsGenerator: generator not honored\n");
result = -311;
goto out;
}
out:
if (cssh != NULL)
wolfSSH_free(cssh);
if (cctx != NULL)
wolfSSH_CTX_free(cctx);
if (sssh != NULL)
wolfSSH_free(sssh);
if (sctx != NULL)
wolfSSH_CTX_free(sctx);
return result;
#else
return 0;
#endif
}
/* SendKexDhGexGroup frees any previously cached group before caching the freshly
* selected one. A first handshake entry always has primeGroup == NULL, so the
* free-before-realloc branch is never reached by an ordinary handshake. Seed a
* stale cached group, then drive the server request path and confirm the seed
* is replaced by a real modulus (not leaked or left stale). */
static int test_DhGexGroupSendRecache(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
byte request[UINT32_SZ * 3];
word32 idx = 0;
const byte* group = NULL;
word32 groupSz = 0;
const byte* generator = NULL;
word32 generatorSz = 0;
int ret;
int result = 0;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -320;
wolfSSH_SetIOSend(ctx, UnitIoSendSink);
ssh = wolfSSH_new(ctx);
if (ssh == NULL || ssh->handshake == NULL) {
result = -321;
goto out;
}
ssh->handshake->kexId = ID_DH_GEX_SHA256;
/* Seed a stale, WMALLOC'd 4-byte group so SendKexDhGexGroup must free it
* before caching the selection. The distinctive size proves replacement;
* a leaked seed is caught by the leak checkers CI runs the suite under. */
ssh->handshake->primeGroup =
(byte*)WMALLOC(4, ssh->ctx->heap, DYNTYPE_MPINT);
if (ssh->handshake->primeGroup == NULL) {
result = -322;
goto out;
}
ssh->handshake->primeGroupSz = 4;
PutU32BE(request, WOLFSSH_DEFAULT_GEXDH_MIN);
PutU32BE(request + UINT32_SZ, WOLFSSH_DEFAULT_GEXDH_PREFERRED);
PutU32BE(request + UINT32_SZ * 2, WOLFSSH_DEFAULT_GEXDH_MAX);
ret = wolfSSH_TestDoKexDhGexRequest(ssh, request, sizeof(request), &idx);
if (ret != WS_SUCCESS || ssh->handshake->primeGroup == NULL) {
printf("DhGexGroupSendRecache: request ret %d\n", ret);
result = -323;
goto out;
}
/* The 4-byte seed must be gone, replaced by a real group modulus. */
if (ssh->handshake->primeGroupSz == 4 ||
ssh->handshake->primeGroupSz == 0) {
printf("DhGexGroupSendRecache: cache not replaced, sz %u\n",
ssh->handshake->primeGroupSz);
result = -324;
goto out;
}
/* The exchange-hash path must hand back that same cached group. */
ret = wolfSSH_TestGetDHPrimeGroup(ssh, &group, &groupSz,
&generator, &generatorSz);
if (ret != WS_SUCCESS || group != ssh->handshake->primeGroup ||
groupSz != ssh->handshake->primeGroupSz) {
printf("DhGexGroupSendRecache: hash group desync sz %u vs %u\n",
groupSz, ssh->handshake->primeGroupSz);
result = -325;
goto out;
}
out:
if (ssh != NULL)
wolfSSH_free(ssh);
if (ctx != NULL)
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* WOLFSSH_TEST_INTERNAL && !WOLFSSH_NO_DH_GEX_SHA256 */
#ifdef WOLFSSH_TEST_INTERNAL
/* Verify DoUserAuthBanner fully consumes the payload, including a non-empty
* language tag. Before the fix, the tag's data bytes were left unconsumed,
* which would misalign packet decoding for subsequent messages. */
static int test_DoUserAuthBanner(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
int result = 0;
/* Payload layout: [4-byte banner len][banner][4-byte lang len][lang] */
struct {
const char* banner;
word32 bannerSz;
const char* lang;
word32 langSz;
int expectRet;
const char* label;
} cases[] = {
{ "Welcome", 7, "", 0, WS_SUCCESS, "empty lang tag" },
{ "Welcome", 7, "en-US", 5, WS_SUCCESS, "non-empty lang tag" },
{ NULL, 0, NULL, 0, WS_BAD_ARGUMENT, "null ssh" },
};
int i;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -300;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return -301;
}
ctx->showBanner = 0;
for (i = 0; i < (int)(sizeof(cases)/sizeof(cases[0])); i++) {
byte buf[128];
word32 idx = 0;
word32 len = 0;
int ret;
if (cases[i].banner == NULL) {
/* null-ssh case: pass NULL ssh, dummy non-null buf */
buf[0] = 0;
len = 1;
ret = wolfSSH_TestDoUserAuthBanner(NULL, buf, len, &idx);
}
else {
/* encode banner string */
buf[len++] = (byte)(cases[i].bannerSz >> 24);
buf[len++] = (byte)(cases[i].bannerSz >> 16);
buf[len++] = (byte)(cases[i].bannerSz >> 8);
buf[len++] = (byte)(cases[i].bannerSz);
WMEMCPY(buf + len, cases[i].banner, cases[i].bannerSz);
len += cases[i].bannerSz;
/* encode language tag string */
buf[len++] = (byte)(cases[i].langSz >> 24);
buf[len++] = (byte)(cases[i].langSz >> 16);
buf[len++] = (byte)(cases[i].langSz >> 8);
buf[len++] = (byte)(cases[i].langSz);
WMEMCPY(buf + len, cases[i].lang, cases[i].langSz);
len += cases[i].langSz;
ret = wolfSSH_TestDoUserAuthBanner(ssh, buf, len, &idx);
}
if (ret != cases[i].expectRet) {
printf("DoUserAuthBanner[%s]: ret=%d, expected=%d\n",
cases[i].label, ret, cases[i].expectRet);
result = -302 - i;
break;
}
/* On success the entire payload must be consumed. */
if (ret == WS_SUCCESS && idx != len) {
printf("DoUserAuthBanner[%s]: idx=%u, len=%u (unconsumed bytes)\n",
cases[i].label, idx, len);
result = -310 - i;
break;
}
}
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* Verify PrepareUserAuthRequestPassword rejects with WS_BUFFER_E instead of
* wrapping *payloadSz when it would exceed MAX_PACKET_SZ. */
static int test_PrepareUserAuthRequestPassword(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
int result = 0;
/* BOOLEAN_SZ + LENGTH_SZ, mirrors internal.c's addSz */
const word32 addSz = 1 + 4;
struct {
word32 startSz;
word32 passwordSz;
int expectRet;
const char* label;
} cases[] = {
{ 10, 20, WS_SUCCESS, "normal small payload" },
{ 35000 - 2, 1, WS_BUFFER_E, "addSz alone overflows" },
{ 100, 34900, WS_BUFFER_E, "passwordSz overflows" },
{ 40000, 0, WS_BUFFER_E, "payloadSz already exceeds max" },
{ 35000 - addSz, 0, WS_SUCCESS, "exact fit" },
};
int i;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -320;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return -321;
}
for (i = 0; i < (int)(sizeof(cases)/sizeof(cases[0])); i++) {
WS_UserAuthData authData;
word32 payloadSz = cases[i].startSz;
int ret;
WMEMSET(&authData, 0, sizeof(authData));
authData.sf.password.passwordSz = cases[i].passwordSz;
ret = wolfSSH_TestPrepareUserAuthRequestPassword(ssh, &payloadSz,
&authData);
if (ret != cases[i].expectRet) {
printf("PrepareUserAuthRequestPassword[%s]: ret=%d, expected=%d\n",
cases[i].label, ret, cases[i].expectRet);
result = -322 - i;
break;
}
if (ret == WS_SUCCESS &&
payloadSz != cases[i].startSz + addSz + cases[i].passwordSz) {
printf("PrepareUserAuthRequestPassword[%s]: payloadSz=%u, "
"expected=%u\n", cases[i].label, payloadSz,
cases[i].startSz + addSz + cases[i].passwordSz);
result = -330 - i;
break;
}
}
if (result == 0) {
int ret = wolfSSH_TestPrepareUserAuthRequestPassword(NULL, NULL, NULL);
if (ret != WS_BAD_ARGUMENT) {
printf("PrepareUserAuthRequestPassword[null args]: ret=%d, "
"expected=%d\n", ret, WS_BAD_ARGUMENT);
result = -340;
}
}
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#if defined(WOLFSSH_TEST_INTERNAL) && defined(WOLFSSH_SCP)
/* Verify GetScpFileMode strips setuid/setgid/sticky bits from a peer-supplied
* SCP C/D record mode, matching the masking already done on the send path.
* The receive path cannot be exercised end-to-end because both peers mask the
* mode before transmitting, so this drives the parser directly. */
static int test_ScpGetFileMode(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
static const char* hdrs[] = {
"C4755 0 f\n", /* setuid set */
"D2755 0 d\n", /* setgid set */
"D1755 0 d\n", /* sticky set */
"D7777 0 d\n", /* all special bits set */
"C0644 0 f\n" /* ordinary mode, unaffected */
};
static const int expected[] = { 0755, 0755, 0755, 0777, 0644 };
/* records the parser must reject */
static const char* badHdrs[] = {
"C8755 0 f\n", /* '8' is not an octal digit */
"X4755 0 f\n", /* prefix is neither 'C' nor 'D' */
"C75" /* shorter than the mode field */
};
int result = 0;
int ret;
int i;
word32 idx;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -420;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return -421;
}
for (i = 0; i < (int)(sizeof(hdrs) / sizeof(hdrs[0])); i++) {
idx = 0;
ssh->scpFileMode = 0;
ret = wolfSSH_TestScpGetFileMode(ssh, (byte*)hdrs[i],
(word32)WSTRLEN(hdrs[i]), &idx);
if (ret != WS_SUCCESS) {
result = -422;
break;
}
if (ssh->scpFileMode != expected[i]) {
result = -423;
break;
}
/* index advances past the 'C'/'D', four mode octets, and the
* trailing space */
if (idx != 6) {
result = -424;
break;
}
}
for (i = 0; result == 0 &&
i < (int)(sizeof(badHdrs) / sizeof(badHdrs[0])); i++) {
idx = 0;
ret = wolfSSH_TestScpGetFileMode(ssh, (byte*)badHdrs[i],
(word32)WSTRLEN(badHdrs[i]), &idx);
if (ret != WS_BAD_ARGUMENT) {
result = -425;
break;
}
}
/* a nonzero start index is bounded by what is left after it */
if (result == 0) {
idx = 2;
ret = wolfSSH_TestScpGetFileMode(ssh, (byte*)"xxC0644 0 f", 11, &idx);
if (ret != WS_SUCCESS || idx != 8 || ssh->scpFileMode != 0644)
result = -426;
}
if (result == 0) {
idx = 6;
ret = wolfSSH_TestScpGetFileMode(ssh, (byte*)"C0644 C", 7, &idx);
if (ret != WS_BAD_ARGUMENT)
result = -427;
}
if (result == 0) {
idx = 7;
ret = wolfSSH_TestScpGetFileMode(ssh, (byte*)"C0644 C", 7, &idx);
if (ret != WS_BAD_ARGUMENT)
result = -428;
}
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* Drive GetScpFileSize directly, covering the digit-validating parsing added to
* replace atoi: valid sizes up to UINT32_MAX are accepted, while signed,
* whitespace-padded, empty, out-of-range, and non-numeric fields are rejected
* instead of silently wrapping into a bogus word32 size. */
static int test_ScpGetFileSize(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
static const char* good[] = {
"0 f\n",
"1024 file.txt\n",
"007 f\n", /* leading zeros are accepted */
"4294967295 f\n" /* UINT32_MAX, the largest accepted size */
};
static const word32 goodSz[] = { 0, 1024, 7, 4294967295UL };
static const char* bad[] = {
"-1 f\n", /* a sign is not a digit */
"+1 f\n",
"\t1 f\n", /* leading whitespace is not a digit */
" f\n", /* empty field, separator comes first */
"4294967296 f\n", /* one past UINT32_MAX */
"18446744073709551616 f\n", /* overflows the 64-bit accumulator */
"12x34 f\n", /* trailing junk before the separator */
"abc f\n" /* not numeric at all */
};
char tmp[48];
int result = 0;
int ret;
int i;
word32 idx;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -430;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return -431;
}
for (i = 0; i < (int)(sizeof(good) / sizeof(good[0])); i++) {
WMEMSET(tmp, 0, sizeof(tmp));
WSTRNCPY(tmp, good[i], sizeof(tmp) - 1);
idx = 0;
ssh->scpFileSz = 0;
ret = wolfSSH_TestScpGetFileSize(ssh, (byte*)tmp,
(word32)WSTRLEN(tmp), &idx);
if (ret != WS_SUCCESS) {
result = -432;
break;
}
if (ssh->scpFileSz != goodSz[i]) {
result = -433;
break;
}
}
for (i = 0; result == 0 &&
i < (int)(sizeof(bad) / sizeof(bad[0])); i++) {
WMEMSET(tmp, 0, sizeof(tmp));
WSTRNCPY(tmp, bad[i], sizeof(tmp) - 1);
idx = 0;
ret = wolfSSH_TestScpGetFileSize(ssh, (byte*)tmp,
(word32)WSTRLEN(tmp), &idx);
if (ret == WS_SUCCESS) {
result = -434;
break;
}
}
/* a NUL byte inside the field does not make it a short field: parsing by
* length rejects "1\0" "23" rather than stopping at the NUL to accept 1 */
if (result == 0) {
WMEMSET(tmp, 0, sizeof(tmp));
WMEMCPY(tmp, "1\0" "23 f\n", 7);
idx = 0;
ret = wolfSSH_TestScpGetFileSize(ssh, (byte*)tmp, 7, &idx);
if (ret == WS_SUCCESS)
result = -435;
}
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* Drive GetScpTimestamp directly, covering the digit-validating parsing of the
* "T<mtime> 0 <atime> 0" record: a well-formed record populates both times,
* while a missing 'T', malformed separator, signed, whitespace-padded,
* non-numeric, and overflowing field are all rejected. These fields are
* unbounded, so a sign is the only thing keeping "-1" from being taken as the
* wrapped 64-bit maximum. */
static int test_ScpGetTimestamp(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
static const char* bad[] = {
"1609459200 0 1609459200 0\n", /* missing leading 'T' */
"T-1 0 100 0\n", /* a sign is not a digit */
"T+1 0 100 0\n",
"T\t1 0 100 0\n", /* leading whitespace */
"T12x 0 100 0\n", /* mtime not fully numeric */
"T18446744073709551616 0 100 0\n", /* one past the 64-bit max */
"T99999999999999999999999999 0 100 0\n", /* mtime overflow */
"T100 5 100 0\n", /* mtime separator not "0 " */
"T100 0 -1 0\n", /* negative atime */
"T100 0 abc 0\n", /* atime not numeric */
"T100 0 99999999999999999999999999 0\n" /* atime overflow */
};
char tmp[64];
int result = 0;
int ret;
int i;
word32 idx;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -440;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return -441;
}
/* a valid record parses both the modification and access times */
WMEMSET(tmp, 0, sizeof(tmp));
WSTRNCPY(tmp, "T1609459200 0 1609459201 0\n", sizeof(tmp) - 1);
idx = 0;
ssh->scpMTime = 0;
ssh->scpATime = 0;
ret = wolfSSH_TestScpGetTimestamp(ssh, (byte*)tmp,
(word32)WSTRLEN(tmp), &idx);
if (ret != WS_SUCCESS)
result = -442;
else if (ssh->scpMTime != (word64)1609459200)
result = -443;
else if (ssh->scpATime != (word64)1609459201)
result = -444;
for (i = 0; result == 0 &&
i < (int)(sizeof(bad) / sizeof(bad[0])); i++) {
WMEMSET(tmp, 0, sizeof(tmp));
WSTRNCPY(tmp, bad[i], sizeof(tmp) - 1);
idx = 0;
ret = wolfSSH_TestScpGetTimestamp(ssh, (byte*)tmp,
(word32)WSTRLEN(tmp), &idx);
if (ret == WS_SUCCESS) {
result = -445;
break;
}
}
/* the fields are unbounded, so the 64-bit maximum itself is accepted */
if (result == 0) {
WMEMSET(tmp, 0, sizeof(tmp));
WSTRNCPY(tmp, "T18446744073709551615 0 18446744073709551614 0\n",
sizeof(tmp) - 1);
idx = 0;
ssh->scpMTime = 0;
ssh->scpATime = 0;
ret = wolfSSH_TestScpGetTimestamp(ssh, (byte*)tmp,
(word32)WSTRLEN(tmp), &idx);
if (ret != WS_SUCCESS)
result = -446;
else if (ssh->scpMTime != W64LIT(0xFFFFFFFFFFFFFFFF))
result = -447;
else if (ssh->scpATime != W64LIT(0xFFFFFFFFFFFFFFFE))
result = -448;
}
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* Drive GetScpFileName directly, covering the reuse-vs-realloc branch added
* to avoid a free/WMALLOC pair on every call: a name that fits within the
* previous allocation reuses ssh->scpFileName (verified by pointer identity),
* while a name too long for it forces a fresh allocation. Each case also
* checks scpFileNameCap, which is the allocation size the reuse condition
* tests against, so an off-by-one there fails deterministically rather than
* only under a heap checker. */
static int test_ScpGetFileName(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
char* firstAlloc = NULL;
char* afterGrow = NULL;
char tmp[64];
int result = 0;
int ret;
word32 idx;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -450;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return -451;
}
/* first call: nothing allocated yet, must allocate */
WSTRNCPY(tmp, "short.txt", sizeof(tmp));
idx = 0;
ret = wolfSSH_TestScpGetFileName(ssh, (byte*)tmp, (word32)WSTRLEN(tmp),
&idx);
if (ret != WS_SUCCESS)
result = -452;
else if (ssh->scpFileName == NULL)
result = -453;
else if (WSTRNCMP(ssh->scpFileName, "short.txt", 10) != 0)
result = -454;
else if (ssh->scpFileNameSz != 9)
result = -455;
else if (ssh->scpFileNameCap != 10)
result = -476;
firstAlloc = ssh->scpFileName;
/* second call: shorter name fits in the existing allocation, reuse it */
if (result == 0) {
WSTRNCPY(tmp, "ab", sizeof(tmp));
idx = 0;
ret = wolfSSH_TestScpGetFileName(ssh, (byte*)tmp,
(word32)WSTRLEN(tmp), &idx);
if (ret != WS_SUCCESS)
result = -456;
else if (ssh->scpFileName != firstAlloc)
result = -457;
else if (WSTRNCMP(ssh->scpFileName, "ab", 3) != 0)
result = -458;
else if (ssh->scpFileNameSz != 2)
result = -459;
}
/* third call: a name as long as the last one is still reused, because the
* check is against the allocation size and not the previous name length */
if (result == 0) {
WSTRNCPY(tmp, "xy", sizeof(tmp));
idx = 0;
ret = wolfSSH_TestScpGetFileName(ssh, (byte*)tmp,
(word32)WSTRLEN(tmp), &idx);
if (ret != WS_SUCCESS)
result = -460;
else if (ssh->scpFileName != firstAlloc)
result = -461;
else if (WSTRNCMP(ssh->scpFileName, "xy", 3) != 0)
result = -462;
else if (ssh->scpFileNameCap != 10)
result = -477;
}
/* fourth call: a name longer than the current allocation forces a fresh
* WMALLOC */
if (result == 0) {
WSTRNCPY(tmp, "a-name-considerably-longer-than-before.bin",
sizeof(tmp));
idx = 0;
ret = wolfSSH_TestScpGetFileName(ssh, (byte*)tmp,
(word32)WSTRLEN(tmp), &idx);
if (ret != WS_SUCCESS)
result = -463;
else if (WSTRNCMP(ssh->scpFileName,
"a-name-considerably-longer-than-before.bin", 43) != 0)
result = -464;
else if (ssh->scpFileNameSz != 42)
result = -465;
else if (ssh->scpFileNameCap != 43)
result = -478;
afterGrow = ssh->scpFileName;
}
/* fifth call: tight-fit boundary. The allocation is exactly 43 bytes
* here, so reusing it for a 42-character name puts the NUL on the
* buffer's final byte -- catches an off-by-one in the WMALLOC size. */
if (result == 0) {
WSTRNCPY(tmp, "a-different-name-of-the-very-same-length.b",
sizeof(tmp));
idx = 0;
ret = wolfSSH_TestScpGetFileName(ssh, (byte*)tmp,
(word32)WSTRLEN(tmp), &idx);
if (ret != WS_SUCCESS)
result = -469;
else if (ssh->scpFileName != afterGrow)
result = -470;
else if (WSTRNCMP(ssh->scpFileName,
"a-different-name-of-the-very-same-length.b", 43) != 0)
result = -471;
else if (ssh->scpFileNameSz != 42)
result = -472;
else if (ssh->scpFileNameCap != 43)
result = -479;
}
/* sixth call: grow by exactly one byte. A 43-character name needs 44
* bytes, one more than the current allocation, so it must not be reused.
* The scpFileNameCap check below is what catches an off-by-one in the
* reuse condition itself: a loosened condition would reuse the 43-byte
* block and write the NUL one past its end, which the content and
* scpFileNameSz checks cannot see. */
if (result == 0) {
WSTRNCPY(tmp, "another-42-char-name-for-tight-fit-case.bin",
sizeof(tmp));
idx = 0;
ret = wolfSSH_TestScpGetFileName(ssh, (byte*)tmp,
(word32)WSTRLEN(tmp), &idx);
if (ret != WS_SUCCESS)
result = -473;
else if (WSTRNCMP(ssh->scpFileName,
"another-42-char-name-for-tight-fit-case.bin", 44) != 0)
result = -474;
else if (ssh->scpFileNameSz != 43)
result = -475;
else if (ssh->scpFileNameCap != 44)
result = -480;
afterGrow = ssh->scpFileName;
}
/* seventh call: back to a short name, reuses the grown allocation */
if (result == 0) {
WSTRNCPY(tmp, "z", sizeof(tmp));
idx = 0;
ret = wolfSSH_TestScpGetFileName(ssh, (byte*)tmp,
(word32)WSTRLEN(tmp), &idx);
if (ret != WS_SUCCESS)
result = -466;
else if (ssh->scpFileName != afterGrow)
result = -467;
else if (WSTRNCMP(ssh->scpFileName, "z", 2) != 0)
result = -468;
else if (ssh->scpFileNameCap != 44)
result = -481;
}
/* a source-path session sets scpFileNameCap without ever putting a name in
* the buffer; a name of exactly that capacity must still reallocate rather
* than write its NUL one byte past the end */
if (result == 0) {
WFREE(ssh->scpFileName, ssh->ctx->heap, DYNTYPE_STRING);
ssh->scpFileName = (char*)WMALLOC(8, ssh->ctx->heap, DYNTYPE_STRING);
if (ssh->scpFileName == NULL) {
result = -482;
}
else {
ssh->scpFileNameCap = 8;
ssh->scpFileNameSz = 0;
WSTRNCPY(tmp, "12345678", sizeof(tmp));
idx = 0;
ret = wolfSSH_TestScpGetFileName(ssh, (byte*)tmp,
(word32)WSTRLEN(tmp), &idx);
if (ret != WS_SUCCESS)
result = -483;
else if (ssh->scpFileNameCap != 9)
result = -484;
else if (WSTRNCMP(ssh->scpFileName, "12345678", 9) != 0)
result = -485;
else if (ssh->scpFileNameSz != 8)
result = -486;
}
}
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#ifndef NO_WOLFSSH_SERVER
/* Run ParseScpCommand on cmd as a fresh session's exec command. */
static int ScpParseCommandCase(const char* cmd, int expRet, byte expDir,
const char* expBase, const char* expFile, byte expRecursive)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* channel = NULL;
word32 cmdSz = (word32)WSTRLEN(cmd);
int result = 0;
int ret;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -4870;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return -4871;
}
channel = ChannelNew(ssh, ID_CHANTYPE_SESSION, 100, 100);
if (channel == NULL)
result = -4872;
if (result == 0) {
channel->command = (char*)WMALLOC(cmdSz + 1, ctx->heap,
DYNTYPE_STRING);
if (channel->command == NULL)
result = -4873;
}
if (result == 0) {
WMEMCPY(channel->command, cmd, cmdSz + 1);
channel->commandSz = cmdSz;
if (ChannelAppend(ssh, channel) != WS_SUCCESS)
result = -4874;
else
channel = NULL;
}
if (result == 0) {
ret = ParseScpCommand(ssh);
if (ret != expRet)
result = -4875;
}
if (result == 0 && expRet == WS_SUCCESS) {
if (ssh->scpDirection != expDir)
result = -4876;
else if (ssh->scpIsRecursive != expRecursive)
result = -4879;
#ifndef USE_WINDOWS_API
/* paths are POSIX-style */
else if (ssh->scpBasePath == NULL ||
WSTRCMP(ssh->scpBasePath, expBase) != 0)
result = -4877;
/* an empty expFile expects no rename */
else if (expFile != NULL && expFile[0] == '\0' &&
ssh->scpFileName != NULL && ssh->scpFileName[0] != '\0')
result = -4878;
else if (expFile != NULL && expFile[0] != '\0' &&
(ssh->scpFileName == NULL ||
WSTRCMP(ssh->scpFileName, expFile) != 0))
result = -4878;
#else
(void)expBase;
(void)expFile;
#endif
}
if (channel != NULL)
ChannelDelete(channel, ctx->heap);
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* Options end at the -t or -f that takes the path, or at a "--" before it.
* A target with no directory part names a file in the current directory. */
static int test_ScpParseCommand(void)
{
int result;
/* the path is not rescanned for options */
result = ScpParseCommandCase("scp -f ./a -t b", WS_SUCCESS,
WOLFSSH_SCP_FROM, "./a -t b", NULL, 0);
if (result == 0)
result = ScpParseCommandCase("scp -f ./x -r", WS_SUCCESS,
WOLFSSH_SCP_FROM, "./x -r", NULL, 0);
/* "--" before a path starting with "-", as OpenSSH sends it */
if (result == 0)
result = ScpParseCommandCase("scp -r -f -- -x", WS_SUCCESS,
WOLFSSH_SCP_FROM, "-x", NULL, 1);
if (result == 0)
result = ScpParseCommandCase("scp -t -- -file", WS_SUCCESS,
WOLFSSH_SCP_TO, ".", "-file", 0);
/* a bare target keeps its whole name */
if (result == 0)
result = ScpParseCommandCase("scp -t newname", WS_SUCCESS,
WOLFSSH_SCP_TO, ".", "newname", 0);
if (result == 0)
result = ScpParseCommandCase("scp -t ./newname", WS_SUCCESS,
WOLFSSH_SCP_TO, "./", "newname", 0);
/* no path at all */
if (result == 0)
result = ScpParseCommandCase("scp -t --", WS_SCP_CMD_E, 0, NULL,
NULL, 0);
#ifndef NO_FILESYSTEM
/* an existing directory takes the files under their own names */
if (result == 0)
result = ScpParseCommandCase("scp -t .", WS_SUCCESS,
WOLFSSH_SCP_TO, ".", "", 0);
if (result == 0)
result = ScpParseCommandCase("scp -t ..", WS_SUCCESS,
WOLFSSH_SCP_TO, "..", "", 0);
if (result == 0) {
WRMDIR(NULL, "scp_parse_dir");
if (WMKDIR(NULL, "scp_parse_dir", 0700) != 0)
result = -4883;
if (result == 0)
result = ScpParseCommandCase("scp -t scp_parse_dir", WS_SUCCESS,
WOLFSSH_SCP_TO, "scp_parse_dir", "", 0);
if (result == 0)
result = ScpParseCommandCase("scp -t ./scp_parse_dir",
WS_SUCCESS, WOLFSSH_SCP_TO, "./scp_parse_dir", "", 0);
if (result == 0)
result = ScpParseCommandCase("scp -r -t ./scp_parse_dir/",
WS_SUCCESS, WOLFSSH_SCP_TO, "./scp_parse_dir", "", 1);
WRMDIR(NULL, "scp_parse_dir");
}
#endif
/* the path is taken as given, spaces and quotes included */
if (result == 0)
result = ScpParseCommandCase("scp -f /tmp/a b", WS_SUCCESS,
WOLFSSH_SCP_FROM, "/tmp/a b", NULL, 0);
if (result == 0)
result = ScpParseCommandCase("scp -f '/tmp/a b'", WS_SUCCESS,
WOLFSSH_SCP_FROM, "'/tmp/a b'", NULL, 0);
return result;
}
#endif /* !NO_WOLFSSH_SERVER */
/* A warning record carries no reply, so the record after it can arrive in
* the same read. ReceiveScpMessage takes one record per call and keeps the
* rest buffered, and notes the warning so the transfer fails at its end. An
* error record fails at once. The records are placed in the receive buffer
* directly, as a read would leave them. */
static int test_ScpReceiveMessageAfterWarning(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
static const char full[] = "\x01scp: a: not a regular file\n"
"C0644 5 name\n";
static const char part[] = "\x01scp: a: not a regular file\n"
"C0644 5 na";
static const char rest[] = "me\n";
static const char fatal[] = "\x02scp: a: open failed\n";
int result = 0;
int ret;
int i;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -4890;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return -4891;
}
ssh->scpRecvMsg = (char*)WMALLOC(DEFAULT_SCP_MSG_SZ, ctx->heap,
DYNTYPE_STRING);
if (ssh->scpRecvMsg == NULL)
result = -4892;
/* warning and a whole header in one read, then the same with only part
* of the header, the rest arriving later */
for (i = 0; result == 0 && i < 2; i++) {
const char* in = (i == 0) ? full : part;
WMEMCPY(ssh->scpRecvMsg, in, WSTRLEN(in));
ssh->scpRecvMsgSz = (int)WSTRLEN(in);
ssh->scpFileSz = 0;
ssh->scpPeerWarned = 0;
ret = ReceiveScpMessage(ssh);
if (ret != WS_SUCCESS || ssh->scpMsgType != WOLFSSH_SCP_MSG_WARN ||
!ssh->scpPeerWarned) {
result = -4893;
break;
}
if (ssh->scpRecvMsgSz <= 0 || ssh->scpRecvMsg[0] != 'C') {
result = -4894;
break;
}
if (i == 1) {
WMEMCPY(ssh->scpRecvMsg + ssh->scpRecvMsgSz, rest,
WSTRLEN(rest));
ssh->scpRecvMsgSz += (int)WSTRLEN(rest);
}
ret = ReceiveScpMessage(ssh);
if (ret != WS_SUCCESS || ssh->scpMsgType != WOLFSSH_SCP_MSG_FILE ||
ssh->scpFileSz != 5 || ssh->scpFileName == NULL ||
WSTRCMP(ssh->scpFileName, "name") != 0) {
result = -4895;
break;
}
if (ssh->scpRecvMsgSz != 0) {
result = -4896;
break;
}
}
if (result == 0) {
WMEMCPY(ssh->scpRecvMsg, fatal, WSTRLEN(fatal));
ssh->scpRecvMsgSz = (int)WSTRLEN(fatal);
if (ReceiveScpMessage(ssh) != WS_FATAL_ERROR)
result = -4897;
}
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
static int scpSinkPartSeen;
static word32 scpSinkPartSz;
static int scpSinkPartRecv(WOLFSSH* ssh, int state, const char* basePath,
const char* fileName, int fileMode, word64 mTime, word64 aTime,
word32 totalFileSz, byte* buf, word32 bufSz, word32 fileOffset,
void* ctx)
{
(void)ssh; (void)basePath; (void)fileName; (void)fileMode; (void)mTime;
(void)aTime; (void)totalFileSz; (void)buf; (void)fileOffset; (void)ctx;
if (state == WOLFSSH_SCP_FILE_PART) {
scpSinkPartSeen = 1;
scpSinkPartSz = bufSz;
}
return WS_SCP_ABORT;
}
/* A sink run of an empty file on a session whose last SCP run was a source
* must not hand the receive callback the source run's stale buffer. The
* source leaves scpFileBufferSz at the buffer capacity. */
static int test_ScpSinkEmptyFileAfterSource(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
int result = 0;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -490;
wolfSSH_SetScpRecv(ctx, scpSinkPartRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return -491;
}
ssh->scpFileBuffer = (byte*)WMALLOC(DEFAULT_SCP_BUFFER_SZ, ssh->ctx->heap,
DYNTYPE_BUFFER);
if (ssh->scpFileBuffer == NULL)
result = -492;
if (result == 0) {
WMEMSET(ssh->scpFileBuffer, 0xA5, DEFAULT_SCP_BUFFER_SZ);
ssh->scpFileBufferSz = DEFAULT_SCP_BUFFER_SZ;
ssh->scpFileSz = 0;
ssh->scpFileOffset = 0;
ssh->scpState = SCP_RECEIVE_FILE;
scpSinkPartSeen = 0;
scpSinkPartSz = 0;
/* the confirmation send fails with no channel; only the callback
* arguments matter here */
(void)wolfSSH_TestDoScpSink(ssh);
if (!scpSinkPartSeen)
result = -493;
else if (scpSinkPartSz != 0)
result = -494;
}
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#ifndef NO_WOLFSSH_CLIENT
/* The client's exec command carries the remote path as given, the way
* OpenSSH scp sends it, and the built-in server reads back the same path. */
static int test_ScpMakeCmd(void)
{
static const struct {
const char* name;
const char* cmd;
} cases[] = {
{ "/tmp/a.txt", "scp -f /tmp/a.txt" },
{ "/tmp/a b", "scp -f /tmp/a b" },
{ "/tmp/it's;$(x)", "scp -f /tmp/it's;$(x)" },
{ "-x", "scp -f -- -x" },
{ "-a b", "scp -f -- -a b" }
};
static const char* bad[] = { "a\nb", "a\rb", "a\tb", "a\x7f" };
char* cmd = NULL;
int result = 0;
int ret;
word32 i;
for (i = 0; result == 0 && i < sizeof(cases) / sizeof(cases[0]); i++) {
cmd = NULL;
ret = wolfSSH_TestScpMakeCmd(cases[i].name, 'f', &cmd, NULL);
if (ret != WS_SUCCESS || cmd == NULL)
result = -4880;
else if (WSTRCMP(cmd, cases[i].cmd) != 0)
result = -4881;
#if !defined(NO_WOLFSSH_SERVER) && !defined(USE_WINDOWS_API)
if (result == 0)
result = ScpParseCommandCase(cmd, WS_SUCCESS, WOLFSSH_SCP_FROM,
cases[i].name, NULL, 0);
#endif
if (cmd != NULL)
WFREE(cmd, NULL, DYNTYPE_STRING);
}
for (i = 0; result == 0 && i < sizeof(bad) / sizeof(bad[0]); i++) {
cmd = NULL;
ret = wolfSSH_TestScpMakeCmd(bad[i], 't', &cmd, NULL);
if (ret != WS_BAD_ARGUMENT || cmd != NULL)
result = -4882;
}
return result;
}
#endif /* !NO_WOLFSSH_CLIENT */
#endif /* WOLFSSH_TEST_INTERNAL && WOLFSSH_SCP */
static int test_ChannelPutData(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* channel = NULL;
byte data[110];
int result = 0;
int ret;
WMEMSET(data, 0xAB, sizeof(data));
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -400;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return -401;
}
/* Window of 100 bytes, matching the input buffer size. */
channel = ChannelNew(ssh, ID_CHANTYPE_SESSION, 100, 100);
if (channel == NULL) {
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return -402;
}
/* NULL channel */
ret = wolfSSH_TestChannelPutData(NULL, data, 10);
if (ret != WS_BAD_ARGUMENT) {
result = -403;
goto done;
}
/* NULL data */
ret = wolfSSH_TestChannelPutData(channel, NULL, 10);
if (ret != WS_BAD_ARGUMENT) {
result = -404;
goto done;
}
/* dataSz exceeds windowSz: 101 > 100 */
ret = wolfSSH_TestChannelPutData(channel, data, 101);
if (ret != WS_FATAL_ERROR) {
result = -405;
goto done;
}
/* Valid write consuming half the window */
ret = wolfSSH_TestChannelPutData(channel, data, 50);
if (ret != WS_SUCCESS) {
result = -406;
goto done;
}
/* Remaining windowSz is 50; sending 51 must be rejected */
ret = wolfSSH_TestChannelPutData(channel, data, 51);
if (ret != WS_FATAL_ERROR) {
result = -407;
goto done;
}
done:
ChannelDelete(channel, ctx->heap);
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* Counter callback for the highwater tests. Records each invocation, and the
* keying state of ssh when one is set, without triggering
* wolfSSH_TriggerKeyExchange (which needs a live session). */
typedef struct HwTestCtx {
WOLFSSH* ssh;
int count;
int keying;
byte lastSide;
} HwTestCtx;
static int HwTestCb(byte side, void* ctx)
{
HwTestCtx* hc = (HwTestCtx*)ctx;
if (hc != NULL) {
hc->count++;
hc->lastSide = side;
hc->keying = wolfSSH_RekeyPending(hc->ssh);
}
return WS_SUCCESS;
}
/* Exercise the wolfSSH_*MsgHighwater APIs and the per-key packet-count
* threshold path inside HighwaterCheck. Covers:
* - NULL safety on getters/setters
* - CTX default value matches WOLFSSH_DEFAULT_MSG_HIGHWATER_MARK
* - CTX/SSH setter round-trip and CTX -> SSH inheritance on wolfSSH_new
* - SSH setter does not bleed back into the CTX
* - Threshold crossing fires the highwater callback exactly once per epoch
* (msgHighwaterFlag gates re-firing under the same keys)
* - Receive side fires independently of the transmit side
* - msgHighwaterMark == 0 disables the per-key packet check */
static int test_MsgHighwater(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
HwTestCtx hc;
int result = 0;
if (wolfSSH_GetMsgHighwater(NULL) != 0)
return -800;
wolfSSH_CTX_SetMsgHighwater(NULL, 1234);
wolfSSH_SetMsgHighwater(NULL, 1234);
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -801;
if (ctx->msgHighwaterMark != WOLFSSH_DEFAULT_MSG_HIGHWATER_MARK) {
result = -802;
goto done;
}
wolfSSH_CTX_SetMsgHighwater(ctx, 4096);
if (ctx->msgHighwaterMark != 4096) {
result = -803;
goto done;
}
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
result = -804;
goto done;
}
if (wolfSSH_GetMsgHighwater(ssh) != 4096) {
result = -805;
goto done;
}
wolfSSH_SetMsgHighwater(ssh, 16);
if (wolfSSH_GetMsgHighwater(ssh) != 16) {
result = -806;
goto done;
}
if (ctx->msgHighwaterMark != 4096) {
result = -807;
goto done;
}
/* Install a counter callback. ssh->highwaterMark stays at the inherited
* default (~1 GiB) and txCount/rxCount are not touched, so the byte-count
* branch cannot fire and only the packet-count branch is under test. */
WMEMSET(&hc, 0, sizeof(hc));
wolfSSH_SetHighwaterCb(ctx, ctx->highwaterMark, HwTestCb);
wolfSSH_SetHighwaterCtx(ssh, &hc);
wolfSSH_SetMsgHighwater(ssh, 8);
ssh->txMsgCount = 7;
if (wolfSSH_TestHighwaterCheck(ssh, WOLFSSH_HWSIDE_TRANSMIT) != WS_SUCCESS
|| hc.count != 0) {
result = -808;
goto done;
}
ssh->txMsgCount = 8;
if (wolfSSH_TestHighwaterCheck(ssh, WOLFSSH_HWSIDE_TRANSMIT) != WS_SUCCESS
|| hc.count != 1
|| hc.lastSide != WOLFSSH_HWSIDE_TRANSMIT) {
result = -809;
goto done;
}
/* Flag-gated: further packets in the same epoch must not re-fire. */
ssh->txMsgCount = 100;
if (wolfSSH_TestHighwaterCheck(ssh, WOLFSSH_HWSIDE_TRANSMIT) != WS_SUCCESS
|| hc.count != 1) {
result = -810;
goto done;
}
/* Simulate a fresh key epoch (msgHighwaterFlag and rx/txMsgCount are
* reset by DoNewKeys/SendNewKeys) and verify the receive side fires. */
ssh->msgHighwaterFlag = 0;
ssh->rxMsgCount = 8;
if (wolfSSH_TestHighwaterCheck(ssh, WOLFSSH_HWSIDE_RECEIVE) != WS_SUCCESS
|| hc.count != 2
|| hc.lastSide != WOLFSSH_HWSIDE_RECEIVE) {
result = -811;
goto done;
}
/* mark == 0 disables the per-key packet check entirely. */
wolfSSH_SetMsgHighwater(ssh, 0);
ssh->msgHighwaterFlag = 0;
ssh->txMsgCount = 0xFFFFFFFFu;
ssh->rxMsgCount = 0xFFFFFFFFu;
if (wolfSSH_TestHighwaterCheck(ssh, WOLFSSH_HWSIDE_TRANSMIT) != WS_SUCCESS
|| hc.count != 2) {
result = -812;
goto done;
}
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* Sibling of test_MsgHighwater for the byte-count branch of HighwaterCheck
* (RFC 4253 Section 9 keystream/IV bound). Covers:
* - Threshold boundary: mark-1 does not fire, mark fires (>= not >)
* - Callback fires exactly once per epoch (highwaterFlag gates re-firing)
* - Receive side fires independently after an epoch reset
* - highwaterMark == 0 disables the byte check */
static int test_ByteHighwater(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
HwTestCtx hc;
int result = 0;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -820;
WMEMSET(&hc, 0, sizeof(hc));
wolfSSH_SetHighwaterCb(ctx, 1024, HwTestCb);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
result = -821;
goto done;
}
wolfSSH_SetHighwaterCtx(ssh, &hc);
/* Disable the packet-count branch so only the byte branch is under
* test. */
wolfSSH_SetMsgHighwater(ssh, 0);
if (wolfSSH_GetHighwater(ssh) != 1024) {
result = -822;
goto done;
}
/* One byte under the mark on both sides: must not fire. */
ssh->txCount = 1023;
ssh->rxCount = 1023;
if (wolfSSH_TestHighwaterCheck(ssh, WOLFSSH_HWSIDE_TRANSMIT) != WS_SUCCESS
|| hc.count != 0) {
result = -823;
goto done;
}
/* At the mark: fires, with the transmit side reported. */
ssh->txCount = 1024;
if (wolfSSH_TestHighwaterCheck(ssh, WOLFSSH_HWSIDE_TRANSMIT) != WS_SUCCESS
|| hc.count != 1
|| hc.lastSide != WOLFSSH_HWSIDE_TRANSMIT) {
result = -824;
goto done;
}
/* Flag-gated: more bytes in the same epoch must not re-fire. */
ssh->txCount = 4096;
if (wolfSSH_TestHighwaterCheck(ssh, WOLFSSH_HWSIDE_TRANSMIT) != WS_SUCCESS
|| hc.count != 1) {
result = -825;
goto done;
}
/* Fresh key epoch (highwaterFlag and tx/rxCount are reset by
* DoNewKeys/SendNewKeys): the receive side fires on its own. */
ssh->highwaterFlag = 0;
ssh->txCount = 0;
ssh->rxCount = 1024;
if (wolfSSH_TestHighwaterCheck(ssh, WOLFSSH_HWSIDE_RECEIVE) != WS_SUCCESS
|| hc.count != 2
|| hc.lastSide != WOLFSSH_HWSIDE_RECEIVE) {
result = -826;
goto done;
}
/* mark == 0 disables the byte check entirely. */
if (wolfSSH_SetHighwater(ssh, 0) != WS_SUCCESS) {
result = -827;
goto done;
}
ssh->highwaterFlag = 0;
ssh->txCount = 0xFFFFFFFFu;
ssh->rxCount = 0xFFFFFFFFu;
if (wolfSSH_TestHighwaterCheck(ssh, WOLFSSH_HWSIDE_TRANSMIT) != WS_SUCCESS
|| hc.count != 2) {
result = -828;
goto done;
}
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
static int test_DoChannelSuccess(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
word32 idx;
/* Short buffer: only 3 bytes, GetUint32 needs 4. */
static const byte payShort[] = { 0x00, 0x00, 0x00 };
/* Unknown channel id = 99 (0x63). */
static const byte payUnknown[] = { 0x00, 0x00, 0x00, 0x63 };
/* Happy path: channel id = 0. */
static const byte payOk[] = { 0x00, 0x00, 0x00, 0x00 };
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -500;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -501; goto done; }
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION,
DEFAULT_WINDOW_SZ, DEFAULT_MAX_PACKET_SZ);
if (ch == NULL) { result = -502; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -503;
goto done;
}
/* Short buffer -> WS_BUFFER_E */
idx = 0;
ret = wolfSSH_TestDoChannelSuccess(ssh, (byte*)payShort,
(word32)sizeof(payShort), &idx);
if (ret != WS_BUFFER_E) { result = -510; goto done; }
if (idx != 0) { result = -514; goto done; }
/* Unknown channel -> WS_INVALID_CHANID */
idx = 0;
ret = wolfSSH_TestDoChannelSuccess(ssh, (byte*)payUnknown,
(word32)sizeof(payUnknown), &idx);
if (ret != WS_INVALID_CHANID) { result = -511; goto done; }
if (idx != 4) { result = -515; goto done; }
/* Happy path -> WS_SUCCESS, serverState == SERVER_DONE */
idx = 0;
ret = wolfSSH_TestDoChannelSuccess(ssh, (byte*)payOk,
(word32)sizeof(payOk), &idx);
if (ret != WS_SUCCESS) { result = -512; goto done; }
if (ssh->serverState != SERVER_DONE) { result = -513; goto done; }
if (idx != 4) { result = -516; goto done; }
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
static int test_DoChannelFailure(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
word32 idx;
static const byte payShort[] = { 0x00, 0x00, 0x00 };
static const byte payUnknown[] = { 0x00, 0x00, 0x00, 0x63 };
static const byte payOk[] = { 0x00, 0x00, 0x00, 0x00 };
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -520;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -521; goto done; }
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION,
DEFAULT_WINDOW_SZ, DEFAULT_MAX_PACKET_SZ);
if (ch == NULL) { result = -522; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -523;
goto done;
}
/* Short buffer -> WS_BUFFER_E */
idx = 0;
ret = wolfSSH_TestDoChannelFailure(ssh, (byte*)payShort,
(word32)sizeof(payShort), &idx);
if (ret != WS_BUFFER_E) { result = -530; goto done; }
if (idx != 0) { result = -533; goto done; }
/* Unknown channel -> WS_INVALID_CHANID */
idx = 0;
ret = wolfSSH_TestDoChannelFailure(ssh, (byte*)payUnknown,
(word32)sizeof(payUnknown), &idx);
if (ret != WS_INVALID_CHANID) { result = -531; goto done; }
if (idx != 4) { result = -534; goto done; }
/* Happy path -> WS_CHANOPEN_FAILED */
idx = 0;
ret = wolfSSH_TestDoChannelFailure(ssh, (byte*)payOk,
(word32)sizeof(payOk), &idx);
if (ret != WS_CHANOPEN_FAILED) { result = -532; goto done; }
if (idx != 4) { result = -535; goto done; }
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
static int test_DoChannelData_overflow(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
word32 idx;
/* Channel id=0, dataSz=65 (> maxPacketSz of 64): overflow case.
* Buffer holds header only; dataSz > maxPacketSz triggers the guard
* before ChannelPutData is ever called. */
static const byte payOver[] = {
0x00, 0x00, 0x00, 0x00, /* channelId = 0 */
0x00, 0x00, 0x00, 0x41, /* dataSz = 65 */
/* 65 payload bytes follow (all zeroes) */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00
};
/* Channel id=0, dataSz=32, but only 8 payload bytes: GetSize() must
* reject the size before anything reads past the buffer. Pins the
* invariant DoChannelData() relies on in place of its own check. */
static const byte payShort[] = {
0x00, 0x00, 0x00, 0x00, /* channelId = 0 */
0x00, 0x00, 0x00, 0x20, /* dataSz = 32 */
/* only 8 payload bytes follow */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
/* Channel id=0, dataSz=0xFFFFFFFF: begin + dataSz wraps and lands back
* inside the buffer. GetSize() measures against the bytes left rather
* than adding, so the wrap the deleted check was named for cannot get
* past it either. */
static const byte payWrap[] = {
0x00, 0x00, 0x00, 0x00, /* channelId = 0 */
0xFF, 0xFF, 0xFF, 0xFF, /* dataSz = 0xFFFFFFFF */
/* only 8 payload bytes follow */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
/* Channel id=0, dataSz=32 (< maxPacketSz of 64): within-limit case. */
static const byte payOk[] = {
0x00, 0x00, 0x00, 0x00, /* channelId = 0 */
0x00, 0x00, 0x00, 0x20, /* dataSz = 32 */
/* 32 payload bytes */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -540;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -541; goto done; }
/* windowSz=128, maxPacketSz=64 */
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 128, 64);
if (ch == NULL) { result = -542; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -543;
goto done;
}
/* dataSz=65 > maxPacketSz=64 -> WS_RECV_OVERFLOW_E */
idx = 0;
ret = wolfSSH_TestDoChannelData(ssh, (byte*)payOver,
(word32)sizeof(payOver), &idx);
if (ret != WS_RECV_OVERFLOW_E) { result = -550; goto done; }
/* dataSz=32 <= maxPacketSz=64 -> WS_CHAN_RXD */
idx = 0;
ret = wolfSSH_TestDoChannelData(ssh, (byte*)payOk,
(word32)sizeof(payOk), &idx);
if (ret != WS_CHAN_RXD) { result = -551; goto done; }
/* dataSz=32 with 8 bytes left -> WS_BUFFER_E out of GetSize() */
idx = 0;
ret = wolfSSH_TestDoChannelData(ssh, (byte*)payShort,
(word32)sizeof(payShort), &idx);
if (ret != WS_BUFFER_E) { result = -552; goto done; }
if (idx != 0) { result = -553; goto done; }
/* dataSz=0xFFFFFFFF -> WS_BUFFER_E, the wrapping case */
idx = 0;
ret = wolfSSH_TestDoChannelData(ssh, (byte*)payWrap,
(word32)sizeof(payWrap), &idx);
if (ret != WS_BUFFER_E) { result = -554; goto done; }
if (idx != 0) { result = -555; goto done; }
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
static int DiscardIoSend(WOLFSSH* ssh, void* buf, word32 sz, void* ctx)
{
(void)ssh; (void)buf; (void)ctx;
return (int)sz;
}
static int s_ioSendCalls = 0;
/* Discards like DiscardIoSend, but counts the calls so a test can assert that
* nothing at all was handed to the transport. */
static WS_MAYBE_UNUSED int CountingIoSend(WOLFSSH* ssh, void* buf, word32 sz,
void* ctx)
{
(void)ssh; (void)buf; (void)ctx;
s_ioSendCalls++;
return (int)sz;
}
/* Reports a short (would-block) write, so an adjust bundled into the output
* buffer reaches the transport but does not fully flush: wolfSSH_SendPacket()
* maps WS_CBIO_ERR_WANT_WRITE to WS_WANT_WRITE. */
static WS_MAYBE_UNUSED int WantWriteIoSend(WOLFSSH* ssh, void* buf, word32 sz,
void* ctx)
{
(void)ssh; (void)buf; (void)sz; (void)ctx;
return WS_CBIO_ERR_WANT_WRITE;
}
/* A socket the peer reset under the send. */
static WS_MAYBE_UNUSED int ConnResetIoSend(WOLFSSH* ssh, void* buf, word32 sz,
void* ctx)
{
(void)ssh; (void)buf; (void)sz; (void)ctx;
return WS_CBIO_ERR_CONN_RST;
}
/* A send callback that claims more bytes than it was handed. */
static WS_MAYBE_UNUSED int OobIoSend(WOLFSSH* ssh, void* buf, word32 sz,
void* ctx)
{
(void)ssh; (void)buf; (void)ctx;
return (int)sz + 1;
}
/* Reports an error whenever the byte or message highwater mark fires. */
static WS_MAYBE_UNUSED int FailHighwater(byte side, void* ctx)
{
(void)side; (void)ctx;
return WS_FATAL_ERROR;
}
static int test_DoChannelExtendedData_overflow(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
word32 idx;
/* channelId=0, dataTypeCode=1 (stderr), dataSz=65 (> maxPacketSz=64) */
static const byte payOver[] = {
0x00, 0x00, 0x00, 0x00, /* channelId = 0 */
0x00, 0x00, 0x00, 0x01, /* dataTypeCode = 1 (stderr)*/
0x00, 0x00, 0x00, 0x41, /* dataSz = 65 */
/* 65 payload bytes */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00
};
/* channelId=0, dataTypeCode=1 (stderr), dataSz=32 (< maxPacketSz=64) */
static const byte payOk[] = {
0x00, 0x00, 0x00, 0x00, /* channelId = 0 */
0x00, 0x00, 0x00, 0x01, /* dataTypeCode = 1 (stderr)*/
0x00, 0x00, 0x00, 0x20, /* dataSz = 32 */
/* 32 payload bytes */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -580;
wolfSSH_SetIOSend(ctx, DiscardIoSend);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -581; goto done; }
/* Allow MSGID_CHANNEL_WINDOW_ADJUST on this bare session. */
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
/* windowSz=128, maxPacketSz=64 */
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 128, 64);
if (ch == NULL) { result = -582; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -583;
goto done;
}
/* dataSz=65 > maxPacketSz=64 -> WS_RECV_OVERFLOW_E */
idx = 0;
ret = wolfSSH_TestDoChannelExtendedData(ssh, (byte*)payOver,
(word32)sizeof(payOver), &idx);
if (ret != WS_RECV_OVERFLOW_E) { result = -590; goto done; }
/* dataSz=32 <= maxPacketSz=64 -> WS_EXTDATA */
idx = 0;
ret = wolfSSH_TestDoChannelExtendedData(ssh, (byte*)payOk,
(word32)sizeof(payOk), &idx);
if (ret != WS_EXTDATA) { result = -591; goto done; }
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* GetString() reserves a byte for the null. A zero-sized destination has
* no room for it and must be rejected, not wrap the subtraction. */
static int test_GetString_zeroDestSz(void)
{
/* SSH string: length 5, then "hello" */
static const byte wire[] = { 0x00, 0x00, 0x00, 0x05, 'h','e','l','l','o' };
/* SSH string: length 0 */
static const byte wireEmpty[] = { 0x00, 0x00, 0x00, 0x00 };
char dest[16];
word32 destSz;
word32 idx;
int result = 0;
int ret;
int i;
/* NULL args. The zero-size check below dereferences sSz, so it must
* stay after this one. */
destSz = (word32)sizeof(dest);
idx = 0;
ret = GetString(NULL, &destSz, wire, (word32)sizeof(wire), &idx);
if (ret != WS_BAD_ARGUMENT) { result = -1048; goto done; }
idx = 0;
ret = GetString(dest, NULL, wire, (word32)sizeof(wire), &idx);
if (ret != WS_BAD_ARGUMENT) { result = -1049; goto done; }
/* zero destination size, non-empty string: reject, touch nothing */
WMEMSET(dest, 0xAA, sizeof(dest));
destSz = 0;
idx = 0;
ret = GetString(dest, &destSz, wire, (word32)sizeof(wire), &idx);
if (ret != WS_BUFFER_E) { result = -1050; goto done; }
if (destSz != 0) { result = -1051; goto done; }
if (idx != 0) { result = -1052; goto done; }
for (i = 0; i < (int)sizeof(dest); i++) {
if ((byte)dest[i] != 0xAA) { result = -1053; goto done; }
}
/* zero destination size, empty string: same rejection */
destSz = 0;
idx = 0;
ret = GetString(dest, &destSz, wireEmpty, (word32)sizeof(wireEmpty), &idx);
if (ret != WS_BUFFER_E) { result = -1054; goto done; }
if (destSz != 0) { result = -1055; goto done; }
for (i = 0; i < (int)sizeof(dest); i++) {
if ((byte)dest[i] != 0xAA) { result = -1056; goto done; }
}
/* room for only the null: empty result, no copy */
WMEMSET(dest, 0xAA, sizeof(dest));
destSz = 1;
idx = 0;
ret = GetString(dest, &destSz, wire, (word32)sizeof(wire), &idx);
if (ret != WS_SUCCESS) { result = -1057; goto done; }
if (destSz != 0 || dest[0] != 0) { result = -1058; goto done; }
/* truncating copy still reserves the null */
WMEMSET(dest, 0xAA, sizeof(dest));
destSz = 3;
idx = 0;
ret = GetString(dest, &destSz, wire, (word32)sizeof(wire), &idx);
if (ret != WS_SUCCESS) { result = -1059; goto done; }
if (destSz != 2 || WSTRCMP(dest, "he") != 0) { result = -1060; goto done; }
/* whole string fits */
WMEMSET(dest, 0xAA, sizeof(dest));
destSz = (word32)sizeof(dest);
idx = 0;
ret = GetString(dest, &destSz, wire, (word32)sizeof(wire), &idx);
if (ret != WS_SUCCESS) { result = -1061; goto done; }
if (destSz != 5 || WSTRCMP(dest, "hello") != 0) {
result = -1062;
goto done;
}
if (idx != (word32)sizeof(wire)) { result = -1063; goto done; }
done:
return result;
}
/* GetBoolean() stores any nonzero wire byte as 1 (RFC 4251 5). */
static int test_GetBoolean(void)
{
static const byte wire[] = { 0x00, 0x01, 0x02, 0x80, 0xFF };
static const byte expect[] = { 0, 1, 1, 1, 1 };
word32 idx = 0;
word32 i;
byte v;
for (i = 0; i < (word32)sizeof(wire); i++) {
v = 0xAA;
if (GetBoolean(&v, wire, (word32)sizeof(wire), &idx) != WS_SUCCESS)
return -1;
if (v != expect[i])
return -2;
if (idx != i + 1)
return -3;
}
/* past the end */
v = 0xAA;
if (GetBoolean(&v, wire, (word32)sizeof(wire), &idx) != WS_BUFFER_E)
return -4;
if (v != 0xAA || idx != (word32)sizeof(wire))
return -5;
return 0;
}
/* DoChannelWindowAdjust adds the peer's advertised bytes to peerWindowSz.
* A crafted bytesToAdd that would wrap the word32 must be rejected with
* WS_OVERFLOW_E and leave the window untouched; a value that fits must be
* applied. No other test exercises this handler. */
static int test_DoChannelWindowAdjust_overflow(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
word32 idx;
/* channelId=0, bytesToAdd=0xFFFFFFFF (UINT32_MAX): wraps peerWindowSz. */
static const byte payOver[] = {
0x00, 0x00, 0x00, 0x00, /* channelId = 0 */
0xFF, 0xFF, 0xFF, 0xFF /* bytesToAdd = UINT32_MAX */
};
/* channelId=0, bytesToAdd=0x40 (64): fits, advances the window. */
static const byte payOk[] = {
0x00, 0x00, 0x00, 0x00, /* channelId = 0 */
0x00, 0x00, 0x00, 0x40 /* bytesToAdd = 64 */
};
/* channelId=0, bytesToAdd=UINT32_MAX-1024 (0xFFFFFBFF): the largest value
* a 1024-byte window accepts. Fills peerWindowSz to exactly UINT32_MAX and
* exercises the exact boundary of the > guard (a >= off-by-one rejects). */
static const byte payEdgeOk[] = {
0x00, 0x00, 0x00, 0x00, /* channelId = 0 */
0xFF, 0xFF, 0xFB, 0xFF /* bytesToAdd = UINT32_MAX - 1024 */
};
/* channelId=0, bytesToAdd=UINT32_MAX-1024+1 (0xFFFFFC00): one past the
* boundary, must overflow a 1024-byte window. */
static const byte payEdgeOver[] = {
0x00, 0x00, 0x00, 0x00, /* channelId = 0 */
0xFF, 0xFF, 0xFC, 0x00 /* bytesToAdd = UINT32_MAX - 1024 + 1 */
};
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -600;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -601; goto done; }
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION,
DEFAULT_WINDOW_SZ, DEFAULT_MAX_PACKET_SZ);
if (ch == NULL) { result = -602; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -603;
goto done;
}
/* Non-zero peer window so a UINT32_MAX adjustment would wrap it. */
ch->peerWindowSz = 1024;
/* bytesToAdd = UINT32_MAX -> WS_OVERFLOW_E, window left unchanged. */
idx = 0;
ret = wolfSSH_TestDoChannelWindowAdjust(ssh, (byte*)payOver,
(word32)sizeof(payOver), &idx);
if (ret != WS_OVERFLOW_E) { result = -610; goto done; }
if (ch->peerWindowSz != 1024) { result = -611; goto done; }
if (idx != 8) { result = -612; goto done; }
/* bytesToAdd = 64 fits -> WS_SUCCESS, window advances by 64. */
idx = 0;
ret = wolfSSH_TestDoChannelWindowAdjust(ssh, (byte*)payOk,
(word32)sizeof(payOk), &idx);
if (ret != WS_SUCCESS) { result = -613; goto done; }
if (ch->peerWindowSz != 1024 + 64) { result = -614; goto done; }
if (idx != 8) { result = -615; goto done; }
/* Boundary +1: bytesToAdd = UINT32_MAX - 1024 + 1 overflows a 1024-byte
* window -> WS_OVERFLOW_E, window left unchanged. */
ch->peerWindowSz = 1024;
idx = 0;
ret = wolfSSH_TestDoChannelWindowAdjust(ssh, (byte*)payEdgeOver,
(word32)sizeof(payEdgeOver), &idx);
if (ret != WS_OVERFLOW_E) { result = -616; goto done; }
if (ch->peerWindowSz != 1024) { result = -617; goto done; }
if (idx != 8) { result = -618; goto done; }
/* Boundary: bytesToAdd = UINT32_MAX - 1024 is the largest value that fits
* -> WS_SUCCESS, window filled to exactly UINT32_MAX. This is the case a
* >= off-by-one in the guard would wrongly reject. */
ch->peerWindowSz = 1024;
idx = 0;
ret = wolfSSH_TestDoChannelWindowAdjust(ssh, (byte*)payEdgeOk,
(word32)sizeof(payEdgeOk), &idx);
if (ret != WS_SUCCESS) { result = -619; goto done; }
if (ch->peerWindowSz != 0xFFFFFFFF) { result = -620; goto done; }
if (idx != 8) { result = -621; goto done; }
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* The tests below drive a server-side session that sends a window adjust.
* With NO_WOLFSSH_SERVER the message filter has no server branch, so every
* message on such a session is refused and the tests cannot run. */
/* Shared test doubles. Endpoint-agnostic on purpose: a receive mock and a
* handful of plaintext packet builders belong to both halves of this file, so
* they sit ahead of every NO_WOLFSSH_SERVER / NO_WOLFSSH_CLIENT region rather
* than inside one of them. */
/* A crafted transport packet staged for the receive path, and the running
* offset PacketIoRecv has delivered. */
static const byte* s_recvPkt = NULL;
static word32 s_recvPktSz = 0;
static word32 s_recvPktOff = 0;
/* IORecv mock that hands out the staged packet, then reports WS_WANT_READ once
* it is drained so a further DoReceive() does not block on a live socket. */
static WS_MAYBE_UNUSED int PacketIoRecv(WOLFSSH* ssh, void* buf, word32 sz, void* ctx)
{
word32 avail, n;
WOLFSSH_UNUSED(ssh);
WOLFSSH_UNUSED(ctx);
avail = s_recvPktSz - s_recvPktOff;
if (avail == 0)
return WS_CBIO_ERR_WANT_READ;
n = (sz < avail) ? sz : avail;
WMEMCPY(buf, s_recvPkt + s_recvPktOff, n);
s_recvPktOff += n;
return (int)n;
}
/* Write budget for the IOSend mocks: that many writes are refused with a
* would-block before the mock acts. */
static int s_sendRefusals = 0;
/* Refuses the first s_sendRefusals writes with a would-block, taking no bytes,
* then resets the socket. */
static WS_MAYBE_UNUSED int RefuseThenResetIoSend(WOLFSSH* ssh, void* buf,
word32 sz, void* ctx)
{
(void)ssh; (void)buf; (void)sz; (void)ctx;
if (s_sendRefusals > 0) {
s_sendRefusals--;
return WS_CBIO_ERR_WANT_WRITE;
}
return WS_CBIO_ERR_CONN_RST;
}
/* Builds a plaintext CHANNEL_EXTENDED_DATA (stderr) SSH packet addressed to
* channelId, carrying 10 bytes of payload set to fill, into pkt (needs 32
* bytes) and returns its size. A bare session negotiates no cipher
* (peerEncryptId ID_NONE, so Decrypt() is a passthrough) and no MAC
* (peerMacSz 0), so the packet goes on the wire in the clear. The total size is
* a multiple of the 8-byte MIN_BLOCK_SZ and the padding meets MIN_PAD_LENGTH.
*
* Layout: [len=28][pad=4][msgid=95][chan][type=1][dataSz=10][data*10][pad*4]. */
static WS_MAYBE_UNUSED word32 BuildExtDataStderrPacket(byte* pkt, word32 channelId, byte fill)
{
word32 i = 0;
/* packet_length = padLen(1) + msgid(1) + chan(4) + type(4) + dataSz(4)
* + data(10) + padding(4) = 28. */
pkt[i++] = 0x00; pkt[i++] = 0x00; pkt[i++] = 0x00; pkt[i++] = 0x1C;
pkt[i++] = 0x04; /* padding length */
pkt[i++] = MSGID_CHANNEL_EXTENDED_DATA;
pkt[i++] = (byte)((channelId >> 24) & 0xFF);
pkt[i++] = (byte)((channelId >> 16) & 0xFF);
pkt[i++] = (byte)((channelId >> 8) & 0xFF);
pkt[i++] = (byte)( channelId & 0xFF);
pkt[i++] = 0x00; pkt[i++] = 0x00; pkt[i++] = 0x00;
pkt[i++] = (byte)CHANNEL_EXTENDED_DATA_STDERR; /* data type = stderr (1) */
pkt[i++] = 0x00; pkt[i++] = 0x00; pkt[i++] = 0x00; pkt[i++] = 0x0A; /* 10 */
WMEMSET(pkt + i, fill, 10); i += 10;
WMEMSET(pkt + i, 0x00, 4); i += 4; /* padding bytes */
return i; /* 32 */
}
/* Builds a plaintext CHANNEL_DATA packet for channelId carrying 10 bytes of
* fill into pkt (needs 32 bytes), returning its size. Same plaintext-session
* reasoning as BuildExtDataStderrPacket().
*
* Layout: [len=28][pad=8][msgid=94][chan][dataSz=10][data*10][pad*8]. */
static WS_MAYBE_UNUSED word32 BuildChannelDataPacket(byte* pkt, word32 channelId, byte fill)
{
word32 i = 0;
/* packet_length = padLen(1) + msgid(1) + chan(4) + dataSz(4) + data(10)
* + padding(8) = 28. */
pkt[i++] = 0x00; pkt[i++] = 0x00; pkt[i++] = 0x00; pkt[i++] = 0x1C;
pkt[i++] = 0x08; /* padding length */
pkt[i++] = MSGID_CHANNEL_DATA;
pkt[i++] = (byte)((channelId >> 24) & 0xFF);
pkt[i++] = (byte)((channelId >> 16) & 0xFF);
pkt[i++] = (byte)((channelId >> 8) & 0xFF);
pkt[i++] = (byte)( channelId & 0xFF);
pkt[i++] = 0x00; pkt[i++] = 0x00; pkt[i++] = 0x00; pkt[i++] = 0x0A; /* 10 */
WMEMSET(pkt + i, fill, 10); i += 10;
WMEMSET(pkt + i, 0x00, 8); i += 8; /* padding bytes */
return i; /* 32 */
}
/* A peer window adjust: DoReceive() consumes it and reports WS_SUCCESS, with
* no channel event to carry. */
static WS_MAYBE_UNUSED word32 BuildWindowAdjustPacket(byte* pkt,
word32 channelId, word32 bytesToAdd)
{
word32 i = 0;
/* packet_length = padLen(1) + msgid(1) + chan(4) + add(4)
* + padding(10) = 20, so the 24 on the wire is a
* multiple of 8. */
pkt[i++] = 0x00; pkt[i++] = 0x00; pkt[i++] = 0x00; pkt[i++] = 0x14;
pkt[i++] = 0x0A; /* padding length */
pkt[i++] = MSGID_CHANNEL_WINDOW_ADJUST;
pkt[i++] = (byte)((channelId >> 24) & 0xFF);
pkt[i++] = (byte)((channelId >> 16) & 0xFF);
pkt[i++] = (byte)((channelId >> 8) & 0xFF);
pkt[i++] = (byte)( channelId & 0xFF);
pkt[i++] = (byte)((bytesToAdd >> 24) & 0xFF);
pkt[i++] = (byte)((bytesToAdd >> 16) & 0xFF);
pkt[i++] = (byte)((bytesToAdd >> 8) & 0xFF);
pkt[i++] = (byte)( bytesToAdd & 0xFF);
WMEMSET(pkt + i, 0x00, 10); i += 10; /* padding bytes */
return i; /* 24 */
}
/* Builds a plaintext CHANNEL_EOF packet for channelId into pkt (needs 16
* bytes), returning its size.
*
* Layout: [len=12][pad=6][msgid=96][chan][pad*6]. */
static WS_MAYBE_UNUSED word32 BuildChannelEofPacket(byte* pkt, word32 channelId)
{
word32 i = 0;
/* packet_length = padLen(1) + msgid(1) + chan(4) + padding(6) = 12. */
pkt[i++] = 0x00; pkt[i++] = 0x00; pkt[i++] = 0x00; pkt[i++] = 0x0C;
pkt[i++] = 0x06; /* padding length */
pkt[i++] = MSGID_CHANNEL_EOF;
pkt[i++] = (byte)((channelId >> 24) & 0xFF);
pkt[i++] = (byte)((channelId >> 16) & 0xFF);
pkt[i++] = (byte)((channelId >> 8) & 0xFF);
pkt[i++] = (byte)( channelId & 0xFF);
WMEMSET(pkt + i, 0x00, 6); i += 6; /* padding bytes */
return i; /* 16 */
}
/* Builds a plaintext CHANNEL_CLOSE packet for channelId into pkt (needs 16
* bytes), returning its size.
*
* Layout: [len=12][pad=6][msgid=97][chan][pad*6]. */
static WS_MAYBE_UNUSED word32 BuildChannelClosePacket(byte* pkt, word32 channelId)
{
word32 i = 0;
/* packet_length = padLen(1) + msgid(1) + chan(4) + padding(6) = 12. */
pkt[i++] = 0x00; pkt[i++] = 0x00; pkt[i++] = 0x00; pkt[i++] = 0x0C;
pkt[i++] = 0x06; /* padding length */
pkt[i++] = MSGID_CHANNEL_CLOSE;
pkt[i++] = (byte)((channelId >> 24) & 0xFF);
pkt[i++] = (byte)((channelId >> 16) & 0xFF);
pkt[i++] = (byte)((channelId >> 8) & 0xFF);
pkt[i++] = (byte)( channelId & 0xFF);
WMEMSET(pkt + i, 0x00, 6); i += 6; /* padding bytes */
return i; /* 16 */
}
/* Builds a plaintext CHANNEL_OPEN_FAILURE for channelId into pkt (needs 32
* bytes), returning its size. Empty description and language strings.
*
* Layout: [len=28][pad=10][msgid=92][chan][reason][0][0][pad*10]. */
static WS_MAYBE_UNUSED word32 BuildChannelOpenFailPacket(byte* pkt, word32 channelId,
word32 reason)
{
word32 i = 0;
/* packet_length = padLen(1) + msgid(1) + chan(4) + reason(4)
* + description(4) + language(4) + padding(10) = 28. */
pkt[i++] = 0x00; pkt[i++] = 0x00; pkt[i++] = 0x00; pkt[i++] = 0x1C;
pkt[i++] = 0x0A; /* padding length */
pkt[i++] = MSGID_CHANNEL_OPEN_FAIL;
pkt[i++] = (byte)((channelId >> 24) & 0xFF);
pkt[i++] = (byte)((channelId >> 16) & 0xFF);
pkt[i++] = (byte)((channelId >> 8) & 0xFF);
pkt[i++] = (byte)( channelId & 0xFF);
pkt[i++] = (byte)((reason >> 24) & 0xFF);
pkt[i++] = (byte)((reason >> 16) & 0xFF);
pkt[i++] = (byte)((reason >> 8) & 0xFF);
pkt[i++] = (byte)( reason & 0xFF);
WMEMSET(pkt + i, 0x00, 4); i += 4; /* description, empty */
WMEMSET(pkt + i, 0x00, 4); i += 4; /* language, empty */
WMEMSET(pkt + i, 0x00, 10); i += 10; /* padding bytes */
return i; /* 32 */
}
/* Fails every send, discarding whatever was bundled (WS_CBIO_ERR_GENERAL makes
* wolfSSH_SendPacket() shrink the output buffer), so an adjust sent through it
* never reaches the peer. */
static WS_MAYBE_UNUSED int FailIoSend(WOLFSSH* ssh, void* buf, word32 sz, void* ctx)
{
(void)ssh; (void)buf; (void)sz; (void)ctx;
return WS_CBIO_ERR_GENERAL;
}
/* Walks a run of plaintext SSH packets and reports whether any of them carries
* msgId. A bare session negotiates no cipher, so queued and sent packets are
* both in the clear. */
static WS_MAYBE_UNUSED int PlainPacketsHaveMsg(const byte* buf, word32 begin, word32 end,
byte msgId)
{
word32 i;
for (i = begin; i + LENGTH_SZ + PAD_LENGTH_SZ + MSG_ID_SZ <= end; ) {
word32 packetSz;
packetSz = ((word32)buf[i] << 24)
| ((word32)buf[i + 1] << 16)
| ((word32)buf[i + 2] << 8)
| (word32)buf[i + 3];
if (packetSz == 0 || i + LENGTH_SZ + packetSz > end)
break;
if (buf[i + LENGTH_SZ + 1] == msgId)
return 1;
i += LENGTH_SZ + packetSz;
}
return 0;
}
#ifndef NO_WOLFSSH_SERVER
/* An unknown extended data type must be ignored (consumed and discarded) per
* RFC 4254, not rejected: the call returns WS_SUCCESS, nothing is buffered for
* the application, and the window is left intact (replenished on receipt). */
static int test_DoChannelExtendedData_unknown_type(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
word32 idx;
byte out[32];
/* channelId=0, unknown type=2, dataSz=5, payload all 0x33 */
static const byte unknownBlob[] = {
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x02,
0x00, 0x00, 0x00, 0x05,
0x33, 0x33, 0x33, 0x33, 0x33
};
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -680;
wolfSSH_SetIOSend(ctx, DiscardIoSend);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -681; goto done; }
/* Allow MSGID_CHANNEL_WINDOW_ADJUST on this bare session. */
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
/* windowSz=128, maxPacketSz=64 */
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 128, 64);
if (ch == NULL) { result = -682; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -683;
goto done;
}
/* Unknown extended data type: ignored (consumed), not rejected. Nothing
* is buffered and the window is left intact (replenished on receipt). */
idx = 0;
ret = wolfSSH_TestDoChannelExtendedData(ssh, (byte*)unknownBlob,
(word32)sizeof(unknownBlob), &idx);
if (ret != WS_SUCCESS) { result = -684; goto done; }
if (ch->windowSz != 128) { result = -685; goto done; }
ret = wolfSSH_extended_data_read(ssh, out, (word32)sizeof(out));
if (ret != 0) { result = -686; goto done; }
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* NO_WOLFSSH_SERVER */
/* Exercises the accumulating extended-data buffer and its window
* back-pressure: two stderr blobs that arrive before the application reads
* must both be preserved (no silent overwrite), the channel window must be
* charged on receipt and replenished on read, and a partial read followed by
* an append must preserve byte ordering and window accounting across the
* GrowBuffer compaction. The final cases cover two channels buffering stderr
* at once (each on its own channel buffer and window, neither displacing the
* other) and removing a channel that still has stderr buffered. */
static int test_DoChannelExtendedData_flow(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
word32 idx;
byte out[32];
/* channelId=0, type=1 (stderr), dataSz=10, payload all 0x11 */
static const byte blob1[] = {
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x0A,
0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11
};
/* channelId=0, type=1 (stderr), dataSz=10, payload all 0x22 */
static const byte blob2[] = {
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x0A,
0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22
};
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -600;
wolfSSH_SetIOSend(ctx, DiscardIoSend);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -601; goto done; }
/* Allow MSGID_CHANNEL_WINDOW_ADJUST on this bare session. */
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
/* windowSz=128, maxPacketSz=64 */
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 128, 64);
if (ch == NULL) { result = -602; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -603;
goto done;
}
/* First stderr blob: buffered, window charged 128 -> 118. */
idx = 0;
ret = wolfSSH_TestDoChannelExtendedData(ssh, (byte*)blob1,
(word32)sizeof(blob1), &idx);
if (ret != WS_EXTDATA) { result = -604; goto done; }
if (ch->windowSz != 118) { result = -605; goto done; }
/* Second stderr blob before any read: must accumulate, not overwrite.
* Window charged 118 -> 108. */
idx = 0;
ret = wolfSSH_TestDoChannelExtendedData(ssh, (byte*)blob2,
(word32)sizeof(blob2), &idx);
if (ret != WS_EXTDATA) { result = -606; goto done; }
if (ch->windowSz != 108) { result = -607; goto done; }
/* Read everything: both blobs present and in order (no data loss). */
ret = wolfSSH_extended_data_read(ssh, out, (word32)sizeof(out));
if (ret != 20) { result = -608; goto done; }
{
int i;
for (i = 0; i < 10; i++)
if (out[i] != 0x11) { result = -609; goto done; }
for (i = 10; i < 20; i++)
if (out[i] != 0x22) { result = -610; goto done; }
}
/* Draining replenishes the window: 108 + 20 -> 128. */
if (ch->windowSz != 128) { result = -611; goto done; }
/* Buffer drained; a further read returns 0. */
ret = wolfSSH_extended_data_read(ssh, out, (word32)sizeof(out));
if (ret != 0) { result = -612; goto done; }
/* Partial-read-then-append: read part of one blob (leaving idx > 0), then
* receive another blob. The append forces GrowBuffer to compact a non-zero
* idx in place (WMEMMOVE) before adding the new data, and the window must
* track a read that is split across the receipt of more data. */
idx = 0;
ret = wolfSSH_TestDoChannelExtendedData(ssh, (byte*)blob1,
(word32)sizeof(blob1), &idx);
if (ret != WS_EXTDATA) { result = -630; goto done; }
if (ch->windowSz != 118) { result = -631; goto done; }
/* Read 4 of the 10 buffered bytes: window 118 + 4 -> 122, idx left at 4. */
ret = wolfSSH_extended_data_read(ssh, out, 4);
if (ret != 4) { result = -632; goto done; }
{
int i;
for (i = 0; i < 4; i++)
if (out[i] != 0x11) { result = -633; goto done; }
}
if (ch->windowSz != 122) { result = -634; goto done; }
/* Append blob2 with 6 unread bytes still pending (idx=4, length=10): the
* 6 remaining 0x11 bytes must be preserved ahead of the new 0x22 bytes.
* Window charged 122 -> 112. */
idx = 0;
ret = wolfSSH_TestDoChannelExtendedData(ssh, (byte*)blob2,
(word32)sizeof(blob2), &idx);
if (ret != WS_EXTDATA) { result = -635; goto done; }
if (ch->windowSz != 112) { result = -636; goto done; }
/* Read the rest: 6 leftover 0x11 followed by 10 0x22, in order. Window
* 112 + 16 -> 128. */
ret = wolfSSH_extended_data_read(ssh, out, (word32)sizeof(out));
if (ret != 16) { result = -637; goto done; }
{
int i;
for (i = 0; i < 6; i++)
if (out[i] != 0x11) { result = -638; goto done; }
for (i = 6; i < 16; i++)
if (out[i] != 0x22) { result = -639; goto done; }
}
if (ch->windowSz != 128) { result = -640; goto done; }
/* Drained again. */
ret = wolfSSH_extended_data_read(ssh, out, (word32)sizeof(out));
if (ret != 0) { result = -641; goto done; }
/* Window-overflow branch: draw the window down below a blob that is
* still <= maxPacketSz, then confirm the next blob is rejected by the
* "dataSz > windowSz" branch and not the maxPacketSz branch. dataSz=60
* stays under maxPacketSz=64 so the maxPacketSz check cannot fire first. */
{
byte big[12 + 60];
int i;
WMEMSET(big, 0, sizeof(big));
big[7] = 0x01; /* type = stderr */
big[11] = 0x3C; /* dataSz = 60 */
for (i = 12; i < (int)sizeof(big); i++)
big[i] = 0x44;
/* window 128 -> 68 */
idx = 0;
ret = wolfSSH_TestDoChannelExtendedData(ssh, big,
(word32)sizeof(big), &idx);
if (ret != WS_EXTDATA) { result = -616; goto done; }
if (ch->windowSz != 68) { result = -617; goto done; }
/* window 68 -> 8 */
idx = 0;
ret = wolfSSH_TestDoChannelExtendedData(ssh, big,
(word32)sizeof(big), &idx);
if (ret != WS_EXTDATA) { result = -618; goto done; }
if (ch->windowSz != 8) { result = -619; goto done; }
/* dataSz=60 <= maxPacketSz but > windowSz=8: window-overflow reject,
* window left unchanged. */
idx = 0;
ret = wolfSSH_TestDoChannelExtendedData(ssh, big,
(word32)sizeof(big), &idx);
if (ret != WS_RECV_OVERFLOW_E) { result = -620; goto done; }
if (ch->windowSz != 8) { result = -621; goto done; }
}
/* Two channels buffer stderr independently: the buffer lives on the
* channel, so neither displaces the other and each window is charged and
* credited on its own. First drain the 120 bytes still pending on channel 0
* from the overflow block (8 + 120 -> 128 on read) to reach a clean state. */
{
WOLFSSH_CHANNEL* chB = NULL;
/* channelId=1, type=1 (stderr), dataSz=10, payload all 0x22 */
static const byte blobB[] = {
0x00, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x0A,
0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22
};
ret = wolfSSH_extended_data_read(ssh, out, (word32)sizeof(out));
if (ret != 32) { result = -650; goto done; }
ret = wolfSSH_extended_data_read(ssh, out, (word32)sizeof(out));
if (ret != 32) { result = -651; goto done; }
ret = wolfSSH_extended_data_read(ssh, out, (word32)sizeof(out));
if (ret != 32) { result = -652; goto done; }
ret = wolfSSH_extended_data_read(ssh, out, (word32)sizeof(out));
if (ret != 24) { result = -653; goto done; }
ret = wolfSSH_extended_data_read(ssh, out, (word32)sizeof(out));
if (ret != 0) { result = -654; goto done; }
if (ch->windowSz != 128) { result = -655; goto done; }
/* Second channel, id 1, same window/packet sizes as channel 0. */
chB = ChannelNew(ssh, ID_CHANTYPE_SESSION, 128, 64);
if (chB == NULL) { result = -656; goto done; }
if (ChannelAppend(ssh, chB) != WS_SUCCESS) {
ChannelDelete(chB, ssh->ctx->heap);
result = -657;
goto done;
}
/* Channel 0 buffers stderr: charged 128 -> 118. */
idx = 0;
ret = wolfSSH_TestDoChannelExtendedData(ssh, (byte*)blob1,
(word32)sizeof(blob1), &idx);
if (ret != WS_EXTDATA) { result = -658; goto done; }
if (ch->windowSz != 118) { result = -659; goto done; }
/* Channel 1 sends stderr while channel 0 still has unread data. It is
* buffered on channel 1 (not dropped, not appended to channel 0), and
* charged to channel 1's window: 128 -> 118. */
idx = 0;
ret = wolfSSH_TestDoChannelExtendedData(ssh, (byte*)blobB,
(word32)sizeof(blobB), &idx);
if (ret != WS_EXTDATA) { result = -660; goto done; }
if (chB->windowSz != 118) { result = -661; goto done; }
if (ch->windowSz != 118) { result = -662; goto done; }
/* wolfSSH_ChannelIdReadExt() reads the named channel, not the head of
* the list: it drains channel 1's 0x22 bytes and credits only channel
* 1 (118 + 10 -> 128), leaving channel 0's 0x11 bytes buffered and its
* window still charged. Neither channel's buffer holds the other's
* bytes. */
ret = wolfSSH_ChannelIdReadExt(ssh, 1, out, (word32)sizeof(out));
if (ret != 10) { result = -663; goto done; }
{
int i;
for (i = 0; i < 10; i++)
if (out[i] != 0x22) { result = -664; goto done; }
}
if (chB->windowSz != 128) { result = -665; goto done; }
if (ch->windowSz != 118) { result = -666; goto done; }
ret = wolfSSH_ChannelIdReadExt(ssh, 1, out, (word32)sizeof(out));
if (ret != 0) { result = -667; goto done; }
/* An unknown channel id is rejected, not silently read off the head. */
ret = wolfSSH_ChannelIdReadExt(ssh, 99, out, (word32)sizeof(out));
if (ret != WS_INVALID_CHANID) { result = -668; goto done; }
/* wolfSSH_extended_data_read() still reads the head of the channel
* list (channel 0), like wolfSSH_stream_read(): 118 + 10 -> 128. */
ret = wolfSSH_extended_data_read(ssh, out, (word32)sizeof(out));
if (ret != 10) { result = -669; goto done; }
{
int i;
for (i = 0; i < 10; i++)
if (out[i] != 0x11) { result = -670; goto done; }
}
if (ch->windowSz != 128) { result = -671; goto done; }
/* Closing channel 0 must not strand channel 1's stderr. Buffer stderr
* on channel 1 again (128 -> 118), remove channel 0, and confirm
* channel 1's bytes are still delivered -- here through the channel
* pointer variant -- and its window still credited: 118 + 10 -> 128.
* Before the buffer moved onto the channel, a shared buffer left
* pointing at a removed channel wedged every later channel's stderr. */
idx = 0;
ret = wolfSSH_TestDoChannelExtendedData(ssh, (byte*)blobB,
(word32)sizeof(blobB), &idx);
if (ret != WS_EXTDATA) { result = -672; goto done; }
if (chB->windowSz != 118) { result = -673; goto done; }
if (ChannelRemove(ssh, 0, WS_CHANNEL_ID_SELF) != WS_SUCCESS) {
result = -674; goto done;
}
ch = NULL;
if (ssh->channelList != chB) { result = -675; goto done; }
ret = wolfSSH_ChannelReadExt(chB, out, (word32)sizeof(out));
if (ret != 10) { result = -676; goto done; }
{
int i;
for (i = 0; i < 10; i++)
if (out[i] != 0x22) { result = -677; goto done; }
}
if (chB->windowSz != 128) { result = -678; goto done; }
ret = wolfSSH_ChannelReadExt(chB, out, (word32)sizeof(out));
if (ret != 0) { result = -679; goto done; }
}
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* Channel data handed to the application is wiped from the channel buffers:
* the consumed bytes on each read, and the copies a compaction leaves above
* the new length. */
static int test_ChannelReadWipesConsumed(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
WOLFSSH_BUFFER* in;
int result = 0;
int ret;
word32 idx;
byte data[40];
byte out[64];
/* channelId=0, type=1 (stderr), dataSz=10, payload all 0x11 */
static const byte blob[] = {
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x0A,
0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11
};
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1900;
wolfSSH_SetIOSend(ctx, DiscardIoSend);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1901; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
/* windowSz=128, so reads compact once length passes 64. */
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 128, 64);
if (ch == NULL) { result = -1902; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1903;
goto done;
}
in = &ch->inputBuffer;
WMEMSET(data, 0x5A, sizeof(data));
if (wolfSSH_TestChannelPutData(ch, data, 40) != WS_SUCCESS) {
result = -1904;
goto done;
}
/* Short reads that do not compact, through both read paths. */
ret = wolfSSH_stream_read(ssh, out, 10);
if (ret != 10) { result = -1905; goto done; }
ret = wolfSSH_ChannelIdRead(ssh, ch->channel, out, 10);
if (ret != 10) { result = -1906; goto done; }
if (in->idx != 20 || in->length != 40) { result = -1907; goto done; }
if (!IsZeroed(in->buffer, 20)) { result = -1908; goto done; }
if (in->buffer[20] != 0x5A || in->buffer[39] != 0x5A) {
result = -1909;
goto done;
}
/* A read that compacts: 50 unread bytes move down from offset 30. */
WMEMSET(data, 0x6B, sizeof(data));
if (wolfSSH_TestChannelPutData(ch, data, 40) != WS_SUCCESS) {
result = -1910;
goto done;
}
ret = wolfSSH_ChannelIdRead(ssh, ch->channel, out, 10);
if (ret != 10) { result = -1911; goto done; }
if (in->idx != 0 || in->length != 50) { result = -1912; goto done; }
if (!IsZeroed(in->buffer + 50, 30)) { result = -1913; goto done; }
/* The unread data survived the move. */
ret = wolfSSH_ChannelIdRead(ssh, ch->channel, out, sizeof(out));
if (ret != 50) { result = -1914; goto done; }
if (out[0] != 0x5A || out[9] != 0x5A || out[10] != 0x6B
|| out[49] != 0x6B) {
result = -1915;
goto done;
}
/* A short stderr chunk sits in the inline buffer and is drained whole. */
idx = 0;
ret = wolfSSH_TestDoChannelExtendedData(ssh, (byte*)blob,
(word32)sizeof(blob), &idx);
if (ret != WS_EXTDATA) { result = -1916; goto done; }
if (ch->extDataBuffer.dynamicFlag) { result = -1917; goto done; }
ret = wolfSSH_ChannelReadExt(ch, out, sizeof(out));
if (ret != 10) { result = -1918; goto done; }
if (!IsZeroed(ch->extDataBuffer.staticBuffer, STATIC_BUFFER_LEN)) {
result = -1919;
goto done;
}
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* GrowBuffer() compacting in place wipes what the move leaves above the new
* length. */
static int test_GrowBufferCompactWipesTail(void)
{
WOLFSSH_BUFFER buf;
int result = 0;
word32 i;
if (BufferInit(&buf, 64, NULL) != WS_SUCCESS)
return -1920;
for (i = 0; i < 40; i++)
buf.buffer[i] = (byte)(i + 1);
buf.length = 40;
buf.idx = 30;
/* 4 more bytes fit, so the allocation is kept. */
if (GrowBuffer(&buf, 4) != WS_SUCCESS) { result = -1921; goto done; }
if (buf.bufferSz != 64 || buf.length != 10 || buf.idx != 0) {
result = -1922;
goto done;
}
for (i = 0; i < 10; i++) {
if (buf.buffer[i] != (byte)(i + 31)) { result = -1923; goto done; }
}
if (!IsZeroed(buf.buffer + 10, 30)) { result = -1924; goto done; }
done:
ShrinkBuffer(&buf, 1);
return result;
}
/* Counts IoSend calls so a test can assert whether anything went on the wire. */
static word32 s_extSendCount = 0;
static int CountIoSend(WOLFSSH* ssh, void* buf, word32 sz, void* ctx)
{
(void)ssh; (void)buf; (void)ctx;
s_extSendCount++;
return (int)sz;
}
#ifndef NO_WOLFSSH_SERVER
/* RFC 4253 section 7.1: no connection-layer message (such as
* SSH_MSG_CHANNEL_WINDOW_ADJUST) may go out between KEXINIT and NEWKEYS.
* Neither DoChannelExtendedData() discarding an unknown data type nor
* wolfSSH_extended_data_read() draining stderr may therefore send a window
* adjust mid-KEX; both park the owed credit on the channel, and
* SendPendingChannelWindowAdjust() flushes it once keying completes. */
static int test_DoChannelExtendedData_keying(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
word32 idx;
byte out[32];
/* channelId=0, unknown type=2, dataSz=5, payload all 0x33 */
static const byte unknownBlob[] = {
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x02,
0x00, 0x00, 0x00, 0x05,
0x33, 0x33, 0x33, 0x33, 0x33
};
/* channelId=0, type=1 (stderr), dataSz=10, payload all 0x11 */
static const byte stderrBlob[] = {
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x0A,
0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11
};
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -700;
wolfSSH_SetIOSend(ctx, CountIoSend);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -701; goto done; }
/* Allow MSGID_CHANNEL_WINDOW_ADJUST on this bare session. */
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 128, 64);
if (ch == NULL) { result = -702; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -703;
goto done;
}
/* Pretend a rekey is in progress. Unknown extended data is consumed, but
* the owed window credit must not go on the wire; it is parked instead. */
ssh->isKeying = WOLFSSH_SELF_IS_KEYING;
s_extSendCount = 0;
idx = 0;
ret = wolfSSH_TestDoChannelExtendedData(ssh, (byte*)unknownBlob,
(word32)sizeof(unknownBlob), &idx);
if (ret != WS_SUCCESS) { result = -704; goto done; }
if (s_extSendCount != 0) { result = -705; goto done; }
if (ch->pendingWindowAdjust != 5) { result = -706; goto done; }
/* Discarded data is never charged to the local window. */
if (ch->windowSz != 128) { result = -707; goto done; }
/* Flushing while still keying is a no-op: credit stays parked. */
ret = wolfSSH_TestSendPendingChannelWindowAdjust(ssh);
if (ret != WS_SUCCESS) { result = -708; goto done; }
if (s_extSendCount != 0) { result = -709; goto done; }
if (ch->pendingWindowAdjust != 5) { result = -710; goto done; }
/* Keying complete: the parked WINDOW_ADJUST is sent and the credit clears. */
ssh->isKeying = 0;
ret = wolfSSH_TestSendPendingChannelWindowAdjust(ssh);
if (ret != WS_SUCCESS) { result = -711; goto done; }
if (s_extSendCount != 1) { result = -712; goto done; }
if (ch->pendingWindowAdjust != 0) { result = -713; goto done; }
/* Reading stderr mid-rekey: extended data is still received while keying
* (IsMessageAllowed() does not gate connection-layer messages on isKeying),
* so the app can drain it, but the resulting window credit must not go on
* the wire until keying ends. The read returns the bytes -- it must not
* fail, or the drained bytes would be lost -- and parks the credit. */
idx = 0;
ret = wolfSSH_TestDoChannelExtendedData(ssh, (byte*)stderrBlob,
(word32)sizeof(stderrBlob), &idx);
if (ret != WS_EXTDATA) { result = -714; goto done; }
if (ch->windowSz != 118) { result = -715; goto done; }
ssh->isKeying = WOLFSSH_SELF_IS_KEYING;
s_extSendCount = 0;
ret = wolfSSH_extended_data_read(ssh, out, (word32)sizeof(out));
if (ret != 10) { result = -716; goto done; }
{
int i;
for (i = 0; i < 10; i++)
if (out[i] != 0x11) { result = -717; goto done; }
}
/* Window credited locally, nothing on the wire, credit parked. */
if (ch->windowSz != 128) { result = -718; goto done; }
if (s_extSendCount != 0) { result = -719; goto done; }
if (ch->pendingWindowAdjust != 10) { result = -720; goto done; }
/* Keying complete: the parked credit reaches the peer. */
ssh->isKeying = 0;
ret = wolfSSH_TestSendPendingChannelWindowAdjust(ssh);
if (ret != WS_SUCCESS) { result = -721; goto done; }
if (s_extSendCount != 1) { result = -722; goto done; }
if (ch->pendingWindowAdjust != 0) { result = -723; goto done; }
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* The parked credit must also reach the wire through the real end-of-keying
* path, not just the SendPendingChannelWindowAdjust() test hook: DoNewKeys()
* flushes only after it clears WOLFSSH_PEER_IS_KEYING, and reordering those two
* would park the credit forever. */
static int test_DoChannelExtendedData_newkeys(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
word32 idx;
byte out[32];
/* channelId=0, type=1 (stderr), dataSz=10, payload all 0x11 */
static const byte stderrBlob[] = {
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x0A,
0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11
};
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1200;
wolfSSH_SetIOSend(ctx, CountIoSend);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1201; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 128, 64);
if (ch == NULL) { result = -1202; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1203;
goto done;
}
idx = 0;
ret = wolfSSH_TestDoChannelExtendedData(ssh, (byte*)stderrBlob,
(word32)sizeof(stderrBlob), &idx);
if (ret != WS_EXTDATA) { result = -1204; goto done; }
/* Only the peer is keying, which is what DoNewKeys() finishes. Draining now
* must park the credit rather than send it. */
ssh->isKeying = WOLFSSH_PEER_IS_KEYING;
s_extSendCount = 0;
ret = wolfSSH_extended_data_read(ssh, out, (word32)sizeof(out));
if (ret != 10) { result = -1205; goto done; }
if (s_extSendCount != 0) { result = -1206; goto done; }
if (ch->pendingWindowAdjust != 10) { result = -1207; goto done; }
/* NEWKEYS from the peer: no payload, and it must flush the parked credit. */
idx = 0;
ret = wolfSSH_TestDoNewKeys(ssh, NULL, 0, &idx);
if (ret != WS_SUCCESS) { result = -1208; goto done; }
if (ssh->isKeying != 0) { result = -1209; goto done; }
if (s_extSendCount != 1) { result = -1210; goto done; }
if (ch->pendingWindowAdjust != 0) { result = -1211; goto done; }
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* NO_WOLFSSH_SERVER */
/* A peer may trickle stderr in tiny packets while the app is slow to drain. The
* data it can send before draining is bounded by the receive window, and the
* buffer holding it must stay bounded too: an AppendBuffer() that reallocates
* on every packet ratchets capacity up by the unread count each time, so
* capacity grows with the square of the packet count while only windowSz bytes
* are ever buffered. Fill a real DEFAULT_WINDOW_SZ channel one byte at a time
* and hold the allocation to a small multiple of the bytes actually held. */
static int test_ChannelExtDataBufferGrowth(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
word32 i, idx, drained;
byte blob[13];
byte out[64];
/* Enough one-byte packets that a quadratic capacity is unmistakable: the
* old growth reaches ~8MB of buffer for 4KB of held data. */
const word32 count = 4096;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1230;
wolfSSH_SetIOSend(ctx, CountIoSend);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1231; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION,
DEFAULT_WINDOW_SZ, DEFAULT_MAX_PACKET_SZ);
if (ch == NULL) { result = -1232; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1233;
goto done;
}
/* channelId=0, type=1 (stderr), dataSz=1, one payload byte. */
WMEMSET(blob, 0, sizeof(blob));
blob[7] = 0x01;
blob[11] = 0x01;
for (i = 0; i < count; i++) {
/* Vary the payload so the drain below proves ordering survived every
* compaction and reallocation. */
blob[12] = (byte)(i & 0xFF);
idx = 0;
ret = wolfSSH_TestDoChannelExtendedData(ssh, blob, (word32)sizeof(blob),
&idx);
if (ret != WS_EXTDATA) { result = -1234; goto done; }
}
/* Nothing drained yet: every byte is held, and the window paid for it. */
if (ch->extDataBuffer.length - ch->extDataBuffer.idx != count) {
result = -1235;
goto done;
}
if (ch->windowSz != DEFAULT_WINDOW_SZ - count) { result = -1236; goto done; }
/* The allocation tracks the data held, not the number of packets it
* arrived in. Doubling settles at 4096 here; the old code reached ~8MB. */
if (ch->extDataBuffer.bufferSz > 4 * count) { result = -1237; goto done; }
/* Drain it all back, in order. */
drained = 0;
while (drained < count) {
word32 j;
ret = wolfSSH_extended_data_read(ssh, out, (word32)sizeof(out));
if (ret <= 0) { result = -1238; goto done; }
for (j = 0; j < (word32)ret; j++) {
if (out[j] != (byte)((drained + j) & 0xFF)) {
result = -1239;
goto done;
}
}
drained += (word32)ret;
}
if (drained != count) { result = -1240; goto done; }
/* Fully drained: the window is whole again and the buffer is released. */
if (ch->windowSz != DEFAULT_WINDOW_SZ) { result = -1241; goto done; }
if (wolfSSH_extended_data_read(ssh, out, (word32)sizeof(out)) != 0) {
result = -1242;
goto done;
}
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#ifndef NO_WOLFSSH_SERVER
/* wolfSSH_SendPacket() runs the highwater check after the packet is on the wire
* and returns the highwater callback's status, so a failing callback makes a
* delivered WINDOW_ADJUST look like a failed send. Credit re-parked then is
* credit the peer already has: resending it would grow the peer's send window
* past our receive window, and the data it let through would be rejected as an
* overflow. Assert the delivered credit is not owed again. */
static int test_ChannelExtDataCreditHighwater(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
word32 idx;
byte out[32];
/* channelId=0, type=1 (stderr), dataSz=10, payload all 0x11 */
static const byte blob[] = {
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x0A,
0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11
};
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1260;
wolfSSH_SetIOSend(ctx, CountIoSend);
/* Level 0 leaves the byte-count highwater off; the message count drives
* this test. */
wolfSSH_SetHighwaterCb(ctx, 0, FailHighwater);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1261; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
/* Any packet sent now trips the highwater callback. */
ssh->msgHighwaterMark = 1;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 128, 64);
if (ch == NULL) { result = -1262; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1263;
goto done;
}
idx = 0;
ret = wolfSSH_TestDoChannelExtendedData(ssh, (byte*)blob,
(word32)sizeof(blob), &idx);
if (ret != WS_EXTDATA) { result = -1264; goto done; }
s_extSendCount = 0;
/* The drain sends the adjust; the send itself succeeds and only the
* highwater callback afterwards fails. The read still reports its bytes. */
ret = wolfSSH_extended_data_read(ssh, out, (word32)sizeof(out));
if (ret != 10) { result = -1265; goto done; }
/* It went out ... */
if (s_extSendCount != 1) { result = -1266; goto done; }
/* ... so the peer has the credit and it must not be owed a second time. */
if (ch->pendingWindowAdjust != 0) { result = -1267; goto done; }
if (ch->windowSz != 128) { result = -1268; goto done; }
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* Stdout and stderr draw on one window (RFC 4254 section 5.2), but only stdout
* consumes the fixed-size channel input buffer. ChannelPutData()'s overflow
* guard depends on windowSz never outrunning the room left in that buffer, an
* invariant stderr can now move without touching the buffer at all. Interleave
* the two on one channel: every byte charged must come back, from either path,
* and a full-window CHANNEL_DATA must still be accepted afterwards. */
static int test_ChannelWindowSharedStdoutStderr(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
word32 idx;
byte out[128];
byte data[8 + 64];
byte ext[12 + 64];
int i;
/* CHANNEL_DATA on channel 0: channelId, dataSz, payload. */
WMEMSET(data, 0, sizeof(data));
data[7] = 0x32; /* dataSz = 50 */
for (i = 8; i < 8 + 50; i++)
data[i] = 0x55;
/* CHANNEL_EXTENDED_DATA on channel 0: channelId, type, dataSz, payload. */
WMEMSET(ext, 0, sizeof(ext));
ext[7] = 0x01; /* type = stderr */
ext[11] = 0x0A; /* dataSz = 10 */
for (i = 12; i < 12 + 10; i++)
ext[i] = 0x66;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -960;
wolfSSH_SetIOSend(ctx, CountIoSend);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -961; goto done; }
/* Allow MSGID_CHANNEL_WINDOW_ADJUST on this bare session. */
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
/* windowSz=128, maxPacketSz=64. The input buffer is windowSz bytes. */
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 128, 64);
if (ch == NULL) { result = -962; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -963;
goto done;
}
/* Stderr charges the window, leaving the input buffer alone: 128 -> 118 */
idx = 0;
ret = wolfSSH_TestDoChannelExtendedData(ssh, ext, 12 + 10, &idx);
if (ret != WS_EXTDATA) { result = -964; goto done; }
if (ch->windowSz != 118) { result = -965; goto done; }
/* Two stdout blobs on the same window: 118 -> 68 -> 18, input buffer at
* 100 of 128 bytes. The second is accepted only because stderr's 10 bytes
* left enough window; ChannelPutData() would reject it otherwise. */
idx = 0;
ret = wolfSSH_TestDoChannelData(ssh, data, 8 + 50, &idx);
if (ret != WS_CHAN_RXD) { result = -966; goto done; }
if (ch->windowSz != 68) { result = -967; goto done; }
idx = 0;
ret = wolfSSH_TestDoChannelData(ssh, data, 8 + 50, &idx);
if (ret != WS_CHAN_RXD) { result = -968; goto done; }
if (ch->windowSz != 18) { result = -969; goto done; }
if (ch->inputBuffer.length != 100) { result = -970; goto done; }
/* Drain stdout. _ChannelRead() advances idx before crediting, so the whole
* 100 bytes come back at once: 18 -> 118. Stderr's 10 stay charged. */
ret = wolfSSH_ChannelIdRead(ssh, 0, out, (word32)sizeof(out));
if (ret != 100) { result = -971; goto done; }
for (i = 0; i < 100; i++)
if (out[i] != 0x55) { result = -972; goto done; }
if (ch->windowSz != 118) { result = -973; goto done; }
/* Drain stderr: the last 10 come back through the other path, 118 -> 128.
* Every byte charged has now been credited exactly once. */
ret = wolfSSH_extended_data_read(ssh, out, (word32)sizeof(out));
if (ret != 10) { result = -974; goto done; }
for (i = 0; i < 10; i++)
if (out[i] != 0x66) { result = -975; goto done; }
if (ch->windowSz != 128) { result = -976; goto done; }
/* Stderr alone can now drive the window to 0 while the input buffer sits
* empty: two maxPacketSz blobs spend all 128 bytes, and none of it lands
* in the input buffer. */
ext[11] = 0x40; /* dataSz = 64 */
for (i = 0; i < 2; i++) {
idx = 0;
ret = wolfSSH_TestDoChannelExtendedData(ssh, ext, 12 + 64, &idx);
if (ret != WS_EXTDATA) { result = -977; goto done; }
}
if (ch->windowSz != 0) { result = -978; goto done; }
if (ch->inputBuffer.length != 0) { result = -979; goto done; }
/* A stdout read now hits _UpdateChannelWindow()'s windowSz == 0 case with
* nothing consumed to credit. It must not put a WINDOW_ADJUST for zero
* bytes on the wire, which it would repeat on every read until the app
* drains stderr. */
s_extSendCount = 0;
ret = wolfSSH_ChannelIdRead(ssh, 0, out, (word32)sizeof(out));
if (ret != 0) { result = -980; goto done; }
if (s_extSendCount != 0) { result = -981; goto done; }
if (ch->windowSz != 0) { result = -982; goto done; }
/* Draining the stderr that spent the window is what reopens it. */
ret = wolfSSH_extended_data_read(ssh, out, (word32)sizeof(out));
if (ret != 128) { result = -983; goto done; }
if (ch->windowSz != 128) { result = -984; goto done; }
/* The window is whole and the input buffer empty, so a full maxPacketSz
* CHANNEL_DATA is accepted: neither read path over- or under-credited, and
* windowSz never outran the room left in the input buffer. */
data[7] = 0x40; /* dataSz = 64 */
idx = 0;
ret = wolfSSH_TestDoChannelData(ssh, data, 8 + 64, &idx);
if (ret != WS_CHAN_RXD) { result = -985; goto done; }
if (ch->windowSz != 64) { result = -986; goto done; }
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* The peer's window only grows by the WINDOW_ADJUSTs it receives, so credit
* counted locally but never sent stalls the channel for good. Covers the two
* ways credit can go missing: an app that under-drains stderr, and an adjust
* whose send fails. */
static int test_ChannelExtDataCredit(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
WOLFSSH_CHANNEL* chB = NULL;
int result = 0;
int ret;
int i;
word32 idx;
byte out[32];
/* channelId=0, type=1 (stderr), dataSz=10, payload all 0x11 */
static const byte blob[] = {
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x0A,
0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11
};
/* channelId=1, type=1 (stderr), dataSz=10, payload all 0x22 */
static const byte blobB[] = {
0x00, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x0A,
0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22
};
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1100;
wolfSSH_SetIOSend(ctx, CountIoSend);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1101; goto done; }
/* Allow MSGID_CHANNEL_WINDOW_ADJUST on this bare session. */
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 128, 64);
if (ch == NULL) { result = -1102; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1103;
goto done;
}
/* Under-drain: three 10-byte blobs arrive, the app reads 4 bytes of each
* (a caller with a small buffer that does not loop). 30 charged, 12
* credited: 18 stay charged and the window erodes every round. */
for (i = 0; i < 3; i++) {
idx = 0;
ret = wolfSSH_TestDoChannelExtendedData(ssh, (byte*)blob,
(word32)sizeof(blob), &idx);
if (ret != WS_EXTDATA) { result = -1104; goto done; }
ret = wolfSSH_extended_data_read(ssh, out, 4);
if (ret != 4) { result = -1105; goto done; }
}
if (ch->windowSz != 128 - 18) { result = -1106; goto done; }
/* Window charged always matches the bytes still buffered. */
if (ch->extDataBuffer.length - ch->extDataBuffer.idx != 18) {
result = -1107; goto done;
}
/* Draining the rest restores the window in full. */
ret = wolfSSH_extended_data_read(ssh, out, (word32)sizeof(out));
if (ret != 18) { result = -1108; goto done; }
if (ch->windowSz != 128) { result = -1109; goto done; }
if (ch->pendingWindowAdjust != 0) { result = -1110; goto done; }
/* Failed send: the credit is parked, not forgotten. The read still reports
* the bytes; they are already in the caller's buffer. */
wolfSSH_SetIOSend(ctx, FailIoSend);
idx = 0;
ret = wolfSSH_TestDoChannelExtendedData(ssh, (byte*)blob,
(word32)sizeof(blob), &idx);
if (ret != WS_EXTDATA) { result = -1111; goto done; }
if (ch->windowSz != 118) { result = -1112; goto done; }
ret = wolfSSH_extended_data_read(ssh, out, (word32)sizeof(out));
if (ret != 10) { result = -1113; goto done; }
if (ch->windowSz != 128) { result = -1114; goto done; }
if (ch->pendingWindowAdjust != 10) { result = -1115; goto done; }
/* The next credit folds in the parked 10 bytes: one adjust returns all 20.
* Nothing lost to the failure, nothing double counted. */
wolfSSH_SetIOSend(ctx, CountIoSend);
s_extSendCount = 0;
idx = 0;
ret = wolfSSH_TestDoChannelExtendedData(ssh, (byte*)blob,
(word32)sizeof(blob), &idx);
if (ret != WS_EXTDATA) { result = -1116; goto done; }
ret = wolfSSH_extended_data_read(ssh, out, (word32)sizeof(out));
if (ret != 10) { result = -1117; goto done; }
if (s_extSendCount != 1) { result = -1118; goto done; }
if (ch->pendingWindowAdjust != 0) { result = -1119; goto done; }
if (ch->windowSz != 128) { result = -1120; goto done; }
/* One flush clears every channel, not just the head of the list. */
chB = ChannelNew(ssh, ID_CHANTYPE_SESSION, 128, 64);
if (chB == NULL) { result = -1121; goto done; }
if (ChannelAppend(ssh, chB) != WS_SUCCESS) {
ChannelDelete(chB, ssh->ctx->heap);
result = -1122;
goto done;
}
ssh->isKeying = WOLFSSH_SELF_IS_KEYING;
s_extSendCount = 0;
idx = 0;
ret = wolfSSH_TestDoChannelExtendedData(ssh, (byte*)blob,
(word32)sizeof(blob), &idx);
if (ret != WS_EXTDATA) { result = -1123; goto done; }
idx = 0;
ret = wolfSSH_TestDoChannelExtendedData(ssh, (byte*)blobB,
(word32)sizeof(blobB), &idx);
if (ret != WS_EXTDATA) { result = -1124; goto done; }
ret = wolfSSH_ChannelReadExt(ch, out, (word32)sizeof(out));
if (ret != 10) { result = -1125; goto done; }
ret = wolfSSH_ChannelReadExt(chB, out, (word32)sizeof(out));
if (ret != 10) { result = -1126; goto done; }
if (s_extSendCount != 0) { result = -1127; goto done; }
if (ch->pendingWindowAdjust != 10) { result = -1128; goto done; }
if (chB->pendingWindowAdjust != 10) { result = -1129; goto done; }
ssh->isKeying = 0;
ret = wolfSSH_TestSendPendingChannelWindowAdjust(ssh);
if (ret != WS_SUCCESS) { result = -1130; goto done; }
if (s_extSendCount != 2) { result = -1131; goto done; }
if (ch->pendingWindowAdjust != 0) { result = -1132; goto done; }
if (chB->pendingWindowAdjust != 0) { result = -1133; goto done; }
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* A drain whose window-adjust send only partially completes (WS_WANT_WRITE)
* must still report the bytes copied -- they are already in the caller's buffer
* -- and leave wolfSSH_get_error() at WS_WANT_WRITE so the caller knows a flush
* is owed. The adjust was bundled into the output buffer before the short
* write, so the credit is NOT re-parked: re-sending it on the next drain would
* hand the peer the same window twice. */
static int test_ChannelExtDataCreditWantWrite(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
int i;
word32 idx;
byte out[32];
/* channelId=0, type=1 (stderr), dataSz=10, payload all 0x11 */
static const byte blob[] = {
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x0A,
0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11
};
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1300;
wolfSSH_SetIOSend(ctx, CountIoSend);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1301; goto done; }
/* Allow MSGID_CHANNEL_WINDOW_ADJUST on this bare session. */
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 128, 64);
if (ch == NULL) { result = -1302; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1303;
goto done;
}
/* Buffer a stderr blob: window charged 128 -> 118. */
idx = 0;
ret = wolfSSH_TestDoChannelExtendedData(ssh, (byte*)blob,
(word32)sizeof(blob), &idx);
if (ret != WS_EXTDATA) { result = -1304; goto done; }
if (ch->windowSz != 118) { result = -1305; goto done; }
/* The next send blocks after the adjust is bundled. */
wolfSSH_SetIOSend(ctx, WantWriteIoSend);
ret = wolfSSH_extended_data_read(ssh, out, (word32)sizeof(out));
/* The bytes are reported despite the short write. */
if (ret != 10) { result = -1306; goto done; }
for (i = 0; i < 10; i++)
if (out[i] != 0x11) { result = -1307; goto done; }
/* The window is credited locally regardless of the send result. */
if (ch->windowSz != 128) { result = -1308; goto done; }
/* The caller can tell a flush is owed. */
if (wolfSSH_get_error(ssh) != WS_WANT_WRITE) { result = -1309; goto done; }
/* Bundled, not re-parked: the credit sits in the output buffer. */
if (ch->pendingWindowAdjust != 0) { result = -1310; goto done; }
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* NO_WOLFSSH_SERVER */
/* ChannelCreditWindow() guards its two defensive early exits: a NULL ssh or
* channel returns WS_BAD_ARGUMENT, and folding a credit that would push
* pendingWindowAdjust past UINT32_MAX returns WS_OVERFLOW_E and leaves the
* parked credit untouched. The overflow bound is exclusive: a credit landing
* exactly on UINT32_MAX is accepted. */
static int test_ChannelCreditWindowGuards(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1320;
wolfSSH_SetIOSend(ctx, CountIoSend);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1321; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 128, 64);
if (ch == NULL) { result = -1322; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1323;
goto done;
}
/* NULL arguments are rejected before anything is touched. */
if (ChannelCreditWindow(NULL, ch, 0) != WS_BAD_ARGUMENT) {
result = -1324; goto done;
}
if (ChannelCreditWindow(ssh, NULL, 0) != WS_BAD_ARGUMENT) {
result = -1325; goto done;
}
/* A credit that would overflow the parked total is refused, and the parked
* credit is left exactly as it was. */
ch->pendingWindowAdjust = UINT32_MAX - 5;
ret = ChannelCreditWindow(ssh, ch, 10);
if (ret != WS_OVERFLOW_E) { result = -1326; goto done; }
if (ch->pendingWindowAdjust != UINT32_MAX - 5) {
result = -1327; goto done;
}
/* Exactly UINT32_MAX does not overflow. Park it (keying) rather than send a
* 4GB adjust; the fold must reach the bound. */
ssh->isKeying = WOLFSSH_SELF_IS_KEYING;
ret = ChannelCreditWindow(ssh, ch, 5);
if (ret != WS_SUCCESS) { result = -1328; goto done; }
if (ch->pendingWindowAdjust != UINT32_MAX) { result = -1329; goto done; }
/* Leave nothing parked for teardown to trip over. */
ssh->isKeying = 0;
ch->pendingWindowAdjust = 0;
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* The read-side extended-data entry points reject bad arguments the same way
* their send-side counterparts do (see test_ChannelSendExt). Each guard has an
* early WS_BAD_ARGUMENT return -- NULL handle, NULL buffer, or zero length --
* and wolfSSH_extended_data_read() additionally rejects a session with no
* channels. An unknown channel id is WS_INVALID_CHANID, not a silent read off
* the list head. */
static int test_ChannelReadExtBadArgs(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
byte out[32];
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1340;
wolfSSH_SetIOSend(ctx, DiscardIoSend);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1341; goto done; }
/* No channel yet: wolfSSH_extended_data_read() rejects a NULL channelList,
* a NULL ssh, and a NULL output before any channel exists. */
if (wolfSSH_extended_data_read(ssh, out, (word32)sizeof(out))
!= WS_BAD_ARGUMENT) {
result = -1342; goto done;
}
if (wolfSSH_extended_data_read(NULL, out, (word32)sizeof(out))
!= WS_BAD_ARGUMENT) {
result = -1343; goto done;
}
if (wolfSSH_extended_data_read(ssh, NULL, (word32)sizeof(out))
!= WS_BAD_ARGUMENT) {
result = -1344; goto done;
}
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 128, 64);
if (ch == NULL) { result = -1345; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1346;
goto done;
}
/* With a channel present, a zero-length read is still rejected. */
if (wolfSSH_extended_data_read(ssh, out, 0) != WS_BAD_ARGUMENT) {
result = -1347; goto done;
}
/* wolfSSH_ChannelReadExt(): NULL channel, NULL buffer, zero length. */
if (wolfSSH_ChannelReadExt(NULL, out, (word32)sizeof(out))
!= WS_BAD_ARGUMENT) {
result = -1348; goto done;
}
if (wolfSSH_ChannelReadExt(ch, NULL, (word32)sizeof(out))
!= WS_BAD_ARGUMENT) {
result = -1349; goto done;
}
if (wolfSSH_ChannelReadExt(ch, out, 0) != WS_BAD_ARGUMENT) {
result = -1350; goto done;
}
/* wolfSSH_ChannelIdReadExt(): NULL ssh, NULL buffer, zero length, and an
* unknown channel id (distinct from the bad-argument cases). */
if (wolfSSH_ChannelIdReadExt(NULL, 0, out, (word32)sizeof(out))
!= WS_BAD_ARGUMENT) {
result = -1351; goto done;
}
if (wolfSSH_ChannelIdReadExt(ssh, 0, NULL, (word32)sizeof(out))
!= WS_BAD_ARGUMENT) {
result = -1352; goto done;
}
if (wolfSSH_ChannelIdReadExt(ssh, 0, out, 0) != WS_BAD_ARGUMENT) {
result = -1353; goto done;
}
if (wolfSSH_ChannelIdReadExt(ssh, 99, out, (word32)sizeof(out))
!= WS_INVALID_CHANID) {
result = -1354; goto done;
}
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#ifndef NO_WOLFSSH_SERVER
/* Integration (M-3): a peer sending stderr on a channel that is not the head of
* the channel list must not surface as stream data. wolfSSH_stream_read() reads
* the head channel only; when DoReceive() returns WS_EXTDATA for another
* channel it returns WS_ERROR rather than stranding the buffered data (whose
* window is already charged). Drives the real receive path -- DoReceive() ->
* DoPacket() -> DoChannelExtendedData() -- via a crafted plaintext packet, then
* confirms the data is still recoverable on the channel it arrived on through
* wolfSSH_ChannelIdReadExt(). */
static int test_StreamReadExtDataOtherChannel(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch0 = NULL;
WOLFSSH_CHANNEL* ch1 = NULL;
int result = 0;
int ret;
int i;
byte pkt[32];
byte out[32];
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1360;
wolfSSH_SetIOSend(ctx, DiscardIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1361; goto done; }
/* Allow the received CHANNEL_EXTENDED_DATA and the drain's window adjust. */
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch0 = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch0 == NULL) { result = -1362; goto done; }
if (ChannelAppend(ssh, ch0) != WS_SUCCESS) {
ChannelDelete(ch0, ssh->ctx->heap);
result = -1363;
goto done;
}
ch1 = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch1 == NULL) { result = -1364; goto done; }
if (ChannelAppend(ssh, ch1) != WS_SUCCESS) {
ChannelDelete(ch1, ssh->ctx->heap);
result = -1365;
goto done;
}
/* The first channel appended is the head that stream_read() drains. */
if (ssh->channelList != ch0) { result = -1366; goto done; }
/* Stage stderr for the non-head channel. */
s_recvPkt = pkt;
s_recvPktSz = BuildExtDataStderrPacket(pkt, ch1->channel, 0x11);
s_recvPktOff = 0;
/* Reading the head channel receives the packet, sees it is for another
* channel, and reports WS_ERROR instead of the extended data. */
ret = wolfSSH_stream_read(ssh, out, (word32)sizeof(out));
if (ret != WS_ERROR) { result = -1367; goto done; }
/* The bytes were buffered on ch1 and its window charged, not lost. */
if (ch1->windowSz != 1024 - 10) { result = -1368; goto done; }
if (ch0->windowSz != 1024) { result = -1369; goto done; }
/* A multi-channel app recovers them with the id-addressed reader. */
ret = wolfSSH_ChannelIdReadExt(ssh, ch1->channel, out,
(word32)sizeof(out));
if (ret != 10) { result = -1370; goto done; }
for (i = 0; i < 10; i++)
if (out[i] != 0x11) { result = -1371; goto done; }
if (ch1->windowSz != 1024) { result = -1372; goto done; }
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* Integration (L-5): wolfSSH_worker() reports the channel that extended data
* arrived on so a multi-channel caller can route the drain to
* wolfSSH_ChannelIdReadExt(). Drives a crafted stderr packet through the real
* receive path and confirms worker() returns WS_EXTDATA and writes the
* receiving channel's id into *channelId, and that the data then drains. */
static int test_WorkerReportsExtDataChannel(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
int i;
word32 reportedId = 0xFFFFFFFF;
byte pkt[32];
byte out[32];
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1380;
wolfSSH_SetIOSend(ctx, DiscardIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1381; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch == NULL) { result = -1382; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1383;
goto done;
}
s_recvPkt = pkt;
s_recvPktSz = BuildExtDataStderrPacket(pkt, ch->channel, 0x22);
s_recvPktOff = 0;
ret = wolfSSH_worker(ssh, &reportedId);
if (ret != WS_EXTDATA) { result = -1384; goto done; }
if (reportedId != ch->channel) { result = -1385; goto done; }
if (ch->windowSz != 1024 - 10) { result = -1386; goto done; }
/* The reported channel is the one to drain. */
ret = wolfSSH_ChannelIdReadExt(ssh, reportedId, out, (word32)sizeof(out));
if (ret != 10) { result = -1387; goto done; }
for (i = 0; i < 10; i++)
if (out[i] != 0x22) { result = -1388; goto done; }
if (ch->windowSz != 1024) { result = -1389; goto done; }
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* Regression: extended data arriving while a rekey is in flight must still be
* reported. WS_EXTDATA is raised once, on arrival, so folding it into
* WS_REKEYING at the isKeying check in wolfSSH_worker() strands the buffered
* stderr and the window credit already charged for it -- nothing re-raises it.
* RFC 4253 section 7.1 requires accepting data the peer sent before it saw our
* KEXINIT, so this is a normal sequence, not a corner case. */
static int test_WorkerReportsExtDataChannelKeying(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
int i;
word32 reportedId = 0xFFFFFFFF;
byte pkt[32];
byte out[32];
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1390;
wolfSSH_SetIOSend(ctx, DiscardIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1391; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch == NULL) { result = -1392; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1393;
goto done;
}
s_recvPkt = pkt;
s_recvPktSz = BuildExtDataStderrPacket(pkt, ch->channel, 0x33);
s_recvPktOff = 0;
/* A rekey is underway when the stderr packet lands. */
ssh->isKeying = WOLFSSH_SELF_IS_KEYING;
ret = wolfSSH_worker(ssh, &reportedId);
if (ret != WS_EXTDATA) { result = -1394; goto done; }
if (reportedId != ch->channel) { result = -1395; goto done; }
if (ch->windowSz != 1024 - 10) { result = -1396; goto done; }
/* The drain works mid-rekey; the credit parks rather than going out, since
* no WINDOW_ADJUST may be sent during KEX. */
ret = wolfSSH_ChannelIdReadExt(ssh, reportedId, out, (word32)sizeof(out));
if (ret != 10) { result = -1397; goto done; }
for (i = 0; i < 10; i++)
if (out[i] != 0x33) { result = -1398; goto done; }
if (ch->windowSz != 1024) { result = -1399; goto done; }
if (ch->pendingWindowAdjust != 10) { result = -1400; goto done; }
/* Once keying completes the parked credit flushes. */
ssh->isKeying = 0;
ret = wolfSSH_TestSendPendingChannelWindowAdjust(ssh);
if (ret != WS_SUCCESS) { result = -1401; goto done; }
if (ch->pendingWindowAdjust != 0) { result = -1402; goto done; }
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#if defined(WOLFSSH_TEST_INTERNAL) && !defined(WOLFSSH_NO_HMAC_SHA2_256)
/* An inbound packet that fails its checks starts no highwater rekey, neither
* from the worker's flush on that pass nor from a later send. */
static int test_HighwaterQuietAfterBadPacket(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
HwTestCtx hc;
Hmac hmac;
int result = 0;
int ret;
word32 prefixLen;
byte seq[LENGTH_SZ];
byte macKey[WC_SHA256_DIGEST_SIZE];
byte digest[WC_SHA256_DIGEST_SIZE];
byte pkt[UINT32_SZ + 12 + WC_SHA256_DIGEST_SIZE];
WMEMSET(&hc, 0, sizeof(hc));
s_extSendCount = 0;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1950;
wolfSSH_SetIOSend(ctx, CountIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
wolfSSH_SetHighwaterCb(ctx, 1, HwTestCb);
/* The session is never keyed, and wolfSSH_SendIgnore() refuses an
* unkeyed send under strict KEX. */
wolfSSH_CTX_SetStrictKex(ctx, 0);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1951; goto done; }
hc.ssh = ssh;
wolfSSH_SetHighwaterCtx(ssh, &hc);
wolfSSH_SetMsgHighwater(ssh, 1);
ssh->txCount = 1;
ssh->txMsgCount = 1;
/* Control: the flush after an idle receive fires the callback. */
ssh->outputBuffer.length = 1;
ssh->outputBuffer.idx = 0;
ssh->outputBuffer.buffer[0] = 0;
ret = wolfSSH_worker(ssh, NULL);
if (ret != WS_FATAL_ERROR || wolfSSH_get_error(ssh) != WS_WANT_READ) {
result = -1952;
goto done;
}
if (hc.count != 1) { result = -1953; goto done; }
/* A new key epoch clears both flags. */
ssh->highwaterFlag = 0;
ssh->msgHighwaterFlag = 0;
hc.count = 0;
/* An IGNORE packet under HMAC-SHA2-256 at peerSeq 0, one MAC bit off. */
prefixLen = BuildMacTestPacketPrefix(MSGID_IGNORE, 10, pkt, sizeof(pkt));
if (prefixLen == 0) { result = -1954; goto done; }
WMEMSET(macKey, 0xA5, sizeof(macKey));
WMEMSET(seq, 0, sizeof(seq));
ret = wc_HmacInit(&hmac, ssh->ctx->heap, INVALID_DEVID);
if (ret == 0) {
ret = wc_HmacSetKey(&hmac, WC_SHA256, macKey, sizeof(macKey));
if (ret == 0)
ret = wc_HmacUpdate(&hmac, seq, sizeof(seq));
if (ret == 0)
ret = wc_HmacUpdate(&hmac, pkt, prefixLen);
if (ret == 0)
ret = wc_HmacFinal(&hmac, digest);
wc_HmacFree(&hmac);
}
if (ret != 0) { result = -1955; goto done; }
WMEMCPY(pkt + prefixLen, digest, sizeof(digest));
pkt[prefixLen] ^= 0x01;
ssh->peerMacId = ID_HMAC_SHA2_256;
ssh->peerMacSz = WC_SHA256_DIGEST_SIZE;
WMEMCPY(ssh->peerKeys.macKey, macKey, sizeof(macKey));
ssh->peerKeys.macKeySz = sizeof(macKey);
s_recvPkt = pkt;
s_recvPktSz = prefixLen + WC_SHA256_DIGEST_SIZE;
s_recvPktOff = 0;
/* The worker still flushes what was queued, but fires nothing. */
ssh->outputBuffer.length = 1;
ssh->outputBuffer.idx = 0;
ssh->outputBuffer.buffer[0] = 0;
s_extSendCount = 0;
ret = wolfSSH_worker(ssh, NULL);
if (ret != WS_FATAL_ERROR || wolfSSH_get_error(ssh) != WS_VERIFY_MAC_E) {
result = -1957;
goto done;
}
if (wolfSSH_OutputPending(ssh) || s_extSendCount == 0) {
result = -1958;
goto done;
}
if (hc.count != 0) { result = -1959; goto done; }
/* Nor does the next send, as a teardown would make. */
ret = wolfSSH_SendIgnore(ssh, NULL, 0);
if (ret != WS_SUCCESS) { result = -1960; goto done; }
if (hc.count != 0) { result = -1961; goto done; }
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
s_extSendCount = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* WOLFSSH_TEST_INTERNAL && !WOLFSSH_NO_HMAC_SHA2_256 */
/* channelId=0, type=1 (stderr), dataSz=10, payload all 0x44. */
static const byte s_workerExtBlob[] = {
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x0A,
0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44
};
/* Bundles a window adjust into ssh->outputBuffer with the send blocked,
* then leaves the receive idle. */
static int WorkerParkAdjust(WOLFSSH_CTX* ctx, WOLFSSH* ssh,
WOLFSSH_CHANNEL* channel)
{
word32 idx = 0;
int ret;
byte out[32];
ret = wolfSSH_TestDoChannelExtendedData(ssh, (byte*)s_workerExtBlob,
(word32)sizeof(s_workerExtBlob),
&idx);
if (ret != WS_EXTDATA)
return WS_FATAL_ERROR;
if (channel->windowSz != 118)
return WS_FATAL_ERROR;
wolfSSH_SetIOSend(ctx, WantWriteIoSend);
ret = wolfSSH_extended_data_read(ssh, out, (word32)sizeof(out));
if (ret != 10)
return WS_FATAL_ERROR;
if (ssh->outputBuffer.length == 0)
return WS_FATAL_ERROR;
if (channel->pendingWindowAdjust != 0)
return WS_FATAL_ERROR;
/* No staged packet, so PacketIoRecv reports want-read. */
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
return WS_SUCCESS;
}
/* A window adjust a short write left in ssh->outputBuffer goes out on a
* later wolfSSH_worker() call. The peer is out of window and sends nothing
* until it arrives, so the receive stays idle. */
static int test_WorkerFlushesOnIdleReceive(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1700;
wolfSSH_SetIOSend(ctx, CountIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1701; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 128, 64);
if (ch == NULL) { result = -1702; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1703;
goto done;
}
if (WorkerParkAdjust(ctx, ssh, ch) != WS_SUCCESS) {
result = -1704;
goto done;
}
/* The socket takes writes again. */
wolfSSH_SetIOSend(ctx, CountIoSend);
s_extSendCount = 0;
ret = wolfSSH_worker(ssh, NULL);
if (s_extSendCount != 1) { result = -1705; goto done; }
if (ssh->outputBuffer.length != 0) { result = -1706; goto done; }
/* Nothing left queued, so the call reports the idle receive. */
if (ret != WS_FATAL_ERROR) { result = -1707; goto done; }
if (wolfSSH_get_error(ssh) != WS_WANT_READ) { result = -1708; goto done; }
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* While the flush stays short, ssh->error keeps reporting WS_WANT_WRITE so
* the caller selects for writability instead of waiting on a read the peer
* cannot produce. */
static int test_WorkerReportsOwedFlush(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1710;
wolfSSH_SetIOSend(ctx, CountIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1711; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 128, 64);
if (ch == NULL) { result = -1712; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1713;
goto done;
}
if (WorkerParkAdjust(ctx, ssh, ch) != WS_SUCCESS) {
result = -1714;
goto done;
}
/* The send still blocks, so the flush stays owed across both calls. */
ret = wolfSSH_worker(ssh, NULL);
if (ret != WS_FATAL_ERROR) { result = -1715; goto done; }
if (wolfSSH_get_error(ssh) != WS_WANT_WRITE) { result = -1716; goto done; }
if (ssh->outputBuffer.length == 0) { result = -1717; goto done; }
ret = wolfSSH_worker(ssh, NULL);
if (ret != WS_FATAL_ERROR) { result = -1718; goto done; }
if (wolfSSH_get_error(ssh) != WS_WANT_WRITE) { result = -1719; goto done; }
if (ssh->outputBuffer.length == 0) { result = -1720; goto done; }
/* Bundled credit is owed by the output buffer, not the channel. */
if (ch->pendingWindowAdjust != 0) { result = -1721; goto done; }
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* A receive that failed keeps ssh->error: the flush runs on the same call
* and wolfSSH_SendPacket() would otherwise leave WS_WANT_WRITE there, which
* reads as transient and would have the caller retry a dead session. */
static int test_WorkerHardRecvErrorOutranksFlush(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
byte pkt[8];
/* packet_length far past MAX_PACKET_SZ, so DoReceive() fails the length
* check with WS_OVERFLOW_E instead of blocking. */
static const byte badLen[8] = {
0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00
};
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1730;
wolfSSH_SetIOSend(ctx, CountIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1731; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 128, 64);
if (ch == NULL) { result = -1732; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1733;
goto done;
}
if (WorkerParkAdjust(ctx, ssh, ch) != WS_SUCCESS) {
result = -1734;
goto done;
}
WMEMCPY(pkt, badLen, sizeof(pkt));
s_recvPkt = pkt;
s_recvPktSz = (word32)sizeof(pkt);
s_recvPktOff = 0;
ret = wolfSSH_worker(ssh, NULL);
if (ret != WS_FATAL_ERROR) { result = -1735; goto done; }
if (wolfSSH_get_error(ssh) != WS_OVERFLOW_E) { result = -1736; goto done; }
if (!ssh->highwaterFlag || !ssh->msgHighwaterFlag) {
result = -1784;
goto done;
}
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* A hard send failure on a pass whose receive was idle leaves
* WS_SOCKET_ERROR_E in ssh->error, not the receive's WS_WANT_READ. A caller
* routing on that would select for read on a reset socket. */
static int test_WorkerHardSendErrorOnIdleReceive(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1740;
wolfSSH_SetIOSend(ctx, CountIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1741; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 128, 64);
if (ch == NULL) { result = -1742; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1743;
goto done;
}
if (WorkerParkAdjust(ctx, ssh, ch) != WS_SUCCESS) {
result = -1744;
goto done;
}
/* The receive stays idle and the peer resets under the flush. */
wolfSSH_SetIOSend(ctx, ConnResetIoSend);
ret = wolfSSH_worker(ssh, NULL);
if (ret != WS_FATAL_ERROR) { result = -1745; goto done; }
if (wolfSSH_get_error(ssh) != WS_SOCKET_ERROR_E) {
result = -1746;
goto done;
}
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* Channel data arrives and the flush fails on the same call. The send's
* code takes ret, since the data is still buffered but the transport is
* gone. */
static int test_WorkerChanRxdSurfacesSendError(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
byte pkt[32];
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1750;
wolfSSH_SetIOSend(ctx, CountIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1751; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 128, 64);
if (ch == NULL) { result = -1752; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1753;
goto done;
}
if (WorkerParkAdjust(ctx, ssh, ch) != WS_SUCCESS) {
result = -1754;
goto done;
}
/* Channel data arrives, and the peer resets the socket on the send. */
s_recvPkt = pkt;
s_recvPktSz = BuildChannelDataPacket(pkt, ch->channel, 0x55);
s_recvPktOff = 0;
wolfSSH_SetIOSend(ctx, ConnResetIoSend);
ret = wolfSSH_worker(ssh, NULL);
if (ret != WS_SOCKET_ERROR_E) { result = -1755; goto done; }
if (wolfSSH_get_error(ssh) != WS_SOCKET_ERROR_E) {
result = -1756;
goto done;
}
/* A reset does not discard, so the bytes stay owed. */
if (ssh->outputBuffer.length == 0) { result = -1757; goto done; }
/* And the failure persists rather than being a one-pass artefact. */
ret = wolfSSH_worker(ssh, NULL);
if (ret != WS_FATAL_ERROR) { result = -1758; goto done; }
if (wolfSSH_get_error(ssh) != WS_SOCKET_ERROR_E) {
result = -1759;
goto done;
}
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* A packet whose framing fails leaves nothing queued behind it. The buffer
* keeps the packets already bundled, so only the aborted one is dropped. */
static int test_BundlePacketFailureDropsPartial(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
word32 queued;
byte bundled = 0;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1850;
wolfSSH_SetIOSend(ctx, WantWriteIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1851; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 128, 64);
if (ch == NULL) { result = -1852; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1853;
goto done;
}
/* One adjust frames cleanly and parks, since the send blocks. */
ret = SendChannelWindowAdjust(ssh, ch->channel, 10, &bundled);
if (ret != WS_WANT_WRITE) { result = -1854; goto done; }
queued = ssh->outputBuffer.length;
if (queued == 0) { result = -1855; goto done; }
/* An unknown cipher fails the next bundle. Check the framing error and
* the staged packet, so an earlier bail cannot stand in for them. */
ssh->encryptId = ID_UNKNOWN;
ret = SendChannelWindowAdjust(ssh, ch->peerChannel, 10, &bundled);
if (ret != WS_INVALID_ALGO_ID) { result = -1856; goto done; }
if (ssh->packetStartIdx != queued) { result = -1858; goto done; }
/* The aborted packet is gone and the framed one is untouched. */
if (ssh->outputBuffer.length != queued) { result = -1857; goto done; }
if (!IsZeroed(ssh->outputBuffer.buffer + queued,
ssh->outputBuffer.bufferSz - queued)) {
result = -1859;
goto done;
}
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* Extended data arrives and the flush fails on the same call. The send's
* code takes ret, and channelId is left alone with it. */
static int test_WorkerExtDataSurfacesSendError(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
word32 reportedId = 0xFFFFFFFF;
byte pkt[32];
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1830;
wolfSSH_SetIOSend(ctx, CountIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1831; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 128, 64);
if (ch == NULL) { result = -1832; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1833;
goto done;
}
if (WorkerParkAdjust(ctx, ssh, ch) != WS_SUCCESS) {
result = -1834;
goto done;
}
/* Stderr arrives, and the peer resets the socket on the send. */
s_recvPkt = pkt;
s_recvPktSz = BuildExtDataStderrPacket(pkt, ch->channel, 0x99);
s_recvPktOff = 0;
wolfSSH_SetIOSend(ctx, ConnResetIoSend);
ret = wolfSSH_worker(ssh, &reportedId);
if (ret != WS_SOCKET_ERROR_E) { result = -1835; goto done; }
if (reportedId != 0xFFFFFFFF) { result = -1836; goto done; }
if (wolfSSH_get_error(ssh) != WS_SOCKET_ERROR_E) {
result = -1837;
goto done;
}
/* A reset does not discard, so the bytes stay owed. */
if (ssh->outputBuffer.length == 0) { result = -1838; goto done; }
/* The stderr is still there to drain, off the channel rather than ret. */
if (ch->extDataBuffer.length - ch->extDataBuffer.idx != 10) {
result = -1839;
goto done;
}
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* The peer half-closes and the flush fails on the same call. The send's
* code takes ret; the half-close is read off the channel instead. */
static int test_WorkerEofSurfacesSendError(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
word32 reportedId = 0xFFFFFFFF;
byte pkt[32];
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1840;
wolfSSH_SetIOSend(ctx, CountIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1841; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 128, 64);
if (ch == NULL) { result = -1842; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1843;
goto done;
}
if (WorkerParkAdjust(ctx, ssh, ch) != WS_SUCCESS) {
result = -1844;
goto done;
}
/* The half-close arrives, and the peer resets the socket on the send. */
s_recvPkt = pkt;
s_recvPktSz = BuildChannelEofPacket(pkt, ch->channel);
s_recvPktOff = 0;
wolfSSH_SetIOSend(ctx, ConnResetIoSend);
ret = wolfSSH_worker(ssh, &reportedId);
if (ret != WS_SOCKET_ERROR_E) { result = -1845; goto done; }
if (reportedId != 0xFFFFFFFF) { result = -1846; goto done; }
if (wolfSSH_get_error(ssh) != WS_SOCKET_ERROR_E) {
result = -1847;
goto done;
}
/* A reset does not discard, so the bytes stay owed. */
if (ssh->outputBuffer.length == 0) { result = -1848; goto done; }
/* The half-close is latched, which is the durable half of the report. */
if (!wolfSSH_ChannelGetEof(ch)) { result = -1849; goto done; }
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* Channel data arrives and the flush only short-writes. ret keeps the data
* report, ssh->error carries the want-write, and the bytes stay owed. */
static int test_WorkerChanRxdSurfacesShortFlush(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
byte pkt[32];
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1870;
wolfSSH_SetIOSend(ctx, CountIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1871; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 128, 64);
if (ch == NULL) { result = -1872; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1873;
goto done;
}
if (WorkerParkAdjust(ctx, ssh, ch) != WS_SUCCESS) {
result = -1874;
goto done;
}
/* Channel data arrives while the socket still refuses writes. */
s_recvPkt = pkt;
s_recvPktSz = BuildChannelDataPacket(pkt, ch->channel, 0xBB);
s_recvPktOff = 0;
wolfSSH_SetIOSend(ctx, WantWriteIoSend);
ret = wolfSSH_worker(ssh, NULL);
if (ret != WS_CHAN_RXD) { result = -1875; goto done; }
if (wolfSSH_get_error(ssh) != WS_WANT_WRITE) { result = -1876; goto done; }
if (!wolfSSH_OutputPending(ssh)) { result = -1877; goto done; }
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* The same pass with a rekey in flight. WS_REKEYING would tell the caller to
* keep turning the crank, so a flush that hard-failed takes ret and the rekey
* mask stands down. */
static int test_WorkerKeyingSurfacesSendError(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
byte pkt[32];
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1800;
wolfSSH_SetIOSend(ctx, CountIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1801; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 128, 64);
if (ch == NULL) { result = -1802; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1803;
goto done;
}
if (WorkerParkAdjust(ctx, ssh, ch) != WS_SUCCESS) {
result = -1804;
goto done;
}
s_recvPkt = pkt;
s_recvPktSz = BuildChannelDataPacket(pkt, ch->channel, 0x77);
s_recvPktOff = 0;
wolfSSH_SetIOSend(ctx, ConnResetIoSend);
ssh->isKeying = WOLFSSH_SELF_IS_KEYING;
ret = wolfSSH_worker(ssh, NULL);
if (ret != WS_SOCKET_ERROR_E) { result = -1805; goto done; }
if (wolfSSH_get_error(ssh) != WS_SOCKET_ERROR_E) {
result = -1806;
goto done;
}
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* The other arm: a rekey in flight and a flush that went out. The worker
* reports WS_REKEYING so the caller keeps driving the rekey. */
static int test_WorkerKeyingReportsRekey(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
word32 reportedId = 0;
byte pkt[32];
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1810;
wolfSSH_SetIOSend(ctx, CountIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1811; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 128, 64);
if (ch == NULL) { result = -1812; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1813;
goto done;
}
if (WorkerParkAdjust(ctx, ssh, ch) != WS_SUCCESS) {
result = -1814;
goto done;
}
/* Channel data arrives and the socket takes the flush. */
s_recvPkt = pkt;
s_recvPktSz = BuildChannelDataPacket(pkt, ch->channel, 0x88);
s_recvPktOff = 0;
wolfSSH_SetIOSend(ctx, CountIoSend);
ssh->isKeying = WOLFSSH_SELF_IS_KEYING;
ret = wolfSSH_worker(ssh, &reportedId);
if (ret != WS_REKEYING) { result = -1815; goto done; }
if (wolfSSH_get_error(ssh) != WS_REKEYING) {
result = -1816;
goto done;
}
if (reportedId != ch->channel) { result = -1818; goto done; }
/* The flush ran and drained, which the rekey report is gated on. */
if (ssh->outputBuffer.length != 0) { result = -1817; goto done; }
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* A send that fails with WS_CBIO_ERR_GENERAL discards the output buffer, so
* no later call retries the flush. The send failure has to reach the caller
* even though the receive reported channel data. */
static int test_WorkerDiscardedFlushKeepsError(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
byte pkt[32];
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1760;
wolfSSH_SetIOSend(ctx, CountIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1761; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 128, 64);
if (ch == NULL) { result = -1762; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1763;
goto done;
}
if (WorkerParkAdjust(ctx, ssh, ch) != WS_SUCCESS) {
result = -1764;
goto done;
}
/* Channel data arrives, and the send throws the queued adjust away. */
s_recvPkt = pkt;
s_recvPktSz = BuildChannelDataPacket(pkt, ch->channel, 0x66);
s_recvPktOff = 0;
wolfSSH_SetIOSend(ctx, FailIoSend);
ret = wolfSSH_worker(ssh, NULL);
if (ret != WS_SOCKET_ERROR_E) { result = -1765; goto done; }
/* Nothing is left to flush, so this is the only report there will be. */
if (ssh->outputBuffer.length != 0) { result = -1766; goto done; }
if (wolfSSH_get_error(ssh) != WS_SOCKET_ERROR_E) {
result = -1767;
goto done;
}
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* A send callback reporting more bytes than it was handed trips the
* out-of-bounds check, and ssh->error carries WS_SEND_OOB_READ_E. */
static int test_WorkerSendOobReadReported(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1770;
wolfSSH_SetIOSend(ctx, CountIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1771; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 128, 64);
if (ch == NULL) { result = -1772; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1773;
goto done;
}
if (WorkerParkAdjust(ctx, ssh, ch) != WS_SUCCESS) {
result = -1774;
goto done;
}
/* The receive stays idle, so only the send can set ssh->error. */
wolfSSH_SetIOSend(ctx, OobIoSend);
ret = wolfSSH_worker(ssh, NULL);
if (ret != WS_FATAL_ERROR) { result = -1775; goto done; }
if (wolfSSH_get_error(ssh) != WS_SEND_OOB_READ_E) {
result = -1776;
goto done;
}
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* A session with no send callback set. wolfSSH_SendPacket() reports the
* socket error before it reaches the transport, and ssh->error carries it. */
static int test_WorkerNoSendCallbackReported(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
int result = 0;
int ret;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1780;
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1781; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ctx->ioSendCb = NULL;
/* Queued output, so the flush runs. */
ssh->outputBuffer.length = 1;
ssh->outputBuffer.idx = 0;
ssh->outputBuffer.buffer[0] = 0;
ret = wolfSSH_worker(ssh, NULL);
if (ret != WS_FATAL_ERROR) { result = -1782; goto done; }
if (wolfSSH_get_error(ssh) != WS_SOCKET_ERROR_E) {
result = -1783;
goto done;
}
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* An output buffer whose length runs past its size. wolfSSH_SendPacket()
* stops on the sanity check and ssh->error carries WS_BUFFER_E. */
static int test_WorkerBadBufferStateReported(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
int result = 0;
int ret;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1785;
wolfSSH_SetIOSend(ctx, CountIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1786; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ssh->outputBuffer.idx = 0;
ssh->outputBuffer.length = ssh->outputBuffer.bufferSz + 1;
ret = wolfSSH_worker(ssh, NULL);
if (ret != WS_FATAL_ERROR) { result = -1787; goto done; }
if (wolfSSH_get_error(ssh) != WS_BUFFER_E) {
result = -1788;
goto done;
}
done:
if (ssh != NULL)
ssh->outputBuffer.length = 0;
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* The documented primary flow: wolfSSH_stream_read() reports WS_EXTDATA when
* stderr arrives on the head channel, and the caller drains it with
* wolfSSH_extended_data_read() until that returns 0 (wolfssh/ssh.h). */
static int test_StreamReadExtDataHeadChannel(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
int i;
byte pkt[32];
byte out[32];
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1410;
wolfSSH_SetIOSend(ctx, DiscardIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1411; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch == NULL) { result = -1412; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1413;
goto done;
}
s_recvPkt = pkt;
s_recvPktSz = BuildExtDataStderrPacket(pkt, ch->channel, 0x44);
s_recvPktOff = 0;
/* Stderr on the head channel surfaces as WS_EXTDATA, not stream data. */
ret = wolfSSH_stream_read(ssh, out, (word32)sizeof(out));
if (ret != WS_EXTDATA) { result = -1414; goto done; }
if (wolfSSH_get_error(ssh) != WS_EXTDATA) { result = -1415; goto done; }
if (ch->windowSz != 1024 - 10) { result = -1416; goto done; }
ret = wolfSSH_extended_data_read(ssh, out, (word32)sizeof(out));
if (ret != 10) { result = -1417; goto done; }
for (i = 0; i < 10; i++)
if (out[i] != 0x44) { result = -1418; goto done; }
if (ch->windowSz != 1024) { result = -1419; goto done; }
/* Drained: the documented loop terminates. */
ret = wolfSSH_extended_data_read(ssh, out, (word32)sizeof(out));
if (ret != 0) { result = -1420; goto done; }
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* SendPendingChannelWindowAdjust() must report transport backpressure rather
* than swallowing it, so the keying path can tell a flush is still owed. The
* empty-channel-list case is what keeps the initial handshake unaffected: with
* no channels there is nothing to flush, so it cannot perturb accept/connect. */
static int test_SendPendingWindowAdjustReportsWantWrite(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1430;
wolfSSH_SetIOSend(ctx, DiscardIoSend);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1431; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
/* No channels yet, as during the initial KEX: nothing to flush. */
ret = wolfSSH_TestSendPendingChannelWindowAdjust(ssh);
if (ret != WS_SUCCESS) { result = -1432; goto done; }
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch == NULL) { result = -1433; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1434;
goto done;
}
/* Park credit as a mid-rekey drain would. */
ch->pendingWindowAdjust = 10;
/* The flush blocks: the status must reach the caller, not be discarded. */
wolfSSH_SetIOSend(ctx, WantWriteIoSend);
ssh->error = WS_SUCCESS;
ret = wolfSSH_TestSendPendingChannelWindowAdjust(ssh);
if (ret != WS_WANT_WRITE) { result = -1435; goto done; }
if (wolfSSH_get_error(ssh) != WS_WANT_WRITE) { result = -1436; goto done; }
/* Bundled before the short write, so not re-parked. */
if (ch->pendingWindowAdjust != 0) { result = -1437; goto done; }
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* A drain whose window adjust hits a dead socket must surface the transport
* failure, not the WS_EXTDATA that prompted the drain. Drives the real
* receive path so ssh->error genuinely holds WS_EXTDATA first. */
static int test_ChannelReadExtHardFailureReported(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
byte pkt[32];
byte out[32];
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1440;
wolfSSH_SetIOSend(ctx, DiscardIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1441; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch == NULL) { result = -1442; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1443;
goto done;
}
s_recvPkt = pkt;
s_recvPktSz = BuildExtDataStderrPacket(pkt, ch->channel, 0x55);
s_recvPktOff = 0;
ret = wolfSSH_stream_read(ssh, out, (word32)sizeof(out));
if (ret != WS_EXTDATA) { result = -1444; goto done; }
/* The stale value the drain must not leave in place. */
if (wolfSSH_get_error(ssh) != WS_EXTDATA) { result = -1445; goto done; }
/* The peer drops the connection before the adjust goes out. */
wolfSSH_SetIOSend(ctx, FailIoSend);
ret = wolfSSH_extended_data_read(ssh, out, (word32)sizeof(out));
/* The bytes are in the caller's buffer, so they are still reported. */
if (ret != 10) { result = -1446; goto done; }
/* ...but the broken transport is visible, not the stale WS_EXTDATA. */
if (wolfSSH_get_error(ssh) != WS_SOCKET_ERROR_E) { result = -1447; goto done; }
/* The send discarded what it bundled, so the credit stays owed. */
if (ch->pendingWindowAdjust != 10) { result = -1448; goto done; }
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* Draining in a loop, as wolfssh/ssh.h mandates, must not resurrect a spent
* WS_WANT_WRITE. wolfSSH_SendPacket() does not clear ssh->error once it drains
* the output buffer, so restoring the saved value unconditionally leaves the
* caller polling for writability with nothing left to write. */
static int test_ChannelReadExtClearsStaleWantWrite(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
word32 idx;
byte out[10];
/* channelId=0, type=1 (stderr), dataSz=10 */
static const byte blobA[] = {
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x0A,
0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11
};
static const byte blobB[] = {
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x0A,
0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22
};
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1450;
wolfSSH_SetIOSend(ctx, DiscardIoSend);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1451; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch == NULL) { result = -1452; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1453;
goto done;
}
/* Two chunks, so the documented drain loop makes two passes. */
idx = 0;
ret = wolfSSH_TestDoChannelExtendedData(ssh, (byte*)blobA,
(word32)sizeof(blobA), &idx);
if (ret != WS_EXTDATA) { result = -1454; goto done; }
idx = 0;
ret = wolfSSH_TestDoChannelExtendedData(ssh, (byte*)blobB,
(word32)sizeof(blobB), &idx);
if (ret != WS_EXTDATA) { result = -1455; goto done; }
/* Pass 1 blocks: a flush is genuinely owed. */
wolfSSH_SetIOSend(ctx, WantWriteIoSend);
ret = wolfSSH_extended_data_read(ssh, out, (word32)sizeof(out));
if (ret != 10) { result = -1456; goto done; }
if (wolfSSH_get_error(ssh) != WS_WANT_WRITE) { result = -1457; goto done; }
/* Pass 2 succeeds and drains the output buffer completely. */
wolfSSH_SetIOSend(ctx, DiscardIoSend);
ret = wolfSSH_extended_data_read(ssh, out, (word32)sizeof(out));
if (ret != 10) { result = -1458; goto done; }
if (ssh->outputBuffer.length != 0) { result = -1459; goto done; }
/* Nothing is queued, so no flush may be reported as owed. */
if (wolfSSH_get_error(ssh) == WS_WANT_WRITE) { result = -1460; goto done; }
if (wolfSSH_get_error(ssh) != WS_SUCCESS) { result = -1461; goto done; }
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* A received SSH_MSG_CHANNEL_EOF is a notification, not a command to answer in
* kind: echoing it sets our eofTxd, and SendChannelData() refuses to send once
* that is set. RFC 4254 section 5.3 closes each direction independently.
*
* Covers the read side too: data buffered ahead of the EOF is still owed to
* the caller, so the EOF is reported only once that buffer is drained. */
static int test_ChannelEofHalfClose(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
int i;
word32 reportedId = 0xFFFFFFFF;
word32 pktSz;
byte pkt[48];
byte out[32];
byte payload[4] = { 0x10, 0x11, 0x12, 0x13 };
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1470;
wolfSSH_SetIOSend(ctx, DiscardIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1471; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch == NULL) { result = -1472; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1473;
goto done;
}
ch->openConfirmed = 1;
ch->peerWindowSz = 1024;
ch->peerMaxPacketSz = 1024;
/* The peer sends its last data and then stops talking, back to back. */
pktSz = BuildChannelDataPacket(pkt, ch->channel, 0x44);
pktSz += BuildChannelEofPacket(pkt + pktSz, ch->channel);
s_recvPkt = pkt;
s_recvPktSz = pktSz;
s_recvPktOff = 0;
ret = wolfSSH_worker(ssh, &reportedId);
if (ret != WS_CHAN_RXD) { result = -1474; goto done; }
if (reportedId != ch->channel) { result = -1475; goto done; }
reportedId = 0xFFFFFFFF;
ret = wolfSSH_worker(ssh, &reportedId);
if (ret != WS_EOF) { result = -1476; goto done; }
/* The caller must be able to tell which channel half-closed. */
if (reportedId != ch->channel) { result = -1477; goto done; }
if (!ch->eofRxd) { result = -1478; goto done; }
/* No auto-echo: our sending direction is untouched. */
if (ch->eofTxd) { result = -1479; goto done; }
/* The data that arrived ahead of the EOF is still deliverable. */
ret = wolfSSH_stream_peek(ssh, out, (word32)sizeof(out));
if (ret != 10) { result = -1480; goto done; }
ret = wolfSSH_stream_read(ssh, out, (word32)sizeof(out));
if (ret != 10) { result = -1481; goto done; }
for (i = 0; i < 10; i++)
if (out[i] != 0x44) { result = -1482; goto done; }
/* Drained: the reader now sees the EOF. */
ret = wolfSSH_stream_read(ssh, out, (word32)sizeof(out));
if (ret != WS_ERROR) { result = -1483; goto done; }
if (wolfSSH_get_error(ssh) != WS_EOF) { result = -1484; goto done; }
ret = wolfSSH_stream_peek(ssh, out, (word32)sizeof(out));
if (ret != WS_ERROR) { result = -1485; goto done; }
if (wolfSSH_get_error(ssh) != WS_EOF) { result = -1486; goto done; }
/* Half-closed one way: we can still answer the peer. */
ret = wolfSSH_stream_send(ssh, payload, (word32)sizeof(payload));
if (ret != (int)sizeof(payload)) { result = -1487; goto done; }
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* wolfSSH_ChannelExit() sends EOF and close, then leaves the channel on the
* list for the peer's own close to retire. Removing it there would free the
* caller's channel pointer and leave the peer's CHANNEL_CLOSE matching nothing,
* which DoReceive() turns into a fatal error on an ordinary shutdown. */
static int test_ChannelExitKeepsChannel(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
word32 pktSz;
byte pkt[16];
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1530;
wolfSSH_SetIOSend(ctx, DiscardIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1531; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch == NULL) { result = -1532; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1533;
goto done;
}
ch->openConfirmed = 1;
ch->peerWindowSz = 1024;
ch->peerMaxPacketSz = 1024;
ret = wolfSSH_ChannelExit(ch);
if (ret != WS_SUCCESS) { result = -1534; goto done; }
if (!ch->eofTxd) { result = -1535; goto done; }
if (!ch->closeTxd) { result = -1536; goto done; }
/* Still on the list, so the pointer the caller passed is still good. */
if (ssh->channelList != ch) { result = -1537; goto done; }
if (ssh->channelListSz != 1) { result = -1538; goto done; }
/* The peer answers with its own close. */
pktSz = BuildChannelClosePacket(pkt, ch->channel);
s_recvPkt = pkt;
s_recvPktSz = pktSz;
s_recvPktOff = 0;
ret = wolfSSH_worker(ssh, NULL);
if (ret != WS_CHANNEL_CLOSED) { result = -1539; goto done; }
/* Retired now, and by the peer's close rather than by the exit. */
if (ssh->channelList != NULL) { result = -1540; goto done; }
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* An EOF arriving on a channel that is not the head of the list is not the
* head's EOF. DoChannelEof() reports WS_EOF for whichever channel it lands on,
* so wolfSSH_stream_read() has to tell the two apart: the head is still open
* and still has nothing buffered, and WS_ERROR with WS_EOF latched is exactly
* what a real head EOF looks like. It keeps waiting instead. */
static int test_StreamReadEofOtherChannel(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch0 = NULL;
WOLFSSH_CHANNEL* ch1 = NULL;
int result = 0;
int ret;
byte pkt[32];
byte out[32];
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1550;
wolfSSH_SetIOSend(ctx, DiscardIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1551; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch0 = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch0 == NULL) { result = -1552; goto done; }
if (ChannelAppend(ssh, ch0) != WS_SUCCESS) {
ChannelDelete(ch0, ssh->ctx->heap);
result = -1553;
goto done;
}
ch1 = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch1 == NULL) { result = -1554; goto done; }
if (ChannelAppend(ssh, ch1) != WS_SUCCESS) {
ChannelDelete(ch1, ssh->ctx->heap);
result = -1555;
goto done;
}
/* The first channel appended is the head that stream_read() drains. */
if (ssh->channelList != ch0) { result = -1556; goto done; }
/* Stage an EOF for the non-head channel only. */
s_recvPkt = pkt;
s_recvPktSz = BuildChannelEofPacket(pkt, ch1->channel);
s_recvPktOff = 0;
/* The read consumes it, sees it is for another channel, and goes back for
* more. The mock has nothing left, so this ends as a want-read, not as
* the head channel's EOF. */
ret = wolfSSH_stream_read(ssh, out, (word32)sizeof(out));
if (ret >= 0) { result = -1557; goto done; }
if (wolfSSH_get_error(ssh) == WS_EOF) { result = -1558; goto done; }
if (wolfSSH_get_error(ssh) != WS_WANT_READ) { result = -1559; goto done; }
/* It landed where it belongs, and the head is untouched. */
if (!ch1->eofRxd) { result = -1560; goto done; }
if (ch0->eofRxd) { result = -1561; goto done; }
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
static byte s_sentBuf[512];
static word32 s_sentSz = 0;
/* Refuses the first s_sendRefusals writes with a would-block, then takes
* everything and keeps a copy of what reached the transport. */
static int RefuseThenCaptureIoSend(WOLFSSH* ssh, void* buf, word32 sz,
void* ctx)
{
WOLFSSH_UNUSED(ssh);
WOLFSSH_UNUSED(ctx);
if (s_sendRefusals > 0) {
s_sendRefusals--;
return WS_CBIO_ERR_WANT_WRITE;
}
if (s_sentSz + sz > (word32)sizeof(s_sentBuf))
return WS_CBIO_ERR_GENERAL;
WMEMCPY(s_sentBuf + s_sentSz, buf, sz);
s_sentSz += sz;
return (int)sz;
}
/* DoPacket() consumes the peer's CHANNEL_CLOSE whatever DoChannelClose()
* returns, so the reply gets one chance to be built. A blocked socket must not
* cost it: the EOF and the close both have to be bundled, and the channel
* retired, with the flush left owed to the caller. */
static int test_DoChannelCloseWantWrite(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
int sawEof = 0;
int sawClose = 0;
word32 chanId;
byte pkt[16];
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1570;
/* The socket takes nothing, so everything bundled stays in the buffer. */
wolfSSH_SetIOSend(ctx, WantWriteIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1571; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch == NULL) { result = -1572; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1573;
goto done;
}
ch->openConfirmed = 1;
ch->peerWindowSz = 1024;
ch->peerMaxPacketSz = 1024;
chanId = ch->channel;
/* The peer closes first. */
s_recvPkt = pkt;
s_recvPktSz = BuildChannelClosePacket(pkt, ch->channel);
s_recvPktOff = 0;
ret = wolfSSH_worker(ssh, NULL);
/* The channel is closed and named even though the flush is owed: a
* back-pressured socket is not a reason to withhold the close signal. */
if (ret != WS_CHANNEL_CLOSED) { result = -1574; goto done; }
if (ssh->lastRxId != chanId) { result = -1575; goto done; }
/* The channel is retired, so ch is freed and must not be read again. */
if (ssh->channelList != NULL) { result = -1576; goto done; }
if (ssh->channelListSz != 0) { result = -1579; goto done; }
/* Both packets are committed, and nothing will revisit the peer's close
* to build them later. Walk the queue and confirm both are there. */
sawEof = PlainPacketsHaveMsg(ssh->outputBuffer.buffer,
ssh->outputBuffer.idx, ssh->outputBuffer.length,
MSGID_CHANNEL_EOF);
sawClose = PlainPacketsHaveMsg(ssh->outputBuffer.buffer,
ssh->outputBuffer.idx, ssh->outputBuffer.length,
MSGID_CHANNEL_CLOSE);
if (!sawEof) { result = -1577; goto done; }
if (!sawClose) { result = -1578; goto done; }
/* And the owed flush is visible: the close is the return value, so
* WS_WANT_WRITE has to reach the caller some other way or the reply sits
* in the buffer while the caller closes the socket. */
if (wolfSSH_get_error(ssh) != WS_WANT_WRITE) { result = -1764; goto done; }
if (!wolfSSH_OutputPending(ssh)) { result = -1765; goto done; }
/* And they really do go out once the socket takes bytes again. */
wolfSSH_SetIOSend(ctx, DiscardIoSend);
ret = wolfSSH_SendPacket(ssh);
if (ret != WS_SUCCESS) { result = -1580; goto done; }
if (ssh->outputBuffer.length != 0) { result = -1581; goto done; }
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* The reply to the peer's close still has to reach the wire when the socket
* was full while it was bundled. DoChannelClose() reports WS_CHANNEL_CLOSED
* whatever the flush does and retires the channel, and every caller treats
* that as terminal, so wolfSSH_worker() owes the flush itself. */
static int test_DoChannelCloseFlushesReply(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
byte pkt[16];
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1610;
/* The socket refuses both sends DoChannelClose() makes -- the EOF's and
* the close's -- and takes bytes again by the time the worker flushes. */
s_sendRefusals = 2;
s_sentSz = 0;
wolfSSH_SetIOSend(ctx, RefuseThenCaptureIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1611; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch == NULL) { result = -1612; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1613;
goto done;
}
ch->openConfirmed = 1;
ch->peerWindowSz = 1024;
ch->peerMaxPacketSz = 1024;
/* The peer closes first. */
s_recvPkt = pkt;
s_recvPktSz = BuildChannelClosePacket(pkt, ch->channel);
s_recvPktOff = 0;
ret = wolfSSH_worker(ssh, NULL);
/* The flush is a courtesy, not the caller's business: it neither replaces
* the close status nor disturbs the latched error. */
if (ret != WS_CHANNEL_CLOSED) { result = -1614; goto done; }
if (wolfSSH_get_error(ssh) != WS_CHANNEL_CLOSED) {
result = -1615;
goto done;
}
/* Nothing is left owed, and both packets really went out. */
if (ssh->outputBuffer.length != 0) { result = -1616; goto done; }
if (!PlainPacketsHaveMsg(s_sentBuf, 0, s_sentSz, MSGID_CHANNEL_EOF)) {
result = -1617;
goto done;
}
if (!PlainPacketsHaveMsg(s_sentBuf, 0, s_sentSz, MSGID_CHANNEL_CLOSE)) {
result = -1618;
goto done;
}
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
s_sendRefusals = 0;
s_sentSz = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* The peer's close, with both of DoChannelClose()'s sends refused and the
* worker's flush then hitting a reset socket. wolfSSH_worker() reports the
* close in ret and ssh->error, not the send's WS_SOCKET_ERROR_E. */
static int test_DoChannelCloseHardFlushKeepsClose(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
byte pkt[16];
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1790;
/* Two refusals cover the EOF and the close it sends. */
s_sendRefusals = 2;
wolfSSH_SetIOSend(ctx, RefuseThenResetIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1791; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch == NULL) { result = -1792; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1793;
goto done;
}
ch->openConfirmed = 1;
ch->peerWindowSz = 1024;
ch->peerMaxPacketSz = 1024;
s_recvPkt = pkt;
s_recvPktSz = BuildChannelClosePacket(pkt, ch->channel);
s_recvPktOff = 0;
ret = wolfSSH_worker(ssh, NULL);
if (ret != WS_CHANNEL_CLOSED) { result = -1794; goto done; }
if (wolfSSH_get_error(ssh) != WS_CHANNEL_CLOSED) {
result = -1795;
goto done;
}
done:
s_sendRefusals = 0;
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#ifdef WOLFSSH_SFTP
static int s_recvCalls = 0;
/* Counts the polls, so a test can prove the wire was never touched. */
static int CountingIoRecv(WOLFSSH* ssh, void* buf, word32 sz, void* ctx)
{
WOLFSSH_UNUSED(ssh);
WOLFSSH_UNUSED(buf);
WOLFSSH_UNUSED(sz);
WOLFSSH_UNUSED(ctx);
s_recvCalls++;
return WS_CBIO_ERR_WANT_READ;
}
/* The SFTP read must not poll a channel that has latched its EOF and been
* drained. No further data can arrive, so the poll cannot finish the message
* and only overwrites the latched WS_EOF with WS_WANT_READ, which the SFTP
* loops read as "come back later" -- or blocks outright on a blocking
* socket. */
static int test_SftpReadEofNoPoll(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1620;
wolfSSH_SetIOSend(ctx, DiscardIoSend);
wolfSSH_SetIORecv(ctx, CountingIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1621; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch == NULL) { result = -1622; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1623;
goto done;
}
ch->openConfirmed = 1;
ch->peerWindowSz = 1024;
ch->peerMaxPacketSz = 1024;
/* The peer half-closed and everything it sent has been read. */
ch->eofRxd = 1;
s_recvCalls = 0;
ret = wolfSSH_SFTP_read(ssh);
if (ret != WS_FATAL_ERROR) { result = -1624; goto done; }
if (wolfSSH_get_error(ssh) != WS_EOF) { result = -1625; goto done; }
if (s_recvCalls != 0) { result = -1626; goto done; }
done:
s_recvCalls = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* WOLFSSH_SFTP */
/* DoReceive() can retire the head channel mid-read: DoChannelClose() frees it
* while wolfSSH_stream_read() still holds its inputBuffer. If the next head
* already has its EOF latched and drained, the EOF override fires while
* lastRxId names the channel that just went away, so the "keep waiting" path
* must not loop -- doing so spins forever on freed memory, and both messages
* that get there are peer-controlled. */
static int test_StreamReadHeadRemoved(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch0 = NULL;
WOLFSSH_CHANNEL* ch1 = NULL;
int result = 0;
int ret;
byte pkt[16];
byte out[32];
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1590;
wolfSSH_SetIOSend(ctx, DiscardIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1591; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch0 = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch0 == NULL) { result = -1592; goto done; }
if (ChannelAppend(ssh, ch0) != WS_SUCCESS) {
ChannelDelete(ch0, ssh->ctx->heap);
result = -1593;
goto done;
}
ch0->openConfirmed = 1;
ch0->peerWindowSz = 1024;
ch0->peerMaxPacketSz = 1024;
ch1 = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch1 == NULL) { result = -1594; goto done; }
if (ChannelAppend(ssh, ch1) != WS_SUCCESS) {
ChannelDelete(ch1, ssh->ctx->heap);
result = -1595;
goto done;
}
/* The other channel is already half-closed, with nothing buffered. */
ch1->eofRxd = 1;
/* The peer closes the channel the read is draining. */
s_recvPkt = pkt;
s_recvPktSz = BuildChannelClosePacket(pkt, ch0->channel);
s_recvPktOff = 0;
/* Must return rather than spin. */
ret = wolfSSH_stream_read(ssh, out, (word32)sizeof(out));
if (ret >= 0) { result = -1596; goto done; }
/* ch0 is retired; ch1 is untouched and still on the list. */
if (ssh->channelListSz != 1) { result = -1597; goto done; }
if (ssh->channelList != ch1) { result = -1598; goto done; }
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#ifndef NO_WOLFSSH_CLIENT
/* The same retirement through DoChannelOpenFail(), which is the case that
* needs the head test: it removes the channel without touching lastRxId, so
* lastRxId still names another channel and the "keep waiting" path would fire
* on a head that has just been freed. The staged packets arrive in one read:
* the EOF for the other channel sets lastRxId away from the head, then the
* open failure takes the head out from under the read in progress. */
static int test_StreamReadHeadOpenFailed(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch0 = NULL;
WOLFSSH_CHANNEL* ch1 = NULL;
int result = 0;
int ret;
byte pkt[48];
byte out[32];
word32 pktSz;
word32 headId = 0;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -1696;
wolfSSH_SetIOSend(ctx, DiscardIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1697; goto done; }
ssh->connectState = CONNECT_SERVER_USERAUTH_ACCEPT_DONE;
/* The head, a channel of ours whose open the peer has not answered. */
ch0 = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch0 == NULL) { result = -1698; goto done; }
if (ChannelAppend(ssh, ch0) != WS_SUCCESS) {
ChannelDelete(ch0, ssh->ctx->heap);
result = -1699;
goto done;
}
ch1 = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch1 == NULL) { result = -1700; goto done; }
if (ChannelAppend(ssh, ch1) != WS_SUCCESS) {
ChannelDelete(ch1, ssh->ctx->heap);
result = -1701;
goto done;
}
ch1->openConfirmed = 1;
ch1->peerWindowSz = 1024;
ch1->peerMaxPacketSz = 1024;
/* ch0 is freed by the open failure, so keep what is needed from it. */
headId = ch0->channel;
pktSz = BuildChannelEofPacket(pkt, ch1->channel);
pktSz += BuildChannelOpenFailPacket(pkt + pktSz, headId,
OPEN_ADMINISTRATIVELY_PROHIBITED);
s_recvPkt = pkt;
s_recvPktSz = pktSz;
s_recvPktOff = 0;
/* Must return rather than spin on the freed head. */
ret = wolfSSH_stream_read(ssh, out, (word32)sizeof(out));
if (ret >= 0) { result = -1702; goto done; }
/* ch0 is gone; the other channel took the head and kept its EOF. */
if (ssh->channelListSz != 1) { result = -1703; goto done; }
if (ssh->channelList != ch1) { result = -1704; goto done; }
if (!ch1->eofRxd) { result = -1705; goto done; }
if (ssh->lastRxId == headId) { result = -1706; goto done; }
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* NO_WOLFSSH_CLIENT */
/* A peer may half-close its channel before it makes its shell/exec/subsystem
* request, RFC 4254 section 5.3. DoChannelEof() reports that as WS_EOF, and
* DoReceive() passes it through, but the accept loop must not read a negative
* return as a dead handshake and tear the session down. */
static int test_AcceptSurvivesChannelEof(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
byte pkt[16];
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1640;
wolfSSH_SetIOSend(ctx, DiscardIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1641; goto done; }
/* Userauth is done and the peer's channel is open. The accept loop is
* waiting on the channel request. */
ssh->acceptState = ACCEPT_SERVER_CHANNEL_ACCEPT_SENT;
ssh->clientState = CLIENT_CHANNEL_OPEN_DONE;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch == NULL) { result = -1642; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1643;
goto done;
}
ch->openConfirmed = 1;
ch->peerWindowSz = 1024;
ch->peerMaxPacketSz = 1024;
s_recvPkt = pkt;
s_recvPktSz = BuildChannelEofPacket(pkt, ch->channel);
s_recvPktOff = 0;
ret = wolfSSH_accept(ssh);
/* The staged packet is the only input, so the accept stops wanting more
* of it. What matters is that WS_EOF is not what it stopped on. */
if (ret != WS_FATAL_ERROR) { result = -1644; goto done; }
if (wolfSSH_get_error(ssh) == WS_EOF) { result = -1645; goto done; }
if (wolfSSH_get_error(ssh) != WS_WANT_READ) { result = -1646; goto done; }
/* The half-close still reached the channel. */
if (!ch->eofRxd) { result = -1647; goto done; }
if (!wolfSSH_ChannelGetEof(ch)) { result = -1648; goto done; }
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* The client's two handshake loops take DoReceiveHandshake() as well, and a
* server may half-close before answering the channel request. Same shape as
* test_AcceptSurvivesChannelEof(), from the other end. Guarded on its own:
* wolfSSH_connect() is not built with NO_WOLFSSH_CLIENT. */
#ifndef NO_WOLFSSH_CLIENT
static int test_ConnectSurvivesChannelEof(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
byte pkt[16];
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -1770;
wolfSSH_SetIOSend(ctx, DiscardIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1771; goto done; }
/* The connect loop is waiting on the channel request to be answered. */
ssh->connectState = CONNECT_CLIENT_CHANNEL_REQUEST_SENT;
ssh->serverState = SERVER_CHANNEL_OPEN_DONE;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch == NULL) { result = -1772; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1773;
goto done;
}
ch->openConfirmed = 1;
ch->peerWindowSz = 1024;
ch->peerMaxPacketSz = 1024;
s_recvPkt = pkt;
s_recvPktSz = BuildChannelEofPacket(pkt, ch->channel);
s_recvPktOff = 0;
ret = wolfSSH_connect(ssh);
/* As with accept: it stops wanting more input, not on the EOF. */
if (ret != WS_FATAL_ERROR) { result = -1774; goto done; }
if (wolfSSH_get_error(ssh) == WS_EOF) { result = -1775; goto done; }
if (wolfSSH_get_error(ssh) != WS_WANT_READ) { result = -1776; goto done; }
if (!ch->eofRxd) { result = -1777; goto done; }
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* NO_WOLFSSH_CLIENT */
/* wolfSSH_worker() exempts WS_EOF from the rekey mask, the same way it exempts
* WS_EXTDATA: the EOF is raised once, on arrival, so masking it as WS_REKEYING
* would strand the event. The drain guards in wolfsshd and the echoservers
* depend on this combination being reachable. */
static int test_WorkerReportsEofChannelKeying(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
word32 reportedId = 0xFFFFFFFF;
byte pkt[16];
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1600;
wolfSSH_SetIOSend(ctx, DiscardIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1601; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch == NULL) { result = -1602; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1603;
goto done;
}
s_recvPkt = pkt;
s_recvPktSz = BuildChannelEofPacket(pkt, ch->channel);
s_recvPktOff = 0;
/* A rekey is underway when the EOF lands. */
ssh->isKeying = WOLFSSH_SELF_IS_KEYING;
ret = wolfSSH_worker(ssh, &reportedId);
if (ret != WS_EOF) { result = -1604; goto done; }
if (reportedId != ch->channel) { result = -1605; goto done; }
if (!ch->eofRxd) { result = -1606; goto done; }
/* And peek still says "rekeying", not "drained" -- which is why the drain
* guards have to tell the two apart. */
ret = wolfSSH_stream_peek(ssh, NULL, 1);
if (ret != WS_REKEYING) { result = -1607; goto done; }
/* The new send-EOF API refuses to put a packet between KEXINIT and
* NEWKEYS. */
ret = wolfSSH_ChannelSendEof(ch);
if (ret != WS_REKEYING) { result = -1608; goto done; }
if (ch->eofTxd) { result = -1609; goto done; }
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* NO_WOLFSSH_SERVER */
#ifndef NO_WOLFSSH_CLIENT
/* A high water mark firing on wolfSSH_shutdown()'s read sends a KEXINIT.
* If the socket will not take it, the teardown must not return success. */
static int test_ShutdownReportsWorkerOwedFlush(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
byte pkt[32];
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -1860;
wolfSSH_SetIOSend(ctx, WantWriteIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1861; goto done; }
ssh->connectState = CONNECT_SERVER_USERAUTH_ACCEPT_DONE;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch == NULL) { result = -1862; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1863;
goto done;
}
ch->openConfirmed = 1;
ch->peerWindowSz = 1024;
ch->peerMaxPacketSz = 1024;
/* The teardown sends are already done, so the read is all that is left
* and the output buffer is empty going into it. */
ch->eofTxd = 1;
ch->closeTxd = 1;
/* The mark fires on the first packet received. */
if (wolfSSH_SetHighwater(ssh, 1) != WS_SUCCESS) {
result = -1864;
goto done;
}
s_recvPkt = pkt;
s_recvPktSz = BuildChannelDataPacket(pkt, ch->channel, 0xAA);
s_recvPktOff = 0;
ret = wolfSSH_shutdown(ssh);
if (ret != WS_WANT_WRITE) { result = -1865; goto done; }
if (!wolfSSH_OutputPending(ssh)) { result = -1866; goto done; }
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* NO_WOLFSSH_CLIENT */
#ifndef NO_WOLFSSH_SERVER
/* A clean receive with the flush short: no event to report, so the send's
* status is the whole of what the pass has to say and takes the return. */
static int test_WorkerCleanReceiveReportsShortFlush(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
byte pkt[32];
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1880;
wolfSSH_SetIOSend(ctx, CountIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1881; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 128, 64);
if (ch == NULL) { result = -1882; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1883;
goto done;
}
if (WorkerParkAdjust(ctx, ssh, ch) != WS_SUCCESS) {
result = -1884;
goto done;
}
/* The peer credits the window, which carries no channel event. */
s_recvPkt = pkt;
s_recvPktSz = BuildWindowAdjustPacket(pkt, ch->channel, 256);
s_recvPktOff = 0;
wolfSSH_SetIOSend(ctx, WantWriteIoSend);
ret = wolfSSH_worker(ssh, NULL);
if (ret != WS_WANT_WRITE) { result = -1885; goto done; }
if (!wolfSSH_OutputPending(ssh)) { result = -1886; goto done; }
/* The credit landed, so the receive did report a clean WS_SUCCESS. */
if (ch->peerWindowSz != 256) { result = -1887; goto done; }
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* NO_WOLFSSH_SERVER */
#ifndef NO_WOLFSSH_CLIENT
/* The mark fires from inside wolfSSH_SendPacket() on a flush that went out.
* The status the pass was already carrying has to survive that. */
static int test_HighwaterRekeyKeepsError(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
int result = 0;
int ret;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -1890;
wolfSSH_SetIOSend(ctx, DiscardIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1891; goto done; }
/* Queued output, so the flush has something to carry out. */
ssh->outputBuffer.length = 1;
ssh->outputBuffer.idx = 0;
ssh->outputBuffer.buffer[0] = 0;
/* The mark is due on this flush. */
if (wolfSSH_SetHighwater(ssh, 1) != WS_SUCCESS) {
result = -1892;
goto done;
}
ssh->txCount = 1;
ssh->error = WS_CHANNEL_CLOSED;
ret = wolfSSH_SendPacket(ssh);
if (ret != WS_SUCCESS) { result = -1893; goto done; }
if (!ssh->highwaterFlag) { result = -1894; goto done; }
if (!ssh->isKeying) { result = -1895; goto done; }
if (wolfSSH_get_error(ssh) != WS_CHANNEL_CLOSED) {
result = -1896;
goto done;
}
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* A rekey that starts cleanly leaves ssh->error alone. It runs from
* HighwaterCheck() inside wolfSSH_SendPacket(), so writing WS_SUCCESS there
* would erase what the pass the mark fired on had already reported. */
static int test_TriggerKeyExchangeKeepsError(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
int result = 0;
int ret;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -1820;
wolfSSH_SetIOSend(ctx, CountIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1821; goto done; }
/* The status the pass was carrying when the mark fired. */
ssh->error = WS_CHANNEL_CLOSED;
ret = wolfSSH_TriggerKeyExchange(ssh);
if (ret != WS_SUCCESS) { result = -1822; goto done; }
if (wolfSSH_get_error(ssh) != WS_CHANNEL_CLOSED) {
result = -1823;
goto done;
}
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* Covers a KEX init the transport rejects, one it refuses with a
* would-block, and one it takes whole with a highwater callback that fails
* or reads the keying flag. */
static int test_KexInitSendAwayGatesKeying(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
HwTestCtx hc;
int result = 0;
int ret;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -1925;
/* No refusals, so the first write resets the socket. */
s_sendRefusals = 0;
wolfSSH_SetIOSend(ctx, RefuseThenResetIoSend);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1926; goto done; }
ret = wolfSSH_TriggerKeyExchange(ssh);
if (ret != WS_SOCKET_ERROR_E) { result = -1927; goto done; }
if (wolfSSH_RekeyPending(ssh)) { result = -1928; goto done; }
if (wolfSSH_OutputPending(ssh)) { result = -1929; goto done; }
wolfSSH_free(ssh);
ssh = NULL;
/* One refusal leaves the packet framed and owed instead. */
s_sendRefusals = 1;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1930; goto done; }
ret = wolfSSH_TriggerKeyExchange(ssh);
if (ret != WS_WANT_WRITE) { result = -1931; goto done; }
if (!wolfSSH_RekeyPending(ssh)) { result = -1932; goto done; }
if (!wolfSSH_OutputPending(ssh)) { result = -1933; goto done; }
wolfSSH_free(ssh);
ssh = NULL;
wolfSSH_CTX_free(ctx);
ctx = NULL;
/* The transport takes the whole packet and the highwater callback then
* fails, so the error arrives with the KEX init already sent. */
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL) { result = -1934; goto done; }
wolfSSH_SetIOSend(ctx, DiscardIoSend);
wolfSSH_SetHighwaterCb(ctx, 1, FailHighwater);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1935; goto done; }
ret = wolfSSH_TriggerKeyExchange(ssh);
if (ret == WS_SUCCESS) { result = -1936; goto done; }
if (!wolfSSH_RekeyPending(ssh)) { result = -1937; goto done; }
wolfSSH_free(ssh);
ssh = NULL;
wolfSSH_CTX_free(ctx);
ctx = NULL;
/* The highwater callback runs from the KEX init's own flush, with the
* packet already on the wire. */
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL) { result = -1938; goto done; }
wolfSSH_SetIOSend(ctx, DiscardIoSend);
wolfSSH_SetHighwaterCb(ctx, 1, HwTestCb);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1939; goto done; }
WMEMSET(&hc, 0, sizeof(hc));
hc.ssh = ssh;
wolfSSH_SetHighwaterCtx(ssh, &hc);
ret = wolfSSH_TriggerKeyExchange(ssh);
if (ret != WS_SUCCESS) { result = -1940; goto done; }
if (hc.count != 1 || !hc.keying) { result = -1941; goto done; }
done:
s_sendRefusals = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* NO_WOLFSSH_CLIENT */
#ifndef NO_WOLFSSH_CLIENT
/* wolfSSH_stream_send_eof() and wolfSSH_ChannelSendEof() close the
* application's own sending direction. Sends afterwards must fail, reads must
* not, and a second call must not put a second EOF on the wire. */
static int test_SendEofApi(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
byte buf[4] = { 0x00, 0x01, 0x02, 0x03 };
if (wolfSSH_stream_send_eof(NULL) != WS_BAD_ARGUMENT)
return -1490;
if (wolfSSH_ChannelSendEof(NULL) != WS_BAD_ARGUMENT)
return -1491;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -1492;
wolfSSH_SetIOSend(ctx, DiscardIoSend);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1493; goto done; }
/* Connection-protocol messages are only allowed once userauth is done. */
ssh->connectState = CONNECT_SERVER_USERAUTH_ACCEPT_DONE;
/* No channel yet: nothing to half-close. */
if (wolfSSH_stream_send_eof(ssh) != WS_BAD_ARGUMENT) {
result = -1494;
goto done;
}
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION,
DEFAULT_WINDOW_SZ, DEFAULT_MAX_PACKET_SZ);
if (ch == NULL) { result = -1495; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1496;
goto done;
}
ch->openConfirmed = 1;
ch->peerWindowSz = 1024;
ch->peerMaxPacketSz = 1024;
ret = wolfSSH_stream_send(ssh, buf, (word32)sizeof(buf));
if (ret != (int)sizeof(buf)) { result = -1497; goto done; }
ret = wolfSSH_stream_send_eof(ssh);
if (ret != WS_SUCCESS) { result = -1498; goto done; }
if (!ch->eofTxd) { result = -1499; goto done; }
/* Our direction is closed. */
ret = wolfSSH_stream_send(ssh, buf, (word32)sizeof(buf));
if (ret != WS_EOF) { result = -1500; goto done; }
/* Idempotent: the second call must not reach the transport at all.
* DiscardIoSend flushes everything, so outputBuffer.length is 0 either
* way and could not tell a second EOF from none. */
wolfSSH_SetIOSend(ctx, CountingIoSend);
s_ioSendCalls = 0;
ret = wolfSSH_ChannelSendEof(ch);
if (ret != WS_SUCCESS) { result = -1501; goto done; }
if (s_ioSendCalls != 0) { result = -1502; goto done; }
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* NO_WOLFSSH_CLIENT */
#ifndef NO_WOLFSSH_CLIENT
/* A disconnect, sent or received, ends the session, so neither send-EOF
* entry point may put a CHANNEL_EOF on the wire afterwards. RFC 4253
* section 11.1. */
static int test_SendEofAfterDisconnect(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -1660;
wolfSSH_SetIOSend(ctx, CountingIoSend);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1661; goto done; }
ssh->connectState = CONNECT_SERVER_USERAUTH_ACCEPT_DONE;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION,
DEFAULT_WINDOW_SZ, DEFAULT_MAX_PACKET_SZ);
if (ch == NULL) { result = -1662; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1663;
goto done;
}
ch->openConfirmed = 1;
ch->peerWindowSz = 1024;
ch->peerMaxPacketSz = 1024;
/* Our own disconnect is the last thing that may go out. */
ret = wolfSSH_SendDisconnect(ssh, WOLFSSH_DISCONNECT_BY_APPLICATION);
if (ret != WS_SUCCESS) { result = -1664; goto done; }
if (!ssh->disconnected) { result = -1665; goto done; }
s_ioSendCalls = 0;
ret = wolfSSH_stream_send_eof(ssh);
if (ret != WS_FATAL_ERROR) { result = -1666; goto done; }
if (wolfSSH_get_error(ssh) != WS_DISCONNECT) { result = -1667; goto done; }
ret = wolfSSH_ChannelSendEof(ch);
if (ret != WS_FATAL_ERROR) { result = -1668; goto done; }
if (wolfSSH_get_error(ssh) != WS_DISCONNECT) { result = -1669; goto done; }
/* Nothing reached the transport and the channel is unmarked, so a
* later drain cannot mistake it for a half-close of ours. */
if (s_ioSendCalls != 0) { result = -1670; goto done; }
if (ch->eofTxd) { result = -1671; goto done; }
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* NO_WOLFSSH_CLIENT */
#if !defined(NO_WOLFSSH_CLIENT) && defined(HAVE_SOCKETPAIR) && \
defined(WSHUTDOWN)
/* The drain helpers run over a real socket, so these use a socket pair with
* the session on one end and the test playing the peer on the other. The
* send callback optionally reports one would-block first. */
static int s_drainWantWrites = 0;
/* A send to a peer that is gone has to fail, not raise SIGPIPE. */
#ifdef MSG_NOSIGNAL
#define DRAIN_SEND_FLAGS MSG_NOSIGNAL
#else
#define DRAIN_SEND_FLAGS 0
#endif
static int DrainSocketIoSend(WOLFSSH* ssh, void* buf, word32 sz, void* ctx)
{
ssize_t n;
(void)ssh;
if (s_drainWantWrites > 0) {
s_drainWantWrites--;
return WS_CBIO_ERR_WANT_WRITE;
}
n = send(*(SOCKET_T*)ctx, buf, sz, DRAIN_SEND_FLAGS);
return (n < 0) ? WS_CBIO_ERR_GENERAL : (int)n;
}
enum {
DRAIN_PEER_HANGS_UP,
DRAIN_SHORT_SEND,
DRAIN_ALREADY_DISCONNECTED,
DRAIN_HALF_CLOSE_ONLY,
DRAIN_QUEUED_DISCONNECT,
DRAIN_PEER_GONE
};
/* Returns 0 when the helper returned want and the peer saw the disconnect
* on the wire, or saw nothing where nothing was meant to be sent. */
static int RunDrainCase(int mode, int want, int base)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
SOCKET_T sv[2] = { -1, -1 };
byte buf[256];
int result = 0;
int ret;
ssize_t n;
if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) != 0)
return base;
#ifdef SO_NOSIGPIPE
{
int on = 1;
(void)setsockopt(sv[0], SOL_SOCKET, SO_NOSIGPIPE, &on, sizeof(on));
}
#endif
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL) { result = base - 1; goto done; }
wolfSSH_SetIOSend(ctx, DrainSocketIoSend);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = base - 2; goto done; }
ssh->connectState = CONNECT_SERVER_USERAUTH_ACCEPT_DONE;
wolfSSH_SetIOWriteCtx(ssh, &sv[0]);
(void)shutdown(sv[1], SHUT_WR); /* the peer hangs up */
if (mode == DRAIN_PEER_GONE) {
/* and is gone before the disconnect goes out */
close(sv[1]);
sv[1] = -1;
}
if (mode == DRAIN_SHORT_SEND)
s_drainWantWrites = 1;
if (mode == DRAIN_ALREADY_DISCONNECTED)
ssh->disconnected = 1; /* the peer's disconnect came first */
if (mode == DRAIN_QUEUED_DISCONNECT) {
/* a short send leaves our own disconnect queued */
s_drainWantWrites = 1;
ret = wolfSSH_SendDisconnect(ssh, WOLFSSH_DISCONNECT_BY_APPLICATION);
if (ret != WS_WANT_WRITE || !wolfSSH_OutputPending(ssh)) {
result = base - 7;
goto done;
}
}
if (mode == DRAIN_HALF_CLOSE_ONLY || mode == DRAIN_QUEUED_DISCONNECT)
ret = HalfCloseAndDrain(ssh, sv[0]);
else
ret = SendDisconnectAndDrain(ssh, sv[0]);
/* the would-block was consumed, so the retry loop really ran */
if (s_drainWantWrites != 0) { result = base - 6; goto done; }
if (ret != want) { result = base - 3; goto done; }
/* The helper half closed its end, so the peer reads what was sent
* and then EOF. */
if (mode == DRAIN_PEER_GONE)
goto done;
n = recv(sv[1], buf, sizeof(buf), MSG_DONTWAIT);
if (mode == DRAIN_ALREADY_DISCONNECTED || mode == DRAIN_HALF_CLOSE_ONLY) {
if (n != 0) { result = base - 4; goto done; }
}
else if (n <= 0) {
result = base - 5;
}
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
if (sv[0] != -1)
close(sv[0]);
if (sv[1] != -1)
close(sv[1]);
return result;
}
/* The disconnect goes out and the peer's hang up ends the drain. */
static int test_DrainPeerHangsUp(void)
{
return RunDrainCase(DRAIN_PEER_HANGS_UP, WS_SUCCESS, -2100);
}
/* A would-block on the first send leaves the disconnect queued; the retry
* flushes it and the drain still completes. */
static int test_DrainRetriesShortSend(void)
{
return RunDrainCase(DRAIN_SHORT_SEND, WS_SUCCESS, -2110);
}
/* The peer disconnected first, so nothing is sent but its hang up is still
* waited for and reported as success. */
static int test_DrainPeerAlreadyDisconnected(void)
{
return RunDrainCase(DRAIN_ALREADY_DISCONNECTED, WS_SUCCESS, -2120);
}
/* The server's path: nothing goes out, the half close alone ends the
* session and the peer's hang up is still seen. */
static int test_DrainHalfCloseOnly(void)
{
return RunDrainCase(DRAIN_HALF_CLOSE_ONLY, WS_SUCCESS, -2130);
}
/* A disconnect of our own that a short send left queued still has to go
* out, though the session is already disconnected and the worker refuses
* to send on it. */
static int test_DrainFlushesQueuedDisconnect(void)
{
return RunDrainCase(DRAIN_QUEUED_DISCONNECT, WS_SUCCESS, -2140);
}
/* The peer closed the connection after the close exchange, so the
* disconnect send fails, and that is the peer having hung up. */
static int test_DrainPeerGone(void)
{
return RunDrainCase(DRAIN_PEER_GONE, WS_SUCCESS, -2150);
}
/* A rekey in flight when the session ends never finishes, so the drain must
* not wait on it. The peer stays quiet until it reads our half close, then
* hangs up: a drain that waited would sit out its deadline. */
static int RunDrainMidRekey(int sendDisconnect, int base)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
SOCKET_T sv[2] = { -1, -1 };
pid_t pid;
time_t start;
int status;
int result = 0;
int ret;
if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) != 0)
return base;
pid = fork();
if (pid < 0) {
close(sv[0]);
close(sv[1]);
return base - 1;
}
if (pid == 0) {
char buf[256];
struct timeval to = { 0, 100000 };
ssize_t got;
close(sv[0]);
/* macOS can miss waking a read() that blocks just as the peer
* half closes, so time the read out and retry. */
(void)setsockopt(sv[1], SOL_SOCKET, SO_RCVTIMEO, &to, sizeof(to));
for (;;) {
got = read(sv[1], buf, sizeof(buf));
if (got > 0)
continue;
if (got < 0 && (errno == EAGAIN || errno == EWOULDBLOCK ||
errno == EINTR))
continue;
break;
}
_exit(0);
}
close(sv[1]);
sv[1] = -1;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL) { result = base - 2; goto done; }
wolfSSH_SetIOSend(ctx, DrainSocketIoSend);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = base - 3; goto done; }
ssh->connectState = CONNECT_SERVER_USERAUTH_ACCEPT_DONE;
wolfSSH_SetIOWriteCtx(ssh, &sv[0]);
ssh->isKeying = WOLFSSH_SELF_IS_KEYING;
start = WTIME(NULL);
if (sendDisconnect) {
ret = SendDisconnectAndDrain(ssh, sv[0]);
}
else {
ssh->error = WS_PARSE_E; /* the key exchange failed */
ret = HalfCloseAndDrain(ssh, sv[0]);
}
if (ret != WS_SUCCESS) { result = base - 4; goto done; }
if (WTIME(NULL) - start > 2) { result = base - 5; goto done; }
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
close(sv[0]);
if (waitpid(pid, &status, 0) != pid && result == 0)
result = base - 6;
return result;
}
/* A key exchange that failed leaves the rekey pending for good. */
static int test_DrainFailedRekey(void)
{
return RunDrainMidRekey(0, -2180);
}
/* Our own disconnect mid-rekey ends the session too. */
static int test_DrainDisconnectMidRekey(void)
{
return RunDrainMidRekey(1, -2190);
}
/* A session an error already ended has no close coming, so the wait reports
* that error at once instead of sitting out its deadline on a peer that is
* still connected. */
static int test_WaitForChannelCloseSessionOver(void)
{
static const int errs[] = { WS_OVERFLOW_E, WS_DISCONNECT };
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
SOCKET_T sv[2] = { -1, -1 };
time_t start;
int result = 0;
int ret;
word32 i;
if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) != 0)
return -2170;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL) { result = -2171; goto done; }
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -2172; goto done; }
ssh->connectState = CONNECT_SERVER_USERAUTH_ACCEPT_DONE;
wolfSSH_set_fd(ssh, sv[0]);
for (i = 0; i < sizeof(errs) / sizeof(errs[0]); i++) {
ssh->error = errs[i];
start = WTIME(NULL);
ret = WaitForChannelClose(ssh, sv[0]);
if (ret != errs[i]) { result = -2173; goto done; }
if (WTIME(NULL) - start > 1) { result = -2174; goto done; }
}
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
close(sv[0]);
close(sv[1]);
return result;
}
#if defined(WOLFSSH_TEST_INTERNAL) && \
(defined(WOLFSSH_TERM) || defined(WOLFSSH_SHELL))
/* Builds a plaintext CHANNEL_REQUEST exit-status packet into pkt (needs 40
* bytes), returning its size. */
static word32 BuildExitStatusPacket(byte* pkt, word32 channelId,
word32 status)
{
word32 i = 0;
/* packet_length = padLen(1) + payload(25) + padding(10) = 36. */
PutU32BE(pkt + i, 36); i += 4;
pkt[i++] = 10;
pkt[i++] = MSGID_CHANNEL_REQUEST;
PutU32BE(pkt + i, channelId); i += 4;
PutU32BE(pkt + i, 11); i += 4;
WMEMCPY(pkt + i, "exit-status", 11); i += 11;
pkt[i++] = 0; /* want reply */
PutU32BE(pkt + i, status); i += 4;
WMEMSET(pkt + i, 0, 10); i += 10;
return i; /* 40 */
}
/* Builds a plaintext empty IGNORE packet into pkt (needs 16 bytes),
* returning its size. */
static word32 BuildIgnorePacket(byte* pkt)
{
word32 i = 0;
/* packet_length = padLen(1) + msgid(1) + string(4) + padding(6) = 12. */
PutU32BE(pkt + i, 12); i += 4;
pkt[i++] = 6;
pkt[i++] = MSGID_IGNORE;
PutU32BE(pkt + i, 0); i += 4;
WMEMSET(pkt + i, 0, 6); i += 6;
return i; /* 16 */
}
/* The client read loop stops at the peer's EOF, and the peer sends one more
* message before its exit status. The worker pass inside wolfSSH_shutdown()
* takes that one, so the exit status is parsed only if the close is waited
* for ahead of the drain, which discards what it reads. */
static int test_WaitForChannelCloseKeepsExitStatus(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch;
SOCKET_T sv[2] = { -1, -1 };
byte pkt[128];
word32 sz = 0;
int result = 0;
int ret;
if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) != 0)
return -2160;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL) { result = -2161; goto done; }
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -2162; goto done; }
ssh->connectState = CONNECT_SERVER_USERAUTH_ACCEPT_DONE;
wolfSSH_set_fd(ssh, sv[0]);
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch == NULL) { result = -2163; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -2164;
goto done;
}
sz += BuildChannelEofPacket(pkt + sz, ch->channel);
sz += BuildIgnorePacket(pkt + sz);
sz += BuildExitStatusPacket(pkt + sz, ch->channel, 42);
sz += BuildChannelClosePacket(pkt + sz, ch->channel);
if (send(sv[1], pkt, sz, 0) != (ssize_t)sz) { result = -2165; goto done; }
(void)wolfSSH_worker(ssh, NULL); /* the read loop's EOF */
ret = wolfSSH_shutdown(ssh);
if (ret == WS_CHANNEL_CLOSED) { result = -2166; goto done; }
ret = WaitForChannelClose(ssh, sv[0]);
if (ret != WS_SUCCESS) { result = -2167; goto done; }
if (wolfSSH_GetExitStatus(ssh) != 42) { result = -2168; goto done; }
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
if (sv[0] != -1)
close(sv[0]);
if (sv[1] != -1)
close(sv[1]);
return result;
}
#endif /* WOLFSSH_TEST_INTERNAL && (WOLFSSH_TERM || WOLFSSH_SHELL) */
#endif /* !NO_WOLFSSH_CLIENT && HAVE_SOCKETPAIR && WSHUTDOWN */
#ifndef NO_WOLFSSH_CLIENT
/* SendChannelEof() addresses the channel by peer id, and peerChannel is 0
* until the peer confirms the open. wolfSSH_ChannelSendEof() on a channel
* still awaiting its confirmation must refuse rather than let the lookup land
* on whichever channel already holds peer id 0. */
static int test_SendEofUnconfirmedChannel(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* sess = NULL;
WOLFSSH_CHANNEL* pend = NULL;
int result = 0;
int ret;
byte buf[4] = { 0x00, 0x01, 0x02, 0x03 };
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -1630;
wolfSSH_SetIOSend(ctx, DiscardIoSend);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1631; goto done; }
ssh->connectState = CONNECT_SERVER_USERAUTH_ACCEPT_DONE;
/* The live session channel, confirmed, holding peer id 0. */
sess = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (sess == NULL) { result = -1632; goto done; }
if (ChannelAppend(ssh, sess) != WS_SUCCESS) {
ChannelDelete(sess, ssh->ctx->heap);
result = -1633;
goto done;
}
sess->openConfirmed = 1;
sess->peerChannel = 0;
sess->peerWindowSz = 1024;
sess->peerMaxPacketSz = 1024;
/* A second channel whose open has only been sent, as
* wolfSSH_ChannelFwdNewLocal() hands back. */
pend = ChannelNew(ssh, ID_CHANTYPE_TCPIP_DIRECT, 1024, 1024);
if (pend == NULL) { result = -1634; goto done; }
if (ChannelAppend(ssh, pend) != WS_SUCCESS) {
ChannelDelete(pend, ssh->ctx->heap);
result = -1635;
goto done;
}
if (pend->openConfirmed || pend->peerChannel != 0) {
result = -1636;
goto done;
}
ret = wolfSSH_ChannelSendEof(pend);
if (ret != WS_CHANNEL_NOT_CONF) { result = -1637; goto done; }
/* wolfSSH_ChannelExit() sends an EOF through the same lookup, ahead of its
* close, so it needs the same guard. */
ret = wolfSSH_ChannelExit(pend);
if (ret != WS_CHANNEL_NOT_CONF) { result = -1654; goto done; }
if (sess->closeTxd || pend->closeTxd) { result = -1655; goto done; }
/* Neither channel was half-closed, and the session can still send. */
if (sess->eofTxd || pend->eofTxd) { result = -1638; goto done; }
ret = wolfSSH_ChannelSend(sess, buf, (word32)sizeof(buf));
if (ret != (int)sizeof(buf)) { result = -1639; goto done; }
/* wolfSSH_stream_send_eof() runs the same lookup on the head, so it
* needs the same guard. An unconfirmed head resolves to whichever
* channel holds peer id 0, itself included, and latching eofTxd there
* would silence the real channel's send direction for good. */
sess->openConfirmed = 0;
ret = wolfSSH_stream_send_eof(ssh);
if (ret != WS_CHANNEL_NOT_CONF) { result = -1650; goto done; }
if (sess->eofTxd || pend->eofTxd) { result = -1651; goto done; }
sess->openConfirmed = 1;
ret = wolfSSH_stream_send_eof(ssh);
if (ret != WS_SUCCESS) { result = -1652; goto done; }
if (!sess->eofTxd) { result = -1653; goto done; }
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* NO_WOLFSSH_CLIENT */
#ifndef NO_WOLFSSH_SERVER
/* The mirror of the above on the receiving side. DoChannelClose() finds its
* channel by self id, so a peer can name a locally opened channel it never
* confirmed. Its reply addresses the peer id, which is still 0 there, so an
* unguarded reply would half-close and close the live session channel
* instead. Retire the named channel and answer nothing. */
static int test_DoChannelCloseUnconfirmedChannel(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* sess = NULL;
WOLFSSH_CHANNEL* pend = NULL;
int result = 0;
int ret;
word32 pendId;
byte pkt[16];
byte buf[4] = { 0x00, 0x01, 0x02, 0x03 };
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1672;
/* The socket takes nothing, so anything sent stays in the buffer where
* this can see it. */
wolfSSH_SetIOSend(ctx, WantWriteIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1673; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
/* The live session channel, confirmed, holding peer id 0. */
sess = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (sess == NULL) { result = -1674; goto done; }
if (ChannelAppend(ssh, sess) != WS_SUCCESS) {
ChannelDelete(sess, ssh->ctx->heap);
result = -1675;
goto done;
}
sess->openConfirmed = 1;
sess->peerChannel = 0;
sess->peerWindowSz = 1024;
sess->peerMaxPacketSz = 1024;
/* A second channel of ours whose open the peer has not answered. */
pend = ChannelNew(ssh, ID_CHANTYPE_TCPIP_DIRECT, 1024, 1024);
if (pend == NULL) { result = -1676; goto done; }
if (ChannelAppend(ssh, pend) != WS_SUCCESS) {
ChannelDelete(pend, ssh->ctx->heap);
result = -1677;
goto done;
}
if (pend->openConfirmed || pend->peerChannel != 0) {
result = -1678;
goto done;
}
pendId = pend->channel;
/* The peer closes the channel it never confirmed. */
s_recvPkt = pkt;
s_recvPktSz = BuildChannelClosePacket(pkt, pendId);
s_recvPktOff = 0;
ret = wolfSSH_worker(ssh, NULL);
if (ret != WS_CHANNEL_CLOSED) { result = -1679; goto done; }
if (ssh->lastRxId != pendId) { result = -1680; goto done; }
/* Only the named channel went away. */
if (ssh->channelListSz != 1) { result = -1681; goto done; }
if (ssh->channelList != sess) { result = -1682; goto done; }
/* Nothing was addressed to peer id 0 on the session channel's behalf. */
if (sess->eofTxd || sess->closeTxd) { result = -1683; goto done; }
if (PlainPacketsHaveMsg(ssh->outputBuffer.buffer, ssh->outputBuffer.idx,
ssh->outputBuffer.length, MSGID_CHANNEL_EOF)) {
result = -1684;
goto done;
}
if (PlainPacketsHaveMsg(ssh->outputBuffer.buffer, ssh->outputBuffer.idx,
ssh->outputBuffer.length, MSGID_CHANNEL_CLOSE)) {
result = -1685;
goto done;
}
/* And the session's send direction is still live. */
wolfSSH_SetIOSend(ctx, DiscardIoSend);
ret = wolfSSH_ChannelSend(sess, buf, (word32)sizeof(buf));
if (ret != (int)sizeof(buf)) { result = -1686; goto done; }
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* NO_WOLFSSH_SERVER */
#ifndef NO_WOLFSSH_CLIENT
/* A bundled but unflushed EOF is committed: the bytes are in the output
* buffer and go out on the next flush. The WS_WANT_WRITE retry an application
* makes must not queue a second EOF behind the first. */
static int test_SendChannelEofWantWrite(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
word32 queued;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -1510;
wolfSSH_SetIOSend(ctx, WantWriteIoSend);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1511; goto done; }
/* Connection-protocol messages are only allowed once userauth is done. */
ssh->connectState = CONNECT_SERVER_USERAUTH_ACCEPT_DONE;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION,
DEFAULT_WINDOW_SZ, DEFAULT_MAX_PACKET_SZ);
if (ch == NULL) { result = -1512; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1513;
goto done;
}
ch->openConfirmed = 1;
/* The socket will not take it, but the packet is built and buffered. */
ret = wolfSSH_ChannelSendEof(ch);
if (ret != WS_WANT_WRITE) { result = -1514; goto done; }
if (!ch->eofTxd) { result = -1515; goto done; }
queued = ssh->outputBuffer.length;
if (queued == 0) { result = -1516; goto done; }
/* The retry an application makes on WS_WANT_WRITE. */
ret = wolfSSH_ChannelSendEof(ch);
if (ret != WS_SUCCESS) { result = -1517; goto done; }
if (ssh->outputBuffer.length != queued) { result = -1518; goto done; }
/* One EOF goes out, and the buffer empties. */
wolfSSH_SetIOSend(ctx, DiscardIoSend);
ret = wolfSSH_SendPacket(ssh);
if (ret != WS_SUCCESS) { result = -1519; goto done; }
if (ssh->outputBuffer.length != 0) { result = -1520; goto done; }
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* NO_WOLFSSH_CLIENT */
#ifndef NO_WOLFSSH_CLIENT
/* A hard send failure is the other side of that latch. WS_CBIO_ERR_GENERAL
* makes wolfSSH_SendPacket() discard the output buffer, so the bundled EOF is
* gone; latching eofTxd there would leave the channel refusing every later
* send for an EOF that never went anywhere. */
static int test_SendChannelEofSendFails(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -1687;
wolfSSH_SetIOSend(ctx, FailIoSend);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1688; goto done; }
ssh->connectState = CONNECT_SERVER_USERAUTH_ACCEPT_DONE;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION,
DEFAULT_WINDOW_SZ, DEFAULT_MAX_PACKET_SZ);
if (ch == NULL) { result = -1689; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1690;
goto done;
}
ch->openConfirmed = 1;
/* The send fails and takes the bundled EOF with it. */
ret = wolfSSH_ChannelSendEof(ch);
if (ret != WS_SOCKET_ERROR_E) { result = -1691; goto done; }
if (ch->eofTxd) { result = -1692; goto done; }
if (ssh->outputBuffer.length != 0) { result = -1693; goto done; }
/* SendChannelClose() has the same shape, and a closeTxd claiming a close
* that never left makes wolfSSH_shutdown() skip the teardown. */
ret = SendChannelClose(ssh, ch->peerChannel);
if (ret != WS_SOCKET_ERROR_E) { result = -1762; goto done; }
if (ch->closeTxd) { result = -1763; goto done; }
/* So the channel is not half-closed, and an EOF can still be built and
* sent once the socket takes bytes again. */
wolfSSH_SetIOSend(ctx, DiscardIoSend);
ret = wolfSSH_ChannelSendEof(ch);
if (ret != WS_SUCCESS) { result = -1694; goto done; }
if (!ch->eofTxd) { result = -1695; goto done; }
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* NO_WOLFSSH_CLIENT */
#ifndef NO_WOLFSSH_CLIENT
/* A connection reset fails the send without discarding the buffer, so the EOF
* is still queued and eofTxd has to latch: the retry flushes those bytes and
* must not build a second EOF behind them. The other arm of the same test. */
static int test_SendChannelEofConnReset(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
word32 queued;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -1750;
wolfSSH_SetIOSend(ctx, ConnResetIoSend);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1751; goto done; }
ssh->connectState = CONNECT_SERVER_USERAUTH_ACCEPT_DONE;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION,
DEFAULT_WINDOW_SZ, DEFAULT_MAX_PACKET_SZ);
if (ch == NULL) { result = -1752; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1753;
goto done;
}
ch->openConfirmed = 1;
ret = wolfSSH_ChannelSendEof(ch);
if (ret != WS_SOCKET_ERROR_E) { result = -1754; goto done; }
if (!wolfSSH_OutputPending(ssh)) { result = -1755; goto done; }
if (!ch->eofTxd) { result = -1756; goto done; }
/* The queued bytes are the EOF; a second call adds nothing to them. */
queued = ssh->outputBuffer.length - ssh->outputBuffer.idx;
ret = wolfSSH_ChannelSendEof(ch);
if (ret != WS_SUCCESS) { result = -1757; goto done; }
if (ssh->outputBuffer.length - ssh->outputBuffer.idx != queued) {
result = -1758;
goto done;
}
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* NO_WOLFSSH_CLIENT */
#ifndef NO_WOLFSSH_SERVER
static int s_eofCbCalls = 0;
static word32 s_eofCbChannel = 0;
static void* s_eofCbCtx = NULL;
static int EofRecordingCb(WOLFSSH_CHANNEL* channel, void* ctx)
{
s_eofCbCalls++;
s_eofCbChannel = (channel != NULL) ? channel->channel : 0;
s_eofCbCtx = ctx;
return WS_SUCCESS;
}
/* The channel EOF callback is the durable half of the contract: the WS_EOF
* from wolfSSH_worker() is raised once and a flush failure can replace it in
* wolfSSH_get_error(), but the callback fires from DoChannelEof() itself. */
static int test_ChannelEofCallback(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
int cbCtx = 0;
byte pkt[16];
s_eofCbCalls = 0;
s_eofCbChannel = 0;
s_eofCbCtx = NULL;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1707;
wolfSSH_SetIOSend(ctx, DiscardIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
if (wolfSSH_CTX_SetChannelEofCb(ctx, EofRecordingCb) != WS_SUCCESS) {
result = -1708;
goto done;
}
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1709; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
if (wolfSSH_SetChannelEofCtx(ssh, &cbCtx) != WS_SUCCESS) {
result = -1710;
goto done;
}
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch == NULL) { result = -1711; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1712;
goto done;
}
ch->openConfirmed = 1;
ch->peerWindowSz = 1024;
ch->peerMaxPacketSz = 1024;
s_recvPkt = pkt;
s_recvPktSz = BuildChannelEofPacket(pkt, ch->channel);
s_recvPktOff = 0;
ret = wolfSSH_worker(ssh, NULL);
if (ret != WS_EOF) { result = -1713; goto done; }
if (s_eofCbCalls != 1) { result = -1714; goto done; }
if (s_eofCbChannel != ch->channel) { result = -1715; goto done; }
if (s_eofCbCtx != &cbCtx) { result = -1716; goto done; }
if (!wolfSSH_ChannelGetEof(ch)) { result = -1717; goto done; }
/* Nothing more arrives, so nothing fires it again. */
ret = wolfSSH_worker(ssh, NULL);
if (ret == WS_EOF) { result = -1718; goto done; }
if (s_eofCbCalls != 1) { result = -1719; goto done; }
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* Disconnects from inside the EOF dispatch. DoChannelEof() discards what
* this returns, so the refused send's status is not an error to report. */
static int EofDisconnectCb(WOLFSSH_CHANNEL* channel, void* ctx)
{
WOLFSSH* ssh = (WOLFSSH*)ctx;
(void)channel;
(void)wolfSSH_SendDisconnect(ssh, WOLFSSH_DISCONNECT_BY_APPLICATION);
return WS_SUCCESS;
}
/* The queued DISCONNECT sets ssh->disconnected, so wolfSSH_worker() skips its
* flush and the pass returns WS_EOF with output still owed. The write outranks
* that event: the teardown reports WS_WANT_WRITE and the retry sends it. */
static int test_ShutdownOwedWriteAfterEofDisconnect(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
byte pkt[16];
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1900;
wolfSSH_SetIOSend(ctx, WantWriteIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
if (wolfSSH_CTX_SetChannelEofCb(ctx, EofDisconnectCb) != WS_SUCCESS) {
result = -1901;
goto done;
}
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1902; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
if (wolfSSH_SetChannelEofCtx(ssh, ssh) != WS_SUCCESS) {
result = -1903;
goto done;
}
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch == NULL) { result = -1904; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1905;
goto done;
}
ch->openConfirmed = 1;
ch->peerWindowSz = 1024;
ch->peerMaxPacketSz = 1024;
/* The teardown sends are already done, so the read is all that is left
* and the output buffer is empty going into it. */
ch->eofTxd = 1;
ch->closeTxd = 1;
s_recvPkt = pkt;
s_recvPktSz = BuildChannelEofPacket(pkt, ch->channel);
s_recvPktOff = 0;
ret = wolfSSH_shutdown(ssh);
if (ret != WS_WANT_WRITE) { result = -1906; goto done; }
if (!wolfSSH_OutputPending(ssh)) { result = -1907; goto done; }
/* And the disconnect really does go out once the socket takes bytes. */
wolfSSH_SetIOSend(ctx, DiscardIoSend);
ret = wolfSSH_shutdown(ssh);
if (ret != WS_SUCCESS) { result = -1908; goto done; }
if (wolfSSH_OutputPending(ssh)) { result = -1909; goto done; }
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* The owed write is what the first call reports even when the disconnect's
* send failed outright, and the retry's flush surfaces the transport error. */
static int test_ShutdownHardEofDisconnectSurfacesOnRetry(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
byte pkt[16];
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1910;
wolfSSH_SetIOSend(ctx, ConnResetIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
if (wolfSSH_CTX_SetChannelEofCb(ctx, EofDisconnectCb) != WS_SUCCESS) {
result = -1911;
goto done;
}
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1912; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
if (wolfSSH_SetChannelEofCtx(ssh, ssh) != WS_SUCCESS) {
result = -1913;
goto done;
}
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch == NULL) { result = -1914; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1915;
goto done;
}
ch->openConfirmed = 1;
ch->peerWindowSz = 1024;
ch->peerMaxPacketSz = 1024;
ch->eofTxd = 1;
ch->closeTxd = 1;
s_recvPkt = pkt;
s_recvPktSz = BuildChannelEofPacket(pkt, ch->channel);
s_recvPktOff = 0;
ret = wolfSSH_shutdown(ssh);
if (ret != WS_WANT_WRITE) { result = -1916; goto done; }
if (!wolfSSH_OutputPending(ssh)) { result = -1917; goto done; }
/* The reset is not lost: it takes the return one call later. */
ret = wolfSSH_shutdown(ssh);
if (ret != WS_SOCKET_ERROR_E) { result = -1918; goto done; }
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* NO_WOLFSSH_SERVER */
#ifndef NO_WOLFSSH_SERVER
/* WS_EOF names its channel the way WS_CHAN_RXD does, so a caller with more
* than one channel open knows which one half-closed rather than assuming the
* head of the list. */
static int test_WorkerReportsEofChannelId(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch0 = NULL;
WOLFSSH_CHANNEL* ch1 = NULL;
int result = 0;
int ret;
word32 reported = 0xFFFFFFFF;
byte pkt[16];
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1720;
wolfSSH_SetIOSend(ctx, DiscardIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1721; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch0 = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch0 == NULL) { result = -1722; goto done; }
if (ChannelAppend(ssh, ch0) != WS_SUCCESS) {
ChannelDelete(ch0, ssh->ctx->heap);
result = -1723;
goto done;
}
ch0->openConfirmed = 1;
ch0->peerWindowSz = 1024;
ch0->peerMaxPacketSz = 1024;
ch1 = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch1 == NULL) { result = -1724; goto done; }
if (ChannelAppend(ssh, ch1) != WS_SUCCESS) {
ChannelDelete(ch1, ssh->ctx->heap);
result = -1725;
goto done;
}
ch1->openConfirmed = 1;
ch1->peerWindowSz = 1024;
ch1->peerMaxPacketSz = 1024;
/* The half-close lands on the channel that is not the head. */
s_recvPkt = pkt;
s_recvPktSz = BuildChannelEofPacket(pkt, ch1->channel);
s_recvPktOff = 0;
ret = wolfSSH_worker(ssh, &reported);
if (ret != WS_EOF) { result = -1726; goto done; }
if (reported != ch1->channel) { result = -1727; goto done; }
if (!ch1->eofRxd) { result = -1728; goto done; }
if (ch0->eofRxd) { result = -1729; goto done; }
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* NO_WOLFSSH_SERVER */
#ifndef NO_WOLFSSH_CLIENT
/* Only KEX traffic may go out mid-rekey, RFC 4253 section 7.1, and the head
* variant needs the same gate as wolfSSH_ChannelSendEof(). It reports the
* rekey itself rather than latching it behind WS_FATAL_ERROR, which is what
* the header promises. */
static int test_StreamSendEofRekeying(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -1730;
wolfSSH_SetIOSend(ctx, DiscardIoSend);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1731; goto done; }
ssh->connectState = CONNECT_SERVER_USERAUTH_ACCEPT_DONE;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch == NULL) { result = -1732; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1733;
goto done;
}
ch->openConfirmed = 1;
ch->peerWindowSz = 1024;
ch->peerMaxPacketSz = 1024;
ssh->isKeying = 1;
ret = wolfSSH_stream_send_eof(ssh);
if (ret != WS_REKEYING) { result = -1734; goto done; }
if (wolfSSH_get_error(ssh) != WS_REKEYING) { result = -1735; goto done; }
if (ch->eofTxd) { result = -1736; goto done; }
if (ssh->outputBuffer.length != 0) { result = -1737; goto done; }
/* And it goes out once the rekey is done. */
ssh->isKeying = 0;
ret = wolfSSH_stream_send_eof(ssh);
if (ret != WS_SUCCESS) { result = -1738; goto done; }
if (!ch->eofTxd) { result = -1739; goto done; }
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* NO_WOLFSSH_CLIENT */
#ifndef NO_WOLFSSH_CLIENT
/* wolfSSH_shutdown() drains for the peer's answer to its close. A peer that
* half-closes first answers with an EOF, which is an ordinary part of the
* teardown and not a failure of it. */
static int test_ShutdownAbsorbsEof(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
byte pkt[16];
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -1740;
wolfSSH_SetIOSend(ctx, DiscardIoSend);
wolfSSH_SetIORecv(ctx, PacketIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1741; goto done; }
ssh->connectState = CONNECT_SERVER_USERAUTH_ACCEPT_DONE;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch == NULL) { result = -1742; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1743;
goto done;
}
ch->openConfirmed = 1;
ch->peerWindowSz = 1024;
ch->peerMaxPacketSz = 1024;
/* All the peer sends back is its own half-close. */
s_recvPkt = pkt;
s_recvPktSz = BuildChannelEofPacket(pkt, ch->channel);
s_recvPktOff = 0;
ret = wolfSSH_shutdown(ssh);
if (ret != WS_SUCCESS) { result = -1744; goto done; }
/* The teardown went out and the channel is still there, waiting for the
* peer's close. */
if (!ch->eofTxd || !ch->closeTxd) { result = -1745; goto done; }
if (!ch->eofRxd) { result = -1746; goto done; }
if (ssh->channelList != ch) { result = -1747; goto done; }
done:
s_recvPkt = NULL;
s_recvPktSz = 0;
s_recvPktOff = 0;
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* NO_WOLFSSH_CLIENT */
#ifndef NO_WOLFSSH_CLIENT
/* wolfSSH_ChannelExit() chains its close on the EOF's send, so a socket that
* will not take the EOF leaves the close unbuilt and the teardown half done.
* The call has to be repeated, and the repeat must finish it rather than put
* a second EOF on the wire. */
static int test_ChannelExitWantWrite(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
word32 queued;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -1748;
wolfSSH_SetIOSend(ctx, WantWriteIoSend);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1749; goto done; }
ssh->connectState = CONNECT_SERVER_USERAUTH_ACCEPT_DONE;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch == NULL) { result = -1750; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1751;
goto done;
}
ch->openConfirmed = 1;
ch->peerWindowSz = 1024;
ch->peerMaxPacketSz = 1024;
/* The EOF is bundled but not away, so the close was never built. */
ret = wolfSSH_ChannelExit(ch);
if (ret != WS_WANT_WRITE) { result = -1752; goto done; }
if (!ch->eofTxd) { result = -1753; goto done; }
if (ch->closeTxd) { result = -1754; goto done; }
queued = ssh->outputBuffer.length;
if (queued == 0) { result = -1755; goto done; }
if (!PlainPacketsHaveMsg(ssh->outputBuffer.buffer, ssh->outputBuffer.idx,
ssh->outputBuffer.length, MSGID_CHANNEL_EOF)) {
result = -1756;
goto done;
}
if (PlainPacketsHaveMsg(ssh->outputBuffer.buffer, ssh->outputBuffer.idx,
ssh->outputBuffer.length, MSGID_CHANNEL_CLOSE)) {
result = -1757;
goto done;
}
/* The repeat builds the close, still against a blocked socket. */
ret = wolfSSH_ChannelExit(ch);
if (ret != WS_WANT_WRITE) { result = -1766; goto done; }
if (!ch->closeTxd) { result = -1767; goto done; }
/* A third call has nothing left to build, so it reports success -- with
* both messages still sitting in the buffer. WS_SUCCESS from this call
* means bundled, not delivered. */
ret = wolfSSH_ChannelExit(ch);
if (ret != WS_SUCCESS) { result = -1768; goto done; }
if (!wolfSSH_OutputPending(ssh)) { result = -1769; goto done; }
/* With both flags latched the call builds nothing and sends nothing --
* it does not even reach the transport, so a working socket does not
* drain what is queued. The caller owns that. */
wolfSSH_SetIOSend(ctx, DiscardIoSend);
ret = wolfSSH_ChannelExit(ch);
if (ret != WS_SUCCESS) { result = -1758; goto done; }
if (!ch->closeTxd) { result = -1759; goto done; }
if (!wolfSSH_OutputPending(ssh)) { result = -1778; goto done; }
/* Driven by hand, both messages go out and no duplicate follows. */
if (wolfSSH_SendPacket(ssh) != WS_SUCCESS) { result = -1779; goto done; }
if (ssh->outputBuffer.length != 0) { result = -1760; goto done; }
/* And the channel is still there for the peer's close to name. */
if (ssh->channelList != ch) { result = -1761; goto done; }
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* NO_WOLFSSH_CLIENT */
static int test_SendChannelData_eofTxd(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
byte buf[4] = { 0x00, 0x01, 0x02, 0x03 };
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -560;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -561; goto done; }
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION,
DEFAULT_WINDOW_SZ, DEFAULT_MAX_PACKET_SZ);
if (ch == NULL) { result = -562; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -563;
goto done;
}
ch->eofTxd = 1;
/* SendChannelData after EOF -> WS_EOF */
ret = SendChannelData(ssh, ch->channel, buf, (word32)sizeof(buf));
if (ret != WS_EOF) { result = -570; goto done; }
/* SendChannelExtendedData after EOF -> WS_EOF */
ret = SendChannelExtendedData(ssh, ch->channel, buf, (word32)sizeof(buf));
if (ret != WS_EOF) { result = -571; goto done; }
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* A peer may advertise a maximum packet size of 0 in its CHANNEL_OPEN or
* CHANNEL_OPEN_CONFIRMATION. Sending must report WS_WINDOW_FULL, not push
* dataSz past the bound and charge it against the window. */
static int test_SendChannelData_zeroPeerMaxPacket(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
byte buf[8] = { 0, 1, 2, 3, 4, 5, 6, 7 };
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -1400;
wolfSSH_SetIOSend(ctx, DiscardIoSend);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1401; goto done; }
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION,
DEFAULT_WINDOW_SZ, DEFAULT_MAX_PACKET_SZ);
if (ch == NULL) { result = -1402; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1403;
goto done;
}
ch->openConfirmed = 1;
/* Window has room, but the peer will not accept a packet of any size. */
ch->peerWindowSz = 100;
ch->peerMaxPacketSz = 0;
ret = SendChannelData(ssh, ch->channel, buf, (word32)sizeof(buf));
if (ret != WS_WINDOW_FULL) { result = -1410; goto done; }
if (ssh->error != WS_WINDOW_FULL) { result = -1411; goto done; }
/* Nothing queued, and the window was not charged. */
if (ssh->outputBuffer.length != 0) { result = -1412; goto done; }
if (ch->peerWindowSz != 100) { result = -1413; goto done; }
ssh->error = WS_SUCCESS;
ret = SendChannelExtendedData(ssh, ch->channel, buf, (word32)sizeof(buf));
if (ret != WS_WINDOW_FULL) { result = -1420; goto done; }
if (ssh->error != WS_WINDOW_FULL) { result = -1421; goto done; }
if (ssh->outputBuffer.length != 0) { result = -1422; goto done; }
if (ch->peerWindowSz != 100) { result = -1423; goto done; }
/* A zero-length send is still allowed through: it charges nothing. */
ssh->error = WS_SUCCESS;
ret = SendChannelData(ssh, ch->channel, buf, 0);
if (ret != 0) { result = -1430; goto done; }
if (ch->peerWindowSz != 100) { result = -1431; goto done; }
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#ifndef NO_WOLFSSH_SERVER
/* wolfSSH_stream_read() counterpart of test_ChannelExtDataCreditWantWrite():
* a deferred credit must not cost the caller the bytes already consumed, and
* an adjust that fails outright must still surface on wolfSSH_get_error(). */
static int test_stream_read_deferredWindowAdjust(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
byte in[64];
byte out[64];
word32 i;
for (i = 0; i < (word32)sizeof(in); i++) {
in[i] = (byte)i;
}
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -6980;
wolfSSH_SetIOSend(ctx, WantWriteIoSend);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -6981; goto done; }
/* Allow MSGID_CHANNEL_WINDOW_ADJUST on this bare session. */
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
/* A window the size of the payload, so draining it in one read leaves
* windowSz at zero and _UpdateChannelWindow() has to credit. */
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION,
(word32)sizeof(in), DEFAULT_MAX_PACKET_SZ);
if (ch == NULL) { result = -6982; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -6983;
goto done;
}
ch->openConfirmed = 1;
if (wolfSSH_TestChannelPutData(ch, in, (word32)sizeof(in)) != WS_SUCCESS) {
result = -6984; goto done;
}
if (ch->windowSz != 0) { result = -6985; goto done; }
/* Every byte is reported, and they are the bytes that were put. */
ret = wolfSSH_stream_read(ssh, out, (word32)sizeof(out));
if (ret != (int)sizeof(in)) { result = -6990; goto done; }
if (WMEMCMP(out, in, sizeof(in)) != 0) { result = -6991; goto done; }
/* The deferral is observable, the window is credited locally, and the
* bytes are consumed rather than left for a re-read. */
if (ssh->error != WS_WANT_WRITE) { result = -6992; goto done; }
if (ch->windowSz != (word32)sizeof(in)) { result = -6993; goto done; }
if (ch->inputBuffer.length - ch->inputBuffer.idx != 0) {
result = -6994; goto done;
}
/* A peer that reset rather than blocked. The read path records the code
* itself: the adjust can fail before it reaches the transport. */
wolfSSH_SetIOSend(ctx, FailIoSend);
if (wolfSSH_TestChannelPutData(ch, in, (word32)sizeof(in)) != WS_SUCCESS) {
result = -6995; goto done;
}
if (ch->windowSz != 0) { result = -6996; goto done; }
ret = wolfSSH_stream_read(ssh, out, (word32)sizeof(out));
if (ret != (int)sizeof(in)) { result = -6997; goto done; }
if (wolfSSH_get_error(ssh) != WS_SOCKET_ERROR_E) {
result = -6998; goto done;
}
/* The send discarded what it bundled, so the credit stays owed. */
if (ch->pendingWindowAdjust != (word32)sizeof(in)) {
result = -6999; goto done;
}
/* Credit is charged for the bytes this read took, so a read that drains
* the window puts an adjust on the wire. */
wolfSSH_SetIOSend(ctx, CountIoSend);
s_extSendCount = 0;
if (wolfSSH_TestChannelPutData(ch, in, (word32)sizeof(in)) != WS_SUCCESS) {
result = -6970; goto done;
}
ret = wolfSSH_stream_read(ssh, out, (word32)sizeof(out));
if (ret != (int)sizeof(in)) { result = -6971; goto done; }
if (s_extSendCount != 1) { result = -6972; goto done; }
if (wolfSSH_get_error(ssh) != WS_SUCCESS) { result = -6973; goto done; }
/* The owed credit from the failed send rode along with this one. */
if (ch->pendingWindowAdjust != 0) { result = -6974; goto done; }
if (ch->windowSz != (word32)sizeof(in)) { result = -6975; goto done; }
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* wolfSSH_ChannelIdPeek() reports a named channel without consuming it. */
static int test_ChannelIdPeek(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
byte in[32];
byte out[32];
word32 i;
for (i = 0; i < (word32)sizeof(in); i++) {
in[i] = (byte)(i + 1);
}
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -7050;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -7051; goto done; }
/* Bad args, before any channel exists. */
if (wolfSSH_ChannelIdPeek(NULL, 0, out, (word32)sizeof(out))
!= WS_BAD_ARGUMENT) {
result = -7052; goto done;
}
if (wolfSSH_ChannelIdPeek(ssh, 99, out, (word32)sizeof(out))
!= WS_INVALID_CHANID) {
result = -7053; goto done;
}
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION,
(word32)sizeof(in), DEFAULT_MAX_PACKET_SZ);
if (ch == NULL) { result = -7054; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -7055;
goto done;
}
ch->openConfirmed = 1;
/* Open and empty: zero, not an error. */
ret = wolfSSH_ChannelIdPeek(ssh, ch->channel, out, (word32)sizeof(out));
if (ret != 0) { result = -7056; goto done; }
if (wolfSSH_TestChannelPutData(ch, in, (word32)sizeof(in)) != WS_SUCCESS) {
result = -7057; goto done;
}
/* Whole payload reported and copied out. */
WMEMSET(out, 0, sizeof(out));
ret = wolfSSH_ChannelIdPeek(ssh, ch->channel, out, (word32)sizeof(out));
if (ret != (int)sizeof(in)) { result = -7058; goto done; }
if (WMEMCMP(out, in, sizeof(in)) != 0) { result = -7059; goto done; }
/* Consumed nothing, credited nothing. */
if (ch->inputBuffer.length - ch->inputBuffer.idx != (word32)sizeof(in)) {
result = -7060; goto done;
}
if (ch->windowSz != 0) { result = -7061; goto done; }
/* bufSz caps the count and the bytes written. */
WMEMSET(out, 0, sizeof(out));
ret = wolfSSH_ChannelIdPeek(ssh, ch->channel, out, 8);
if (ret != 8) { result = -7062; goto done; }
if (WMEMCMP(out, in, 8) != 0) { result = -7063; goto done; }
if (out[8] != 0) { result = -7064; goto done; }
/* A NULL buffer asks only for the count. */
ret = wolfSSH_ChannelIdPeek(ssh, ch->channel, NULL, (word32)sizeof(out));
if (ret != (int)sizeof(in)) { result = -7065; goto done; }
/* Still reported mid-rekey, where stream_peek returns WS_REKEYING. */
ssh->isKeying = WOLFSSH_SELF_IS_KEYING;
if (wolfSSH_stream_peek(ssh, out, (word32)sizeof(out)) != WS_REKEYING) {
result = -7066; goto done;
}
ret = wolfSSH_ChannelIdPeek(ssh, ch->channel, out, (word32)sizeof(out));
if (ret != (int)sizeof(in)) { result = -7067; goto done; }
ssh->isKeying = 0;
/* EOF stays hidden until the buffered data is drained. */
ch->eofRxd = 1;
ret = wolfSSH_ChannelIdPeek(ssh, ch->channel, out, (word32)sizeof(out));
if (ret != (int)sizeof(in)) { result = -7068; goto done; }
ret = wolfSSH_ChannelIdRead(ssh, ch->channel, out, (word32)sizeof(out));
if (ret != (int)sizeof(in)) { result = -7069; goto done; }
ssh->error = WS_SUCCESS;
ret = wolfSSH_ChannelIdPeek(ssh, ch->channel, out, (word32)sizeof(out));
if (ret != WS_ERROR) { result = -7070; goto done; }
if (ssh->error != WS_EOF) { result = -7071; goto done; }
/* EOF outranks a disconnect. */
ssh->disconnected = 1;
ssh->error = WS_SUCCESS;
ret = wolfSSH_ChannelIdPeek(ssh, ch->channel, out, (word32)sizeof(out));
if (ret != WS_ERROR) { result = -7072; goto done; }
if (ssh->error != WS_EOF) { result = -7073; goto done; }
/* Without the EOF, the dead session is reported instead. */
ch->eofRxd = 0;
ssh->error = WS_SUCCESS;
ret = wolfSSH_ChannelIdPeek(ssh, ch->channel, out, (word32)sizeof(out));
if (ret != WS_FATAL_ERROR) { result = -7074; goto done; }
if (ssh->error != WS_DISCONNECT) { result = -7075; goto done; }
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* wolfSSH_ChannelIdRead() counterpart of
* test_stream_read_deferredWindowAdjust(): callers break out on a non-positive
* read, and this entry point has to retire the owed-flush status itself. */
static int test_ChannelIdRead_deferredWindowAdjust(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int ret;
byte in[64];
byte out[64];
word32 i;
for (i = 0; i < (word32)sizeof(in); i++) {
in[i] = (byte)i;
}
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -7010;
wolfSSH_SetIOSend(ctx, WantWriteIoSend);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -7011; goto done; }
/* Allow MSGID_CHANNEL_WINDOW_ADJUST on this bare session. */
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
/* A window the size of the payload, so draining it in one read leaves
* windowSz at zero and _UpdateChannelWindow() has to credit. */
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION,
(word32)sizeof(in), DEFAULT_MAX_PACKET_SZ);
if (ch == NULL) { result = -7012; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -7013;
goto done;
}
ch->openConfirmed = 1;
if (wolfSSH_TestChannelPutData(ch, in, (word32)sizeof(in)) != WS_SUCCESS) {
result = -7014; goto done;
}
if (ch->windowSz != 0) { result = -7015; goto done; }
/* Unlike wolfSSH_stream_read(), this entry point does not clear the error,
* so seed it: the assert below has to prove the read recorded it. */
ssh->error = WS_SUCCESS;
/* Every byte is reported, and they are the bytes that were put. */
ret = wolfSSH_ChannelIdRead(ssh, ch->channel, out, (word32)sizeof(out));
if (ret != (int)sizeof(in)) { result = -7016; goto done; }
if (WMEMCMP(out, in, sizeof(in)) != 0) { result = -7017; goto done; }
/* The deferral is observable, the window is credited locally, and the
* bytes are consumed rather than left for a re-read. */
if (ssh->error != WS_WANT_WRITE) { result = -7018; goto done; }
if (ch->windowSz != (word32)sizeof(in)) { result = -7019; goto done; }
if (ch->inputBuffer.length - ch->inputBuffer.idx != 0) {
result = -7020; goto done;
}
/* A peer that reset rather than blocked. The read path records the code
* itself: the adjust can fail before it reaches the transport. */
wolfSSH_SetIOSend(ctx, FailIoSend);
if (wolfSSH_TestChannelPutData(ch, in, (word32)sizeof(in)) != WS_SUCCESS) {
result = -7021; goto done;
}
if (ch->windowSz != 0) { result = -7022; goto done; }
ret = wolfSSH_ChannelIdRead(ssh, ch->channel, out, (word32)sizeof(out));
if (ret != (int)sizeof(in)) { result = -7023; goto done; }
if (ssh->error != WS_SOCKET_ERROR_E) { result = -7024; goto done; }
/* The send discarded what it bundled, so the credit stays owed. */
if (ch->pendingWindowAdjust != (word32)sizeof(in)) {
result = -7025; goto done;
}
/* This entry point never resets ssh->error, so a credit that does go out
* has to retire the owed-flush status itself. */
wolfSSH_SetIOSend(ctx, DiscardIoSend);
ssh->error = WS_WANT_WRITE;
if (wolfSSH_TestChannelPutData(ch, in, (word32)sizeof(in)) != WS_SUCCESS) {
result = -7026; goto done;
}
ret = wolfSSH_ChannelIdRead(ssh, ch->channel, out, (word32)sizeof(out));
if (ret != (int)sizeof(in)) { result = -7027; goto done; }
if (ssh->outputBuffer.length != 0) { result = -7028; goto done; }
if (wolfSSH_get_error(ssh) != WS_SUCCESS) { result = -7029; goto done; }
/* Both the parked credit and the new one reached the peer. */
if (ch->pendingWindowAdjust != 0) { result = -7030; goto done; }
/* A read with nothing buffered sends no credit, so it has no standing to
* retire a WS_WANT_WRITE some other sender is still owed. */
ssh->error = WS_WANT_WRITE;
ret = wolfSSH_ChannelIdRead(ssh, ch->channel, out, (word32)sizeof(out));
if (ret != 0) { result = -7031; goto done; }
if (ssh->outputBuffer.length != 0) { result = -7032; goto done; }
if (wolfSSH_get_error(ssh) != WS_WANT_WRITE) { result = -7033; goto done; }
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* NO_WOLFSSH_SERVER */
/* CreateMpint() strips leading zeros, keeping one 0 in front of a set MSB
* instead of asking for a pad byte. */
static int test_CreateMpint(void)
{
static const struct {
byte in[4];
word32 inSz;
byte out[4];
word32 outSz;
byte pad;
} cases[] = {
{ {0x00}, 1, {0}, 0, 0 },
{ {0x00, 0x00, 0x00}, 3, {0}, 0, 0 },
{ {0x7F}, 1, {0x7F}, 1, 0 },
{ {0x80}, 1, {0x80}, 1, 1 },
{ {0xFF, 0x01}, 2, {0xFF, 0x01}, 2, 1 },
{ {0x00, 0x7F}, 2, {0x7F}, 1, 0 },
{ {0x00, 0x80}, 2, {0x00, 0x80}, 2, 0 },
{ {0x00, 0x00, 0x7F, 0x01}, 4, {0x7F, 0x01}, 2, 0 },
{ {0x00, 0x00, 0x80, 0x01}, 4, {0x00, 0x80, 0x01}, 3, 0 },
{ {0x01, 0x80, 0x00, 0x00}, 4, {0x01, 0x80, 0x00, 0x00}, 4, 0 },
};
byte buf[4];
word32 i, sz;
byte pad;
int ret;
int result = 0;
for (i = 0; i < (word32)(sizeof(cases) / sizeof(cases[0])); i++) {
WMEMCPY(buf, cases[i].in, sizeof(buf));
sz = cases[i].inSz;
pad = 0xAA;
ret = wolfSSH_TestCreateMpint(buf, &sz, &pad);
if (ret != WS_SUCCESS || sz != cases[i].outSz
|| pad != cases[i].pad
|| WMEMCMP(buf, cases[i].out, sz) != 0) {
printf("CreateMpint: case %u ret=%d sz=%u pad=%u\n",
i, ret, sz, pad);
result = -1450;
}
}
/* An empty input is an empty mpint and still sets pad. */
sz = 0;
pad = 0xAA;
ret = wolfSSH_TestCreateMpint(buf, &sz, &pad);
if (ret != WS_SUCCESS || sz != 0 || pad != 0)
result = -1451;
if (wolfSSH_TestCreateMpint(NULL, &sz, &pad) != WS_BAD_ARGUMENT
|| wolfSSH_TestCreateMpint(buf, NULL, &pad) != WS_BAD_ARGUMENT
|| wolfSSH_TestCreateMpint(buf, &sz, NULL) != WS_BAD_ARGUMENT)
result = -1452;
return result;
}
/* BuildNameList() returns a C string. On an empty id list it must still
* terminate the buffer: SendKexInit() measures the result with WSTRLEN
* through AlgoListSz() and copies that many bytes into the KEXINIT. */
static int test_BuildNameList_emptySrc(void)
{
char buf[64];
byte src[1] = { ID_AES128_GCM };
int ret;
/* Poison, so a missing terminator is a wrong length rather than luck. */
WMEMSET(buf, 'A', sizeof(buf));
ret = wolfSSH_TestBuildNameList(buf, (word32)sizeof(buf), src, 0);
if (ret != 0)
return -1440;
if (buf[0] != '\0')
return -1441;
if (WSTRLEN(buf) != 0)
return -1442;
/* The sizing call takes buf == NULL and must not touch anything. */
ret = wolfSSH_TestBuildNameList(NULL, 0, src, 0);
if (ret != 0)
return -1443;
/* One name still behaves: length excluding the terminator. */
WMEMSET(buf, 'A', sizeof(buf));
ret = wolfSSH_TestBuildNameList(buf, (word32)sizeof(buf), src, 1);
if (ret != (int)WSTRLEN(IdToName(ID_AES128_GCM)))
return -1444;
if (WSTRLEN(buf) != (size_t)ret)
return -1445;
return 0;
}
/* Plaintext SSH packet from IoSend (before encryption/MAC): LENGTH_SZ,
* PAD_LENGTH_SZ, then payload starting with the message ID (RFC 4253;
* wolfSSH PreparePacket/BundlePacket). Not for encrypted payloads or
* arbitrary truncated chunks. */
static int CaptureMsgId(const byte* buf, word32 len)
{
word32 off = LENGTH_SZ + PAD_LENGTH_SZ;
if (len <= off)
return -1;
return (int)buf[off];
}
/* Verify DoChannelRequest sends CHANNEL_SUCCESS for known types and
* CHANNEL_FAILURE for unrecognized ones (RFC 4254 Section 5.4).
*
* A custom IoSend callback captures the outgoing packet in plaintext
* (no cipher negotiated on a fresh session). Message ID is read via
* CaptureMsgId() using LENGTH_SZ + PAD_LENGTH_SZ. */
/* A session request callback that refuses everything, and counts. The
* callback sees the session type and command of the request it is vetting;
* what it does not see is a session already committed to the channel. */
static int s_rejectChanReqCalls;
static int RejectChanReqCb(WOLFSSH_CHANNEL* channel, void* ctx)
{
(void)ctx;
s_rejectChanReqCalls++;
if (channel == NULL
|| wolfSSH_ChannelGetSessionType(channel)
== WOLFSSH_SESSION_UNKNOWN) {
return 0;
}
return 1;
}
static byte s_chanReqCapture[256];
static word32 s_chanReqCaptureSz = 0;
static int CaptureIoSendChanReq(WOLFSSH* ssh, void* buf, word32 sz, void* ctx)
{
(void)ssh; (void)ctx;
s_chanReqCaptureSz = (sz < (word32)sizeof(s_chanReqCapture))
? sz : (word32)sizeof(s_chanReqCapture);
WMEMCPY(s_chanReqCapture, buf, s_chanReqCaptureSz);
return (int)sz;
}
/* The Ext send functions put a CHANNEL_EXTENDED_DATA message on the wire where
* their non-Ext counterparts put CHANNEL_DATA, address the channel they are
* given rather than the head of the channel list, and share the non-Ext
* argument and open-confirmed checks. */
static int test_ChannelSendExt(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
WOLFSSH_CHANNEL* chB = NULL;
int result = 0;
int ret;
byte payload[4] = { 0x11, 0x22, 0x33, 0x44 };
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -730;
wolfSSH_SetIOSend(ctx, CaptureIoSendChanReq);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -731; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 128, 64);
if (ch == NULL) { result = -732; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -733;
goto done;
}
chB = ChannelNew(ssh, ID_CHANTYPE_SESSION, 128, 64);
if (chB == NULL) { result = -734; goto done; }
if (ChannelAppend(ssh, chB) != WS_SUCCESS) {
ChannelDelete(chB, ssh->ctx->heap);
result = -735;
goto done;
}
/* Bad arguments, matching wolfSSH_ChannelSend/wolfSSH_ChannelIdSend. */
ret = wolfSSH_ChannelSendExt(NULL, payload, (word32)sizeof(payload));
if (ret != WS_BAD_ARGUMENT) { result = -736; goto done; }
ret = wolfSSH_ChannelSendExt(ch, NULL, (word32)sizeof(payload));
if (ret != WS_BAD_ARGUMENT) { result = -737; goto done; }
ret = wolfSSH_ChannelIdSendExt(NULL, 0, payload, (word32)sizeof(payload));
if (ret != WS_BAD_ARGUMENT) { result = -738; goto done; }
ret = wolfSSH_ChannelIdSendExt(ssh, 99, payload, (word32)sizeof(payload));
if (ret != WS_INVALID_CHANID) { result = -739; goto done; }
/* Both refuse to send before the channel is confirmed open. */
ret = wolfSSH_ChannelSendExt(ch, payload, (word32)sizeof(payload));
if (ret != WS_CHANNEL_NOT_CONF) { result = -740; goto done; }
ret = wolfSSH_ChannelIdSendExt(ssh, 0, payload, (word32)sizeof(payload));
if (ret != WS_CHANNEL_NOT_CONF) { result = -741; goto done; }
ch->openConfirmed = 1;
chB->openConfirmed = 1;
/* CHANNEL_OPEN_CONFIRMATION normally supplies these; without a peer window
* a send is refused with WS_WINDOW_FULL. */
ch->peerWindowSz = 128;
ch->peerMaxPacketSz = 64;
chB->peerWindowSz = 128;
chB->peerMaxPacketSz = 64;
/* Ext send emits CHANNEL_EXTENDED_DATA... */
s_chanReqCaptureSz = 0;
ret = wolfSSH_ChannelSendExt(ch, payload, (word32)sizeof(payload));
if (ret != (int)sizeof(payload)) { result = -742; goto done; }
if (CaptureMsgId(s_chanReqCapture, s_chanReqCaptureSz)
!= MSGID_CHANNEL_EXTENDED_DATA) {
result = -743; goto done;
}
/* ...where the non-Ext send emits CHANNEL_DATA. */
s_chanReqCaptureSz = 0;
ret = wolfSSH_ChannelSend(ch, payload, (word32)sizeof(payload));
if (ret != (int)sizeof(payload)) { result = -744; goto done; }
if (CaptureMsgId(s_chanReqCapture, s_chanReqCaptureSz)
!= MSGID_CHANNEL_DATA) {
result = -745; goto done;
}
/* The Id variant addresses the named channel, not the list head: sending on
* channel 1 draws down channel 1's peer window, leaving channel 0's alone. */
{
word32 peerWindowB = chB->peerWindowSz;
word32 peerWindowA = ch->peerWindowSz;
s_chanReqCaptureSz = 0;
ret = wolfSSH_ChannelIdSendExt(ssh, 1, payload,
(word32)sizeof(payload));
if (ret != (int)sizeof(payload)) { result = -746; goto done; }
if (CaptureMsgId(s_chanReqCapture, s_chanReqCaptureSz)
!= MSGID_CHANNEL_EXTENDED_DATA) {
result = -747; goto done;
}
if (chB->peerWindowSz != peerWindowB - sizeof(payload)) {
result = -748; goto done;
}
if (ch->peerWindowSz != peerWindowA) { result = -749; goto done; }
}
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#ifdef WOLFSSH_CERTS
/* RFC 6187 chain: [name][certCount][certSz][cert]...[ocspCount] */
static int test_ParseLeafCert_certCount(void)
{
static const byte blobEmpty[] = {
0x00,0x00,0x00,0x0E, /* nameSz = 14 */
0x78,0x35,0x30,0x39,0x76,0x33,0x2D, /* "x509v3-" */
0x73,0x73,0x68,0x2D,0x72,0x73,0x61, /* "ssh-rsa" */
0x00,0x00,0x00,0x00, /* certCount = 0 */
0x00,0x00,0x00,0x00 /* ocspCount = 0 */
};
static const byte blobOne[] = {
0x00,0x00,0x00,0x0E, /* nameSz = 14 */
0x78,0x35,0x30,0x39,0x76,0x33,0x2D, /* "x509v3-" */
0x73,0x73,0x68,0x2D,0x72,0x73,0x61, /* "ssh-rsa" */
0x00,0x00,0x00,0x01, /* certCount = 1 */
0x00,0x00,0x00,0x04, /* certSz = 4 */
0xDE,0xAD,0xBE,0xEF, /* leaf */
0x00,0x00,0x00,0x00 /* ocspCount = 0 */
};
byte* leaf = NULL;
word32 leafSz = 0;
int ret;
ret = wolfSSH_TestParseLeafCert((byte*)blobEmpty, (word32)sizeof(blobEmpty),
&leaf, &leafSz);
if (ret == WS_SUCCESS) {
printf("ParseLeafCert: accepted an empty certificate chain\n");
return -7100;
}
if (leaf != NULL || leafSz != 0) {
printf("ParseLeafCert: leaf set from an empty chain\n");
return -7101;
}
/* A well formed single-cert chain must still parse. */
ret = wolfSSH_TestParseLeafCert((byte*)blobOne, (word32)sizeof(blobOne),
&leaf, &leafSz);
if (ret != WS_SUCCESS) {
printf("ParseLeafCert: ret=%d on a one-cert chain\n", ret);
return -7102;
}
if (leaf != blobOne + 26 || leafSz != 4) {
printf("ParseLeafCert: wrong leaf, sz=%u\n", leafSz);
return -7103;
}
return 0;
}
#endif /* WOLFSSH_CERTS */
#ifndef NO_SHA256
/* RFC 4253 sec 7.2 key expansion, SHA-256, keySz = two digests plus a
* remainder, so the multi-block loop runs. Run once with K's MSB clear and
* once with it set, so the mpint pad byte is hashed. Guards the derived key
* only; the loop's error propagation is not covered. */
static int test_GenerateKey_multiBlock(void)
{
static const byte kBuf[] = {
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10,
0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20
};
static const byte hBuf[] = {
0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50,
0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50
};
static const byte sessionId[] = {
0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60,
0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60
};
static const byte expected[] = {
0xE1, 0x5C, 0x71, 0xCF, 0x66, 0xC2, 0x63, 0x7C,
0xC7, 0xB5, 0x07, 0x41, 0x3E, 0x3A, 0x1A, 0x74,
0x16, 0xC6, 0xE8, 0x63, 0x0F, 0xFC, 0x4B, 0x52,
0xB0, 0x70, 0x6C, 0xC2, 0xE4, 0x5B, 0x1D, 0x22,
0x15, 0xCB, 0xFE, 0x3C, 0xB2, 0x14, 0x5A, 0xF0,
0x02, 0x54, 0xC1, 0x44, 0x6D, 0xCF, 0xED, 0x58,
0x7B, 0xE2, 0x4C, 0x6E, 0xE9, 0x14, 0x01, 0xA0,
0x09, 0x36, 0x16, 0xBE, 0xE8, 0xD5, 0x08, 0xBA,
0x9B, 0x2C, 0xD0, 0x51, 0x7B
};
/* Same inputs with K[0] = 0x81. */
static const byte expectedPad[] = {
0x41, 0xC8, 0xD0, 0x42, 0xF2, 0x31, 0xEC, 0x12,
0x1C, 0xAC, 0x9B, 0x25, 0xC6, 0x50, 0xD2, 0xA7,
0x7E, 0x1A, 0xCD, 0x43, 0xCA, 0x6E, 0x23, 0xD1,
0xC4, 0x17, 0x28, 0x13, 0x69, 0xCD, 0x09, 0x45,
0xC5, 0xAD, 0x8B, 0x1D, 0x09, 0xA9, 0x8E, 0x0B,
0xE8, 0x92, 0x51, 0x9F, 0x7B, 0xF5, 0x37, 0x57,
0x7A, 0xF7, 0x3F, 0xA4, 0xB6, 0x08, 0x55, 0x5D,
0xF4, 0x76, 0xF9, 0x81, 0xC9, 0x38, 0x73, 0xAE,
0x4F, 0xAE, 0x32, 0x95, 0x5B
};
byte kPadBuf[sizeof(kBuf)];
byte key[sizeof(expected)];
int ret;
WMEMSET(key, 0, sizeof(key));
ret = GenerateKey(WC_HASH_TYPE_SHA256, 'A', key, (word32)sizeof(key),
kBuf, (word32)sizeof(kBuf), hBuf, (word32)sizeof(hBuf),
sessionId, (word32)sizeof(sessionId), 1);
if (ret != WS_SUCCESS) {
printf("GenerateKey_multiBlock: ret=%d\n", ret);
return -7000;
}
if (WMEMCMP(key, expected, sizeof(expected)) != 0) {
printf("GenerateKey_multiBlock: derived key mismatch\n");
return -7001;
}
WMEMCPY(kPadBuf, kBuf, sizeof(kBuf));
kPadBuf[0] = 0x81;
WMEMSET(key, 0, sizeof(key));
ret = GenerateKey(WC_HASH_TYPE_SHA256, 'A', key, (word32)sizeof(key),
kPadBuf, (word32)sizeof(kPadBuf), hBuf, (word32)sizeof(hBuf),
sessionId, (word32)sizeof(sessionId), 1);
if (ret != WS_SUCCESS) {
printf("GenerateKey_multiBlock: padded K ret=%d\n", ret);
return -7002;
}
if (WMEMCMP(key, expectedPad, sizeof(expectedPad)) != 0) {
printf("GenerateKey_multiBlock: padded K derived key mismatch\n");
return -7003;
}
return 0;
}
#endif /* !NO_SHA256 */
static int test_DoChannelRequest(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
int i;
/* Payloads: [uint32 channelId=0][string type][byte wantReply=1][extra] */
static const byte payShell[] = {
0x00,0x00,0x00,0x00, /* channelId = 0 */
0x00,0x00,0x00,0x05, /* typeSz = 5 */
0x73,0x68,0x65,0x6C,0x6C, /* "shell" */
0x01 /* wantReply = 1 */
};
static const byte payExec[] = {
0x00,0x00,0x00,0x00, /* channelId = 0 */
0x00,0x00,0x00,0x04, /* typeSz = 4 */
0x65,0x78,0x65,0x63, /* "exec" */
0x01, /* wantReply = 1 */
0x00,0x00,0x00,0x02, /* cmdSz = 2 */
0x6C,0x73 /* "ls" */
};
static const byte paySubsys[] = {
0x00,0x00,0x00,0x00, /* channelId = 0 */
0x00,0x00,0x00,0x09, /* typeSz = 9 */
0x73,0x75,0x62,0x73,0x79,0x73,
0x74,0x65,0x6D, /* "subsystem" */
0x01, /* wantReply = 1 */
0x00,0x00,0x00,0x04, /* nameSz = 4 */
0x73,0x66,0x74,0x70 /* "sftp" */
};
static const byte payUnknown[] = {
0x00,0x00,0x00,0x00, /* channelId = 0 */
0x00,0x00,0x00,0x0C, /* typeSz = 12 */
0x75,0x6E,0x6B,0x6E,0x6F,0x77,
0x6E,0x2D,0x74,0x79,0x70,0x65, /* "unknown-type" */
0x01 /* wantReply = 1 */
};
struct {
const char* label;
const byte* payload;
word32 payloadSz;
int expectRet;
byte expectMsgId;
} cases[] = {
{ "exec",
payExec, (word32)sizeof(payExec),
WS_SUCCESS, MSGID_CHANNEL_SUCCESS },
/* RFC 4254 sec 6.5: the exec holds the session. */
{ "shell-after-exec",
payShell, (word32)sizeof(payShell),
WS_SUCCESS, MSGID_CHANNEL_FAILURE },
{ "unknown-type",
payUnknown, (word32)sizeof(payUnknown),
WS_SUCCESS, MSGID_CHANNEL_FAILURE },
};
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -400;
wolfSSH_SetIOSend(ctx, CaptureIoSendChanReq);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
result = -401;
goto done;
}
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION,
DEFAULT_WINDOW_SZ, DEFAULT_MAX_PACKET_SZ);
if (ch == NULL) {
result = -402;
goto done;
}
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -403;
goto done;
}
/* A request type must match a handled name exactly. Truncated,
* empty, and NUL-padded types have to be rejected. These run before
* the positive cases below, which set the channel session type. */
{
static const byte payShellPrefix[] = {
0x00,0x00,0x00,0x00, /* channelId = 0 */
0x00,0x00,0x00,0x02, /* typeSz = 2 */
0x73,0x68, /* "sh" */
0x01 /* wantReply = 1 */
};
static const byte paySubPrefix[] = {
0x00,0x00,0x00,0x00, /* channelId = 0 */
0x00,0x00,0x00,0x03, /* typeSz = 3 */
0x73,0x75,0x62, /* "sub" */
0x01 /* wantReply = 1 */
};
static const byte payEmptyType[] = {
0x00,0x00,0x00,0x00, /* channelId = 0 */
0x00,0x00,0x00,0x00, /* typeSz = 0 */
0x01, /* wantReply = 1 */
0x00,0x00,0x00,0x00, /* env name = "" */
0x00,0x00,0x00,0x00 /* env value = "" */
};
static const byte payShellNul[] = {
0x00,0x00,0x00,0x00, /* channelId = 0 */
0x00,0x00,0x00,0x0A, /* typeSz = 10 */
0x73,0x68,0x65,0x6C,0x6C, /* "shell" */
0x00,0x41,0x41,0x41,0x41, /* "\0AAAA" */
0x01 /* wantReply = 1 */
};
struct { const char* label; const byte* buf; word32 sz; } badCases[] = {
{ "sh", payShellPrefix, (word32)sizeof(payShellPrefix) },
{ "sub", paySubPrefix, (word32)sizeof(paySubPrefix) },
{ "empty", payEmptyType, (word32)sizeof(payEmptyType) },
{ "shell-nul", payShellNul, (word32)sizeof(payShellNul) },
};
int b;
for (b = 0; b < (int)(sizeof(badCases)/sizeof(badCases[0])); b++) {
word32 idxBad = 0;
int retBad, capMsgId;
s_chanReqCaptureSz = 0;
WMEMSET(s_chanReqCapture, 0, sizeof(s_chanReqCapture));
retBad = wolfSSH_TestDoChannelRequest(ssh, (byte*)badCases[b].buf,
badCases[b].sz, &idxBad);
if (retBad != WS_SUCCESS) {
printf("DoChannelRequest[%s]: ret=%d, expected=%d\n",
badCases[b].label, retBad, WS_SUCCESS);
result = -460 - b;
goto done;
}
capMsgId = CaptureMsgId(s_chanReqCapture, s_chanReqCaptureSz);
if (capMsgId != (int)MSGID_CHANNEL_FAILURE) {
printf("DoChannelRequest[%s]: msg_id=0x%02x, expected=0x%02x\n",
badCases[b].label, capMsgId, MSGID_CHANNEL_FAILURE);
result = -470 - b;
goto done;
}
if (ch->sessionType == WOLFSSH_SESSION_SHELL) {
printf("DoChannelRequest[%s]: session type changed\n",
badCases[b].label);
result = -480 - b;
goto done;
}
if (ssh->clientState == CLIENT_DONE) {
printf("DoChannelRequest[%s]: client state changed\n",
badCases[b].label);
result = -490 - b;
goto done;
}
}
}
/* A callback that refuses a shell, exec or subsystem request must leave
* nothing behind: no session type or command on the channel, and the
* client state short of CLIENT_DONE, or wolfSSH_accept() would go on to
* serve the session it just refused. */
{
struct {
const char* label;
const byte* payload;
word32 payloadSz;
int errBase;
} rejCases[] = {
{ "shell", payShell, (word32)sizeof(payShell), -520 },
{ "exec", payExec, (word32)sizeof(payExec), -525 },
{ "subsystem", paySubsys, (word32)sizeof(paySubsys), -530 }
};
int r;
wolfSSH_CTX_SetChannelReqShellCb(ctx, RejectChanReqCb);
wolfSSH_CTX_SetChannelReqExecCb(ctx, RejectChanReqCb);
wolfSSH_CTX_SetChannelReqSubsysCb(ctx, RejectChanReqCb);
for (r = 0; r < (int)(sizeof(rejCases) / sizeof(rejCases[0])); r++) {
word32 idxRej = 0;
int retRej, capMsgId;
s_chanReqCaptureSz = 0;
WMEMSET(s_chanReqCapture, 0, sizeof(s_chanReqCapture));
s_rejectChanReqCalls = 0;
retRej = wolfSSH_TestDoChannelRequest(ssh,
(byte*)rejCases[r].payload, rejCases[r].payloadSz,
&idxRej);
if (retRej != WS_SUCCESS) {
printf("DoChannelRequest[rej-%s]: ret=%d, expected=%d\n",
rejCases[r].label, retRej, WS_SUCCESS);
result = rejCases[r].errBase;
goto done;
}
if (s_rejectChanReqCalls != 1) {
printf("DoChannelRequest[rej-%s]: callback ran %d times\n",
rejCases[r].label, s_rejectChanReqCalls);
result = rejCases[r].errBase - 1;
goto done;
}
capMsgId = CaptureMsgId(s_chanReqCapture, s_chanReqCaptureSz);
if (capMsgId != (int)MSGID_CHANNEL_FAILURE) {
printf("DoChannelRequest[rej-%s]: msg_id=0x%02x, "
"expected=0x%02x\n", rejCases[r].label, capMsgId,
MSGID_CHANNEL_FAILURE);
result = rejCases[r].errBase - 2;
goto done;
}
if (ch->sessionType != WOLFSSH_SESSION_UNKNOWN
|| ch->command != NULL) {
printf("DoChannelRequest[rej-%s]: session committed\n",
rejCases[r].label);
result = rejCases[r].errBase - 3;
goto done;
}
if (ssh->clientState == CLIENT_DONE) {
printf("DoChannelRequest[rej-%s]: client state changed\n",
rejCases[r].label);
result = rejCases[r].errBase - 4;
goto done;
}
}
wolfSSH_CTX_SetChannelReqShellCb(ctx, NULL);
wolfSSH_CTX_SetChannelReqExecCb(ctx, NULL);
wolfSSH_CTX_SetChannelReqSubsysCb(ctx, NULL);
}
for (i = 0; i < (int)(sizeof(cases) / sizeof(cases[0])); i++) {
word32 idx = 0;
int ret;
s_chanReqCaptureSz = 0;
WMEMSET(s_chanReqCapture, 0, sizeof(s_chanReqCapture));
ret = wolfSSH_TestDoChannelRequest(ssh,
(byte*)cases[i].payload, cases[i].payloadSz, &idx);
if (ret != cases[i].expectRet) {
printf("DoChannelRequest[%s]: ret=%d, expected=%d\n",
cases[i].label, ret, cases[i].expectRet);
result = -404 - i;
goto done;
}
{
int capMsgId = CaptureMsgId(s_chanReqCapture, s_chanReqCaptureSz);
if (capMsgId < 0) {
printf("DoChannelRequest[%s]: captured packet too short (%u)\n",
cases[i].label, s_chanReqCaptureSz);
result = -410 - i;
goto done;
}
if (capMsgId != (int)cases[i].expectMsgId) {
printf("DoChannelRequest[%s]: msg_id=0x%02x, expected=0x%02x\n",
cases[i].label,
capMsgId, cases[i].expectMsgId);
result = -420 - i;
goto done;
}
}
}
/* A second exec is refused without asking the callback and must not
* replace the granted command. */
{
static const byte payExecOther[] = {
0x00,0x00,0x00,0x00, /* channelId = 0 */
0x00,0x00,0x00,0x04, /* typeSz = 4 */
0x65,0x78,0x65,0x63, /* "exec" */
0x01, /* wantReply = 1 */
0x00,0x00,0x00,0x06, /* cmdSz = 6 */
0x77,0x68,0x6F,0x61,0x6D,0x69 /* "whoami" */
};
word32 idxRej = 0;
const char* cmd;
int retRej, capMsgId;
if (wolfSSH_CTX_SetChannelReqExecCb(ctx, RejectChanReqCb)
!= WS_SUCCESS) {
printf("DoChannelRequest[rej-exec-granted]: no callback set\n");
result = -505;
goto done;
}
s_chanReqCaptureSz = 0;
WMEMSET(s_chanReqCapture, 0, sizeof(s_chanReqCapture));
s_rejectChanReqCalls = 0;
retRej = wolfSSH_TestDoChannelRequest(ssh, (byte*)payExecOther,
(word32)sizeof(payExecOther), &idxRej);
if (retRej != WS_SUCCESS || s_rejectChanReqCalls != 0) {
printf("DoChannelRequest[rej-exec-granted]: ret=%d, callback ran "
"%d times\n", retRej, s_rejectChanReqCalls);
result = -506;
goto done;
}
capMsgId = CaptureMsgId(s_chanReqCapture, s_chanReqCaptureSz);
if (capMsgId != (int)MSGID_CHANNEL_FAILURE) {
printf("DoChannelRequest[rej-exec-granted]: msg_id=0x%02x, "
"expected=0x%02x\n", capMsgId, MSGID_CHANNEL_FAILURE);
result = -507;
goto done;
}
/* "ls" is intact: pointer and length. */
cmd = wolfSSH_ChannelGetSessionCommand(ch);
if (cmd == NULL || WSTRCMP(cmd, "ls") != 0
|| wolfSSH_ChannelGetSessionCommandSz(ch) != 2) {
printf("DoChannelRequest[rej-exec-granted]: command = %s, sz = %u\n",
cmd == NULL ? "(null)" : cmd,
wolfSSH_ChannelGetSessionCommandSz(ch));
result = -508;
goto done;
}
if (wolfSSH_ChannelGetSessionType(ch) != WOLFSSH_SESSION_EXEC) {
printf("DoChannelRequest[rej-exec-granted]: type not exec\n");
result = -509;
goto done;
}
/* The refusal answered this request, it did not take back the
* session the granted exec won. */
if (!ch->sessionGranted) {
printf("DoChannelRequest[rej-exec-granted]: grant lost\n");
result = -510;
goto done;
}
if (wolfSSH_CTX_SetChannelReqExecCb(ctx, NULL) != WS_SUCCESS) {
printf("DoChannelRequest[rej-exec-granted]: callback not cleared\n");
result = -511;
goto done;
}
}
/* The refused shell leaves the exec's command and type alone. */
{
word32 idxShell = 0;
const char* cmd;
if (wolfSSH_TestDoChannelRequest(ssh, (byte*)payShell,
(word32)sizeof(payShell), &idxShell) != WS_SUCCESS) {
printf("DoChannelRequest[shell-after-exec]: failed\n");
result = -512;
goto done;
}
cmd = wolfSSH_ChannelGetSessionCommand(ch);
if (cmd == NULL || WSTRCMP(cmd, "ls") != 0) {
printf("DoChannelRequest[shell-after-exec]: command = %s\n",
cmd == NULL ? "(null)" : cmd);
result = -501;
goto done;
}
if (wolfSSH_ChannelGetSessionType(ch) != WOLFSSH_SESSION_EXEC) {
printf("DoChannelRequest[shell-after-exec]: type not exec\n");
result = -502;
goto done;
}
}
/* RFC 4254 sec 6.10: exit-status and exit-signal must not send a reply
* even if the wire wantReply byte is 1. DoChannelRequest overrides
* wantReply=0 for these types, so no CHANNEL_SUCCESS/FAILURE packet
* should be emitted. */
#if defined(WOLFSSH_TERM) || defined(WOLFSSH_SHELL)
{
static const byte payExitStatus[] = {
0x00,0x00,0x00,0x00, /* channelId = 0 */
0x00,0x00,0x00,0x0B, /* typeSz = 11 */
0x65,0x78,0x69,0x74,0x2D, /* "exit-" */
0x73,0x74,0x61,0x74,0x75,0x73, /* "status" */
0x01, /* wantReply = 1 (wire) */
0x00,0x00,0x00,0x00 /* exitStatus = 0 */
};
/* exit-signal: sigName="TERM", coreDumped=0, errorMsg="",
* languageTag="" */
static const byte payExitSignal[] = {
0x00,0x00,0x00,0x00, /* channelId = 0 */
0x00,0x00,0x00,0x0B, /* typeSz = 11 */
0x65,0x78,0x69,0x74,0x2D, /* "exit-" */
0x73,0x69,0x67,0x6E,0x61,0x6C, /* "signal" */
0x01, /* wantReply = 1 (wire) */
0x00,0x00,0x00,0x04, /* sigNameSz = 4 */
0x54,0x45,0x52,0x4D, /* "TERM" */
0x00, /* coreDumped = false */
0x00,0x00,0x00,0x00, /* errorMsg = "" */
0x00,0x00,0x00,0x00 /* languageTag = "" */
};
struct { const char* label; const byte* buf; word32 sz; int errBase; }
noReplyCases[] = {
{ "exit-status", payExitStatus, (word32)sizeof(payExitStatus), -430 },
{ "exit-signal", payExitSignal, (word32)sizeof(payExitSignal), -440 },
};
int k;
for (k = 0; k < (int)(sizeof(noReplyCases)/sizeof(noReplyCases[0]));
k++) {
word32 idx2 = 0;
int ret2;
s_chanReqCaptureSz = 0;
WMEMSET(s_chanReqCapture, 0, sizeof(s_chanReqCapture));
ret2 = wolfSSH_TestDoChannelRequest(ssh, (byte*)noReplyCases[k].buf,
noReplyCases[k].sz, &idx2);
if (ret2 != WS_SUCCESS) {
printf("DoChannelRequest[%s]: ret=%d, expected=%d\n",
noReplyCases[k].label, ret2, WS_SUCCESS);
result = noReplyCases[k].errBase;
goto done;
}
if (s_chanReqCaptureSz != 0) {
printf("DoChannelRequest[%s]: unexpected reply packet "
"(sz=%u)\n", noReplyCases[k].label,
s_chanReqCaptureSz);
result = noReplyCases[k].errBase - 1;
goto done;
}
}
}
#endif /* WOLFSSH_TERM || WOLFSSH_SHELL */
/* RFC 4254 sec 6.7: window-change must not send a reply even if the
* wire wantReply byte is 1. No pty-req has been seen on this channel
* yet, so the request is also rejected and the size stays put. */
#if defined(WOLFSSH_SHELL) && defined(WOLFSSH_TERM)
{
static const byte payWindowChange[] = {
0x00,0x00,0x00,0x00, /* channelId = 0 */
0x00,0x00,0x00,0x0D, /* typeSz = 13 */
0x77,0x69,0x6E,0x64,0x6F,0x77,0x2D, /* "window-" */
0x63,0x68,0x61,0x6E,0x67,0x65, /* "change" */
0x01, /* wantReply = 1 (wire) */
0x00,0x00,0x00,0x50, /* widthChar = 80 */
0x00,0x00,0x00,0x18, /* heightRows = 24 */
0x00,0x00,0x00,0x00, /* widthPixels = 0 */
0x00,0x00,0x00,0x00 /* heightPixels = 0 */
};
word32 idx2 = 0;
int ret2;
s_chanReqCaptureSz = 0;
WMEMSET(s_chanReqCapture, 0, sizeof(s_chanReqCapture));
ret2 = wolfSSH_TestDoChannelRequest(ssh, (byte*)payWindowChange,
(word32)sizeof(payWindowChange), &idx2);
if (ret2 != WS_SUCCESS) {
printf("DoChannelRequest[window-change]: ret=%d, expected=%d\n",
ret2, WS_SUCCESS);
result = -450;
goto done;
}
if (s_chanReqCaptureSz != 0) {
printf("DoChannelRequest[window-change]: unexpected reply packet "
"(sz=%u)\n", s_chanReqCaptureSz);
result = -451;
goto done;
}
if (ssh->widthChar != 0 || ssh->heightRows != 0) {
printf("DoChannelRequest[window-change]: applied %ux%u without "
"a pty\n", ssh->widthChar, ssh->heightRows);
result = -452;
goto done;
}
}
/* A pty-req establishes the pty and the size, and runs the same
* clamping the window-change branch does. */
{
static byte payPtyReq[] = {
0x00,0x00,0x00,0x00, /* channelId = 0 */
0x00,0x00,0x00,0x07, /* typeSz = 7 */
0x70,0x74,0x79,0x2D,0x72,0x65,0x71, /* "pty-req" */
0x00, /* wantReply = 0 */
0x00,0x00,0x00,0x05, /* termSz = 5 */
0x76,0x74,0x31,0x30,0x30, /* "vt100" */
0x00,0x00,0x00,0x50, /* widthChar = 80 */
0x00,0x00,0x00,0x18, /* heightRows = 24 */
0x00,0x00,0x02,0x80, /* widthPixels = 640 */
0x00,0x00,0x01,0xE0, /* heightPixels = 480 */
0x00,0x00,0x00,0x01, /* modesSz = 1 */
0x00 /* TTY_OP_END */
};
/* offsets of the four dimensions within the payload above */
const word32 pwcOff = 25, phrOff = 29, pwpOff = 33, phpOff = 37;
word32 idx2 = 0;
int ret2;
ret2 = wolfSSH_TestDoChannelRequest(ssh, payPtyReq,
(word32)sizeof(payPtyReq), &idx2);
if (ret2 != WS_SUCCESS) {
printf("DoChannelRequest[pty-req]: ret=%d, expected=%d\n",
ret2, WS_SUCCESS);
result = -453;
goto done;
}
if (ssh->widthChar != 80 || ssh->heightRows != 24 ||
ssh->widthPixels != 640 || ssh->heightPixels != 480) {
printf("DoChannelRequest[pty-req]: got %ux%u %ux%u, "
"expected 80x24 640x480\n", ssh->widthChar,
ssh->heightRows, ssh->widthPixels, ssh->heightPixels);
result = -454;
goto done;
}
/* the clamp is on the pty-req path too, pixels included */
PutU32BE(payPtyReq + pwcOff, 0x10000);
PutU32BE(payPtyReq + phrOff, 0x10000);
PutU32BE(payPtyReq + pwpOff, 0xFFFFFFFF);
PutU32BE(payPtyReq + phpOff, 0xFFFFFFFF);
idx2 = 0;
ret2 = wolfSSH_TestDoChannelRequest(ssh, payPtyReq,
(word32)sizeof(payPtyReq), &idx2);
if (ret2 != WS_SUCCESS) {
printf("DoChannelRequest[pty-req clamp]: ret=%d, expected=%d\n",
ret2, WS_SUCCESS);
result = -455;
goto done;
}
if (ssh->widthChar != 65535 || ssh->heightRows != 65535 ||
ssh->widthPixels != 65535 || ssh->heightPixels != 65535) {
printf("DoChannelRequest[pty-req clamp]: got %ux%u %ux%u, "
"expected 65535 throughout\n", ssh->widthChar,
ssh->heightRows, ssh->widthPixels, ssh->heightPixels);
result = -456;
goto done;
}
}
/* Dimensions are stored as sent, zero included, as others do.
* Oversized ones are clamped to what a struct winsize holds. */
{
static byte payWindowChange[] = {
0x00,0x00,0x00,0x00, /* channelId = 0 */
0x00,0x00,0x00,0x0D, /* typeSz = 13 */
0x77,0x69,0x6E,0x64,0x6F,0x77,0x2D, /* "window-" */
0x63,0x68,0x61,0x6E,0x67,0x65, /* "change" */
0x00, /* wantReply = 0 */
0x00,0x00,0x00,0x00, /* widthChar */
0x00,0x00,0x00,0x00, /* heightRows */
0x00,0x00,0x00,0x00, /* widthPixels */
0x00,0x00,0x00,0x00 /* heightPixels */
};
/* offsets of the four dimensions within the payload above */
const word32 wcOff = 22, hrOff = 26, wpOff = 30, hpOff = 34;
word32 idx2;
int ret2;
int d;
struct {
const char* label;
word32 widthChar;
word32 heightRows;
word32 widthPixels;
word32 heightPixels;
word32 expectWidth;
word32 expectRows;
word32 expectPixWidth;
word32 expectPixHeight;
int errBase;
} dimCases[] = {
/* establish a known size first */
{ "baseline", 120, 40, 960, 640, 120, 40, 960, 640, -1600 },
/* zeros are stored as sent, not merged with the previous size */
{ "zeroes", 0, 0, 0, 0, 0, 0, 0, 0, -1602 },
/* including a zero in one dimension only */
{ "zeroWidth", 0, 50, 0, 640, 0, 50, 0, 640, -1604 },
/* out of range is clamped, not wrapped to zero */
{ "wrapping", 0x10000, 0x10000, 0x10000, 0x10000,
65535, 65535, 65535, 65535, -1606 },
{ "huge", 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
65535, 65535, 65535, 65535, -1608 }
};
for (d = 0; d < (int)(sizeof(dimCases) / sizeof(dimCases[0])); d++) {
PutU32BE(payWindowChange + wcOff, dimCases[d].widthChar);
PutU32BE(payWindowChange + hrOff, dimCases[d].heightRows);
PutU32BE(payWindowChange + wpOff, dimCases[d].widthPixels);
PutU32BE(payWindowChange + hpOff, dimCases[d].heightPixels);
idx2 = 0;
ret2 = wolfSSH_TestDoChannelRequest(ssh, payWindowChange,
(word32)sizeof(payWindowChange), &idx2);
if (ret2 != WS_SUCCESS) {
printf("DoChannelRequest[%s]: ret=%d, expected=%d\n",
dimCases[d].label, ret2, WS_SUCCESS);
result = dimCases[d].errBase;
goto done;
}
if (ssh->widthChar != dimCases[d].expectWidth ||
ssh->heightRows != dimCases[d].expectRows ||
ssh->widthPixels != dimCases[d].expectPixWidth ||
ssh->heightPixels != dimCases[d].expectPixHeight) {
printf("DoChannelRequest[%s]: got %ux%u %ux%u, "
"expected %ux%u %ux%u\n", dimCases[d].label,
ssh->widthChar, ssh->heightRows,
ssh->widthPixels, ssh->heightPixels,
dimCases[d].expectWidth, dimCases[d].expectRows,
dimCases[d].expectPixWidth,
dimCases[d].expectPixHeight);
result = dimCases[d].errBase - 1;
goto done;
}
}
}
#endif /* WOLFSSH_SHELL && WOLFSSH_TERM */
/* Application-driven channels flip the no-callback default: with
* accept() already returned there is nothing left to start a shell,
* exec or subsystem, so all three are refused rather than accepted. */
{
struct {
const char* label;
const byte* payload;
word32 payloadSz;
int errBase;
} appCases[] = {
{ "shell", payShell, (word32)sizeof(payShell), -495 },
{ "exec", payExec, (word32)sizeof(payExec), -497 },
{ "subsystem", paySubsys, (word32)sizeof(paySubsys), -499 }
};
int a;
for (a = 0; a < (int)(sizeof(appCases) / sizeof(appCases[0])); a++) {
word32 idxApp = 0;
int retApp, capMsgId;
if (wolfSSH_SetAppChannels(ssh, 1) != WS_SUCCESS) {
printf("DoChannelRequest[app-%s]: set failed\n",
appCases[a].label);
result = appCases[a].errBase;
goto done;
}
s_chanReqCaptureSz = 0;
WMEMSET(s_chanReqCapture, 0, sizeof(s_chanReqCapture));
retApp = wolfSSH_TestDoChannelRequest(ssh,
(byte*)appCases[a].payload, appCases[a].payloadSz,
&idxApp);
wolfSSH_SetAppChannels(ssh, 0);
if (retApp != WS_SUCCESS) {
printf("DoChannelRequest[app-%s]: ret=%d, expected=%d\n",
appCases[a].label, retApp, WS_SUCCESS);
result = appCases[a].errBase;
goto done;
}
capMsgId = CaptureMsgId(s_chanReqCapture, s_chanReqCaptureSz);
if (capMsgId != (int)MSGID_CHANNEL_FAILURE) {
printf("DoChannelRequest[app-%s]: msg_id=0x%02x, "
"expected=0x%02x\n", appCases[a].label, capMsgId,
MSGID_CHANNEL_FAILURE);
result = appCases[a].errBase - 1;
goto done;
}
}
}
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#ifdef TEST_TERM_REQUEST_NO_TTY
static word32 CaptureUint32(const byte* buf)
{
return ((word32)buf[0] << 24) | ((word32)buf[1] << 16) |
((word32)buf[2] << 8) | (word32)buf[3];
}
/* Without a tty the terminal settings and window size can't be read. The
* request falls back to the default modes and an 80x24 window. */
static int test_SendChannelTerminalRequestNoTty(void)
{
/* bitrate 38400 is 0x9600, sent in and out, then the terminator */
static const byte expectedModes[] = {
WOLFSSH_TTY_OP_ISPEED, 0x00, 0x00, 0x96, 0x00,
WOLFSSH_TTY_OP_OSPEED, 0x00, 0x00, 0x96, 0x00,
WOLFSSH_TTY_OP_END
};
static const char ptyReq[] = "pty-req";
static const char testTerm[] = "vt100";
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
const char* termEnv;
char* termSave = NULL;
int result = 0;
int ret;
int termPinned = 0;
int stdinCopy = -1;
int stdoutCopy = -1;
int devNull = -1;
int inBack, outBack;
word32 termSaveSz;
word32 idx, typeSz, termSz, modeSz;
word32 width, height, pixWidth, pixHeight;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -1470;
wolfSSH_SetIOSend(ctx, CaptureIoSendChanReq);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1471; goto done; }
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION,
DEFAULT_WINDOW_SZ, DEFAULT_MAX_PACKET_SZ);
if (ch == NULL) { result = -1472; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1473;
goto done;
}
ch->peerChannel = ch->channel;
ssh->defaultPeerChannelId = ch->peerChannel;
s_chanReqCaptureSz = 0;
WMEMSET(s_chanReqCapture, 0, sizeof(s_chanReqCapture));
/* TERM is echoed into the packet, so pin it rather than let the host
* environment decide how big the capture has to be */
termEnv = getenv("TERM");
if (termEnv != NULL) {
termSaveSz = (word32)WSTRLEN(termEnv) + 1;
termSave = (char*)malloc(termSaveSz);
if (termSave == NULL) { result = -1474; goto done; }
WMEMCPY(termSave, termEnv, termSaveSz);
}
if (setenv("TERM", testTerm, 1) != 0) { result = -1475; goto done; }
termPinned = 1;
/* stdin carries the terminal settings and stdout the window size, so
* both are pointed at /dev/null to model a client with no terminal */
stdinCopy = dup(STDIN_FILENO);
stdoutCopy = dup(STDOUT_FILENO);
devNull = open("/dev/null", O_RDWR);
if (stdinCopy < 0 || stdoutCopy < 0 || devNull < 0) {
result = -1476;
goto done;
}
if (dup2(devNull, STDIN_FILENO) < 0) { result = -1477; goto done; }
if (dup2(devNull, STDOUT_FILENO) < 0) { result = -1478; goto done; }
ret = SendChannelTerminalRequest(ssh);
/* put the streams back before anything is printed, restoring stdout
* even when stdin fails so later tests are not silenced */
inBack = dup2(stdinCopy, STDIN_FILENO);
outBack = dup2(stdoutCopy, STDOUT_FILENO);
if (inBack < 0 || outBack < 0) {
result = -1479;
}
close(stdinCopy);
stdinCopy = -1;
close(stdoutCopy);
stdoutCopy = -1;
if (result != 0)
goto done;
if (ret != WS_SUCCESS) {
printf("SendChannelTerminalRequest: ret=%d, expected=%d\n",
ret, WS_SUCCESS);
result = -1480;
goto done;
}
if (s_chanReqCaptureSz == 0 ||
s_chanReqCaptureSz >= (word32)sizeof(s_chanReqCapture)) {
printf("SendChannelTerminalRequest: capture sz=%u\n",
s_chanReqCaptureSz);
result = -1481;
goto done;
}
if (CaptureMsgId(s_chanReqCapture, s_chanReqCaptureSz)
!= MSGID_CHANNEL_REQUEST) {
result = -1482;
goto done;
}
/* walk the payload, keeping idx inside the capture at every step */
idx = LENGTH_SZ + PAD_LENGTH_SZ + MSG_ID_SZ + UINT32_SZ;
if (idx + UINT32_SZ > s_chanReqCaptureSz) { result = -1483; goto done; }
typeSz = CaptureUint32(s_chanReqCapture + idx);
idx += UINT32_SZ;
if (typeSz != (word32)(sizeof(ptyReq) - 1) ||
typeSz > s_chanReqCaptureSz - idx) {
printf("SendChannelTerminalRequest: typeSz=%u\n", typeSz);
result = -1484;
goto done;
}
if (WMEMCMP(s_chanReqCapture + idx, ptyReq, typeSz) != 0) {
result = -1485;
goto done;
}
idx += typeSz;
if (BOOLEAN_SZ + UINT32_SZ > s_chanReqCaptureSz - idx) {
result = -1486;
goto done;
}
idx += BOOLEAN_SZ;
termSz = CaptureUint32(s_chanReqCapture + idx);
idx += UINT32_SZ;
if (termSz != (word32)(sizeof(testTerm) - 1) ||
termSz > s_chanReqCaptureSz - idx) {
printf("SendChannelTerminalRequest: termSz=%u\n", termSz);
result = -1487;
goto done;
}
if (WMEMCMP(s_chanReqCapture + idx, testTerm, termSz) != 0) {
result = -1488;
goto done;
}
idx += termSz;
/* the window size must never be negotiated as 0x0 */
if (UINT32_SZ * 4 > s_chanReqCaptureSz - idx) { result = -1489; goto done; }
width = CaptureUint32(s_chanReqCapture + idx);
height = CaptureUint32(s_chanReqCapture + idx + UINT32_SZ);
pixWidth = CaptureUint32(s_chanReqCapture + idx + (UINT32_SZ * 2));
pixHeight = CaptureUint32(s_chanReqCapture + idx + (UINT32_SZ * 3));
idx += UINT32_SZ * 4;
if (width != TERMINAL_WIDTH_DEFAULT || height != TERMINAL_HEIGHT_DEFAULT ||
pixWidth != 0 || pixHeight != 0) {
printf("SendChannelTerminalRequest: window %ux%u (%ux%u px)\n",
width, height, pixWidth, pixHeight);
result = -1490;
goto done;
}
/* the modes are the fixed fallback list, not whatever termios left */
if (UINT32_SZ > s_chanReqCaptureSz - idx) { result = -1491; goto done; }
modeSz = CaptureUint32(s_chanReqCapture + idx);
idx += UINT32_SZ;
if (modeSz != (word32)sizeof(expectedModes) ||
modeSz > s_chanReqCaptureSz - idx) {
printf("SendChannelTerminalRequest: modeSz=%u, expected=%u\n",
modeSz, (word32)sizeof(expectedModes));
result = -1492;
goto done;
}
if (WMEMCMP(s_chanReqCapture + idx, expectedModes, modeSz) != 0) {
result = -1493;
goto done;
}
done:
/* Only reached with a descriptor still open on an already-failed path, so
* restore it but keep the original error code. Unlike the TERM block
* below, a result check here would never be true. */
if (stdinCopy >= 0) {
(void)dup2(stdinCopy, STDIN_FILENO);
close(stdinCopy);
}
if (stdoutCopy >= 0) {
(void)dup2(stdoutCopy, STDOUT_FILENO);
close(stdoutCopy);
}
if (termPinned) {
if (termSave != NULL) {
if (setenv("TERM", termSave, 1) != 0 && result == 0)
result = -1496;
}
else if (unsetenv("TERM") != 0 && result == 0) {
result = -1496;
}
}
if (termSave != NULL)
free(termSave);
if (devNull >= 0)
close(devNull);
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* TEST_TERM_REQUEST_NO_TTY */
/* IO send that always wants write, the state a peer forces by not reading. */
static int UnitIoSendWantWrite(WOLFSSH* ssh, void* buf, word32 sz, void* ctx)
{
(void)ssh; (void)buf; (void)sz; (void)ctx;
return WS_CBIO_ERR_WANT_WRITE;
}
static int UnitAuthAlwaysFail(byte authType, WS_UserAuthData* authData,
void* ctx)
{
(void)authType; (void)authData; (void)ctx;
return WOLFSSH_USERAUTH_INVALID_PASSWORD;
}
#ifdef WOLFSSH_KEYBOARD_INTERACTIVE
/* Set when the callback sees a response, so a processed INFO_RESPONSE is
* visible even when rejected. */
static int s_kbRespCbCalled = 0;
/* Keyboard setup that accepts, sending an INFO_REQUEST with no prompts so the
* exchange goes outstanding (kbSetupPending). Every other outcome fails. */
static int UnitAuthKbSetupOk(byte authType, WS_UserAuthData* authData,
void* ctx)
{
(void)ctx;
if (authType == WOLFSSH_USERAUTH_KEYBOARD_SETUP) {
authData->sf.keyboard.promptCount = 0;
return WOLFSSH_USERAUTH_SUCCESS;
}
if (authType == WOLFSSH_USERAUTH_KEYBOARD) {
s_kbRespCbCalled = 1;
}
return WOLFSSH_USERAUTH_INVALID_PASSWORD;
}
#endif /* WOLFSSH_KEYBOARD_INTERACTIVE */
#if defined(WOLFSSH_KEYBOARD_INTERACTIVE) || \
defined(WOLFSSH_ALLOW_USERAUTH_NONE) || !defined(WOLFSSH_NO_PUBKEY_AUTH)
/* Build a USERAUTH_REQUEST payload for `service` and auth method `method`
* with no method-specific fields, as DoUserAuthRequest() sees it with the
* message id already consumed. The keyboard and none dispatch paths don't
* parse trailing fields, so three strings (user, service, method) suffice,
* and the publickey path appends its own fields to this. A NULL method omits
* that field, which a bad service name never reaches. Returns the payload
* size, 0 on overflow. */
static word32 BuildAuthMethodRequest(byte* buf, word32 bufSz,
const char* service, const char* method)
{
const char* fields[3];
word32 idx = 0, i, fieldCount;
word32 fieldSz;
fields[0] = "jill";
fields[1] = service;
fields[2] = method;
fieldCount = (method == NULL) ? 2 : 3;
for (i = 0; i < fieldCount; i++) {
fieldSz = (word32)WSTRLEN(fields[i]);
if (idx + UINT32_SZ + fieldSz > bufSz)
return 0;
PutU32BE(buf + idx, fieldSz);
idx += UINT32_SZ;
WMEMCPY(buf + idx, fields[i], fieldSz);
idx += fieldSz;
}
return idx;
}
#ifndef WOLFSSH_NO_PUBKEY_AUTH
/* A public key algorithm the server offers, so the request gets past the
* algorithm match and reaches the userauth callback. */
#ifndef WOLFSSH_NO_ECDSA_SHA2_NISTP256
#define UNIT_AUTH_PK_ALGO "ecdsa-sha2-nistp256"
#elif !defined(WOLFSSH_NO_RSA_SHA2_256)
#define UNIT_AUTH_PK_ALGO "rsa-sha2-256"
#elif !defined(WOLFSSH_NO_ED25519)
#define UNIT_AUTH_PK_ALGO "ssh-ed25519"
#endif
#ifdef UNIT_AUTH_PK_ALGO
/* Build the no-signature "publickey" USERAUTH_REQUEST, the PK_OK probe. The
* handler reads the key blob only as far as its format string before calling
* the userauth callback, so the algorithm name stands in for the key. Returns
* the payload size, 0 on overflow. */
static word32 BuildAuthPkRequest(byte* buf, word32 bufSz)
{
word32 idx, algoSz = (word32)WSTRLEN(UNIT_AUTH_PK_ALGO);
idx = BuildAuthMethodRequest(buf, bufSz, "ssh-connection", "publickey");
if (idx == 0)
return 0;
if (idx + BOOLEAN_SZ + 3 * UINT32_SZ + 2 * algoSz > bufSz)
return 0;
buf[idx++] = 0; /* has signature FALSE */
PutU32BE(buf + idx, algoSz);
idx += UINT32_SZ;
WMEMCPY(buf + idx, UNIT_AUTH_PK_ALGO, algoSz);
idx += algoSz;
/* Key blob, itself a string holding the key format. */
PutU32BE(buf + idx, UINT32_SZ + algoSz);
idx += UINT32_SZ;
PutU32BE(buf + idx, algoSz);
idx += UINT32_SZ;
WMEMCPY(buf + idx, UNIT_AUTH_PK_ALGO, algoSz);
idx += algoSz;
return idx;
}
#endif /* UNIT_AUTH_PK_ALGO */
#endif /* !WOLFSSH_NO_PUBKEY_AUTH */
#endif /* WOLFSSH_KEYBOARD_INTERACTIVE || WOLFSSH_ALLOW_USERAUTH_NONE
* || !WOLFSSH_NO_PUBKEY_AUTH */
/* Build a "password" USERAUTH_REQUEST payload, as DoUserAuthRequest() sees it
* with the message id already consumed. Returns the payload size. */
static word32 BuildAuthPwRequest(byte* buf, word32 bufSz)
{
static const char* fields[] = { "jill", "ssh-connection", "password" };
word32 idx = 0, i, fieldSz;
for (i = 0; i < sizeof(fields)/sizeof(fields[0]); i++) {
fieldSz = (word32)WSTRLEN(fields[i]);
if (idx + UINT32_SZ + fieldSz > bufSz)
return 0;
PutU32BE(buf + idx, fieldSz);
idx += UINT32_SZ;
WMEMCPY(buf + idx, fields[i], fieldSz);
idx += fieldSz;
}
fieldSz = (word32)WSTRLEN("badpass");
if (idx + 1 + UINT32_SZ + fieldSz > bufSz)
return 0;
buf[idx++] = 0; /* no password change */
PutU32BE(buf + idx, fieldSz);
idx += UINT32_SZ;
WMEMCPY(buf + idx, "badpass", fieldSz);
idx += fieldSz;
return idx;
}
/* Verify the failed-userauth cap actually fires, and that it fires whether or
* not the USERAUTH_FAILURE send completes. The want-write case is the
* regression: WS_WANT_WRITE is non-fatal in DoReceive(), so a peer that stops
* reading its socket must not be able to pipeline uncounted guesses.
*
* Asserts, with the limit set to 3: attempts 1 and 2 leave the connection up
* (WS_SUCCESS, or WS_WANT_WRITE when the send blocks) and attempt 3 returns
* WS_USER_AUTH_E, ending the accept loop. */
static int test_MaxAuthAttempts(void)
{
byte request[128];
word32 requestSz;
int result = 0;
int i;
struct {
WS_CallbackIOSend send;
int expectRet; /* return for the under-the-limit attempts */
const char* label;
} cases[] = {
{ UnitIoSendSink, WS_SUCCESS, "send completes" },
{ UnitIoSendWantWrite, WS_WANT_WRITE, "send wants write" },
};
requestSz = BuildAuthPwRequest(request, (word32)sizeof(request));
if (requestSz == 0)
return -700;
for (i = 0; i < (int)(sizeof(cases)/sizeof(cases[0])); i++) {
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
int attempt;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL) { result = -701; break; }
wolfSSH_SetUserAuth(ctx, UnitAuthAlwaysFail);
wolfSSH_SetIOSend(ctx, cases[i].send);
if (wolfSSH_CTX_SetMaxAuthAttempts(ctx, 3) != WS_SUCCESS) {
wolfSSH_CTX_free(ctx);
result = -702;
break;
}
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { wolfSSH_CTX_free(ctx); result = -703; break; }
for (attempt = 1; attempt <= 3 && result == 0; attempt++) {
word32 idx = 0;
int expect = (attempt < 3) ? cases[i].expectRet : WS_USER_AUTH_E;
int ret = wolfSSH_TestDoUserAuthRequest(ssh, request, requestSz,
&idx);
if (ret != expect) {
printf("MaxAuthAttempts[%s]: attempt %d ret=%d expected %d\n",
cases[i].label, attempt, ret, expect);
result = -710 - (i * 10) - attempt;
}
}
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
}
/* The opening "none" probe clients send to learn the method list is exempt
* from the cap. With the limit at 1: the first "none" must leave the
* connection up (not counted), and the second must be counted and trip the
* cap. This covers the invalid-method else-branch, and DoUserAuthRequestNone
* under WOLFSSH_ALLOW_USERAUTH_NONE, both of which share the exemption. */
if (result == 0) {
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
byte noneReq[64];
word32 noneReqSz = 0;
const char* fields[3];
word32 idx = 0, f, fieldSz;
fields[0] = "jill"; fields[1] = "ssh-connection"; fields[2] = "none";
for (f = 0; f < 3; f++) {
fieldSz = (word32)WSTRLEN(fields[f]);
PutU32BE(noneReq + idx, fieldSz);
idx += UINT32_SZ;
WMEMCPY(noneReq + idx, fields[f], fieldSz);
idx += fieldSz;
}
noneReqSz = idx;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL) { result = -740; }
else {
wolfSSH_SetUserAuth(ctx, UnitAuthAlwaysFail);
wolfSSH_SetIOSend(ctx, UnitIoSendSink);
if (wolfSSH_CTX_SetMaxAuthAttempts(ctx, 1) != WS_SUCCESS)
result = -741;
ssh = (result == 0) ? wolfSSH_new(ctx) : NULL;
if (result == 0 && ssh == NULL)
result = -742;
if (result == 0) {
word32 di = 0;
int ret = wolfSSH_TestDoUserAuthRequest(ssh, noneReq,
noneReqSz, &di);
if (ret != WS_SUCCESS) {
printf("MaxAuthAttempts[none]: probe ret=%d expected %d\n",
ret, WS_SUCCESS);
result = -743;
}
}
if (result == 0) {
word32 di = 0;
int ret = wolfSSH_TestDoUserAuthRequest(ssh, noneReq,
noneReqSz, &di);
if (ret != WS_USER_AUTH_E) {
printf("MaxAuthAttempts[none]: 2nd ret=%d expected %d\n",
ret, WS_USER_AUTH_E);
result = -744;
}
}
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
}
}
#ifdef WOLFSSH_KEYBOARD_INTERACTIVE
/* An abandoned keyboard-interactive exchange is charged no matter which
* method the peer switches to next. With the limit at 2: an accepted
* keyboard request leaves an INFO_REQUEST outstanding (uncounted), then a
* failed password request charges both the abandoned exchange and itself,
* tripping the cap on that single password request. Before the fix the
* abandoned exchange escaped counting on a non-keyboard follow-up and the
* password returned WS_SUCCESS. */
if (result == 0) {
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
byte kbReq[64];
word32 kbReqSz = BuildAuthMethodRequest(kbReq, (word32)sizeof(kbReq),
"ssh-connection", "keyboard-interactive");
if (kbReqSz == 0)
result = -750;
ctx = (result == 0) ? wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL)
: NULL;
if (result == 0 && ctx == NULL) result = -751;
if (result == 0) {
wolfSSH_SetUserAuth(ctx, UnitAuthKbSetupOk);
wolfSSH_SetIOSend(ctx, UnitIoSendSink);
if (wolfSSH_CTX_SetMaxAuthAttempts(ctx, 2) != WS_SUCCESS)
result = -752;
ssh = (result == 0) ? wolfSSH_new(ctx) : NULL;
if (result == 0 && ssh == NULL) result = -753;
if (result == 0) {
word32 di = 0;
int ret = wolfSSH_TestDoUserAuthRequest(ssh, kbReq, kbReqSz,
&di);
if (ret != WS_SUCCESS) {
printf("MaxAuthAttempts[kb]: setup ret=%d expected %d\n",
ret, WS_SUCCESS);
result = -754;
}
}
if (result == 0) {
word32 di = 0;
int ret = wolfSSH_TestDoUserAuthRequest(ssh, request,
requestSz, &di);
if (ret != WS_USER_AUTH_E) {
printf("MaxAuthAttempts[kb]: pw-after-abandon ret=%d "
"expected %d\n", ret, WS_USER_AUTH_E);
result = -755;
}
}
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
}
}
/* A rejected keyboard setup (no INFO_REQUEST sent) is charged. With the
* limit at 2: the first rejected request leaves the connection up, the
* second trips the cap. */
if (result == 0) {
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
byte kbReq[64];
word32 kbReqSz = BuildAuthMethodRequest(kbReq, (word32)sizeof(kbReq),
"ssh-connection", "keyboard-interactive");
int attempt;
if (kbReqSz == 0)
result = -760;
ctx = (result == 0) ? wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL)
: NULL;
if (result == 0 && ctx == NULL) result = -761;
if (result == 0) {
wolfSSH_SetUserAuth(ctx, UnitAuthAlwaysFail); /* setup rejects */
wolfSSH_SetIOSend(ctx, UnitIoSendSink);
if (wolfSSH_CTX_SetMaxAuthAttempts(ctx, 2) != WS_SUCCESS)
result = -762;
ssh = (result == 0) ? wolfSSH_new(ctx) : NULL;
if (result == 0 && ssh == NULL) result = -763;
for (attempt = 1; attempt <= 2 && result == 0; attempt++) {
word32 di = 0;
int expect = (attempt < 2) ? WS_SUCCESS : WS_USER_AUTH_E;
int ret = wolfSSH_TestDoUserAuthRequest(ssh, kbReq, kbReqSz,
&di);
if (ret != expect) {
printf("MaxAuthAttempts[kb-reject]: attempt %d ret=%d "
"expected %d\n", attempt, ret, expect);
result = -764 - attempt;
}
}
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
}
}
#endif /* WOLFSSH_KEYBOARD_INTERACTIVE */
return result;
}
/* Capture buffer for the service-name unit test. Separate from the channel-
* request capture so the two tests can run independently in any order. */
static byte s_authSvcCapture[256];
static word32 s_authSvcCaptureSz = 0;
static word32 s_authSvcSendCount = 0;
static int CaptureIoSendAuthSvc(WOLFSSH* ssh, void* buf, word32 sz, void* ctx)
{
(void)ssh; (void)ctx;
s_authSvcCaptureSz = (sz < (word32)sizeof(s_authSvcCapture))
? sz : (word32)sizeof(s_authSvcCapture);
WMEMCPY(s_authSvcCapture, buf, s_authSvcCaptureSz);
s_authSvcSendCount++;
return (int)sz;
}
/* Userauth callback that rejects outright. */
static int UnitAuthAlwaysReject(byte authType, WS_UserAuthData* authData,
void* ctx)
{
(void)authType;
(void)authData;
(void)ctx;
return WOLFSSH_USERAUTH_REJECTED;
}
#ifdef WOLFSSH_KEYBOARD_INTERACTIVE
/* Accept the setup so the exchange gets past SendUserAuthKeyboardRequest(),
* then reject the response, which is the DoUserAuthInfoResponse() branch. */
static int UnitAuthKbRespReject(byte authType, WS_UserAuthData* authData,
void* ctx)
{
(void)ctx;
if (authType == WOLFSSH_USERAUTH_KEYBOARD_SETUP) {
authData->sf.keyboard.promptCount = 0;
return WOLFSSH_USERAUTH_SUCCESS;
}
return WOLFSSH_USERAUTH_REJECTED;
}
/* Drive an accepted keyboard-interactive setup, then a rejected
* INFO_RESPONSE, and check the rejection drew a USERAUTH_FAILURE. Returns 0,
* or 1..5 naming what failed. */
static int RunRejectedInfoResponse(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
byte request[64];
byte infoRsp[UINT32_SZ];
word32 requestSz, idx = 0;
int ret;
int result = 0;
requestSz = BuildAuthMethodRequest(request, (word32)sizeof(request),
"ssh-connection", "keyboard-interactive");
if (requestSz == 0)
return 1;
/* INFO_RESPONSE body: response count of 0, matching promptCount. */
PutU32BE(infoRsp, 0);
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return 1;
wolfSSH_SetUserAuth(ctx, UnitAuthKbRespReject);
wolfSSH_SetIOSend(ctx, CaptureIoSendAuthSvc);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return 1;
}
ret = wolfSSH_TestDoUserAuthRequest(ssh, request, requestSz, &idx);
if (ret != WS_SUCCESS) {
printf("UserAuthRejectedSendsFailure: kb setup ret=%d expected %d\n",
ret, WS_SUCCESS);
result = 2;
}
if (result == 0) {
/* Drop the INFO_REQUEST the setup sent; the assertion is on what the
* response draws. */
s_authSvcCaptureSz = 0;
s_authSvcSendCount = 0;
WMEMSET(s_authSvcCapture, 0, sizeof(s_authSvcCapture));
idx = 0;
ret = wolfSSH_TestDoUserAuthInfoResponse(ssh, infoRsp,
(word32)sizeof(infoRsp), &idx);
if (ret != WS_USER_AUTH_E) {
printf("UserAuthRejectedSendsFailure: info response ret=%d "
"expected %d\n", ret, WS_USER_AUTH_E);
result = 3;
}
else if (s_authSvcSendCount == 0) {
printf("UserAuthRejectedSendsFailure: info response sent nothing "
"on rejection\n");
result = 4;
}
else if (CaptureMsgId(s_authSvcCapture, s_authSvcCaptureSz)
!= MSGID_USERAUTH_FAILURE) {
printf("UserAuthRejectedSendsFailure: info response msgId=%d "
"expected USERAUTH_FAILURE\n",
CaptureMsgId(s_authSvcCapture, s_authSvcCaptureSz));
result = 5;
}
}
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* WOLFSSH_KEYBOARD_INTERACTIVE */
/* Drive one rejected USERAUTH_REQUEST on a fresh session and check that a
* USERAUTH_FAILURE went out. Returns 0, or 1..3 naming what failed. */
static int RunRejectedRequest(const byte* request, word32 requestSz,
const char* method)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
word32 idx = 0;
int ret;
int result = 0;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return 1;
wolfSSH_SetUserAuth(ctx, UnitAuthAlwaysReject);
wolfSSH_SetIOSend(ctx, CaptureIoSendAuthSvc);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return 1;
}
s_authSvcCaptureSz = 0;
s_authSvcSendCount = 0;
WMEMSET(s_authSvcCapture, 0, sizeof(s_authSvcCapture));
ret = wolfSSH_TestDoUserAuthRequest(ssh, (byte*)request, requestSz, &idx);
if (ret != WS_USER_AUTH_E) {
printf("UserAuthRejectedSendsFailure: %s ret=%d expected %d\n",
method, ret, WS_USER_AUTH_E);
result = 1;
}
else if (s_authSvcSendCount == 0) {
printf("UserAuthRejectedSendsFailure: %s sent nothing on rejection\n",
method);
result = 2;
}
else if (CaptureMsgId(s_authSvcCapture, s_authSvcCaptureSz)
!= MSGID_USERAUTH_FAILURE) {
printf("UserAuthRejectedSendsFailure: %s msgId=%d expected"
" USERAUTH_FAILURE\n", method,
CaptureMsgId(s_authSvcCapture, s_authSvcCaptureSz));
result = 3;
}
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* RFC 4252 section 5.1: a rejected request is answered with
* USERAUTH_FAILURE. The handler returns WS_USER_AUTH_E either way, so the
* assertion is on what went out on the wire. Every method the build dispatches
* has its own reject branch, so each is driven here.
*
* The keyboard method has two: the setup callback, which answers the request
* before any prompt goes out, and the response callback, driven separately
* through the INFO_RESPONSE shim. The publickey case needs one of the offered
* key algorithms compiled in. */
static int test_UserAuthRejectedSendsFailure(void)
{
byte request[128];
word32 requestSz;
int ret;
requestSz = BuildAuthPwRequest(request, (word32)sizeof(request));
if (requestSz == 0)
return -790;
ret = RunRejectedRequest(request, requestSz, "password");
if (ret != 0)
return -790 - ret;
#ifdef WOLFSSH_KEYBOARD_INTERACTIVE
requestSz = BuildAuthMethodRequest(request, (word32)sizeof(request),
"ssh-connection", "keyboard-interactive");
if (requestSz == 0)
return -800;
ret = RunRejectedRequest(request, requestSz, "keyboard-interactive");
if (ret != 0)
return -800 - ret;
ret = RunRejectedInfoResponse();
if (ret != 0)
return -810 - ret;
#endif
#ifdef WOLFSSH_ALLOW_USERAUTH_NONE
requestSz = BuildAuthMethodRequest(request, (word32)sizeof(request),
"ssh-connection", "none");
if (requestSz == 0)
return -795;
/* The opening probe is exempt from the failure count, not from the
* reply. */
ret = RunRejectedRequest(request, requestSz, "none");
if (ret != 0)
return -795 - ret;
#endif
#ifdef UNIT_AUTH_PK_ALGO
requestSz = BuildAuthPkRequest(request, (word32)sizeof(request));
if (requestSz == 0)
return -805;
/* No signature, so the callback answers the PK_OK probe. */
ret = RunRejectedRequest(request, requestSz, "publickey");
if (ret != 0)
return -805 - ret;
#endif
return 0;
}
#ifdef WOLFSSH_ALLOW_NONE_CIPHER
static int s_noneCipherAuthCalls = 0;
/* Counts the calls a cleartext secret would reach, and fails them. */
static int UnitAuthCountFail(byte authType, WS_UserAuthData* authData,
void* ctx)
{
(void)authType;
(void)authData;
(void)ctx;
s_noneCipherAuthCalls++;
return WOLFSSH_USERAUTH_INVALID_PASSWORD;
}
/* Returns 1 when the captured USERAUTH_FAILURE name-list holds name. */
static int CaptureFailureListHas(const char* name)
{
word32 off = LENGTH_SZ + PAD_LENGTH_SZ + MSG_ID_SZ;
word32 listSz, nameSz, i, start;
if (s_authSvcCaptureSz < off + LENGTH_SZ)
return 0;
listSz = ((word32)s_authSvcCapture[off] << 24) |
((word32)s_authSvcCapture[off + 1] << 16) |
((word32)s_authSvcCapture[off + 2] << 8) |
((word32)s_authSvcCapture[off + 3]);
off += LENGTH_SZ;
if (s_authSvcCaptureSz < off + listSz)
return 0;
nameSz = (word32)WSTRLEN(name);
start = 0;
for (i = 0; i <= listSz; i++) {
if (i == listSz || s_authSvcCapture[off + i] == ',') {
if (i - start == nameSz &&
WMEMCMP(s_authSvcCapture + off + start, name, nameSz) == 0)
return 1;
start = i + 1;
}
}
return 0;
}
/* Over the "none" cipher, in either direction, the server refuses password
* and keyboard-interactive before the callback sees a secret, and leaves
* both out of the method list it sends back. */
static int test_UserAuthNoneCipherRefusesSecrets(void)
{
byte request[128];
word32 requestSz, idx;
word32 i, m;
WOLFSSH_CTX* ctx;
WOLFSSH* ssh;
int ret;
int result = 0;
/* i: 0 inbound only, 1 outbound only, 2 both */
for (i = 0; i < 3 && result == 0; i++) {
for (m = 0; m < 2 && result == 0; m++) {
if (m == 0) {
requestSz = BuildAuthPwRequest(request,
(word32)sizeof(request));
}
else {
#ifdef WOLFSSH_KEYBOARD_INTERACTIVE
requestSz = BuildAuthMethodRequest(request,
(word32)sizeof(request), "ssh-connection",
"keyboard-interactive");
#else
continue;
#endif
}
if (requestSz == 0)
return -1500;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1501;
wolfSSH_SetUserAuth(ctx, UnitAuthCountFail);
wolfSSH_SetIOSend(ctx, CaptureIoSendAuthSvc);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return -1502;
}
/* As DoNewKeys() and SendNewKeys() leave them. */
ssh->noneCipherIn = (i != 1);
ssh->noneCipherOut = (i != 0);
s_noneCipherAuthCalls = 0;
s_authSvcCaptureSz = 0;
s_authSvcSendCount = 0;
idx = 0;
ret = wolfSSH_TestDoUserAuthRequest(ssh, request, requestSz,
&idx);
if (ret != WS_SUCCESS) {
printf("NoneCipherRefusesSecrets[%u,%u]: ret=%d\n",
i, m, ret);
result = -1503;
}
else if (s_noneCipherAuthCalls != 0) {
printf("NoneCipherRefusesSecrets[%u,%u]: callback ran\n",
i, m);
result = -1504;
}
else if (s_authSvcSendCount != 1 ||
CaptureMsgId(s_authSvcCapture, s_authSvcCaptureSz)
!= MSGID_USERAUTH_FAILURE) {
printf("NoneCipherRefusesSecrets[%u,%u]: no FAILURE sent\n",
i, m);
result = -1505;
}
else if (CaptureFailureListHas("password") ||
CaptureFailureListHas("keyboard-interactive")) {
printf("NoneCipherRefusesSecrets[%u,%u]: list offers a"
" secret method\n", i, m);
result = -1506;
}
else if (idx != requestSz) {
result = -1507;
}
#ifdef WOLFSSH_KEYBOARD_INTERACTIVE
else if (m == 1) {
/* A zero-answer INFO_RESPONSE matches the never-set prompt
* count; the refused request must not leave it a live
* exchange that reaches the callback. */
byte infoRsp[UINT32_SZ];
PutU32BE(infoRsp, 0);
idx = 0;
ret = wolfSSH_TestDoUserAuthInfoResponse(ssh, infoRsp,
(word32)sizeof(infoRsp), &idx);
if (ret == WS_SUCCESS || s_noneCipherAuthCalls != 0) {
printf("NoneCipherRefusesSecrets[%u,%u]: INFO_RESPONSE"
" after refusal ret=%d, callback calls=%d\n",
i, m, ret, s_noneCipherAuthCalls);
result = -1508;
}
}
#endif
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
}
}
return result;
}
#ifdef WOLFSSH_KEYBOARD_INTERACTIVE
static word32 s_noneKbPromptLen = 9;
static byte s_noneKbPromptEcho = 0;
static byte* s_noneKbPrompts[1] = { (byte*)"Password:" };
/* Sets up one prompt, and counts and fails each answer to it. */
static int UnitAuthKbCountFail(byte authType, WS_UserAuthData* authData,
void* ctx)
{
(void)ctx;
if (authType == WOLFSSH_USERAUTH_KEYBOARD_SETUP) {
authData->sf.keyboard.promptCount = 1;
authData->sf.keyboard.promptLengths = &s_noneKbPromptLen;
authData->sf.keyboard.prompts = s_noneKbPrompts;
authData->sf.keyboard.promptEcho = &s_noneKbPromptEcho;
return WOLFSSH_USERAUTH_SUCCESS;
}
s_noneCipherAuthCalls++;
return WOLFSSH_USERAUTH_INVALID_PASSWORD;
}
/* A keyboard-interactive request starts under encryption, then a rekey
* installs the "none" cipher with the prompt outstanding. The cleartext
* answer is refused before the callback, and a second one is fatal. */
static int test_UserAuthNoneCipherRekeyMidKb(void)
{
byte request[128];
byte infoRsp[UINT32_SZ * 2 + 1];
word32 requestSz, idx;
word32 i;
WOLFSSH_CTX* ctx;
WOLFSSH* ssh;
int ret;
int result = 0;
requestSz = BuildAuthMethodRequest(request, (word32)sizeof(request),
"ssh-connection", "keyboard-interactive");
if (requestSz == 0)
return -1510;
PutU32BE(infoRsp, 1);
PutU32BE(infoRsp + UINT32_SZ, 1);
infoRsp[UINT32_SZ * 2] = 'x';
/* i: 0 inbound only, 1 outbound only, 2 both */
for (i = 0; i < 3 && result == 0; i++) {
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1511;
wolfSSH_SetUserAuth(ctx, UnitAuthKbCountFail);
wolfSSH_SetIOSend(ctx, CaptureIoSendAuthSvc);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return -1512;
}
s_noneCipherAuthCalls = 0;
idx = 0;
ret = wolfSSH_TestDoUserAuthRequest(ssh, request, requestSz, &idx);
if (ret != WS_SUCCESS || ssh->authId != ID_USERAUTH_KEYBOARD) {
printf("NoneCipherRekeyMidKb[%u]: request ret=%d\n", i, ret);
result = -1513;
}
if (result == 0) {
/* As DoNewKeys() and SendNewKeys() leave them after a rekey. */
ssh->noneCipherIn = (i != 1);
ssh->noneCipherOut = (i != 0);
s_authSvcCaptureSz = 0;
s_authSvcSendCount = 0;
idx = 0;
ret = wolfSSH_TestDoUserAuthInfoResponse(ssh, infoRsp,
(word32)sizeof(infoRsp), &idx);
if (ret != WS_SUCCESS || s_noneCipherAuthCalls != 0) {
printf("NoneCipherRekeyMidKb[%u]: response ret=%d, callback"
" calls=%d\n", i, ret, s_noneCipherAuthCalls);
result = -1514;
}
else if (s_authSvcSendCount != 1 ||
CaptureMsgId(s_authSvcCapture, s_authSvcCaptureSz)
!= MSGID_USERAUTH_FAILURE ||
CaptureFailureListHas("password") ||
CaptureFailureListHas("keyboard-interactive")) {
printf("NoneCipherRekeyMidKb[%u]: no FAILURE without the"
" secret methods\n", i);
result = -1515;
}
}
if (result == 0) {
idx = 0;
ret = wolfSSH_TestDoUserAuthInfoResponse(ssh, infoRsp,
(word32)sizeof(infoRsp), &idx);
if (ret != WS_FATAL_ERROR || s_noneCipherAuthCalls != 0) {
printf("NoneCipherRekeyMidKb[%u]: second response ret=%d\n",
i, ret);
result = -1516;
}
}
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
}
return result;
}
#endif /* WOLFSSH_KEYBOARD_INTERACTIVE */
#endif /* WOLFSSH_ALLOW_NONE_CIPHER */
/* Verify DoUserAuthRequest rejects non-"ssh-connection" service names per
* RFC 4252 Section 5. For each case we assert:
* 1. ret == WS_SUCCESS (connection stays open for retry)
* 2. SSH_MSG_USERAUTH_FAILURE is actually sent (see CaptureMsgId():
* LENGTH_SZ + PAD_LENGTH_SZ then msg id)
* 3. *idx == len (entire payload consumed; buffer stays aligned)
*
* For invalid-service cases the auth-method field is intentionally omitted
* from the payload. DoUserAuthRequest must short-circuit at the service-name
* check and still satisfy all three assertions - proving it never tries to
* parse the missing auth-method field. If the short-circuit were absent,
* GetSize() for authNameSz would hit end-of-buffer and return WS_BUFFER_E,
* failing assertion 1.
*
* For the valid-service case, auth method "xyz-unknown" (always unsupported
* regardless of compile-time options) is included. The function reaches
* auth-method dispatch, falls to the unknown-method else-branch, and sends
* USERAUTH_FAILURE via that normal path.
*
* A second valid-service row appends fake password-style bytes after the
* method name. That proves DoUserAuthRequest() consumes trailing
* method-specific payload (begin = len in the unknown-method branch); without
* it, DoReceive() could advance inputBuffer.idx short of the packet end and
* misalign decoding. */
static const byte s_unknownAuthTrailingFakePassword[] = {
0x00, /* "change password" FALSE */
0x00, 0x00, 0x00, 0x08,
'p', 'a', 's', 's', 'w', 'o', 'r', 'd',
};
static int test_DoUserAuthRequest_serviceName(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
int result = 0;
struct {
const char* svcName;
word32 svcNameSz;
const char* authMethod; /* NULL = omit field (proves short-circuit) */
word32 authMethodSz;
int expectRet;
const char* label;
const byte* authTrailing; /* bytes after auth method; NULL if none */
word32 authTrailingSz;
} cases[] = {
/* valid service: auth dispatch fires, fails on unknown method */
{ "ssh-connection", 14, "xyz-unknown", 11, WS_SUCCESS,
"valid svc unknown auth", NULL, 0 },
/* same but trailing junk must be skipped so *idx reaches len */
{ "ssh-connection", 14, "xyz-unknown", 11, WS_SUCCESS,
"valid svc unknown auth trailing junk",
s_unknownAuthTrailingFakePassword,
(word32)sizeof(s_unknownAuthTrailingFakePassword) },
/* invalid service: short-circuit, auth-method field absent */
{ "ssh-agent", 9, NULL, 0, WS_SUCCESS,
"invalid ssh-agent svc", NULL, 0 },
{ "bad", 3, NULL, 0, WS_SUCCESS,
"invalid bad svc", NULL, 0 },
/* zero-length service name: NameToId("",0)==ID_UNKNOWN, must reject */
{ "", 0, NULL, 0, WS_SUCCESS,
"zero-length svc", NULL, 0 },
/* ssh-userauth: NameToId returns ID_SERVICE_USERAUTH, not
* ID_SERVICE_CONNECTION, so must also be rejected */
{ "ssh-userauth", 12, NULL, 0, WS_SUCCESS,
"invalid ssh-userauth svc", NULL, 0 },
};
int i;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL) return -500;
wolfSSH_SetIOSend(ctx, CaptureIoSendAuthSvc);
for (i = 0; i < (int)(sizeof(cases)/sizeof(cases[0])); i++) {
byte buf[128];
word32 len = 0, idx = 0;
word32 snsz = cases[i].svcNameSz;
int ret;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -501; goto done; }
s_authSvcCaptureSz = 0;
s_authSvcSendCount = 0;
WMEMSET(s_authSvcCapture, 0, sizeof(s_authSvcCapture));
/* username: "user" */
buf[len++] = 0; buf[len++] = 0; buf[len++] = 0; buf[len++] = 4;
WMEMCPY(buf + len, "user", 4); len += 4;
/* service name */
buf[len++] = (byte)(snsz >> 24); buf[len++] = (byte)(snsz >> 16);
buf[len++] = (byte)(snsz >> 8); buf[len++] = (byte)snsz;
if (snsz > 0) { WMEMCPY(buf + len, cases[i].svcName, snsz); }
len += snsz;
/* auth method: omit for invalid-service cases to prove short-circuit */
if (cases[i].authMethod != NULL) {
word32 amsz = cases[i].authMethodSz;
buf[len++] = (byte)(amsz >> 24); buf[len++] = (byte)(amsz >> 16);
buf[len++] = (byte)(amsz >> 8); buf[len++] = (byte)amsz;
WMEMCPY(buf + len, cases[i].authMethod, amsz); len += amsz;
if (cases[i].authTrailingSz > 0U) {
WMEMCPY(buf + len, cases[i].authTrailing,
cases[i].authTrailingSz);
len += cases[i].authTrailingSz;
}
}
ret = wolfSSH_TestDoUserAuthRequest(ssh, buf, len, &idx);
if (s_authSvcSendCount != 1) {
printf("DoUserAuthRequest_svcName[%s]: expected 1 send, got %u\n",
cases[i].label, s_authSvcSendCount);
result = -540 - i;
goto done;
}
if (ret != cases[i].expectRet) {
printf("DoUserAuthRequest_svcName[%s]: ret=%d expected=%d\n",
cases[i].label, ret, cases[i].expectRet);
result = -502 - i;
goto done;
}
/* MSGID_USERAUTH_FAILURE must be in the captured packet. */
{
int capMsgId = CaptureMsgId(s_authSvcCapture, s_authSvcCaptureSz);
if (capMsgId < 0 || capMsgId != MSGID_USERAUTH_FAILURE) {
printf("DoUserAuthRequest_svcName[%s]: USERAUTH_FAILURE not "
"sent (capSz=%u msg_id=0x%02x)\n", cases[i].label,
s_authSvcCaptureSz,
capMsgId >= 0 ? capMsgId : 0);
result = -520 - i;
goto done;
}
}
/* All cases must consume the entire payload. */
if (idx != len) {
printf("DoUserAuthRequest_svcName[%s]: idx=%u expected len=%u\n",
cases[i].label, idx, len);
result = -510 - i;
goto done;
}
/* Invalid-service cases must NOT record the username. */
if (cases[i].authMethod == NULL && ssh->userName != NULL) {
printf("DoUserAuthRequest_svcName[%s]: userName set on invalid "
"service (expected NULL)\n", cases[i].label);
result = -530 - i;
goto done;
}
wolfSSH_free(ssh);
ssh = NULL;
}
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#ifdef WOLFSSH_KEYBOARD_INTERACTIVE
/* Counts KEYBOARD (response) callbacks, so a processed INFO_RESPONSE is
* visible even when rejected. */
/* A USERAUTH_REQUEST naming a service other than "ssh-connection" must not
* leave a keyboard-interactive exchange outstanding.
*
* Asserts, in order: an accepted keyboard request leaves the exchange
* outstanding; a bad-service request clears authId and kbSetupPending; a
* following INFO_RESPONSE is rejected without reaching the callback. */
static int test_DoUserAuthRequest_badServiceClearsKb(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
byte kbReq[64], badReq[64], infoRsp[UINT32_SZ];
word32 kbReqSz, badReqSz, idx;
int result = 0;
int ret;
kbReqSz = BuildAuthMethodRequest(kbReq, (word32)sizeof(kbReq),
"ssh-connection", "keyboard-interactive");
badReqSz = BuildAuthMethodRequest(badReq, (word32)sizeof(badReq),
"ssh-userauth", NULL);
if (kbReqSz == 0 || badReqSz == 0)
return -800;
/* INFO_RESPONSE body: response count of 0, matching promptCount. */
PutU32BE(infoRsp, 0);
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -801;
wolfSSH_SetUserAuth(ctx, UnitAuthKbSetupOk);
wolfSSH_SetIOSend(ctx, UnitIoSendSink);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return -802;
}
s_kbRespCbCalled = 0;
idx = 0;
ret = wolfSSH_TestDoUserAuthRequest(ssh, kbReq, kbReqSz, &idx);
if (ret != WS_SUCCESS) {
printf("badServiceClearsKb: kb request ret=%d expected %d\n",
ret, WS_SUCCESS);
result = -803;
}
if (result == 0 && (ssh->authId != ID_USERAUTH_KEYBOARD
|| !ssh->kbSetupPending)) {
printf("badServiceClearsKb: kb exchange not outstanding "
"(authId=%d pending=%d)\n", ssh->authId, ssh->kbSetupPending);
result = -804;
}
if (result == 0) {
idx = 0;
ret = wolfSSH_TestDoUserAuthRequest(ssh, badReq, badReqSz, &idx);
if (ret != WS_SUCCESS) {
printf("badServiceClearsKb: bad service ret=%d expected %d\n",
ret, WS_SUCCESS);
result = -805;
}
}
if (result == 0 && ssh->authId == ID_USERAUTH_KEYBOARD) {
printf("badServiceClearsKb: authId still ID_USERAUTH_KEYBOARD after "
"bad service name\n");
result = -806;
}
if (result == 0 && ssh->kbSetupPending) {
printf("badServiceClearsKb: kbSetupPending still set after bad "
"service name\n");
result = -807;
}
/* One charge for the refusal, one for the exchange it abandoned. */
if (result == 0 && ssh->authFailures != 2) {
printf("badServiceClearsKb: authFailures=%u expected 2\n",
ssh->authFailures);
result = -810;
}
if (result == 0) {
idx = 0;
ret = wolfSSH_TestDoUserAuthInfoResponse(ssh, infoRsp,
(word32)sizeof(infoRsp), &idx);
if (ret != WS_FATAL_ERROR) {
printf("badServiceClearsKb: stale INFO_RESPONSE ret=%d "
"expected %d\n", ret, WS_FATAL_ERROR);
result = -808;
}
}
if (result == 0 && s_kbRespCbCalled) {
printf("badServiceClearsKb: userauth callback reached by stale "
"INFO_RESPONSE\n");
result = -809;
}
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* WOLFSSH_KEYBOARD_INTERACTIVE */
#ifdef WOLFSSH_KEYBOARD_INTERACTIVE
static int s_kbStaleSetupRet = WOLFSSH_USERAUTH_SUCCESS;
static int s_kbStaleRespRet = WOLFSSH_USERAUTH_INVALID_PASSWORD;
static int s_kbStaleRespCalls = 0;
static word32 s_kbStalePromptLen = 9;
static byte s_kbStalePromptEcho = 0;
static byte* s_kbStalePrompts[1] = { (byte*)"Password:" };
/* Setup returns s_kbStaleSetupRet with one prompt; each response is counted
* and answered with s_kbStaleRespRet. */
static int UnitAuthKbStale(byte authType, WS_UserAuthData* authData,
void* ctx)
{
(void)ctx;
if (authType == WOLFSSH_USERAUTH_KEYBOARD_SETUP) {
authData->sf.keyboard.promptCount = 1;
authData->sf.keyboard.promptLengths = &s_kbStalePromptLen;
authData->sf.keyboard.prompts = s_kbStalePrompts;
authData->sf.keyboard.promptEcho = &s_kbStalePromptEcho;
return s_kbStaleSetupRet;
}
if (authType == WOLFSSH_USERAUTH_KEYBOARD) {
s_kbStaleRespCalls++;
return s_kbStaleRespRet;
}
return WOLFSSH_USERAUTH_FAILURE;
}
/* A server session with UnitAuthKbStale. When kbRequest is set, it has
* taken a keyboard-interactive USERAUTH_REQUEST. */
static WOLFSSH* NewKbStaleSession(WOLFSSH_CTX** ctx, int kbRequest,
int setupRet, int respRet)
{
WOLFSSH* ssh;
byte kbReq[64];
word32 kbReqSz, idx = 0;
s_kbStaleSetupRet = setupRet;
s_kbStaleRespRet = respRet;
s_kbStaleRespCalls = 0;
kbReqSz = BuildAuthMethodRequest(kbReq, (word32)sizeof(kbReq),
"ssh-connection", "keyboard-interactive");
if (kbReqSz == 0)
return NULL;
*ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (*ctx == NULL)
return NULL;
wolfSSH_SetUserAuth(*ctx, UnitAuthKbStale);
wolfSSH_SetIOSend(*ctx, UnitIoSendSink);
ssh = wolfSSH_new(*ctx);
if (ssh != NULL && kbRequest &&
wolfSSH_TestDoUserAuthRequest(ssh, kbReq, kbReqSz, &idx)
!= WS_SUCCESS) {
wolfSSH_free(ssh);
ssh = NULL;
}
if (ssh == NULL) {
wolfSSH_CTX_free(*ctx);
*ctx = NULL;
}
return ssh;
}
/* Feed one INFO_RESPONSE with responseCount responses of "x". */
static int KbStaleInfoResponse(WOLFSSH* ssh, word32 responseCount)
{
byte infoRsp[UINT32_SZ * 2 + 1];
word32 infoRspSz = UINT32_SZ, idx = 0;
PutU32BE(infoRsp, responseCount);
if (responseCount == 1) {
PutU32BE(infoRsp + UINT32_SZ, 1);
infoRsp[UINT32_SZ * 2] = 'x';
infoRspSz = (word32)sizeof(infoRsp);
}
return wolfSSH_TestDoUserAuthInfoResponse(ssh, infoRsp, infoRspSz, &idx);
}
/* An INFO_RESPONSE with no INFO_REQUEST outstanding is refused before the
* callback. kbRequest sends a keyboard-interactive request first;
* answerFirst answers its INFO_REQUEST once. Returns 0 or a negative code. */
static int RunStaleInfoResponse(const char* label, int kbRequest,
int answerFirst, int setupRet, int respRet, word32 staleCount)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh;
int result = 0;
int ret;
ssh = NewKbStaleSession(&ctx, kbRequest, setupRet, respRet);
if (ssh == NULL)
return -900;
if (answerFirst) {
(void)KbStaleInfoResponse(ssh, 1);
if (s_kbStaleRespCalls != 1) {
printf("StaleInfoResponse(%s): solicited response calls=%d "
"expected 1\n", label, s_kbStaleRespCalls);
result = -901;
}
}
if (result == 0) {
s_kbStaleRespCalls = 0;
ret = KbStaleInfoResponse(ssh, staleCount);
if (ret != WS_FATAL_ERROR) {
printf("StaleInfoResponse(%s): ret=%d expected %d\n",
label, ret, WS_FATAL_ERROR);
result = -902;
}
else if (s_kbStaleRespCalls != 0) {
printf("StaleInfoResponse(%s): userauth callback reached\n",
label);
result = -903;
}
else if (ssh->clientState == CLIENT_USERAUTH_DONE) {
printf("StaleInfoResponse(%s): session authenticated\n", label);
result = -904;
}
}
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* A response kept for redispatch on WS_AUTH_PENDING still passes the gate:
* a blocked check (anotherRound 0), or a blocked second-round setup
* (anotherRound 1). Returns 0 or a negative code. */
static int RunPendingInfoResponse(const char* label, int anotherRound)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh;
int result = 0;
int ret;
ssh = NewKbStaleSession(&ctx, 1, WOLFSSH_USERAUTH_SUCCESS,
anotherRound ? WOLFSSH_USERAUTH_SUCCESS_ANOTHER
: WOLFSSH_USERAUTH_WOULD_BLOCK);
if (ssh == NULL)
return -910;
if (anotherRound)
s_kbStaleSetupRet = WOLFSSH_USERAUTH_WOULD_BLOCK;
ret = KbStaleInfoResponse(ssh, 1);
if (ret != WS_AUTH_PENDING || !ssh->kbSetupPending) {
printf("PendingInfoResponse(%s): ret=%d pending=%d expected %d, 1\n",
label, ret, ssh->kbSetupPending, WS_AUTH_PENDING);
result = -911;
}
if (result == 0) {
/* Redispatch of the kept packet. */
s_kbStaleSetupRet = WOLFSSH_USERAUTH_SUCCESS;
if (!anotherRound)
s_kbStaleRespRet = WOLFSSH_USERAUTH_SUCCESS;
ret = KbStaleInfoResponse(ssh, 1);
if (ret != WS_SUCCESS) {
printf("PendingInfoResponse(%s): retry ret=%d expected %d\n",
label, ret, WS_SUCCESS);
result = -912;
}
}
if (result == 0 && anotherRound) {
/* The retry sent the second INFO_REQUEST; answer it. */
if (!ssh->kbSetupPending) {
printf("PendingInfoResponse(%s): second round not outstanding\n",
label);
result = -913;
}
else {
s_kbStaleRespRet = WOLFSSH_USERAUTH_SUCCESS;
ret = KbStaleInfoResponse(ssh, 1);
if (ret != WS_SUCCESS) {
printf("PendingInfoResponse(%s): second round ret=%d "
"expected %d\n", label, ret, WS_SUCCESS);
result = -914;
}
}
}
if (result == 0 && (ssh->clientState != CLIENT_USERAUTH_DONE
|| ssh->kbSetupPending)) {
printf("PendingInfoResponse(%s): clientState=%d pending=%d after "
"success\n", label, ssh->clientState, ssh->kbSetupPending);
result = -915;
}
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* The highwater callback runs once INFO_REQUEST is out, so its error leaves
* the exchange outstanding and the response is still taken. Returns 0 or a
* negative code. */
static int RunHighwaterInfoRequest(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh;
byte kbReq[64];
word32 kbReqSz, idx = 0;
int result = 0;
int ret;
ssh = NewKbStaleSession(&ctx, 0, WOLFSSH_USERAUTH_SUCCESS,
WOLFSSH_USERAUTH_SUCCESS);
if (ssh == NULL)
return -920;
/* Level 0 leaves the byte count off; the first packet trips the
* message count. */
wolfSSH_SetHighwaterCb(ctx, 0, FailHighwater);
ssh->msgHighwaterMark = 1;
kbReqSz = BuildAuthMethodRequest(kbReq, (word32)sizeof(kbReq),
"ssh-connection", "keyboard-interactive");
ret = wolfSSH_TestDoUserAuthRequest(ssh, kbReq, kbReqSz, &idx);
if (ret != WS_FATAL_ERROR || !ssh->kbSetupPending) {
printf("HighwaterInfoRequest: ret=%d pending=%d expected %d, 1\n",
ret, ssh->kbSetupPending, WS_FATAL_ERROR);
result = -921;
}
if (result == 0) {
ret = KbStaleInfoResponse(ssh, 1);
if (ret != WS_SUCCESS || s_kbStaleRespCalls != 1) {
printf("HighwaterInfoRequest: response ret=%d calls=%d "
"expected %d, 1\n", ret, s_kbStaleRespCalls, WS_SUCCESS);
result = -922;
}
}
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
static int test_DoUserAuthInfoResponse_unsolicited(void)
{
int result = 0, r;
/* No keyboard-interactive request at all. */
r = RunStaleInfoResponse("no request", 0, 0,
WOLFSSH_USERAUTH_SUCCESS, WOLFSSH_USERAUTH_SUCCESS, 0);
if (result == 0) result = r;
/* Setup declined, so no INFO_REQUEST went out. A callback that accepts
* would authenticate the session. */
r = RunStaleInfoResponse("setup declined", 1, 0,
WOLFSSH_USERAUTH_FAILURE, WOLFSSH_USERAUTH_SUCCESS, 0);
if (result == 0) result = r;
/* A round answered and failed; a second response replays it. */
r = RunStaleInfoResponse("after failed round", 1, 1,
WOLFSSH_USERAUTH_SUCCESS, WOLFSSH_USERAUTH_INVALID_PASSWORD, 1);
if (result == 0) result = r;
/* A round answered with partial success; a second response is checked
* again without a new INFO_REQUEST. */
r = RunStaleInfoResponse("after partial success", 1, 1,
WOLFSSH_USERAUTH_SUCCESS, WOLFSSH_USERAUTH_PARTIAL_SUCCESS, 1);
if (result == 0) result = r;
r = RunPendingInfoResponse("check would block", 0);
if (result == 0) result = r;
r = RunPendingInfoResponse("setup would block", 1);
if (result == 0) result = r;
r = RunHighwaterInfoRequest();
if (result == 0) result = r;
return result;
}
#endif /* WOLFSSH_KEYBOARD_INTERACTIVE */
/* userauth callback that records whether it was invoked. Returns SUCCESS so
* that, if it were ever reached for a password-change request, the request
* would be (incorrectly) authenticated - making a missed rejection visible. */
static int s_pwChangeCbCalled = 0;
static int UnitAuthAlwaysSucceed(byte authType, WS_UserAuthData* authData,
void* ctx)
{
(void)authData;
(void)ctx;
if (authType == WOLFSSH_USERAUTH_PASSWORD) {
s_pwChangeCbCalled = 1;
}
return WOLFSSH_USERAUTH_SUCCESS;
}
/* Verify DoUserAuthRequest rejects a password request that sets the
* password-change flag (RFC 4252 Section 8: an expired password MUST NOT be
* used for authentication). The request is otherwise well-formed and the
* userauth callback would return SUCCESS, so a missing rejection would let the
* old password authenticate. Asserts:
* 1. ret == WS_SUCCESS (connection stays open for retry)
* 2. the userauth callback is never invoked
* 3. exactly one packet is sent and it is SSH_MSG_USERAUTH_FAILURE
* 4. *idx == len (the new-password field is fully consumed) */
static int test_DoUserAuthRequest_rejectsPasswordChange(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
int result = 0;
int ret;
int capMsgId;
byte buf[128];
word32 len = 0, idx = 0;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -660;
wolfSSH_SetIOSend(ctx, CaptureIoSendAuthSvc);
wolfSSH_SetUserAuth(ctx, UnitAuthAlwaysSucceed);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
result = -661;
goto out;
}
s_pwChangeCbCalled = 0;
s_authSvcCaptureSz = 0;
s_authSvcSendCount = 0;
WMEMSET(s_authSvcCapture, 0, sizeof(s_authSvcCapture));
/* username: "user" */
buf[len++] = 0; buf[len++] = 0; buf[len++] = 0; buf[len++] = 4;
WMEMCPY(buf + len, "user", 4); len += 4;
/* service name: "ssh-connection" */
buf[len++] = 0; buf[len++] = 0; buf[len++] = 0; buf[len++] = 14;
WMEMCPY(buf + len, "ssh-connection", 14); len += 14;
/* auth method: "password" */
buf[len++] = 0; buf[len++] = 0; buf[len++] = 0; buf[len++] = 8;
WMEMCPY(buf + len, "password", 8); len += 8;
/* password-change flag: TRUE */
buf[len++] = 1;
/* current password: "oldpass" */
buf[len++] = 0; buf[len++] = 0; buf[len++] = 0; buf[len++] = 7;
WMEMCPY(buf + len, "oldpass", 7); len += 7;
/* new password: "newpass" */
buf[len++] = 0; buf[len++] = 0; buf[len++] = 0; buf[len++] = 7;
WMEMCPY(buf + len, "newpass", 7); len += 7;
ret = wolfSSH_TestDoUserAuthRequest(ssh, buf, len, &idx);
if (ret != WS_SUCCESS) {
result = -662;
goto out;
}
if (s_pwChangeCbCalled) {
/* The callback must not run for a password-change request. */
result = -663;
goto out;
}
if (s_authSvcSendCount != 1) {
result = -664;
goto out;
}
capMsgId = CaptureMsgId(s_authSvcCapture, s_authSvcCaptureSz);
if (capMsgId != MSGID_USERAUTH_FAILURE) {
result = -665;
goto out;
}
if (idx != len) {
result = -666;
goto out;
}
out:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* userAuthTypesCb that advertises no methods (returns mask 0). Mirrors a
* wolfsshd configuration with both PasswordAuthentication no and
* PubkeyAuthentication no. */
static int UnitAuthTypesReturnZero(WOLFSSH* ssh, void* ctx)
{
(void)ssh;
(void)ctx;
return 0;
}
/* Regression test for the 0-mask case (issue 4115 follow-up). When the
* userAuthTypesCb advertises no methods, SendUserAuthFailure must still emit a
* well-formed USERAUTH_FAILURE carrying an empty "authentications that can
* continue" name-list (RFC 4252 Section 5.1) and return WS_SUCCESS, instead of
* underflowing the name-list length to -1 and dropping the connection.
*
* Asserts:
* 1. wolfSSH_TestSendUserAuthFailure() returns WS_SUCCESS (not negative).
* 2. Exactly one packet is emitted (connection not dropped).
* 3. The packet's message id is MSGID_USERAUTH_FAILURE.
* 4. The name-list length field is 0 (empty method list).
*
* The control case (a permissive callback advertising publickey+password)
* confirms the same path produces a non-empty name-list, so the empty result
* is specific to the 0-mask input rather than the test always seeing 0. */
static int test_SendUserAuthFailure_emptyMethods(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
int result = 0;
int i;
struct {
WS_CallbackUserAuthTypes cb;
int expectEmpty; /* 1 = name-list must be empty, 0 = non-empty */
const char* label;
} cases[] = {
{ UnitAuthTypesReturnZero, 1, "no methods advertised" },
{ NULL, 0, "default methods advertised" },
};
word32 off = LENGTH_SZ + PAD_LENGTH_SZ;
for (i = 0; i < (int)(sizeof(cases)/sizeof(cases[0])); i++) {
word32 nameListSz;
int capMsgId;
int ret;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL) { result = -600; break; }
if (cases[i].cb != NULL) {
wolfSSH_SetUserAuthTypes(ctx, cases[i].cb);
}
wolfSSH_SetIOSend(ctx, CaptureIoSendAuthSvc);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -601; break; }
s_authSvcCaptureSz = 0;
s_authSvcSendCount = 0;
WMEMSET(s_authSvcCapture, 0, sizeof(s_authSvcCapture));
ret = wolfSSH_TestSendUserAuthFailure(ssh, 0);
if (ret != WS_SUCCESS) {
printf("SendUserAuthFailure[%s]: ret=%d expected WS_SUCCESS\n",
cases[i].label, ret);
result = -602 - i;
break;
}
if (s_authSvcSendCount != 1) {
printf("SendUserAuthFailure[%s]: expected 1 send, got %u\n",
cases[i].label, s_authSvcSendCount);
result = -610 - i;
break;
}
capMsgId = CaptureMsgId(s_authSvcCapture, s_authSvcCaptureSz);
if (capMsgId != MSGID_USERAUTH_FAILURE) {
printf("SendUserAuthFailure[%s]: msgId=%d expected"
" USERAUTH_FAILURE\n", cases[i].label, capMsgId);
result = -620 - i;
break;
}
/* name-list length is the 4 bytes following the message id */
if (s_authSvcCaptureSz < off + MSG_ID_SZ + LENGTH_SZ) {
printf("SendUserAuthFailure[%s]: packet too short (%u)\n",
cases[i].label, s_authSvcCaptureSz);
result = -630 - i;
break;
}
nameListSz =
((word32)s_authSvcCapture[off + MSG_ID_SZ] << 24) |
((word32)s_authSvcCapture[off + MSG_ID_SZ + 1] << 16) |
((word32)s_authSvcCapture[off + MSG_ID_SZ + 2] << 8) |
((word32)s_authSvcCapture[off + MSG_ID_SZ + 3]);
if (cases[i].expectEmpty && nameListSz != 0) {
printf("SendUserAuthFailure[%s]: nameListSz=%u expected 0\n",
cases[i].label, nameListSz);
result = -640 - i;
break;
}
if (!cases[i].expectEmpty && nameListSz == 0) {
printf("SendUserAuthFailure[%s]: nameListSz=0 expected non-empty\n",
cases[i].label);
result = -650 - i;
break;
}
wolfSSH_free(ssh);
ssh = NULL;
wolfSSH_CTX_free(ctx);
ctx = NULL;
}
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#if !defined(WOLFSSH_NO_ECDSA_SHA2_NISTP256) && \
!defined(WOLFSSH_NO_ECDSA_SHA2_NISTP384)
/* Append an SSH string (uint32 BE length followed by the bytes) at *pIdx. */
static void AppendSshString(byte* buf, word32* pIdx,
const void* data, word32 dataSz)
{
PutU32BE(buf + *pIdx, dataSz);
*pIdx += UINT32_SZ;
if (dataSz > 0) {
WMEMCPY(buf + *pIdx, data, dataSz);
}
*pIdx += dataSz;
}
/* Verify DoUserAuthRequestEcc() binds the curve name carried in the public key
* blob to the declared public key algorithm (RFC 5656 Section 3.1: the key blob
* is string "ecdsa-sha2-[identifier]" || string [identifier] || string Q, so
* the two identifiers must agree).
*
* Without that binding the blob's curve name is discarded and the point is
* imported with the curve inferred from its own size, so a request declaring
* ecdsa-sha2-nistp256 while carrying a P-384 curve name, a P-384 point, and a
* P-384 signature over the SHA-256 digest verifies and authenticates. The
* declared algorithm picks the hash, and signing a 32-byte digest with a P-384
* key is valid ECDSA, so nothing else in the path rejects it.
*
* Four cases, each on a fresh WOLFSSH:
* 1. Control: P-256 key, curve name "nistp256". Must authenticate - proves
* the message layout and signing recipe are right, so the mismatch cases
* fail for the intended reason, and that the check does not break the
* happy path.
* 2. Mismatch: P-384 key and curve name "nistp384", algorithm still
* ecdsa-sha2-nistp256. Same length as "nistp256", so this exercises the
* content arm of the curve name check. Must be rejected with
* USERAUTH_FAILURE.
* 3. Point mismatch: curve name "nistp256" agrees with the algorithm but
* the point and signature are P-384. The name check passes; only the
* import pinned to the declared curve (wc_ecc_import_x963_ex) rejects
* it. Must be rejected with USERAUTH_FAILURE.
* 4. Truncated name: curve name "nistp" with a P-256 key, exercising the
* length arm of the curve name check. Must be rejected with
* USERAUTH_FAILURE.
*
* All cases assert ret == WS_SUCCESS (the connection stays up either way) and
* idx == len (the whole payload is consumed). */
static int test_EccUserAuthCurveMismatch(void)
{
static const char algoName[] = "ecdsa-sha2-nistp256";
static const struct {
const char* curveName;
int keySz;
int curveId;
int expectAuth;
const char* label;
} cases[] = {
{ "nistp256", 32, ECC_SECP256R1, 1, "matching curve" },
{ "nistp384", 48, ECC_SECP384R1, 0, "curve mismatch" },
{ "nistp256", 48, ECC_SECP384R1, 0, "matching name, wrong point" },
{ "nistp", 32, ECC_SECP256R1, 0, "truncated curve name" },
};
int result = 0;
int i;
for (i = 0; i < (int)(sizeof(cases)/sizeof(cases[0])); i++) {
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WC_RNG rng;
ecc_key key;
byte buf[512];
byte toSign[512];
byte q[133];
byte der[140];
byte r[66];
byte s[66];
byte digest[WC_MAX_DIGEST_SIZE];
word32 algoSz = (word32)WSTRLEN(algoName);
word32 curveSz = (word32)WSTRLEN(cases[i].curveName);
word32 qSz = (word32)sizeof(q);
word32 derSz = (word32)sizeof(der);
word32 rSz = (word32)sizeof(r);
word32 sSz = (word32)sizeof(s);
word32 len = 0, idx = 0, blobSz, sigBlobSz, tsSz;
byte rPad, sPad;
int rngReady = 0, keyReady = 0;
int ret;
WMEMSET(&rng, 0, sizeof(rng));
WMEMSET(&key, 0, sizeof(key));
WMEMSET(digest, 0, sizeof(digest));
if (wc_ecc_init(&key) != 0) {
result = -776;
break;
}
keyReady = 1;
if (wc_InitRng(&rng) != 0) {
result = -777;
goto caseDone;
}
rngReady = 1;
if (wc_ecc_make_key_ex(&rng, cases[i].keySz, &key,
cases[i].curveId) != 0) {
result = -778;
goto caseDone;
}
if (wc_ecc_export_x963(&key, q, &qSz) != 0) {
result = -779;
goto caseDone;
}
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL) {
result = -780;
goto caseDone;
}
wolfSSH_SetIOSend(ctx, CaptureIoSendAuthSvc);
wolfSSH_SetUserAuth(ctx, UnitAuthAlwaysSucceed);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
result = -781;
goto caseDone;
}
/* The digest recipe below assumes an empty session id. */
if (ssh->sessionIdSz != 0) {
result = -782;
goto caseDone;
}
s_authSvcCaptureSz = 0;
s_authSvcSendCount = 0;
WMEMSET(s_authSvcCapture, 0, sizeof(s_authSvcCapture));
/* Fields 1-6, the region covered by the signature. */
AppendSshString(buf, &len, "user", 4);
AppendSshString(buf, &len, "ssh-connection", 14);
AppendSshString(buf, &len, "publickey", 9);
buf[len++] = 1; /* has signature */
AppendSshString(buf, &len, algoName, algoSz);
/* Key blob: string(algo) || string(curve name) || string(Q). */
blobSz = (UINT32_SZ + algoSz) + (UINT32_SZ + curveSz)
+ (UINT32_SZ + qSz);
PutU32BE(buf + len, blobSz);
len += UINT32_SZ;
AppendSshString(buf, &len, algoName, algoSz);
AppendSshString(buf, &len, cases[i].curveName, curveSz);
AppendSshString(buf, &len, q, qSz);
/* Signed data: uint32(sessionIdSz) || sessionId || msg id || fields
* 1-6. sessionIdSz is 0, so the first two collapse to four zeros. */
PutU32BE(toSign, 0);
tsSz = UINT32_SZ;
toSign[tsSz++] = MSGID_USERAUTH_REQUEST;
WMEMCPY(toSign + tsSz, buf, len);
tsSz += len;
/* The declared algorithm selects SHA-256 for both cases. */
if (wc_Hash(WC_HASH_TYPE_SHA256, toSign, tsSz,
digest, WC_SHA256_DIGEST_SIZE) != 0) {
result = -783;
goto caseDone;
}
if (wc_ecc_sign_hash(digest, WC_SHA256_DIGEST_SIZE, der, &derSz,
&rng, &key) != 0) {
result = -784;
goto caseDone;
}
if (wc_ecc_sig_to_rs(der, derSz, r, &rSz, s, &sSz) != 0) {
result = -785;
goto caseDone;
}
/* r and s come back minimal big-endian; pad to keep the mpints
* positive, as SendUserAuthRequest() does. */
rPad = (r[0] & 0x80) ? 1 : 0;
sPad = (s[0] & 0x80) ? 1 : 0;
sigBlobSz = (UINT32_SZ * 2) + rSz + rPad + sSz + sPad;
/* Field 7: string(string(algo) || string(string(r) || string(s))). */
PutU32BE(buf + len, (UINT32_SZ + algoSz) + (UINT32_SZ + sigBlobSz));
len += UINT32_SZ;
AppendSshString(buf, &len, algoName, algoSz);
PutU32BE(buf + len, sigBlobSz);
len += UINT32_SZ;
PutU32BE(buf + len, rSz + rPad);
len += UINT32_SZ;
if (rPad)
buf[len++] = 0;
WMEMCPY(buf + len, r, rSz);
len += rSz;
PutU32BE(buf + len, sSz + sPad);
len += UINT32_SZ;
if (sPad)
buf[len++] = 0;
WMEMCPY(buf + len, s, sSz);
len += sSz;
ret = wolfSSH_TestDoUserAuthRequest(ssh, buf, len, &idx);
if (ret != WS_SUCCESS) {
printf("EccUserAuthCurveMismatch[%s]: ret=%d expected"
" WS_SUCCESS\n", cases[i].label, ret);
result = -786;
goto caseDone;
}
if (idx != len) {
printf("EccUserAuthCurveMismatch[%s]: idx=%u expected %u\n",
cases[i].label, idx, len);
result = -787;
goto caseDone;
}
if (cases[i].expectAuth) {
if (s_authSvcSendCount != 0) {
printf("EccUserAuthCurveMismatch[%s]: expected 0 sends,"
" got %u\n", cases[i].label, s_authSvcSendCount);
result = -788;
goto caseDone;
}
if (ssh->clientState != CLIENT_USERAUTH_DONE) {
printf("EccUserAuthCurveMismatch[%s]: not authenticated\n",
cases[i].label);
result = -789;
goto caseDone;
}
}
else {
if (s_authSvcSendCount != 1) {
printf("EccUserAuthCurveMismatch[%s]: expected 1 send,"
" got %u\n", cases[i].label, s_authSvcSendCount);
result = -790;
goto caseDone;
}
if (CaptureMsgId(s_authSvcCapture, s_authSvcCaptureSz)
!= MSGID_USERAUTH_FAILURE) {
printf("EccUserAuthCurveMismatch[%s]: expected"
" USERAUTH_FAILURE\n", cases[i].label);
result = -791;
goto caseDone;
}
if (ssh->clientState == CLIENT_USERAUTH_DONE) {
printf("EccUserAuthCurveMismatch[%s]: authenticated with a"
" mismatched curve\n", cases[i].label);
result = -792;
goto caseDone;
}
}
caseDone:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
if (rngReady)
wc_FreeRng(&rng);
if (keyReady)
wc_ecc_free(&key);
if (result != 0)
break;
}
return result;
}
#endif /* !WOLFSSH_NO_ECDSA_SHA2_NISTP256 && !WOLFSSH_NO_ECDSA_SHA2_NISTP384 */
#if !defined(WOLFSSH_NO_RSA)
/* 2048-bit RSA private key (PKCS#1 DER).
* Same key as tests/auth.c hanselPrivateRsa - copied here so this
* test has no dependency on WOLFSSH_KEYGEN. */
static const byte unitTestRsaPrivKey[] = {
0x30, 0x82, 0x04, 0xa3, 0x02, 0x01, 0x00, 0x02, 0x82, 0x01, 0x01, 0x00,
0xbd, 0x3f, 0x76, 0x45, 0xa3, 0x03, 0xac, 0x38, 0xd5, 0xc7, 0x0f, 0x93,
0x30, 0x5a, 0x20, 0x9c, 0x89, 0x7c, 0xad, 0x05, 0x16, 0x46, 0x86, 0x83,
0x0d, 0x8a, 0x2b, 0x16, 0x4a, 0x05, 0x2c, 0xe4, 0x77, 0x47, 0x70, 0x00,
0xae, 0x1d, 0x83, 0xe2, 0xd9, 0x6e, 0x99, 0xd4, 0xf0, 0x45, 0x98, 0x15,
0x93, 0xf6, 0x87, 0x4e, 0xac, 0x64, 0x63, 0xa1, 0x95, 0xc9, 0x7c, 0x30,
0xe8, 0x3e, 0x2f, 0xa3, 0xf1, 0x24, 0x9f, 0x0c, 0x6b, 0x1c, 0xfe, 0x1b,
0x02, 0x99, 0xcd, 0xc6, 0xa7, 0x6c, 0x84, 0x85, 0x46, 0x54, 0x12, 0x40,
0xe1, 0xb4, 0xe5, 0xf2, 0xaa, 0x39, 0xec, 0xd6, 0x27, 0x24, 0x0b, 0xd1,
0xa1, 0xe2, 0xef, 0x34, 0x69, 0x25, 0x6d, 0xc0, 0x74, 0x67, 0x25, 0x98,
0x7d, 0xc4, 0xf8, 0x52, 0xab, 0x9b, 0x4b, 0x3a, 0x12, 0x1d, 0xe1, 0xe3,
0xfa, 0xd6, 0xcf, 0x9a, 0xe6, 0x9c, 0x23, 0x4e, 0x39, 0xc4, 0x84, 0x16,
0x88, 0x3d, 0x42, 0x4e, 0xd8, 0x2f, 0xcc, 0xd2, 0x91, 0x67, 0x9d, 0xb6,
0x71, 0x2a, 0x02, 0x65, 0x5f, 0xbb, 0x75, 0x0e, 0x8c, 0xbb, 0x87, 0x97,
0x97, 0xc6, 0xf8, 0xb2, 0x98, 0xe2, 0x2f, 0x68, 0x26, 0x4a, 0x53, 0xec,
0x79, 0x3a, 0x8a, 0x5f, 0xcc, 0xcf, 0xf0, 0x16, 0x47, 0xb2, 0xd0, 0x43,
0xd6, 0x36, 0x6c, 0xc8, 0xe7, 0x2f, 0xfe, 0xa7, 0x35, 0x39, 0x69, 0xfb,
0x1d, 0x78, 0x45, 0x9d, 0x89, 0x00, 0xc8, 0x41, 0xcf, 0x34, 0x1f, 0xa3,
0xf3, 0xf1, 0xfb, 0x28, 0x14, 0xfb, 0xd8, 0x48, 0x6f, 0xac, 0xe3, 0xfc,
0x33, 0xd1, 0xdb, 0xae, 0xef, 0x27, 0x9e, 0x57, 0x56, 0x29, 0xa2, 0x1a,
0x3a, 0xe5, 0x9a, 0xfe, 0xa4, 0x49, 0xc8, 0x7f, 0xb7, 0x4e, 0xd0, 0x1f,
0x04, 0x6e, 0x58, 0x16, 0xb7, 0xeb, 0x9d, 0xf8, 0x92, 0x3c, 0xc2, 0xb0,
0x21, 0x7c, 0x4e, 0x31, 0x02, 0x03, 0x01, 0x00, 0x01, 0x02, 0x82, 0x01,
0x01, 0x00, 0x8d, 0xa4, 0x61, 0x06, 0x2f, 0xc3, 0x40, 0xf4, 0x6c, 0xf4,
0x87, 0x30, 0xb8, 0x00, 0xcc, 0xe5, 0xbc, 0x75, 0x87, 0x1e, 0x06, 0x95,
0x14, 0x7a, 0x23, 0xf9, 0x24, 0xd4, 0x92, 0xe4, 0x1a, 0xbc, 0x88, 0x95,
0xfc, 0x3b, 0x56, 0x16, 0x1b, 0x2e, 0xff, 0x64, 0x2b, 0x58, 0xd7, 0xd8,
0x8e, 0xc2, 0x9f, 0xb2, 0xe5, 0x84, 0xb9, 0xbc, 0x8d, 0x61, 0x54, 0x35,
0xb0, 0x70, 0xfe, 0x72, 0x04, 0xc0, 0x24, 0x6d, 0x2f, 0x69, 0x61, 0x06,
0x1b, 0x1d, 0xe6, 0x2d, 0x6d, 0x79, 0x60, 0xb7, 0xf4, 0xdb, 0xb7, 0x4e,
0x97, 0x36, 0xde, 0x77, 0xc1, 0x9f, 0x85, 0x4e, 0xc3, 0x77, 0x69, 0x66,
0x2e, 0x3e, 0x61, 0x76, 0xf3, 0x67, 0xfb, 0xc6, 0x9a, 0xc5, 0x6f, 0x99,
0xff, 0xe6, 0x89, 0x43, 0x92, 0x44, 0x75, 0xd2, 0x4e, 0x54, 0x91, 0x58,
0xb2, 0x48, 0x2a, 0xe6, 0xfa, 0x0d, 0x4a, 0xca, 0xd4, 0x14, 0x9e, 0xf6,
0x27, 0x67, 0xb7, 0x25, 0x7a, 0x43, 0xbb, 0x2b, 0x67, 0xd1, 0xfe, 0xd1,
0x68, 0x23, 0x06, 0x30, 0x7c, 0xbf, 0x60, 0x49, 0xde, 0xcc, 0x7e, 0x26,
0x5a, 0x3b, 0xfe, 0xa6, 0xa6, 0xe7, 0xa8, 0xdd, 0xac, 0xb9, 0xaf, 0x82,
0x9a, 0x3a, 0x41, 0x7e, 0x61, 0x21, 0x37, 0xa3, 0x08, 0xe4, 0xc4, 0xbc,
0x11, 0xf5, 0x3b, 0x8e, 0x4d, 0x51, 0xf3, 0xbd, 0xda, 0xba, 0xb2, 0xc5,
0xee, 0xfb, 0xcf, 0xdf, 0x83, 0xa1, 0x82, 0x01, 0xe1, 0x51, 0x9d, 0x07,
0x5a, 0x5d, 0xd8, 0xc7, 0x5b, 0x3f, 0x97, 0x13, 0x6a, 0x4d, 0x1e, 0x8d,
0x39, 0xac, 0x40, 0x95, 0x82, 0x6c, 0xa2, 0xa1, 0xcc, 0x8a, 0x9b, 0x21,
0x32, 0x3a, 0x58, 0xcc, 0xe7, 0x2d, 0x1a, 0x79, 0xa4, 0x31, 0x50, 0xb1,
0x4b, 0x76, 0x23, 0x1b, 0xb3, 0x40, 0x3d, 0x3d, 0x72, 0x72, 0x32, 0xec,
0x5f, 0x38, 0xb5, 0x8d, 0xb2, 0x8d, 0x02, 0x81, 0x81, 0x00, 0xed, 0x5a,
0x7e, 0x8e, 0xa1, 0x62, 0x7d, 0x26, 0x5c, 0x78, 0xc4, 0x87, 0x71, 0xc9,
0x41, 0x57, 0x77, 0x94, 0x93, 0x93, 0x26, 0x78, 0xc8, 0xa3, 0x15, 0xbd,
0x59, 0xcb, 0x1b, 0xb4, 0xb2, 0x6b, 0x0f, 0xe7, 0x80, 0xf2, 0xfa, 0xfc,
0x8e, 0x32, 0xa9, 0x1b, 0x1e, 0x7f, 0xe1, 0x26, 0xef, 0x00, 0x25, 0xd8,
0xdd, 0xc9, 0x1a, 0x23, 0x00, 0x26, 0x3b, 0x46, 0x23, 0xc0, 0x50, 0xe7,
0xce, 0x62, 0xb2, 0x36, 0xb2, 0x98, 0x09, 0x16, 0x34, 0x18, 0x9e, 0x46,
0xbc, 0xaf, 0x2c, 0x28, 0x94, 0x2f, 0xe0, 0x5d, 0xc9, 0xb2, 0xc8, 0xfb,
0x5d, 0x13, 0xd5, 0x36, 0xaa, 0x15, 0x0f, 0x89, 0xa5, 0x16, 0x59, 0x5d,
0x22, 0x74, 0xa4, 0x47, 0x5d, 0xfa, 0xfb, 0x0c, 0x5e, 0x80, 0xbf, 0x0f,
0xc2, 0x9c, 0x95, 0x0f, 0xe7, 0xaa, 0x7f, 0x16, 0x1b, 0xd4, 0xdb, 0x38,
0x7d, 0x58, 0x2e, 0x57, 0x78, 0x2f, 0x02, 0x81, 0x81, 0x00, 0xcc, 0x1d,
0x7f, 0x74, 0x36, 0x6d, 0xb4, 0x92, 0x25, 0x62, 0xc5, 0x50, 0xb0, 0x5c,
0xa1, 0xda, 0xf3, 0xb2, 0xfd, 0x1e, 0x98, 0x0d, 0x8b, 0x05, 0x69, 0x60,
0x8e, 0x5e, 0xd2, 0x89, 0x90, 0x4a, 0x0d, 0x46, 0x7e, 0xe2, 0x54, 0x69,
0xae, 0x16, 0xe6, 0xcb, 0xd5, 0xbd, 0x7b, 0x30, 0x2b, 0x7b, 0x5c, 0xee,
0x93, 0x12, 0xcf, 0x63, 0x89, 0x9c, 0x3d, 0xc8, 0x2d, 0xe4, 0x7a, 0x61,
0x09, 0x5e, 0x80, 0xfb, 0x3c, 0x03, 0xb3, 0x73, 0xd6, 0x98, 0xd0, 0x84,
0x0c, 0x59, 0x9f, 0x4e, 0x80, 0xf3, 0x46, 0xed, 0x03, 0x9d, 0xd5, 0xdc,
0x8b, 0xe7, 0xb1, 0xe8, 0xaa, 0x57, 0xdc, 0xd1, 0x41, 0x55, 0x07, 0xc7,
0xdf, 0x67, 0x3c, 0x72, 0x78, 0xb0, 0x60, 0x8f, 0x85, 0xa1, 0x90, 0x99,
0x0c, 0xa5, 0x67, 0xab, 0xf0, 0xb6, 0x74, 0x90, 0x03, 0x55, 0x7b, 0x5e,
0xcc, 0xc5, 0xbf, 0xde, 0xa7, 0x9f, 0x02, 0x81, 0x80, 0x40, 0x81, 0x6e,
0x91, 0xae, 0xd4, 0x88, 0x74, 0xab, 0x7e, 0xfa, 0xd2, 0x60, 0x9f, 0x34,
0x8d, 0xe3, 0xe6, 0xd2, 0x30, 0x94, 0xad, 0x10, 0xc2, 0x19, 0xbf, 0x6b,
0x2e, 0xe2, 0xe9, 0xb9, 0xef, 0x94, 0xd3, 0xf2, 0xdc, 0x96, 0x4f, 0x9b,
0x09, 0xb3, 0xa1, 0xb6, 0x29, 0x44, 0xf4, 0x82, 0xd1, 0xc4, 0x77, 0x6a,
0xd7, 0x23, 0xae, 0x4d, 0x75, 0x16, 0x78, 0xda, 0x70, 0x82, 0xcc, 0x6c,
0xef, 0xaf, 0xc5, 0x63, 0xc6, 0x23, 0xfa, 0x0f, 0xd0, 0x7c, 0xfb, 0x76,
0x7e, 0x18, 0xff, 0x32, 0x3e, 0xcc, 0xb8, 0x50, 0x7f, 0xb1, 0x55, 0x77,
0x17, 0x53, 0xc3, 0xd6, 0x77, 0x80, 0xd0, 0x84, 0xb8, 0x4d, 0x33, 0x1d,
0x91, 0x1b, 0xb0, 0x75, 0x9f, 0x27, 0x29, 0x56, 0x69, 0xa1, 0x03, 0x54,
0x7d, 0x9f, 0x99, 0x41, 0xf9, 0xb9, 0x2e, 0x36, 0x04, 0x24, 0x4b, 0xf6,
0xec, 0xc7, 0x33, 0x68, 0x6b, 0x02, 0x81, 0x80, 0x60, 0x35, 0xcb, 0x3c,
0xd0, 0xe6, 0xf7, 0x05, 0x28, 0x20, 0x1d, 0x57, 0x82, 0x39, 0xb7, 0x85,
0x07, 0xf7, 0xa7, 0x3d, 0xc3, 0x78, 0x26, 0xbe, 0x3f, 0x44, 0x66, 0xf7,
0x25, 0x0f, 0xf8, 0x76, 0x1f, 0x39, 0xca, 0x57, 0x0e, 0x68, 0xdd, 0xc9,
0x27, 0xb2, 0x8e, 0xa6, 0x08, 0xa9, 0xd4, 0xe5, 0x0a, 0x11, 0xde, 0x3b,
0x30, 0x8b, 0xff, 0x72, 0x28, 0xe0, 0xf1, 0x58, 0xcf, 0xa2, 0x6b, 0x93,
0x23, 0x02, 0xc8, 0xf0, 0x09, 0xa7, 0x21, 0x50, 0xd8, 0x80, 0x55, 0x7d,
0xed, 0x0c, 0x48, 0xd5, 0xe2, 0xe9, 0x97, 0x19, 0xcf, 0x93, 0x6c, 0x52,
0xa2, 0xd6, 0x43, 0x6c, 0xb4, 0xc5, 0xe1, 0xa0, 0x9d, 0xd1, 0x45, 0x69,
0x58, 0xe1, 0xb0, 0x27, 0x9a, 0xec, 0x2b, 0x95, 0xd3, 0x1d, 0x81, 0x0b,
0x7a, 0x09, 0x5e, 0xa5, 0xf1, 0xdd, 0x6b, 0xe4, 0xe0, 0x08, 0xf8, 0x46,
0x81, 0xc1, 0x06, 0x8b, 0x02, 0x81, 0x80, 0x00, 0xf6, 0xf2, 0xeb, 0x25,
0xba, 0x78, 0x04, 0xad, 0x0e, 0x0d, 0x2e, 0xa7, 0x69, 0xd6, 0x57, 0xe6,
0x36, 0x32, 0x50, 0xd2, 0xf2, 0xeb, 0xad, 0x31, 0x46, 0x65, 0xc0, 0x07,
0x97, 0x83, 0x6c, 0x66, 0x27, 0x3e, 0x94, 0x2c, 0x05, 0x01, 0x5f, 0x5c,
0xe0, 0x31, 0x30, 0xec, 0x61, 0xd2, 0x74, 0x35, 0xb7, 0x9f, 0x38, 0xe7,
0x8e, 0x67, 0xb1, 0x50, 0x08, 0x68, 0xce, 0xcf, 0xd8, 0xee, 0x88, 0xfd,
0x5d, 0xc4, 0xcd, 0xe2, 0x86, 0x3d, 0x4a, 0x0e, 0x04, 0x7f, 0xee, 0x8a,
0xe8, 0x9b, 0x16, 0xa1, 0xfc, 0x09, 0x82, 0xe2, 0x62, 0x03, 0x3c, 0xe8,
0x25, 0x7f, 0x3c, 0x9a, 0xaa, 0x83, 0xf8, 0xd8, 0x93, 0xd1, 0x54, 0xf9,
0xce, 0xb4, 0xfa, 0x35, 0x36, 0xcc, 0x18, 0x54, 0xaa, 0xf2, 0x90, 0xb7,
0x7c, 0x97, 0x0b, 0x27, 0x2f, 0xae, 0xfc, 0xc3, 0x93, 0xaf, 0x1a, 0x75,
0xec, 0x18, 0xdb
};
static const word32 unitTestRsaPrivKeySz =
(word32)sizeof(unitTestRsaPrivKey);
/* SubjectPublicKeyInfo DER for unitTestRsaPrivKey. Inlined so the ASN.1
* public-key test does not need wc_RsaKeyToPublicDer, which wolfSSL only
* builds under WOLFSSL_KEY_TO_DER or WOLFSSL_CERT_GEN. */
static const byte unitTestRsaPubKey[] = {
0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00,
0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01, 0x00, 0xbd, 0x3f, 0x76,
0x45, 0xa3, 0x03, 0xac, 0x38, 0xd5, 0xc7, 0x0f, 0x93, 0x30, 0x5a, 0x20,
0x9c, 0x89, 0x7c, 0xad, 0x05, 0x16, 0x46, 0x86, 0x83, 0x0d, 0x8a, 0x2b,
0x16, 0x4a, 0x05, 0x2c, 0xe4, 0x77, 0x47, 0x70, 0x00, 0xae, 0x1d, 0x83,
0xe2, 0xd9, 0x6e, 0x99, 0xd4, 0xf0, 0x45, 0x98, 0x15, 0x93, 0xf6, 0x87,
0x4e, 0xac, 0x64, 0x63, 0xa1, 0x95, 0xc9, 0x7c, 0x30, 0xe8, 0x3e, 0x2f,
0xa3, 0xf1, 0x24, 0x9f, 0x0c, 0x6b, 0x1c, 0xfe, 0x1b, 0x02, 0x99, 0xcd,
0xc6, 0xa7, 0x6c, 0x84, 0x85, 0x46, 0x54, 0x12, 0x40, 0xe1, 0xb4, 0xe5,
0xf2, 0xaa, 0x39, 0xec, 0xd6, 0x27, 0x24, 0x0b, 0xd1, 0xa1, 0xe2, 0xef,
0x34, 0x69, 0x25, 0x6d, 0xc0, 0x74, 0x67, 0x25, 0x98, 0x7d, 0xc4, 0xf8,
0x52, 0xab, 0x9b, 0x4b, 0x3a, 0x12, 0x1d, 0xe1, 0xe3, 0xfa, 0xd6, 0xcf,
0x9a, 0xe6, 0x9c, 0x23, 0x4e, 0x39, 0xc4, 0x84, 0x16, 0x88, 0x3d, 0x42,
0x4e, 0xd8, 0x2f, 0xcc, 0xd2, 0x91, 0x67, 0x9d, 0xb6, 0x71, 0x2a, 0x02,
0x65, 0x5f, 0xbb, 0x75, 0x0e, 0x8c, 0xbb, 0x87, 0x97, 0x97, 0xc6, 0xf8,
0xb2, 0x98, 0xe2, 0x2f, 0x68, 0x26, 0x4a, 0x53, 0xec, 0x79, 0x3a, 0x8a,
0x5f, 0xcc, 0xcf, 0xf0, 0x16, 0x47, 0xb2, 0xd0, 0x43, 0xd6, 0x36, 0x6c,
0xc8, 0xe7, 0x2f, 0xfe, 0xa7, 0x35, 0x39, 0x69, 0xfb, 0x1d, 0x78, 0x45,
0x9d, 0x89, 0x00, 0xc8, 0x41, 0xcf, 0x34, 0x1f, 0xa3, 0xf3, 0xf1, 0xfb,
0x28, 0x14, 0xfb, 0xd8, 0x48, 0x6f, 0xac, 0xe3, 0xfc, 0x33, 0xd1, 0xdb,
0xae, 0xef, 0x27, 0x9e, 0x57, 0x56, 0x29, 0xa2, 0x1a, 0x3a, 0xe5, 0x9a,
0xfe, 0xa4, 0x49, 0xc8, 0x7f, 0xb7, 0x4e, 0xd0, 0x1f, 0x04, 0x6e, 0x58,
0x16, 0xb7, 0xeb, 0x9d, 0xf8, 0x92, 0x3c, 0xc2, 0xb0, 0x21, 0x7c, 0x4e,
0x31, 0x02, 0x03, 0x01, 0x00, 0x01,
};
static const word32 unitTestRsaPubKeySz =
(word32)sizeof(unitTestRsaPubKey);
#endif /* WOLFSSH_NO_RSA */
/* Keys for test_IdentifyAsn1Key: inline DER so the test is self-contained
* in both filesystem and NO_FILESYSTEM builds. Each array matches the
* corresponding file under keys/. */
#ifndef WOLFSSH_NO_ECDSA_SHA2_NISTP256
/* keys/server-key-ecc.der - P-256 RFC-5915 ECPrivateKey */
static const byte unitTestEcc256PrivKey[] = {
0x30, 0x77, 0x02, 0x01, 0x01, 0x04, 0x20, 0x61, 0x09, 0x99,
0x0B, 0x79, 0xD2, 0x5F, 0x28, 0x5A, 0x0F, 0x5D, 0x15, 0xCC,
0xA1, 0x56, 0x54, 0xF9, 0x2B, 0x39, 0x87, 0x21, 0x2D, 0xA7,
0x7D, 0x85, 0x7B, 0xB8, 0x7F, 0x38, 0xC6, 0x6D, 0xD5, 0xA0,
0x0A, 0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01,
0x07, 0xA1, 0x44, 0x03, 0x42, 0x00, 0x04, 0x81, 0x13, 0xFF,
0xA4, 0x2B, 0xB7, 0x9C, 0x45, 0x74, 0x7A, 0x83, 0x4C, 0x61,
0xF3, 0x3F, 0xAD, 0x26, 0xCF, 0x22, 0xCD, 0xA9, 0xA3, 0xBC,
0xA5, 0x61, 0xB4, 0x7C, 0xE6, 0x62, 0xD4, 0xC2, 0xF7, 0x55,
0x43, 0x9A, 0x31, 0xFB, 0x80, 0x11, 0x20, 0xB5, 0x12, 0x4B,
0x24, 0xF5, 0x78, 0xD7, 0xFD, 0x22, 0xEF, 0x46, 0x35, 0xF0,
0x05, 0x58, 0x6B, 0x5F, 0x63, 0xC8, 0xDA, 0x1B, 0xC4, 0xF5,
0x69
};
#endif /* WOLFSSH_NO_ECDSA_SHA2_NISTP256 */
#ifndef WOLFSSH_NO_ECDSA_SHA2_NISTP384
/* keys/server-key-ecc-384.der - P-384 RFC-5915 ECPrivateKey */
static const byte unitTestEcc384PrivKey[] = {
0x30, 0x81, 0xA4, 0x02, 0x01, 0x01, 0x04, 0x30, 0x3E, 0xAD,
0xD2, 0xBB, 0xBF, 0x05, 0xA7, 0xBE, 0x3A, 0x3F, 0x7C, 0x28,
0x15, 0x12, 0x89, 0xDE, 0x5B, 0xB3, 0x64, 0x4D, 0x70, 0x11,
0x76, 0x1D, 0xB5, 0x6F, 0x2A, 0x03, 0x62, 0xFB, 0xA6, 0x4F,
0x98, 0xE6, 0x4F, 0xF9, 0x86, 0xDC, 0x4F, 0xB8, 0xEF, 0xDB,
0x2D, 0x6B, 0x8D, 0xA5, 0x71, 0x42, 0xA0, 0x07, 0x06, 0x05,
0x2B, 0x81, 0x04, 0x00, 0x22, 0xA1, 0x64, 0x03, 0x62, 0x00,
0x04, 0x38, 0xD6, 0x2B, 0xE4, 0x18, 0xFF, 0x57, 0x3F, 0xD0,
0xE0, 0x20, 0xD4, 0x88, 0x76, 0xC4, 0xE1, 0x12, 0x1D, 0xFB,
0x2D, 0x6E, 0xBE, 0xE4, 0x89, 0x5D, 0x77, 0x24, 0x31, 0x6D,
0x46, 0xA2, 0x31, 0x05, 0x87, 0x3F, 0x29, 0x86, 0xD5, 0xC7,
0x12, 0x80, 0x3A, 0x6F, 0x47, 0x1A, 0xB8, 0x68, 0x50, 0xEB,
0x06, 0x3E, 0x10, 0x89, 0x61, 0x34, 0x9C, 0xF8, 0xB4, 0xC6,
0xA4, 0xCF, 0x5E, 0x97, 0xBD, 0x7E, 0x51, 0xE9, 0x75, 0xE3,
0xE9, 0x21, 0x72, 0x61, 0x50, 0x6E, 0xB9, 0xCF, 0x3C, 0x49,
0x3D, 0x3E, 0xB8, 0x8D, 0x46, 0x7B, 0x5F, 0x27, 0xEB, 0xAB,
0x21, 0x61, 0xC0, 0x00, 0x66, 0xFE, 0xBD
};
#endif /* WOLFSSH_NO_ECDSA_SHA2_NISTP384 */
#ifndef WOLFSSH_NO_ECDSA_SHA2_NISTP521
/* keys/server-key-ecc-521.der - P-521 RFC-5915 ECPrivateKey */
static const byte unitTestEcc521PrivKey[] = {
0x30, 0x81, 0xDC, 0x02, 0x01, 0x01, 0x04, 0x42, 0x00, 0x4C,
0xA4, 0xD8, 0x64, 0x28, 0xD9, 0x40, 0x0E, 0x7B, 0x2D, 0xF3,
0x91, 0x2E, 0xB9, 0x96, 0xC1, 0x95, 0x89, 0x50, 0x43, 0xAF,
0x92, 0xE8, 0x6D, 0xE7, 0x0A, 0xE4, 0xDF, 0x46, 0xF2, 0x2A,
0x29, 0x1A, 0x6B, 0xB2, 0x74, 0x8A, 0xAE, 0x82, 0x58, 0x0D,
0xF6, 0xC3, 0x9F, 0x49, 0xB3, 0xED, 0x82, 0xF1, 0x78, 0x9E,
0xCE, 0x1B, 0x65, 0x7D, 0x45, 0x43, 0x8C, 0xFF, 0x15, 0x65,
0x34, 0x35, 0x45, 0x75, 0xA0, 0x07, 0x06, 0x05, 0x2B, 0x81,
0x04, 0x00, 0x23, 0xA1, 0x81, 0x89, 0x03, 0x81, 0x86, 0x00,
0x04, 0x01, 0xF8, 0xD0, 0xA7, 0xC3, 0xC5, 0x8D, 0x84, 0x19,
0x57, 0x96, 0x9F, 0x21, 0x3A, 0x94, 0xF3, 0xDA, 0x55, 0x0E,
0xDF, 0x76, 0xD8, 0xDD, 0x17, 0x15, 0x31, 0xF3, 0x5B, 0xB0,
0x69, 0xC8, 0xBC, 0x30, 0x0D, 0x6F, 0x6B, 0x37, 0xD1, 0x80,
0x46, 0xA9, 0x71, 0x7F, 0x2C, 0x6F, 0x59, 0x51, 0x9C, 0x82,
0x70, 0x95, 0xB2, 0x9A, 0x63, 0x13, 0x30, 0x62, 0x18, 0xC2,
0x35, 0x76, 0x94, 0x00, 0xD0, 0xF9, 0x6D, 0x00, 0x0A, 0x19,
0x3B, 0xA3, 0x46, 0x65, 0x2B, 0xEB, 0x40, 0x9A, 0x9A, 0x45,
0xC5, 0x97, 0xA3, 0xED, 0x93, 0x2D, 0xD5, 0xAA, 0xAE, 0x96,
0xBF, 0x2F, 0x31, 0x7E, 0x5A, 0x7A, 0xC7, 0x45, 0x8B, 0x3C,
0x6C, 0xDB, 0xAA, 0x90, 0xC3, 0x55, 0x38, 0x2C, 0xDF, 0xCD,
0xCA, 0x73, 0x77, 0xD9, 0x2E, 0xB2, 0x0A, 0x5E, 0x8C, 0x74,
0x23, 0x7C, 0xA5, 0xA3, 0x45, 0xB1, 0x9E, 0x3F, 0x1A, 0x22,
0x90, 0xB1, 0x54
};
#endif /* WOLFSSH_NO_ECDSA_SHA2_NISTP521 */
#if !defined(WOLFSSH_NO_ED25519)
/* keys/server-key-ed25519.der - Ed25519 OneAsymmetricKey (RFC 8410) */
static const byte unitTestEd25519PrivKey[] = {
0x30, 0x50, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b,
0x65, 0x70, 0x04, 0x22, 0x04, 0x20, 0x6a, 0x67, 0xf3, 0x0e,
0x64, 0xea, 0x52, 0xfe, 0xf4, 0xad, 0x65, 0x4d, 0x45, 0x60,
0x61, 0x38, 0x58, 0x11, 0x07, 0x84, 0xf0, 0x03, 0x94, 0x93,
0x14, 0x7b, 0x7b, 0x33, 0x1a, 0xba, 0xf6, 0x19, 0x81, 0x20,
0x0f, 0x56, 0x0c, 0x9f, 0x7d, 0x7a, 0x62, 0x87, 0xf0, 0x26,
0x16, 0x19, 0x31, 0xe4, 0xb2, 0x1d, 0xe9, 0xbd, 0xee, 0x4a,
0x7f, 0x55, 0xae, 0x26, 0x2d, 0xa1, 0x25, 0xe4, 0xee, 0x4a,
0x51, 0x00
};
#endif /* !WOLFSSH_NO_ED25519 */
#ifdef WOLFSSH_OSSH_CERTS
/* Each OpenSSH-certificate key ID must free the key it was loaded into. One
* case per branch of wolfSSH_KEY_clean(), so a cert ID landing in the wrong
* branch frees the wrong union member and shows up here. */
static int test_KEY_clean_osshCert(void)
{
WS_KeySignature keySig;
word32 idx;
int ret;
/* Every case below is optional; keep the locals used if all compile out. */
(void)keySig;
(void)idx;
(void)ret;
#if !defined(WOLFSSH_NO_RSA) && !defined(WOLFSSH_NO_OSSH_CERT_RSA)
idx = 0;
WMEMSET(&keySig, 0, sizeof(keySig));
keySig.keyId = ID_OSSH_CERT_RSA;
if (wc_InitRsaKey(&keySig.ks.rsa.key, NULL) != 0)
return -7200;
ret = wc_RsaPrivateKeyDecode(unitTestRsaPrivKey, &idx,
&keySig.ks.rsa.key, (word32)sizeof(unitTestRsaPrivKey));
if (ret != 0) {
wc_FreeRsaKey(&keySig.ks.rsa.key);
printf("KEY_clean_osshCert: RSA decode failed (%d)\n", ret);
return -7201;
}
if (keySig.ks.rsa.key.n.used == 0) {
wc_FreeRsaKey(&keySig.ks.rsa.key);
printf("KEY_clean_osshCert: RSA key did not load\n");
return -7202;
}
wolfSSH_KEY_clean(&keySig);
if (keySig.ks.rsa.key.n.used != 0) {
printf("KEY_clean_osshCert: RSA key was not freed\n");
wc_FreeRsaKey(&keySig.ks.rsa.key);
return -7203;
}
#endif /* !WOLFSSH_NO_RSA && !WOLFSSH_NO_OSSH_CERT_RSA */
#ifndef WOLFSSH_NO_ECDSA_SHA2_NISTP256
idx = 0;
WMEMSET(&keySig, 0, sizeof(keySig));
keySig.keyId = ID_OSSH_CERT_ECDSA_SHA2_NISTP256;
if (wc_ecc_init(&keySig.ks.ecc.key) != 0)
return -7204;
ret = wc_EccPrivateKeyDecode(unitTestEcc256PrivKey, &idx,
&keySig.ks.ecc.key, (word32)sizeof(unitTestEcc256PrivKey));
if (ret != 0) {
wc_ecc_free(&keySig.ks.ecc.key);
printf("KEY_clean_osshCert: ECC decode failed (%d)\n", ret);
return -7205;
}
if (keySig.ks.ecc.key.pubkey.x->used == 0) {
wc_ecc_free(&keySig.ks.ecc.key);
printf("KEY_clean_osshCert: ECC key did not load\n");
return -7206;
}
wolfSSH_KEY_clean(&keySig);
if (keySig.ks.ecc.key.pubkey.x->used != 0) {
printf("KEY_clean_osshCert: ECC key was not freed\n");
wc_ecc_free(&keySig.ks.ecc.key);
return -7207;
}
#endif /* !WOLFSSH_NO_ECDSA_SHA2_NISTP256 */
#ifndef WOLFSSH_NO_ED25519
idx = 0;
WMEMSET(&keySig, 0, sizeof(keySig));
keySig.keyId = ID_OSSH_CERT_ED25519;
if (wc_ed25519_init(&keySig.ks.ed25519.key) != 0)
return -7208;
ret = wc_Ed25519PrivateKeyDecode(unitTestEd25519PrivKey, &idx,
&keySig.ks.ed25519.key, (word32)sizeof(unitTestEd25519PrivKey));
if (ret != 0) {
wc_ed25519_free(&keySig.ks.ed25519.key);
printf("KEY_clean_osshCert: Ed25519 decode failed (%d)\n", ret);
return -7209;
}
if (keySig.ks.ed25519.key.privKeySet == 0) {
wc_ed25519_free(&keySig.ks.ed25519.key);
printf("KEY_clean_osshCert: Ed25519 key did not load\n");
return -7210;
}
wolfSSH_KEY_clean(&keySig);
if (keySig.ks.ed25519.key.privKeySet != 0) {
printf("KEY_clean_osshCert: Ed25519 key was not freed\n");
wc_ed25519_free(&keySig.ks.ed25519.key);
return -7211;
}
#endif /* !WOLFSSH_NO_ED25519 */
return 0;
}
#endif /* WOLFSSH_OSSH_CERTS */
#if !defined(WOLFSSH_NO_MLDSA) && !defined(WOLFSSH_NO_MLDSA44)
/* keys/server-key-mldsa44.der - MlDsa44 OneAsymmetricKey */
static const byte unitTestMlDsaPrivKey[] = {
0x30, 0x82, 0x0a, 0x3e, 0x02, 0x01, 0x00, 0x30,
0x0b, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65,
0x03, 0x04, 0x03, 0x11, 0x04, 0x82, 0x0a, 0x2a,
0x30, 0x82, 0x0a, 0x26, 0x04, 0x20, 0x07, 0x99,
0x36, 0x30, 0xd1, 0xef, 0x77, 0x3e, 0x75, 0x79,
0xbc, 0x3f, 0xb5, 0x78, 0xfa, 0x10, 0x26, 0x77,
0x79, 0x27, 0x19, 0x34, 0xf7, 0x68, 0x83, 0xce,
0x08, 0xb6, 0xbb, 0xe9, 0x06, 0x18, 0x04, 0x82,
0x0a, 0x00, 0x9d, 0x7b, 0x66, 0x85, 0x9a, 0xb3,
0xcb, 0xdf, 0x19, 0xc5, 0xaa, 0xe2, 0xac, 0x2a,
0x79, 0xaf, 0xf1, 0xfd, 0xe2, 0xb8, 0x8d, 0x91,
0xda, 0xf5, 0x8e, 0x86, 0xb4, 0x91, 0x3c, 0x15,
0x2a, 0x12, 0xc6, 0x98, 0x49, 0x63, 0xed, 0x50,
0xcb, 0x79, 0x0d, 0x58, 0x43, 0xf2, 0x00, 0x8e,
0x35, 0x5f, 0x25, 0x2f, 0x3c, 0xcb, 0xab, 0xd9,
0x04, 0x85, 0x20, 0x1d, 0x5e, 0x55, 0x88, 0x94,
0x64, 0x37, 0x4f, 0xd3, 0x64, 0x89, 0xbe, 0xe2,
0xcb, 0xdc, 0x96, 0xcc, 0x62, 0x99, 0x56, 0xde,
0x26, 0x8c, 0xde, 0x30, 0x18, 0x66, 0xf9, 0xd9,
0x1b, 0xf1, 0xcf, 0x32, 0xc5, 0x78, 0x48, 0x02,
0x04, 0xb2, 0x3b, 0x16, 0x3d, 0xe9, 0xa8, 0x6c,
0x81, 0x06, 0x9f, 0xf4, 0x69, 0x77, 0x7e, 0x86,
0x34, 0xa5, 0xdd, 0xb1, 0x49, 0x20, 0xe0, 0x2f,
0x17, 0x2b, 0xdc, 0x62, 0xf9, 0x93, 0x5e, 0x17,
0x51, 0x38, 0x4a, 0x82, 0x08, 0x48, 0x06, 0x24,
0x08, 0x48, 0x60, 0x92, 0xb4, 0x51, 0x13, 0x05,
0x28, 0x1a, 0xb8, 0x8d, 0x89, 0xb4, 0x28, 0x90,
0xa8, 0x64, 0x0c, 0x81, 0x44, 0xe3, 0xc6, 0x89,
0x84, 0x16, 0x0e, 0x44, 0x02, 0x40, 0x0b, 0x97,
0x2d, 0xd9, 0x48, 0x92, 0x01, 0x15, 0x64, 0x42,
0x38, 0x68, 0x1a, 0x27, 0x8e, 0x13, 0x13, 0x52,
0x00, 0x31, 0x02, 0xc4, 0x02, 0x26, 0x14, 0x42,
0x4d, 0x10, 0x28, 0x90, 0x20, 0x31, 0x32, 0x01,
0xc1, 0x60, 0x0b, 0x01, 0x6c, 0x80, 0x00, 0x6c,
0x63, 0x26, 0x50, 0x02, 0x80, 0x45, 0x4a, 0xa6,
0x40, 0x1c, 0xb2, 0x25, 0x08, 0x21, 0x62, 0x24,
0x49, 0x4e, 0x21, 0x87, 0x48, 0x1b, 0x48, 0x02,
0x1c, 0x86, 0x64, 0x04, 0xa2, 0x90, 0xda, 0xb0,
0x89, 0x14, 0x19, 0x4e, 0x49, 0x26, 0x05, 0x18,
0xc9, 0x00, 0x9a, 0xa4, 0x85, 0xdc, 0xa4, 0x48,
0x41, 0x22, 0x81, 0x02, 0x35, 0x70, 0x63, 0x26,
0x8a, 0xd4, 0x10, 0x61, 0x20, 0x44, 0x88, 0xa3,
0xa2, 0x60, 0x02, 0xa2, 0x81, 0x19, 0xb4, 0x70,
0x9c, 0x16, 0x84, 0x81, 0x02, 0x41, 0x22, 0xb5,
0x91, 0xd2, 0x08, 0x51, 0x12, 0x34, 0x41, 0xd3,
0xb8, 0x11, 0x08, 0x21, 0x32, 0x42, 0x44, 0x65,
0x00, 0x48, 0x69, 0x92, 0x46, 0x12, 0x22, 0x94,
0x61, 0xc2, 0xb6, 0x70, 0xe2, 0x98, 0x8d, 0xd3,
0x26, 0x09, 0x84, 0x22, 0x0a, 0x09, 0xb9, 0x0d,
0x4c, 0xb0, 0x64, 0x03, 0x24, 0x2e, 0x01, 0x96,
0x84, 0x99, 0x04, 0x11, 0x9b, 0xc8, 0x11, 0xa3,
0x12, 0x90, 0x0c, 0x16, 0x0a, 0x8c, 0x20, 0x2c,
0x94, 0x08, 0x46, 0x04, 0xb6, 0x0d, 0x60, 0xb0,
0x88, 0xdc, 0x04, 0x22, 0x9a, 0x46, 0x42, 0x21,
0x42, 0x4d, 0x49, 0x46, 0x29, 0x24, 0x27, 0x62,
0x13, 0x25, 0x05, 0x0a, 0x84, 0x05, 0x4a, 0x10,
0x46, 0xa4, 0x06, 0x80, 0x1c, 0x34, 0x82, 0x1a,
0xa5, 0x4c, 0x19, 0x96, 0x89, 0x24, 0x26, 0x61,
0x10, 0x46, 0x8c, 0xc1, 0x18, 0x48, 0x1c, 0x19,
0x6d, 0x04, 0x98, 0x8d, 0x8b, 0x46, 0x02, 0x02,
0x90, 0x0d, 0x5c, 0x12, 0x65, 0x4a, 0x14, 0x72,
0x02, 0xc1, 0x65, 0x1b, 0x21, 0x4d, 0x5c, 0x38,
0x6d, 0x03, 0x41, 0x8c, 0xa4, 0x26, 0x0e, 0x89,
0xa2, 0x80, 0x4a, 0x40, 0x26, 0x1c, 0x99, 0x69,
0x81, 0x12, 0x30, 0xc3, 0x40, 0x21, 0x22, 0x46,
0x61, 0x22, 0x43, 0x72, 0x02, 0x47, 0x26, 0x10,
0xa1, 0x09, 0x81, 0x22, 0x06, 0xc3, 0x22, 0x2e,
0x64, 0x32, 0x12, 0x01, 0xb2, 0x01, 0x59, 0x96,
0x45, 0x04, 0x35, 0x08, 0xc3, 0xb6, 0x8d, 0x14,
0x30, 0x6c, 0x0c, 0x95, 0x0c, 0xa3, 0x48, 0x80,
0x63, 0x40, 0x50, 0x00, 0x20, 0x26, 0xdc, 0x20,
0x24, 0x01, 0x46, 0x71, 0xe1, 0x40, 0x51, 0xc2,
0x12, 0x0d, 0xc4, 0x10, 0x40, 0x0c, 0x43, 0x24,
0x02, 0x33, 0x26, 0x02, 0xc8, 0x04, 0x1a, 0x23,
0x08, 0xe0, 0x16, 0x8a, 0x9a, 0xb0, 0x2d, 0x13,
0x40, 0x08, 0x43, 0x22, 0x32, 0x44, 0x38, 0x6d,
0xd1, 0x44, 0x90, 0xd4, 0x86, 0x09, 0x48, 0x82,
0x00, 0xe2, 0x98, 0x68, 0x12, 0xb1, 0x91, 0x09,
0x90, 0x6d, 0xc9, 0x30, 0x85, 0xc0, 0x84, 0x80,
0x9c, 0xc6, 0x4c, 0xe1, 0x10, 0x91, 0xd8, 0x96,
0x30, 0xda, 0xb6, 0x68, 0xc8, 0xc6, 0x65, 0xe3,
0x06, 0x50, 0x5c, 0x14, 0x11, 0x02, 0x44, 0x49,
0x9b, 0xa2, 0x68, 0x5a, 0x32, 0x90, 0x52, 0x80,
0x45, 0x00, 0x26, 0x30, 0x02, 0x46, 0x4c, 0xd4,
0xc8, 0x49, 0x9c, 0xb8, 0x90, 0xc4, 0x20, 0x8a,
0x0c, 0x15, 0x0d, 0x09, 0x37, 0x8e, 0x12, 0x46,
0x45, 0x08, 0x23, 0x25, 0x21, 0xa1, 0x11, 0x80,
0x90, 0x65, 0x93, 0x46, 0x72, 0xe1, 0x28, 0x6d,
0x44, 0x96, 0x51, 0x81, 0x12, 0x80, 0x04, 0x46,
0x4a, 0x8b, 0x10, 0x6d, 0x13, 0x46, 0x51, 0x53,
0x36, 0x4a, 0xe1, 0xa6, 0x45, 0xe0, 0x22, 0x01,
0x48, 0xa6, 0x00, 0x12, 0x91, 0x70, 0x23, 0xb3,
0x40, 0x02, 0xa8, 0x65, 0xdb, 0x42, 0x06, 0xe0,
0x06, 0x6a, 0xe3, 0x96, 0x61, 0x48, 0x94, 0x65,
0x43, 0x22, 0x69, 0xdc, 0x22, 0x85, 0x9b, 0x84,
0x89, 0x59, 0x18, 0x64, 0x43, 0xb0, 0x20, 0x8b,
0xa8, 0x29, 0x58, 0x30, 0x24, 0x0a, 0x17, 0x8e,
0x11, 0x41, 0x2d, 0x24, 0xb8, 0x25, 0x89, 0x14,
0x20, 0x14, 0x41, 0x91, 0x23, 0xa2, 0x24, 0x21,
0x17, 0x21, 0x11, 0xb1, 0x04, 0x03, 0x84, 0x4c,
0x0b, 0x23, 0x62, 0x50, 0x86, 0x65, 0x54, 0x22,
0x42, 0x42, 0x82, 0x80, 0x08, 0xa5, 0x51, 0xd9,
0x06, 0x31, 0x23, 0x00, 0x91, 0x10, 0xa9, 0x4d,
0xe2, 0x04, 0x66, 0x44, 0x36, 0x30, 0x8b, 0xb2,
0x49, 0x98, 0xc6, 0x70, 0x19, 0xa4, 0x8c, 0x5a,
0xa6, 0x0d, 0x63, 0x00, 0x2e, 0x9b, 0x94, 0x70,
0x8a, 0x20, 0x2d, 0x62, 0x26, 0x2c, 0x42, 0x26,
0x6c, 0x12, 0x13, 0x2e, 0xdb, 0x18, 0x08, 0x11,
0x21, 0x2e, 0x8a, 0xb0, 0x71, 0x01, 0xc1, 0x2c,
0xe3, 0x44, 0x62, 0xe3, 0x94, 0x28, 0x0b, 0x38,
0x70, 0x40, 0x14, 0x65, 0x62, 0xc0, 0x41, 0xa1,
0x06, 0x21, 0x82, 0xa2, 0x44, 0x94, 0xb0, 0x2c,
0x21, 0x10, 0x8d, 0x14, 0x96, 0x71, 0x12, 0x14,
0x05, 0x11, 0x27, 0x04, 0x12, 0x97, 0x65, 0xc4,
0x02, 0x6e, 0x58, 0xc4, 0x6c, 0xc0, 0x10, 0x70,
0x84, 0xc0, 0x45, 0x99, 0x12, 0x52, 0x80, 0xa8,
0x88, 0xd3, 0xb8, 0x28, 0x01, 0x17, 0x70, 0x03,
0xc3, 0x10, 0x88, 0x18, 0x0a, 0x53, 0x92, 0x40,
0x53, 0xc6, 0x20, 0x93, 0xc0, 0x81, 0xa4, 0x90,
0x90, 0x93, 0x92, 0x05, 0x22, 0x88, 0x08, 0xc8,
0x00, 0x64, 0xf0, 0x19, 0xcf, 0xdf, 0x37, 0x19,
0x32, 0xc9, 0xaf, 0x0a, 0x3c, 0x4a, 0x8f, 0x9c,
0xb3, 0xb4, 0x4a, 0x29, 0x5c, 0x6d, 0xd2, 0x81,
0x10, 0x3f, 0x9f, 0x4d, 0x23, 0x18, 0x65, 0xee,
0x03, 0xa7, 0xeb, 0x14, 0x99, 0xc0, 0xab, 0x6c,
0x2e, 0xad, 0x31, 0xa0, 0x15, 0x7f, 0xfd, 0x12,
0xc3, 0x0b, 0x86, 0x8d, 0x1d, 0x0f, 0x19, 0x8e,
0x2c, 0xdd, 0xc1, 0xce, 0xf2, 0x75, 0xc2, 0x3f,
0xff, 0xc3, 0xbc, 0x7d, 0x5c, 0x40, 0x50, 0x81,
0xd5, 0x92, 0xc9, 0xdc, 0x89, 0x56, 0x00, 0x04,
0x64, 0x66, 0x27, 0xa9, 0xc0, 0x43, 0xcd, 0x5d,
0xd6, 0xe6, 0xc7, 0x84, 0xa8, 0xf0, 0x02, 0xda,
0xa3, 0xf2, 0xd7, 0x27, 0xac, 0x52, 0x30, 0xb3,
0x95, 0x53, 0x34, 0x31, 0x1f, 0x06, 0xf2, 0x74,
0xba, 0x58, 0x52, 0xcf, 0xb9, 0x0b, 0xd1, 0x39,
0x3e, 0x60, 0xfe, 0xd9, 0x55, 0x72, 0xfb, 0xd9,
0x5c, 0x2d, 0x9e, 0x5f, 0x5d, 0x95, 0xe3, 0xf8,
0x25, 0x6d, 0x14, 0x70, 0x24, 0xf8, 0x15, 0x04,
0x24, 0x14, 0x15, 0xab, 0xa5, 0x33, 0xc9, 0xe0,
0xfd, 0x9c, 0xb3, 0x3d, 0x57, 0xef, 0xf4, 0xe2,
0x87, 0x21, 0x9b, 0xd4, 0x27, 0x3e, 0x6e, 0x7b,
0x23, 0x9e, 0x56, 0x7c, 0x67, 0xd2, 0x39, 0xea,
0x52, 0xb5, 0xbd, 0x6d, 0xda, 0x00, 0xc7, 0x1e,
0x0a, 0xee, 0x6d, 0x16, 0xfb, 0x9a, 0x34, 0xae,
0x8b, 0x85, 0x7b, 0x69, 0x9a, 0x98, 0xd6, 0x15,
0x26, 0x19, 0x4f, 0x09, 0xbd, 0xe0, 0x06, 0x79,
0x93, 0x2c, 0x9e, 0xaa, 0x87, 0x3c, 0xc6, 0xab,
0xca, 0x07, 0x98, 0xa9, 0xb4, 0x63, 0x90, 0x78,
0x13, 0x28, 0xdc, 0x62, 0xf3, 0x04, 0x04, 0xd5,
0x55, 0x8a, 0x91, 0xfb, 0x8b, 0xdc, 0x1d, 0x6a,
0x53, 0x16, 0xde, 0x19, 0x88, 0xe7, 0x96, 0xfc,
0xb1, 0xb5, 0x11, 0xe7, 0x91, 0x4e, 0x62, 0xc6,
0xa4, 0xb8, 0xab, 0x08, 0x7f, 0x75, 0x06, 0x45,
0x0b, 0x54, 0x63, 0x78, 0x7d, 0x0a, 0x84, 0x64,
0x96, 0xa3, 0x9d, 0x44, 0x73, 0xf6, 0x16, 0x74,
0x46, 0x35, 0x10, 0xa2, 0x9c, 0xbe, 0x5b, 0xc0,
0xe1, 0x5e, 0xc4, 0xa8, 0x24, 0xab, 0xe1, 0xc2,
0x59, 0x52, 0x16, 0xd8, 0xc9, 0xb6, 0x3e, 0x58,
0xad, 0xfb, 0xc8, 0x36, 0x65, 0x7e, 0xf1, 0x8e,
0x4f, 0x91, 0xc8, 0xe2, 0xf3, 0xa7, 0xd3, 0x28,
0xab, 0x62, 0x21, 0x96, 0x96, 0x31, 0xef, 0xa1,
0xaf, 0xe9, 0x2e, 0x36, 0xfe, 0x09, 0xeb, 0xf1,
0x8d, 0xfa, 0xfb, 0x58, 0x39, 0xa3, 0xce, 0x45,
0xe4, 0x1f, 0xdd, 0x8c, 0x24, 0xa9, 0xd7, 0x33,
0x80, 0xf5, 0xbb, 0x05, 0x11, 0x52, 0xcb, 0xbc,
0xb3, 0x09, 0x14, 0x2e, 0x0a, 0xdd, 0x44, 0xe4,
0x2f, 0x85, 0x84, 0x4e, 0x09, 0xda, 0x0b, 0x20,
0x78, 0x61, 0x2a, 0xb9, 0x67, 0x9c, 0x84, 0xe0,
0xeb, 0xbb, 0x95, 0xd0, 0x31, 0x5d, 0x83, 0x91,
0x15, 0xbf, 0x27, 0xf5, 0x1e, 0x25, 0xc9, 0xc5,
0x48, 0xa8, 0xaa, 0x8c, 0xfc, 0xea, 0x60, 0x7a,
0xcd, 0x97, 0x92, 0xab, 0x07, 0xc7, 0x9e, 0x0b,
0x54, 0xbc, 0x41, 0xdc, 0x7f, 0xf7, 0x89, 0x72,
0x12, 0xee, 0x85, 0x18, 0x86, 0x1b, 0xe0, 0x44,
0xe1, 0x4f, 0x7b, 0x75, 0x3d, 0x27, 0xf7, 0x82,
0xee, 0x38, 0xf7, 0x61, 0xe3, 0xc9, 0xa5, 0xdb,
0x59, 0xff, 0x20, 0x0d, 0x7c, 0xb8, 0xd2, 0x2c,
0xec, 0x88, 0x5d, 0xc4, 0x03, 0x08, 0x67, 0xb4,
0x72, 0x3b, 0x5c, 0xc6, 0x16, 0xab, 0x1a, 0x6b,
0x72, 0x99, 0x87, 0x80, 0xa7, 0x35, 0x5a, 0xb9,
0x91, 0x4e, 0x5c, 0x7a, 0xc6, 0x94, 0x18, 0xd2,
0xe5, 0x97, 0x7c, 0xd5, 0x91, 0x5d, 0x57, 0x56,
0xe9, 0xff, 0x5a, 0x64, 0xf9, 0xc8, 0xff, 0x2a,
0x5a, 0xba, 0xce, 0x0d, 0xcf, 0x67, 0x09, 0xb1,
0x2d, 0x63, 0xc5, 0x72, 0x78, 0xc7, 0x4f, 0xc1,
0xc0, 0x23, 0x42, 0xaf, 0xf2, 0xb8, 0x2f, 0x79,
0xb7, 0xf7, 0x5d, 0xa5, 0xba, 0xd5, 0x0f, 0xa8,
0x9b, 0xf2, 0xaf, 0x5d, 0x72, 0x92, 0x86, 0xce,
0x10, 0x52, 0xd3, 0xdd, 0x15, 0x15, 0x65, 0xa8,
0x38, 0xc2, 0x98, 0x27, 0x47, 0x4e, 0xb1, 0xde,
0x05, 0x8b, 0xd9, 0x36, 0xd7, 0x0f, 0xf5, 0x33,
0x6e, 0x4c, 0x9c, 0x49, 0x7d, 0x8e, 0x07, 0x79,
0x77, 0x14, 0x8a, 0xea, 0x3b, 0x86, 0xc4, 0xaf,
0xf9, 0x4c, 0x8f, 0x43, 0x26, 0xbf, 0xa4, 0x68,
0xf4, 0xb3, 0xe7, 0xd2, 0x03, 0xc4, 0x85, 0x1c,
0xd5, 0x0a, 0x18, 0x55, 0x51, 0xfe, 0xb1, 0x5b,
0x8e, 0x79, 0xed, 0x07, 0x87, 0x7d, 0xba, 0xd4,
0x09, 0x98, 0x93, 0xcb, 0xa9, 0x4f, 0x31, 0xce,
0xe2, 0xab, 0x3a, 0xf2, 0x6d, 0x3a, 0xeb, 0x4f,
0x2c, 0x1a, 0x6b, 0xf2, 0xff, 0x81, 0xfa, 0xf4,
0x34, 0xbe, 0xb5, 0x4e, 0x1a, 0xea, 0xf2, 0x10,
0x7b, 0x3e, 0x96, 0xcf, 0x67, 0x37, 0xd8, 0xae,
0xf0, 0x3d, 0x03, 0xa8, 0xe6, 0x93, 0x1d, 0x59,
0xbc, 0x1a, 0x06, 0xb4, 0x1c, 0x0d, 0x68, 0xf2,
0xbe, 0x27, 0x58, 0x1a, 0x66, 0x92, 0xca, 0x37,
0x63, 0x67, 0x2a, 0x59, 0x62, 0xbd, 0x40, 0xd5,
0xe9, 0xd9, 0x4a, 0x49, 0x69, 0x8c, 0x4c, 0xf4,
0x65, 0x85, 0x34, 0xcc, 0x37, 0xd0, 0x5e, 0x3e,
0x65, 0x8a, 0x73, 0x6b, 0x32, 0xd2, 0xfa, 0x6c,
0x54, 0x94, 0xb7, 0x20, 0x75, 0x6e, 0x4a, 0xc9,
0xf8, 0x72, 0xc8, 0xdc, 0xda, 0x09, 0xca, 0xe3,
0x94, 0x9b, 0xf8, 0xeb, 0xe8, 0x32, 0xbe, 0xbb,
0x41, 0x68, 0xb6, 0x01, 0x8d, 0xe9, 0x9f, 0xd3,
0x7f, 0xfd, 0x91, 0xe2, 0x2b, 0xc0, 0x4e, 0xf9,
0x42, 0x5b, 0xa2, 0xec, 0xc8, 0x35, 0x0f, 0x36,
0xd9, 0xd1, 0x88, 0x65, 0xa2, 0x2a, 0xea, 0x50,
0x99, 0x19, 0x50, 0x31, 0x24, 0x10, 0x7b, 0x56,
0x67, 0xa4, 0xa5, 0xca, 0xe3, 0xa5, 0xc9, 0x77,
0xb4, 0xd1, 0x8a, 0xdc, 0xa4, 0xff, 0xca, 0xee,
0xd8, 0x58, 0x3e, 0x6d, 0xa5, 0xd4, 0xb3, 0x39,
0x15, 0xa2, 0xcb, 0x02, 0x9c, 0xfe, 0x93, 0x66,
0x18, 0xd8, 0xd2, 0xce, 0xb2, 0x8d, 0x4d, 0x28,
0x62, 0xc4, 0x7b, 0x39, 0xe2, 0x2a, 0x02, 0x6e,
0x38, 0x59, 0xcc, 0x35, 0xda, 0x99, 0xb2, 0xc1,
0x93, 0x24, 0xb6, 0x63, 0xa8, 0xfe, 0x37, 0x91,
0x32, 0x78, 0x11, 0xf9, 0x95, 0x72, 0x2d, 0xd1,
0x51, 0x40, 0x13, 0x90, 0xfa, 0xa7, 0x3d, 0x5d,
0xfa, 0xce, 0xc1, 0x3d, 0xd4, 0xab, 0xb7, 0x4b,
0x8c, 0xd1, 0xd9, 0x45, 0xc6, 0x7e, 0x0c, 0xc6,
0xbc, 0xdd, 0x11, 0xfa, 0x52, 0x83, 0x59, 0x2d,
0xa7, 0xa8, 0xae, 0x3f, 0xb8, 0x58, 0xa2, 0x84,
0x14, 0x05, 0x77, 0xf9, 0xb9, 0xfe, 0x05, 0xd1,
0x4a, 0xf9, 0xe8, 0x7d, 0x1e, 0xb8, 0xb4, 0x39,
0xfc, 0x80, 0x1d, 0xb2, 0x38, 0x8d, 0xc4, 0x63,
0xc0, 0xe9, 0x15, 0x5f, 0xfe, 0xf6, 0x81, 0xb2,
0x3d, 0xe0, 0x13, 0xec, 0xd0, 0x75, 0x1d, 0x03,
0xb8, 0x6b, 0xdc, 0x13, 0xb6, 0x09, 0xb1, 0x82,
0xe4, 0x02, 0x12, 0x18, 0xcb, 0x1e, 0x2d, 0xce,
0xee, 0xf2, 0xc4, 0xa4, 0x9a, 0x1b, 0xa6, 0x51,
0xc3, 0xfd, 0x73, 0xc1, 0xc5, 0x85, 0xe7, 0xbb,
0x44, 0xe7, 0x61, 0x9e, 0x00, 0x03, 0x0a, 0x18,
0xe4, 0x62, 0x86, 0x45, 0xd8, 0xfa, 0x5b, 0x71,
0x46, 0x86, 0x0e, 0x3a, 0x89, 0x6d, 0xb2, 0xd7,
0x0e, 0xd7, 0x65, 0x3e, 0xcc, 0x16, 0xe5, 0x9c,
0x2d, 0xf2, 0x0e, 0x44, 0x64, 0x14, 0xfd, 0xa9,
0x2f, 0xb6, 0xe8, 0x78, 0xa2, 0x54, 0xa3, 0x45,
0x5e, 0xb0, 0x14, 0x02, 0xf7, 0xa1, 0xe0, 0x16,
0x58, 0xd9, 0xc3, 0x58, 0x5a, 0xe6, 0x72, 0xa7,
0x0a, 0x9f, 0x33, 0xf8, 0xd5, 0x18, 0x54, 0x1e,
0x80, 0x54, 0x1e, 0x51, 0x69, 0x53, 0x60, 0x57,
0xf0, 0xf9, 0xc6, 0x97, 0x4b, 0x5b, 0x98, 0xe6,
0x1a, 0xc1, 0xb4, 0x61, 0xed, 0x3d, 0xc7, 0xe8,
0x14, 0xd6, 0x92, 0x49, 0x7c, 0x46, 0x1e, 0x3a,
0x20, 0xb6, 0x20, 0xb3, 0x25, 0xe0, 0xf8, 0x39,
0xea, 0xc9, 0x7d, 0xcb, 0x38, 0x98, 0x03, 0x95,
0x9a, 0x99, 0x69, 0xae, 0xd4, 0x0c, 0x1e, 0x50,
0x34, 0x6d, 0x85, 0x6a, 0x33, 0x2f, 0x8c, 0x03,
0x6a, 0xa4, 0x1a, 0xfd, 0xac, 0x8a, 0x34, 0x08,
0xe9, 0x88, 0xb6, 0xa0, 0xb9, 0x96, 0xa7, 0x41,
0x37, 0x7f, 0xe7, 0xc2, 0xd1, 0xaf, 0xe5, 0x60,
0x68, 0x06, 0xfe, 0x70, 0x81, 0x80, 0xb4, 0xfe,
0xf7, 0x6d, 0x88, 0xec, 0xc6, 0x90, 0x38, 0x04,
0x34, 0x24, 0x1b, 0xb8, 0x57, 0x86, 0x40, 0xd2,
0x19, 0xec, 0xa1, 0x36, 0x11, 0xff, 0x22, 0x34,
0x8c, 0x31, 0x3f, 0x63, 0xa1, 0x4f, 0xce, 0x67,
0x73, 0x5c, 0x78, 0x5d, 0x85, 0xc8, 0xd8, 0x40,
0x5a, 0x40, 0xdf, 0x88, 0x3d, 0xf3, 0x6d, 0xf4,
0x9b, 0xb6, 0x29, 0xbf, 0x07, 0xdd, 0xd9, 0x51,
0x27, 0xa6, 0x97, 0xb2, 0x6f, 0x61, 0xef, 0x1c,
0xa9, 0x01, 0x52, 0x2b, 0xd0, 0x12, 0xe4, 0x40,
0xa6, 0xea, 0x25, 0x80, 0xba, 0x80, 0x61, 0x87,
0xa5, 0x8d, 0x7e, 0x71, 0x09, 0x68, 0xfb, 0xc6,
0x08, 0x2f, 0x98, 0x2c, 0xe7, 0xab, 0x30, 0xb4,
0xde, 0x39, 0xb6, 0x71, 0xff, 0x32, 0x90, 0x61,
0x65, 0xf9, 0xc4, 0x16, 0x7e, 0xda, 0xc4, 0x05,
0x77, 0x0b, 0xf1, 0xf9, 0xe0, 0xc0, 0x7d, 0x14,
0x57, 0x6f, 0x48, 0xba, 0xea, 0xe0, 0xc5, 0x93,
0x60, 0x14, 0xe3, 0xf8, 0x6a, 0x67, 0xb2, 0xdc,
0x56, 0xe8, 0x37, 0x7f, 0x59, 0x63, 0x5c, 0x77,
0xd2, 0xe3, 0xa7, 0x73, 0x53, 0x9c, 0x8d, 0xf4,
0xac, 0xe9, 0x07, 0x8a, 0x1c, 0xbe, 0xa7, 0x4d,
0x1f, 0x60, 0x36, 0x9f, 0x33, 0x9d, 0xf4, 0x2d,
0x4f, 0x61, 0xdd, 0x33, 0x40, 0x1f, 0x6e, 0x10,
0x9f, 0xf7, 0x1f, 0xf0, 0x95, 0x89, 0x62, 0x8c,
0x04, 0xf7, 0x64, 0xe0, 0x66, 0xd0, 0x4b, 0x4a,
0x79, 0x96, 0x70, 0x56, 0xdb, 0x07, 0xda, 0xaf,
0x00, 0xd1, 0x54, 0xec, 0x07, 0xac, 0x09, 0x25,
0x91, 0x46, 0xd1, 0x4f, 0xbf, 0x50, 0xe9, 0xe6,
0x54, 0x73, 0x91, 0xc7, 0xfb, 0x67, 0x33, 0xeb,
0x01, 0x1b, 0xdc, 0x45, 0x5a, 0xdc, 0xa3, 0x96,
0x35, 0x6c, 0x71, 0x9b, 0xa6, 0xe7, 0x2b, 0x65,
0x95, 0x2d, 0xae, 0x81, 0x0a, 0x28, 0x31, 0xf0,
0x2a, 0x9e, 0x01, 0xe2, 0x83, 0x2f, 0xe0, 0xa4,
0x65, 0xca, 0x92, 0x4a, 0x0f, 0x32, 0x45, 0xb5,
0xe6, 0x19, 0x24, 0x44, 0x2b, 0x2b, 0xea, 0x64,
0x46, 0xb2, 0x49, 0xd0, 0x2f, 0xe2, 0x64, 0x0d,
0x1f, 0xee, 0xe4, 0x29, 0x04, 0x99, 0x80, 0x8b,
0x7c, 0x7a, 0x3a, 0x4c, 0xd4, 0x18, 0xd4, 0xf7,
0x3b, 0x0c, 0x44, 0x39, 0x3d, 0x0f, 0x10, 0xd4,
0x1f, 0x47, 0x7f, 0xb1, 0xdf, 0xd2, 0xc1, 0xd7,
0x1d, 0x1f, 0xf7, 0x29, 0x36, 0x54, 0x4b, 0x8e,
0x55, 0x9b, 0xcb, 0x08, 0xf5, 0x31, 0x0f, 0xd4,
0x0c, 0x5e, 0x18, 0x59, 0x7e, 0xea, 0xef, 0x5a,
0xd2, 0x0d, 0xc6, 0x94, 0x5d, 0x83, 0xbd, 0x55,
0xa9, 0x2f, 0xfe, 0x85, 0x82, 0xd9, 0xa9, 0x91,
0x40, 0xf6, 0xcc, 0xf9, 0x88, 0xba, 0x72, 0x09,
0x36, 0x9f, 0xa1, 0xc5, 0x7c, 0xea, 0x93, 0xd4,
0xae, 0x48, 0xaa, 0x2e, 0x91, 0x93, 0x2f, 0x1b,
0x66, 0x3e, 0x87, 0x0e, 0xdd, 0xa0, 0x1e, 0x19,
0x8d, 0x25, 0xdf, 0xbf, 0x39, 0x82, 0xdf, 0x7a,
0x7c, 0x7c, 0x95, 0xb2, 0xbd, 0x27, 0x2b, 0x3d,
0x76, 0xef, 0x05, 0x38, 0xfc, 0x8a, 0x38, 0x46,
0x6d, 0xd5, 0xaa, 0x39, 0x6b, 0xa9, 0xca, 0xf5,
0x9f, 0xfd, 0x81, 0xc2, 0x4f, 0xa5, 0x8c, 0x12,
0x90, 0xa3, 0x03, 0xe6, 0xfd, 0x79, 0x6a, 0x48,
0x69, 0x6c, 0xc3, 0x78, 0x30, 0x9d, 0x79, 0xa6,
0x81, 0xa7, 0xf4, 0xe9, 0xcf, 0x4e, 0x9d, 0x58,
0x01, 0x10, 0xed, 0x2c, 0x27, 0x2e, 0x5c, 0xaa,
0xc8, 0xd0, 0x57, 0xef, 0x05, 0xa5, 0xe7, 0x9f,
0x8d, 0x07, 0xa7, 0xd7, 0x48, 0x05, 0x7b, 0x70,
0x17, 0xac, 0xe3, 0xd4, 0x4a, 0x09, 0x92, 0xc4,
0x8e, 0x84, 0x03, 0x74, 0x5a, 0x61, 0x61, 0x0e,
0x1a, 0x0c, 0x1f, 0x8c, 0x4e, 0xd9, 0x6c, 0x96,
0x42, 0xac, 0x93, 0x0b, 0xd4, 0x14, 0x6c, 0xd8,
0x27, 0x0e, 0x9b, 0xb9, 0x77, 0x0d, 0xd5, 0xdd,
0x82, 0x08, 0xf5, 0x89, 0xdb, 0x44, 0x86, 0x8d,
0xb2, 0x2c, 0xa8, 0x06, 0x5f, 0xbc, 0x4c, 0x73,
0x27, 0xfe, 0x32, 0x26, 0x3c, 0x33, 0x83, 0xda,
0x18, 0xc9
};
#endif /* !WOLFSSH_NO_MLDSA && !WOLFSSH_NO_MLDSA44 */
#ifndef WOLFSSH_NO_ECDSA
/* P-256 DER with the OID last byte changed 0x07 -> 0x01 (secp192r1).
* Forces wc_EccPrivateKeyDecode to fail or to return an unsupported curve id,
* exercising the wc_ecc_free cleanup in both the default: and else paths. */
static const byte unitTestEccUnsupportedCurveKey[] = {
0x30, 0x77, 0x02, 0x01, 0x01, 0x04, 0x20, 0x61, 0x09, 0x99,
0x0B, 0x79, 0xD2, 0x5F, 0x28, 0x5A, 0x0F, 0x5D, 0x15, 0xCC,
0xA1, 0x56, 0x54, 0xF9, 0x2B, 0x39, 0x87, 0x21, 0x2D, 0xA7,
0x7D, 0x85, 0x7B, 0xB8, 0x7F, 0x38, 0xC6, 0x6D, 0xD5, 0xA0,
0x0A, 0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01,
0x01, /* 0x07 (secp256r1) changed to 0x01 (secp192r1) */
0xA1, 0x44, 0x03, 0x42, 0x00, 0x04, 0x81, 0x13, 0xFF,
0xA4, 0x2B, 0xB7, 0x9C, 0x45, 0x74, 0x7A, 0x83, 0x4C, 0x61,
0xF3, 0x3F, 0xAD, 0x26, 0xCF, 0x22, 0xCD, 0xA9, 0xA3, 0xBC,
0xA5, 0x61, 0xB4, 0x7C, 0xE6, 0x62, 0xD4, 0xC2, 0xF7, 0x55,
0x43, 0x9A, 0x31, 0xFB, 0x80, 0x11, 0x20, 0xB5, 0x12, 0x4B,
0x24, 0xF5, 0x78, 0xD7, 0xFD, 0x22, 0xEF, 0x46, 0x35, 0xF0,
0x05, 0x58, 0x6B, 0x5F, 0x63, 0xC8, 0xDA, 0x1B, 0xC4, 0xF5,
0x69
};
#endif /* WOLFSSH_NO_ECDSA */
#ifndef WOLFSSH_NO_RSA
/* wolfSSH_RsaVerify unit test
*
* Verifies that wolfSSH_RsaVerify returns WS_RSA_E when given a signature
* whose decoded digest is the correct size but contains wrong content.
* This makes the `compare = ConstantCompare(...)` term in wolfSSH_RsaVerify
* load-bearing: deleting it from the condition would silently pass this test.
*/
static int test_RsaVerify_BadDigest(void)
{
int result = 0;
int ret;
RsaKey key;
WC_RNG rng;
word32 idx = 0;
byte data[32];
byte digest[WC_SHA256_DIGEST_SIZE];
byte encDigest[MAX_ENCODED_SIG_SZ];
int encDigestSz;
byte badEncDigest[MAX_ENCODED_SIG_SZ];
byte sig[256]; /* 2048-bit RSA produces a 256-byte signature */
int sigSz;
WMEMSET(data, 0x42, sizeof(data));
if (wc_InitRng(&rng) != 0) {
printf("RsaVerify_BadDigest: wc_InitRng failed\n");
return -500;
}
if (wc_InitRsaKey(&key, NULL) != 0) {
printf("RsaVerify_BadDigest: wc_InitRsaKey failed\n");
wc_FreeRng(&rng);
return -501;
}
ret = wc_RsaPrivateKeyDecode(unitTestRsaPrivKey, &idx, &key,
unitTestRsaPrivKeySz);
if (ret != 0) { result = -502; goto done; }
/* Hash the payload */
ret = wc_Hash(WC_HASH_TYPE_SHA256, data, sizeof(data),
digest, WC_SHA256_DIGEST_SIZE);
if (ret != 0) { result = -503; goto done; }
/* Encode as PKCS#1 v1.5 DigestInfo */
encDigestSz = wc_EncodeSignature(encDigest, digest,
WC_SHA256_DIGEST_SIZE, wc_HashGetOID(WC_HASH_TYPE_SHA256));
if (encDigestSz <= 0) { result = -504; goto done; }
/* Sign */
sigSz = wc_RsaSSL_Sign(encDigest, (word32)encDigestSz,
sig, sizeof(sig), &key, &rng);
if (sigSz <= 0) { result = -505; goto done; }
/* Positive case: correct sig + correct encDigest must succeed */
ret = wolfSSH_TestRsaVerify(sig, (word32)sigSz,
encDigest, (word32)encDigestSz, &key, NULL);
if (ret != WS_SUCCESS) { result = -506; goto done; }
/* Negative case: correct sig but tampered encDigest (same size,
* last byte of the SHA-256 hash flipped) must return WS_RSA_E.
* This is the scenario that deleting `compare` from the condition
* inside wolfSSH_RsaVerify would silently pass. */
WMEMCPY(badEncDigest, encDigest, encDigestSz);
badEncDigest[encDigestSz - 1] ^= 0xFF;
ret = wolfSSH_TestRsaVerify(sig, (word32)sigSz,
badEncDigest, (word32)encDigestSz, &key, NULL);
if (ret != WS_RSA_E) { result = -507; goto done; }
/* A NULL signature must hit the early guard and return WS_RSA_E without
* dereferencing the pointer. */
ret = wolfSSH_TestRsaVerify(NULL, (word32)sigSz,
encDigest, (word32)encDigestSz, &key, NULL);
if (ret != WS_RSA_E) { result = -508; goto done; }
done:
wc_FreeRng(&rng);
wc_FreeRsaKey(&key);
return result;
}
/* wolfSSH_RsaVerify compares whole blocks, so a signature over malformed
* EMSA-PKCS1-v1_5 padding must be refused. The blocks are signed with a raw
* private-key operation, since normal signing would not produce them. The
* control case guards against a broken harness passing everything. */
static int test_RsaVerify_BadPadding(void)
{
int result = 0;
int ret;
RsaKey key;
WC_RNG rng;
word32 idx = 0;
word32 keySz;
word32 padSz;
byte data[32];
byte digest[WC_SHA256_DIGEST_SIZE];
byte encDigest[MAX_ENCODED_SIG_SZ];
int encDigestSz;
byte block[512];
byte sig[512];
word32 sigSz;
int encryptSz;
int keyInit = 0, rngInit = 0;
WMEMSET(data, 0x42, sizeof(data));
if (wc_InitRng(&rng) != 0) {
printf("RsaVerify_BadPadding: wc_InitRng failed\n");
return -520;
}
rngInit = 1;
if (wc_InitRsaKey(&key, NULL) != 0) {
printf("RsaVerify_BadPadding: wc_InitRsaKey failed\n");
result = -521;
goto done;
}
keyInit = 1;
ret = wc_RsaPrivateKeyDecode(unitTestRsaPrivKey, &idx, &key,
unitTestRsaPrivKeySz);
if (ret != 0) { result = -522; goto done; }
encryptSz = wc_RsaEncryptSize(&key);
if (encryptSz <= 0 || (word32)encryptSz > sizeof(block)) {
result = -523;
goto done;
}
keySz = (word32)encryptSz;
ret = wc_Hash(WC_HASH_TYPE_SHA256, data, sizeof(data),
digest, WC_SHA256_DIGEST_SIZE);
if (ret != 0) { result = -524; goto done; }
encDigestSz = wc_EncodeSignature(encDigest, digest,
WC_SHA256_DIGEST_SIZE, wc_HashGetOID(WC_HASH_TYPE_SHA256));
if (encDigestSz <= 0) { result = -525; goto done; }
/* The fixed test key has room; a smaller one would underflow padSz. */
if (keySz < (word32)encDigestSz + RSA_MIN_PAD_SZ) {
result = -532;
goto done;
}
padSz = keySz - (word32)encDigestSz - 3;
/* Control: a well-formed block must verify. */
block[0] = 0x00;
block[1] = 0x01;
WMEMSET(block + 2, 0xFF, padSz);
block[2 + padSz] = 0x00;
WMEMCPY(block + 3 + padSz, encDigest, (word32)encDigestSz);
sigSz = (word32)sizeof(sig);
ret = wc_RsaFunction(block, keySz, sig, &sigSz, RSA_PRIVATE_DECRYPT,
&key, &rng);
if (ret != 0) { result = -526; goto done; }
ret = wolfSSH_TestRsaVerify(sig, sigSz, encDigest, (word32)encDigestSz,
&key, NULL);
if (ret != WS_SUCCESS) {
printf("RsaVerify_BadPadding: well-formed block ret=%d expected %d\n",
ret, WS_SUCCESS);
result = -527;
goto done;
}
/* A pad byte that is not 0xFF. */
block[2 + (padSz / 2)] = 0xFE;
sigSz = (word32)sizeof(sig);
ret = wc_RsaFunction(block, keySz, sig, &sigSz, RSA_PRIVATE_DECRYPT,
&key, &rng);
if (ret != 0) { result = -528; goto done; }
ret = wolfSSH_TestRsaVerify(sig, sigSz, encDigest, (word32)encDigestSz,
&key, NULL);
if (ret != WS_RSA_E) {
printf("RsaVerify_BadPadding: bad pad byte ret=%d expected %d\n",
ret, WS_RSA_E);
result = -529;
goto done;
}
/* A wrong block type. */
block[2 + (padSz / 2)] = 0xFF;
block[1] = 0x02;
sigSz = (word32)sizeof(sig);
ret = wc_RsaFunction(block, keySz, sig, &sigSz, RSA_PRIVATE_DECRYPT,
&key, &rng);
if (ret != 0) { result = -530; goto done; }
ret = wolfSSH_TestRsaVerify(sig, sigSz, encDigest, (word32)encDigestSz,
&key, NULL);
if (ret != WS_RSA_E) {
printf("RsaVerify_BadPadding: bad block type ret=%d expected %d\n",
ret, WS_RSA_E);
result = -531;
}
done:
if (rngInit)
wc_FreeRng(&rng);
if (keyInit)
wc_FreeRsaKey(&key);
return result;
}
/* A signature is only valid in 0 <= s < n. The raw public operation reduces
* mod n on its own, so s + n recovers the same block and would verify without
* an explicit range check. Also covers a signature longer than the key and
* the two key-size guards. */
static int test_RsaVerify_SigRange(void)
{
int result = 0;
int ret;
RsaKey key;
RsaKey emptyKey;
WC_RNG rng;
word32 idx = 0;
word32 keySz;
word32 eSz, nSz;
byte data[32];
byte digest[WC_SHA256_DIGEST_SIZE];
byte encDigest[MAX_ENCODED_SIG_SZ];
int encDigestSz = 0;
byte bigDigest[512];
byte nBuf[512];
byte eBuf[512];
byte sig[512];
byte sum[513];
word32 sigSz = 0;
int encryptSz;
int attempt;
int carry = 1;
int keyInit = 0, rngInit = 0, emptyInit = 0;
if (wc_InitRng(&rng) != 0) {
printf("RsaVerify_SigRange: wc_InitRng failed\n");
return -540;
}
rngInit = 1;
if (wc_InitRsaKey(&key, NULL) != 0) {
printf("RsaVerify_SigRange: wc_InitRsaKey failed\n");
result = -541;
goto done;
}
keyInit = 1;
ret = wc_RsaPrivateKeyDecode(unitTestRsaPrivKey, &idx, &key,
unitTestRsaPrivKeySz);
if (ret != 0) { result = -542; goto done; }
encryptSz = wc_RsaEncryptSize(&key);
if (encryptSz <= 0 || (word32)encryptSz > sizeof(sig)) {
result = -543;
goto done;
}
keySz = (word32)encryptSz;
eSz = (word32)sizeof(eBuf);
nSz = (word32)sizeof(nBuf);
ret = wc_RsaFlattenPublicKey(&key, eBuf, &eSz, nBuf, &nSz);
if (ret != 0 || nSz != keySz) { result = -544; goto done; }
/* s + n has to fit in keySz bytes to be a signature at all. s depends on
* the message, so sign a few until one does. */
for (attempt = 0; attempt < 16 && carry; attempt++) {
int i;
word32 acc = 0;
WMEMSET(data, (byte)(0x42 + attempt), sizeof(data));
ret = wc_Hash(WC_HASH_TYPE_SHA256, data, sizeof(data),
digest, WC_SHA256_DIGEST_SIZE);
if (ret != 0) { result = -545; goto done; }
encDigestSz = wc_EncodeSignature(encDigest, digest,
WC_SHA256_DIGEST_SIZE, wc_HashGetOID(WC_HASH_TYPE_SHA256));
if (encDigestSz <= 0) { result = -546; goto done; }
ret = wc_RsaSSL_Sign(encDigest, (word32)encDigestSz, sig, sizeof(sig),
&key, &rng);
if (ret <= 0 || (word32)ret != keySz) { result = -547; goto done; }
sigSz = (word32)ret;
for (i = (int)keySz - 1; i >= 0; i--) {
acc = (word32)sig[i] + (word32)nBuf[i] + (acc >> 8);
sum[i + 1] = (byte)(acc & 0xFF);
}
sum[0] = (byte)(acc >> 8);
carry = sum[0] != 0;
}
if (carry) { result = -548; goto done; }
/* The signature itself still verifies. */
ret = wolfSSH_TestRsaVerify(sig, sigSz, encDigest, (word32)encDigestSz,
&key, NULL);
if (ret != WS_SUCCESS) {
printf("RsaVerify_SigRange: valid sig ret=%d expected %d\n",
ret, WS_SUCCESS);
result = -549;
goto done;
}
/* Nor does it with a byte appended. */
if (keySz + 1 > (word32)sizeof(sig)) { result = -555; goto done; }
sig[keySz] = 0x00;
ret = wolfSSH_TestRsaVerify(sig, keySz + 1, encDigest,
(word32)encDigestSz, &key, NULL);
if (ret != WS_RSA_E) {
printf("RsaVerify_SigRange: trailing byte ret=%d expected %d\n",
ret, WS_RSA_E);
result = -556;
goto done;
}
/* s + n must not. */
ret = wolfSSH_TestRsaVerify(sum + 1, keySz, encDigest, (word32)encDigestSz,
&key, NULL);
if (ret != WS_RSA_E) {
printf("RsaVerify_SigRange: sig plus modulus ret=%d expected %d\n",
ret, WS_RSA_E);
result = -550;
goto done;
}
/* The smallest digest the key has no room to pad. */
WMEMSET(bigDigest, 0, sizeof(bigDigest));
ret = wolfSSH_TestRsaVerify(sig, sigSz, bigDigest,
keySz - RSA_MIN_PAD_SZ + 1, &key, NULL);
if (ret != WS_RSA_E) {
printf("RsaVerify_SigRange: oversized digest ret=%d expected %d\n",
ret, WS_RSA_E);
result = -551;
goto done;
}
/* Bigger than the block itself. Without the guard, padSz underflows and
* the pad WMEMSET runs off the scratch buffer, so only the guard can
* bring this back. */
ret = wolfSSH_TestRsaVerify(sig, sigSz, bigDigest, keySz - 2, &key, NULL);
if (ret != WS_RSA_E) {
printf("RsaVerify_SigRange: unpaddable digest ret=%d expected %d\n",
ret, WS_RSA_E);
result = -554;
goto done;
}
/* A key with no size to it is refused as well. */
if (wc_InitRsaKey(&emptyKey, NULL) != 0) { result = -552; goto done; }
emptyInit = 1;
ret = wolfSSH_TestRsaVerify(sig, sigSz, encDigest, (word32)encDigestSz,
&emptyKey, NULL);
if (ret != WS_RSA_E) {
printf("RsaVerify_SigRange: empty key ret=%d expected %d\n",
ret, WS_RSA_E);
result = -553;
}
done:
if (rngInit)
wc_FreeRng(&rng);
if (keyInit)
wc_FreeRsaKey(&key);
if (emptyInit)
wc_FreeRsaKey(&emptyKey);
return result;
}
#endif /* !WOLFSSH_NO_RSA */
#if !defined(WOLFSSH_NO_ED25519) && defined(HAVE_ED25519) && \
defined(HAVE_ED25519_SIGN) && defined(HAVE_ED25519_VERIFY) && \
defined(WOLFSSL_ED25519_STREAMING_VERIFY)
/* Locally-generated Ed25519 keypair for the DoUserAuthRequestEd25519 test.
* 32-byte private seed followed by the 32-byte raw public key. Created with
* ssh-keygen and decoded from the OpenSSH private key format so the test is
* deterministic and does not depend on an RNG. */
static const byte unitTestEd25519Priv[32] = {
0x05, 0xf5, 0x9c, 0x02, 0x55, 0x93, 0x32, 0x93,
0xb9, 0xc2, 0x2e, 0xa7, 0x20, 0x05, 0x33, 0x0c,
0x40, 0xcd, 0xfa, 0xff, 0x73, 0xe4, 0x4a, 0xe1,
0x50, 0x2a, 0x4b, 0x37, 0x20, 0x66, 0xc5, 0x56
};
static const byte unitTestEd25519Pub[32] = {
0x33, 0x76, 0xaf, 0x20, 0x97, 0xce, 0x38, 0xdf,
0x5a, 0x76, 0x62, 0xfc, 0xb2, 0x87, 0x6e, 0x9d,
0xd3, 0x9e, 0x85, 0x87, 0xf3, 0x0e, 0x72, 0x6c,
0x1e, 0xc0, 0x01, 0xe2, 0x81, 0x96, 0xb8, 0x49
};
/* Write a 32-bit big-endian length prefix at out. */
static void Ed25519Test_PutLen(byte* out, word32 v)
{
out[0] = (byte)(v >> 24);
out[1] = (byte)(v >> 16);
out[2] = (byte)(v >> 8);
out[3] = (byte)(v);
}
static int test_ParseEd25519PubKey(void)
{
static const char keyTypeName[] = "ssh-ed25519";
const word32 keyTypeNameSz = (word32)(sizeof(keyTypeName) - 1);
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
byte blob[64];
word32 blobSz, off;
int ret;
int failures = 0;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return 1;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return 1;
}
/* string "ssh-ed25519" || string pubkey */
off = 0;
Ed25519Test_PutLen(blob + off, keyTypeNameSz); off += UINT32_SZ;
WMEMCPY(blob + off, keyTypeName, keyTypeNameSz); off += keyTypeNameSz;
Ed25519Test_PutLen(blob + off, (word32)sizeof(unitTestEd25519Pub));
off += UINT32_SZ;
WMEMCPY(blob + off, unitTestEd25519Pub, sizeof(unitTestEd25519Pub));
off += (word32)sizeof(unitTestEd25519Pub);
blobSz = off;
/* valid blob */
ret = wolfSSH_TestParseEd25519PubKey(ssh, blob, blobSz);
if (ret != WS_SUCCESS) {
fprintf(stderr, "\t\"valid\" FAIL: got %d, expected %d\n",
ret, WS_SUCCESS);
failures++;
}
/* truncated blob: fails after the key is initialized */
ret = wolfSSH_TestParseEd25519PubKey(ssh, blob, blobSz - 4);
if (ret != WS_BUFFER_E) {
fprintf(stderr, "\t\"truncated\" FAIL: got %d, expected %d\n",
ret, WS_BUFFER_E);
failures++;
}
/* format identifier other than "ssh-ed25519" */
blob[UINT32_SZ + keyTypeNameSz - 1] = '8';
ret = wolfSSH_TestParseEd25519PubKey(ssh, blob, blobSz);
if (ret != WS_INVALID_ALGO_ID) {
fprintf(stderr, "\t\"format mismatch\" FAIL: got %d, expected %d\n",
ret, WS_INVALID_ALGO_ID);
failures++;
}
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return failures;
}
/* DoUserAuthRequestEd25519 unit test
*
* Drives DoUserAuthRequestEd25519 directly with a fully-formed Ed25519
* USERAUTH_REQUEST and asserts (1) a correct signature returns WS_SUCCESS
* and (2) a tampered signature returns either WS_ED25519_E or
* WS_CRYPTO_FAILED. This is the test that makes the
* `status ? WS_SUCCESS : WS_ED25519_E` style mapping load-bearing -- without
* the negative case any mutation that hard-codes WS_SUCCESS or inverts the
* status would silently survive.
*
* The Ed25519 verifier in wolfSSL has two failure paths reachable from this
* function: wc_ed25519_verify_msg_final returns non-zero (WS_CRYPTO_FAILED)
* or returns zero with status=0 (WS_ED25519_E). Different wolfSSL versions
* have routed bad signatures through either branch; we accept either failure
* code so the test stays portable while still killing the most dangerous
* mutation -- turning either error into WS_SUCCESS.
*/
static int test_DoUserAuthRequestEd25519(void)
{
static const char keyTypeName[] = "ssh-ed25519";
static const char username[] = "wolfssh";
static const char serviceName[] = "ssh-connection";
static const char authName[] = "publickey";
const word32 keyTypeNameSz = (word32)(sizeof(keyTypeName) - 1);
const word32 usernameSz = (word32)(sizeof(username) - 1);
const word32 serviceNameSz = (word32)(sizeof(serviceName) - 1);
const word32 authNameSz = (word32)(sizeof(authName) - 1);
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
ed25519_key signingKey;
int signingKeyInit = 0;
WS_UserAuthData authData;
byte pubKeyBlob[64];
byte sigBlob[128];
byte badSigBlob[128];
byte dataToSign[256];
byte checkData[512];
byte sig[ED25519_SIG_SIZE];
word32 pubKeyBlobSz = 0;
word32 sigBlobSz = 0;
word32 dataToSignSz = 0;
word32 checkDataSz = 0;
word32 sigSz = sizeof(sig);
word32 fieldSum = 0;
word32 off;
int result = 0;
int ret;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL) return -600;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -601; goto done; }
/* Stub a session id so the verify hash has something to absorb. */
ssh->sessionIdSz = 16;
WMEMSET(ssh->sessionId, 0xA5, ssh->sessionIdSz);
/* Load the embedded Ed25519 keypair for signing. */
if (wc_ed25519_init(&signingKey) != 0) { result = -602; goto done; }
signingKeyInit = 1;
if (wc_ed25519_import_private_key(unitTestEd25519Priv,
(word32)sizeof(unitTestEd25519Priv),
unitTestEd25519Pub, (word32)sizeof(unitTestEd25519Pub),
&signingKey) != 0) {
result = -603; goto done;
}
/* Build the SSH public key blob: string "ssh-ed25519" || string pubkey */
off = 0;
Ed25519Test_PutLen(pubKeyBlob + off, keyTypeNameSz); off += UINT32_SZ;
WMEMCPY(pubKeyBlob + off, keyTypeName, keyTypeNameSz);
off += keyTypeNameSz;
Ed25519Test_PutLen(pubKeyBlob + off,
(word32)sizeof(unitTestEd25519Pub));
off += UINT32_SZ;
WMEMCPY(pubKeyBlob + off, unitTestEd25519Pub,
sizeof(unitTestEd25519Pub));
off += (word32)sizeof(unitTestEd25519Pub);
pubKeyBlobSz = off;
/* Build the dataToSign region the same way the wire packet would lay it
* out: username || service || authmethod || hasSig=1 || pkAlgo || pkBlob.
* DoUserAuthRequestEd25519 hashes exactly this region. */
off = 0;
Ed25519Test_PutLen(dataToSign + off, usernameSz); off += UINT32_SZ;
WMEMCPY(dataToSign + off, username, usernameSz); off += usernameSz;
Ed25519Test_PutLen(dataToSign + off, serviceNameSz); off += UINT32_SZ;
WMEMCPY(dataToSign + off, serviceName, serviceNameSz);
off += serviceNameSz;
Ed25519Test_PutLen(dataToSign + off, authNameSz); off += UINT32_SZ;
WMEMCPY(dataToSign + off, authName, authNameSz); off += authNameSz;
dataToSign[off++] = 1; /* hasSignature */
Ed25519Test_PutLen(dataToSign + off, keyTypeNameSz); off += UINT32_SZ;
WMEMCPY(dataToSign + off, keyTypeName, keyTypeNameSz);
off += keyTypeNameSz;
Ed25519Test_PutLen(dataToSign + off, pubKeyBlobSz); off += UINT32_SZ;
WMEMCPY(dataToSign + off, pubKeyBlob, pubKeyBlobSz); off += pubKeyBlobSz;
dataToSignSz = off;
/* Build the bytes that get signed: sessionIdSz || sessionId ||
* MSGID_USERAUTH_REQUEST || dataToSign. Mirrors BuildUserAuthRequestEd25519
* on the client side. */
off = 0;
Ed25519Test_PutLen(checkData + off, ssh->sessionIdSz); off += UINT32_SZ;
WMEMCPY(checkData + off, ssh->sessionId, ssh->sessionIdSz);
off += ssh->sessionIdSz;
checkData[off++] = MSGID_USERAUTH_REQUEST;
WMEMCPY(checkData + off, dataToSign, dataToSignSz);
off += dataToSignSz;
checkDataSz = off;
if (wc_ed25519_sign_msg(checkData, checkDataSz, sig, &sigSz,
&signingKey) != 0) {
result = -604; goto done;
}
/* Build the SSH signature blob: string "ssh-ed25519" || string sig */
off = 0;
Ed25519Test_PutLen(sigBlob + off, keyTypeNameSz); off += UINT32_SZ;
WMEMCPY(sigBlob + off, keyTypeName, keyTypeNameSz);
off += keyTypeNameSz;
Ed25519Test_PutLen(sigBlob + off, sigSz); off += UINT32_SZ;
WMEMCPY(sigBlob + off, sig, sigSz); off += sigSz;
sigBlobSz = off;
/* Populate authData the way DoUserAuthRequest/DoUserAuthRequestPublicKey
* would before dispatching to DoUserAuthRequestEd25519. */
WMEMSET(&authData, 0, sizeof(authData));
authData.type = WOLFSSH_USERAUTH_PUBLICKEY;
authData.username = (const byte*)username;
authData.usernameSz = usernameSz;
authData.serviceName = (const byte*)serviceName;
authData.serviceNameSz = serviceNameSz;
authData.authName = (const byte*)authName;
authData.authNameSz = authNameSz;
authData.sf.publicKey.dataToSign = dataToSign;
authData.sf.publicKey.publicKeyType = (const byte*)keyTypeName;
authData.sf.publicKey.publicKeyTypeSz = keyTypeNameSz;
authData.sf.publicKey.publicKey = pubKeyBlob;
authData.sf.publicKey.publicKeySz = pubKeyBlobSz;
authData.sf.publicKey.hasSignature = 1;
authData.sf.publicKey.signature = sigBlob;
authData.sf.publicKey.signatureSz = sigBlobSz;
/* Positive case: untouched signature must verify. authData was zeroed, so
* dataToSignSz is 0 here and the field-sum fallback is exercised. */
ret = wolfSSH_TestDoUserAuthRequestEd25519(ssh, &authData);
if (ret != WS_SUCCESS) {
printf("DoUserAuthRequestEd25519 positive: ret=%d (expected %d)\n",
ret, WS_SUCCESS);
result = -605; goto done;
}
/* The wire-derived signed length must equal the legacy field-sum for a
* plain Ed25519 request and verify identically; lock in that equivalence
* so the non-certificate path cannot regress. */
fieldSum = usernameSz + serviceNameSz + authNameSz + BOOLEAN_SZ +
keyTypeNameSz + pubKeyBlobSz + (UINT32_SZ * 5);
if (fieldSum != dataToSignSz) {
printf("DoUserAuthRequestEd25519 length mismatch: wire=%u sum=%u\n",
dataToSignSz, fieldSum);
result = -607; goto done;
}
authData.sf.publicKey.dataToSignSz = dataToSignSz;
ret = wolfSSH_TestDoUserAuthRequestEd25519(ssh, &authData);
if (ret != WS_SUCCESS) {
printf("DoUserAuthRequestEd25519 wire-length: ret=%d (expected %d)\n",
ret, WS_SUCCESS);
result = -608; goto done;
}
/* Negative case: flip a byte inside the raw signature (skip past the
* 4 + keyTypeNameSz + 4 header so we land in the actual signature
* material). Must NOT return WS_SUCCESS. */
WMEMCPY(badSigBlob, sigBlob, sigBlobSz);
badSigBlob[UINT32_SZ + keyTypeNameSz + UINT32_SZ + 10] ^= 0xFF;
authData.sf.publicKey.signature = badSigBlob;
ret = wolfSSH_TestDoUserAuthRequestEd25519(ssh, &authData);
if (ret != WS_ED25519_E && ret != WS_CRYPTO_FAILED) {
printf("DoUserAuthRequestEd25519 tampered: ret=%d\n", ret);
result = -606; goto done;
}
/* A declared type that differs from the blob's is reported as such, not
* as a key decode failure. */
authData.sf.publicKey.signature = sigBlob;
authData.sf.publicKey.publicKeyType = (const byte*)"ssh-ed448";
authData.sf.publicKey.publicKeyTypeSz = 9;
ret = wolfSSH_TestDoUserAuthRequestEd25519(ssh, &authData);
authData.sf.publicKey.publicKeyType = (const byte*)keyTypeName;
authData.sf.publicKey.publicKeyTypeSz = keyTypeNameSz;
if (ret != WS_INVALID_ALGO_ID) {
printf("DoUserAuthRequestEd25519 type mismatch: ret=%d\n", ret);
result = -609; goto done;
}
/* A truncated public key blob is a buffer error. */
authData.sf.publicKey.publicKeySz = pubKeyBlobSz - 1;
ret = wolfSSH_TestDoUserAuthRequestEd25519(ssh, &authData);
authData.sf.publicKey.publicKeySz = pubKeyBlobSz;
if (ret != WS_BUFFER_E) {
printf("DoUserAuthRequestEd25519 truncated key: ret=%d\n", ret);
result = -610; goto done;
}
done:
if (signingKeyInit)
wc_ed25519_free(&signingKey);
if (ssh != NULL)
wolfSSH_free(ssh);
if (ctx != NULL)
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* Ed25519 verify test guards */
#ifndef WOLFSSH_NO_MLDSA
/* Write 32-bit big-endian length into out. */
static void MlDsaTest_PutLen(byte* out, word32 v)
{
out[0] = (byte)(v >> 24);
out[1] = (byte)(v >> 16);
out[2] = (byte)(v >> 8);
out[3] = (byte)(v);
}
static int test_DoUserAuthRequestMlDsa_Params(const char* keyTypeName,
byte level)
{
static const char username[] = "wolfssh";
static const char serviceName[] = "ssh-connection";
static const char authName[] = "publickey";
const word32 keyTypeNameSz = (word32)(WSTRLEN(keyTypeName));
const word32 usernameSz = (word32)(sizeof(username) - 1);
const word32 serviceNameSz = (word32)(sizeof(serviceName) - 1);
const word32 authNameSz = (word32)(sizeof(authName) - 1);
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
MlDsaKey signingKey;
int signingKeyInit = 0;
WC_RNG rng;
int rngInit = 0;
WS_UserAuthData authData;
byte* pubKeyBlob = NULL;
byte* sigBlob = NULL;
byte* badSigBlob = NULL;
byte* dataToSign = NULL;
byte* checkData = NULL;
byte* sig = NULL;
byte* pubRaw = NULL;
word32 pubKeyBlobSz = 0;
word32 sigBlobSz = 0;
word32 dataToSignSz = 0;
word32 checkDataSz = 0;
int sigSzInt;
word32 sigSz = 0;
int pubRawSzInt;
word32 pubRawSz = 0;
word32 off;
int result = 0;
int ret;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL) return -700;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -701; goto done; }
/* Stub a session id so the verify hash has something to absorb. */
ssh->sessionIdSz = 16;
WMEMSET(ssh->sessionId, 0xA5, ssh->sessionIdSz);
if (wc_InitRng(&rng) != 0) {
result = -702;
goto done;
}
rngInit = 1;
if (wc_MlDsaKey_Init(&signingKey, NULL, INVALID_DEVID) != 0) {
result = -703; goto done;
}
signingKeyInit = 1;
if (wc_MlDsaKey_SetParams(&signingKey, level) != 0) {
result = -704; goto done;
}
if (wc_MlDsaKey_MakeKey(&signingKey, &rng) != 0) {
result = -705; goto done;
}
sigSzInt = wc_MlDsaKey_SigSize(&signingKey);
if (sigSzInt < 0) { result = -706; goto done; }
sigSz = (word32)sigSzInt;
sig = (byte*)WMALLOC(sigSz, NULL, 0);
if (sig == NULL) { result = -718; goto done; }
/* Get raw public key to build pubKeyBlob */
pubRawSzInt = wc_MlDsaKey_PubSize(&signingKey);
if (pubRawSzInt < 0) { result = -707; goto done; }
pubRawSz = (word32)pubRawSzInt;
pubRaw = (byte*)WMALLOC(pubRawSz, NULL, 0);
if (pubRaw == NULL) { result = -717; goto done; }
if (wc_MlDsaKey_ExportPubRaw(&signingKey, pubRaw, &pubRawSz) != 0) {
result = -708; goto done;
}
pubKeyBlob = (byte*)WMALLOC(UINT32_SZ * 2 + keyTypeNameSz + pubRawSz,
NULL, 0);
if (pubKeyBlob == NULL) { result = -709; goto done; }
/* Build the SSH public key blob: string keyTypeName || string pubkey */
off = 0;
MlDsaTest_PutLen(pubKeyBlob + off, keyTypeNameSz); off += UINT32_SZ;
WMEMCPY(pubKeyBlob + off, keyTypeName, keyTypeNameSz);
off += keyTypeNameSz;
MlDsaTest_PutLen(pubKeyBlob + off, pubRawSz); off += UINT32_SZ;
WMEMCPY(pubKeyBlob + off, pubRaw, pubRawSz); off += pubRawSz;
pubKeyBlobSz = off;
/* Build dataToSign: user || svc || auth || hasSig || algo || blob. */
dataToSignSz = UINT32_SZ * 5 + usernameSz + serviceNameSz + authNameSz +
1 + keyTypeNameSz + pubKeyBlobSz;
dataToSign = (byte*)WMALLOC(dataToSignSz, NULL, 0);
if (dataToSign == NULL) { result = -710; goto done; }
off = 0;
MlDsaTest_PutLen(dataToSign + off, usernameSz); off += UINT32_SZ;
WMEMCPY(dataToSign + off, username, usernameSz); off += usernameSz;
MlDsaTest_PutLen(dataToSign + off, serviceNameSz); off += UINT32_SZ;
WMEMCPY(dataToSign + off, serviceName, serviceNameSz); off += serviceNameSz;
MlDsaTest_PutLen(dataToSign + off, authNameSz); off += UINT32_SZ;
WMEMCPY(dataToSign + off, authName, authNameSz); off += authNameSz;
dataToSign[off++] = 1; /* hasSignature */
MlDsaTest_PutLen(dataToSign + off, keyTypeNameSz); off += UINT32_SZ;
WMEMCPY(dataToSign + off, keyTypeName, keyTypeNameSz); off += keyTypeNameSz;
MlDsaTest_PutLen(dataToSign + off, pubKeyBlobSz); off += UINT32_SZ;
WMEMCPY(dataToSign + off, pubKeyBlob, pubKeyBlobSz); off += pubKeyBlobSz;
/* Build checkData: session ID || msg ID || dataToSign. */
checkDataSz = UINT32_SZ + ssh->sessionIdSz + MSG_ID_SZ + dataToSignSz;
checkData = (byte*)WMALLOC(checkDataSz, NULL, 0);
if (checkData == NULL) { result = -711; goto done; }
off = 0;
MlDsaTest_PutLen(checkData + off, ssh->sessionIdSz); off += UINT32_SZ;
WMEMCPY(checkData + off, ssh->sessionId, ssh->sessionIdSz);
off += ssh->sessionIdSz;
checkData[off++] = MSGID_USERAUTH_REQUEST;
WMEMCPY(checkData + off, dataToSign, dataToSignSz);
if (wc_MlDsaKey_SignCtx(&signingKey, NULL, 0, sig, &sigSz, checkData,
checkDataSz, &rng) != 0) {
result = -712; goto done;
}
/* Build the SSH signature blob: string keyTypeName || string sig */
sigBlobSz = UINT32_SZ * 2 + keyTypeNameSz + sigSz;
sigBlob = (byte*)WMALLOC(sigBlobSz, NULL, 0);
if (sigBlob == NULL) { result = -713; goto done; }
off = 0;
MlDsaTest_PutLen(sigBlob + off, keyTypeNameSz); off += UINT32_SZ;
WMEMCPY(sigBlob + off, keyTypeName, keyTypeNameSz); off += keyTypeNameSz;
MlDsaTest_PutLen(sigBlob + off, sigSz); off += UINT32_SZ;
WMEMCPY(sigBlob + off, sig, sigSz); off += sigSz;
sigBlobSz = off;
/* Populate authData */
WMEMSET(&authData, 0, sizeof(authData));
authData.type = WOLFSSH_USERAUTH_PUBLICKEY;
authData.username = (const byte*)username;
authData.usernameSz = usernameSz;
authData.serviceName = (const byte*)serviceName;
authData.serviceNameSz = serviceNameSz;
authData.authName = (const byte*)authName;
authData.authNameSz = authNameSz;
authData.sf.publicKey.dataToSign = dataToSign;
authData.sf.publicKey.publicKeyType = (const byte*)keyTypeName;
authData.sf.publicKey.publicKeyTypeSz = keyTypeNameSz;
authData.sf.publicKey.publicKey = pubKeyBlob;
authData.sf.publicKey.publicKeySz = pubKeyBlobSz;
authData.sf.publicKey.hasSignature = 1;
authData.sf.publicKey.signature = sigBlob;
authData.sf.publicKey.signatureSz = sigBlobSz;
/* Positive case: untouched signature must verify. */
ret = wolfSSH_TestDoUserAuthRequestMlDsa(ssh, &authData, pubKeyBlobSz);
if (ret != WS_SUCCESS) {
printf("DoUserAuthRequestMlDsa positive (%s): ret=%d (expected %d)\n",
keyTypeName, ret, WS_SUCCESS);
result = -714; goto done;
}
/* Negative case: flip a byte inside the raw signature */
badSigBlob = (byte*)WMALLOC(sigBlobSz, NULL, 0);
if (badSigBlob == NULL) { result = -715; goto done; }
WMEMCPY(badSigBlob, sigBlob, sigBlobSz);
badSigBlob[UINT32_SZ + keyTypeNameSz + UINT32_SZ + 10] ^= 0xFF;
authData.sf.publicKey.signature = badSigBlob;
ret = wolfSSH_TestDoUserAuthRequestMlDsa(ssh, &authData, pubKeyBlobSz);
if (ret != WS_MLDSA_E && ret != WS_CRYPTO_FAILED) {
printf("DoUserAuthRequestMlDsa tampered (%s): ret=%d (expected %d)\n",
keyTypeName, ret, WS_MLDSA_E);
result = -716; goto done;
}
done:
if (signingKeyInit)
wc_MlDsaKey_Free(&signingKey);
if (rngInit)
wc_FreeRng(&rng);
if (pubKeyBlob != NULL) WFREE(pubKeyBlob, NULL, 0);
if (sigBlob != NULL) WFREE(sigBlob, NULL, 0);
if (badSigBlob != NULL) WFREE(badSigBlob, NULL, 0);
if (dataToSign != NULL) WFREE(dataToSign, NULL, 0);
if (checkData != NULL) WFREE(checkData, NULL, 0);
if (sig != NULL) WFREE(sig, NULL, 0);
if (pubRaw != NULL) WFREE(pubRaw, NULL, 0);
if (ssh != NULL) wolfSSH_free(ssh);
if (ctx != NULL) wolfSSH_CTX_free(ctx);
return result;
}
/* unknown publicKeyType must be rejected at the boundary */
static int test_DoUserAuthRequestMlDsa_BadAlgo(void)
{
static const char badAlgo[] = "not-an-mldsa-key";
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WS_UserAuthData authData;
int result = 0;
int ret;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL) return -800;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -801; goto done; }
WMEMSET(&authData, 0, sizeof(authData));
authData.type = WOLFSSH_USERAUTH_PUBLICKEY;
authData.sf.publicKey.publicKeyType =
(const byte*)badAlgo;
authData.sf.publicKey.publicKeyTypeSz =
(word32)(sizeof(badAlgo) - 1);
/* pubKeyBlobSz=0: the bad key type is rejected before dataToSign is sized,
* so the value is irrelevant for this code path. */
ret = wolfSSH_TestDoUserAuthRequestMlDsa(ssh, &authData, 0);
if (ret != WS_INVALID_ALGO_ID) {
printf("DoUserAuthRequestMlDsa bad-algo: ret=%d expected %d\n",
ret, WS_INVALID_ALGO_ID);
result = -802;
}
done:
if (ssh != NULL) wolfSSH_free(ssh);
if (ctx != NULL) wolfSSH_CTX_free(ctx);
return result;
}
#ifdef WOLFSSH_CERTS
/* Confirm the cert branch is entered, ParseCertChainVerify intentionally
* rejects this. */
static int test_DoUserAuthRequestMlDsa_CertPath(const char* keyTypeName)
{
static const char username[] = "wolfssh";
static const char serviceName[] = "ssh-connection";
static const char authName[] = "publickey";
const word32 keyTypeNameSz = (word32)WSTRLEN(keyTypeName);
/* NOTE: pubKeyBlob is an RFC 6187 wire blob, not leaf-cert DER. The real
* server path calls ParseLeafCert() first to extract DER. This test
* exercises ASN.1-invalid rejection rather than cryptographic rejection,
* valid for a negative path test, but does not cover the DER-valid case. */
static const byte junkCert[] = { 0x30, 0x05, 0x00, 0x00, 0x00, 0x00 };
const word32 junkCertSz = (word32)sizeof(junkCert);
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WS_UserAuthData authData;
byte* pubKeyBlob = NULL;
byte* sigBlob = NULL;
word32 pubKeyBlobSz, off;
int result = 0;
int ret;
/* RFC 6187 cert chain blob:
* string keyTypeName
* uint32 certCount=1
* string junkCert
* uint32 ocspCount=0 */
pubKeyBlobSz = UINT32_SZ + keyTypeNameSz + UINT32_SZ +
UINT32_SZ + junkCertSz + UINT32_SZ;
pubKeyBlob = (byte*)WMALLOC(pubKeyBlobSz, NULL, 0);
if (pubKeyBlob == NULL) { result = -820; goto done; }
off = 0;
MlDsaTest_PutLen(pubKeyBlob + off, keyTypeNameSz); off += UINT32_SZ;
WMEMCPY(pubKeyBlob + off, keyTypeName, keyTypeNameSz); off += keyTypeNameSz;
MlDsaTest_PutLen(pubKeyBlob + off, 1); off += UINT32_SZ;
MlDsaTest_PutLen(pubKeyBlob + off, junkCertSz); off += UINT32_SZ;
WMEMCPY(pubKeyBlob + off, junkCert, junkCertSz); off += junkCertSz;
MlDsaTest_PutLen(pubKeyBlob + off, 0); off += UINT32_SZ;
/* Minimal sig blob: string keyTypeName || string(1 zero byte) */
sigBlob = (byte*)WMALLOC(UINT32_SZ * 2 + keyTypeNameSz + 1, NULL, 0);
if (sigBlob == NULL) { result = -821; goto done; }
off = 0;
MlDsaTest_PutLen(sigBlob + off, keyTypeNameSz); off += UINT32_SZ;
WMEMCPY(sigBlob + off, keyTypeName, keyTypeNameSz); off += keyTypeNameSz;
MlDsaTest_PutLen(sigBlob + off, 1); off += UINT32_SZ;
sigBlob[off] = 0x00;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL) { result = -822; goto done; }
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -823; goto done; }
ssh->sessionIdSz = 16;
WMEMSET(ssh->sessionId, 0xA5, ssh->sessionIdSz);
WMEMSET(&authData, 0, sizeof(authData));
authData.type = WOLFSSH_USERAUTH_PUBLICKEY;
authData.username = (const byte*)username;
authData.usernameSz = (word32)(sizeof(username) - 1);
authData.serviceName = (const byte*)serviceName;
authData.serviceNameSz = (word32)(sizeof(serviceName) - 1);
authData.authName = (const byte*)authName;
authData.authNameSz = (word32)(sizeof(authName) - 1);
authData.sf.publicKey.publicKeyType = (const byte*)keyTypeName;
authData.sf.publicKey.publicKeyTypeSz = keyTypeNameSz;
authData.sf.publicKey.publicKey = pubKeyBlob;
authData.sf.publicKey.publicKeySz = pubKeyBlobSz;
authData.sf.publicKey.hasSignature = 1;
authData.sf.publicKey.signature = sigBlob;
authData.sf.publicKey.signatureSz = UINT32_SZ * 2 + keyTypeNameSz + 1;
ret = wolfSSH_TestDoUserAuthRequestMlDsa(ssh, &authData, pubKeyBlobSz);
if (ret == WS_INVALID_ALGO_ID) {
/* Routing failed: x509v3-mldsa-* was not recognised and hit the
* unknown-algo guard instead of the cert parse path. */
printf("DoUserAuthRequestMlDsa cert-path (%s): routing failed\n",
keyTypeName);
result = -824;
}
else if (ret == WS_SUCCESS) {
/* Wrongful acceptance: junk cert should have been rejected */
printf("DoUserAuthRequestMlDsa cert-path (%s): "
"wrongfully accepted junk cert\n",
keyTypeName);
result = -825;
}
/* Any other error is expected: junk cert correctly rejected. */
done:
if (pubKeyBlob != NULL) WFREE(pubKeyBlob, NULL, 0);
if (sigBlob != NULL) WFREE(sigBlob, NULL, 0);
if (ssh != NULL) wolfSSH_free(ssh);
if (ctx != NULL) wolfSSH_CTX_free(ctx);
return result;
}
#if defined(WOLFSSH_CERTS) && defined(WOLFSSL_CERT_GEN)
/* Positive cert-path test: generate a real ML-DSA self-signed cert, build a
* valid auth request, and verify that DoUserAuthRequestMlDsa accepts it. */
static int test_DoUserAuthRequestMlDsa_CertPath_Valid(
const char* keyTypeName, byte level, int certSigType)
{
static const char username[] = "wolfssh";
static const char serviceName[] = "ssh-connection";
static const char authName[] = "publickey";
const word32 keyTypeNameSz = (word32)WSTRLEN(keyTypeName);
const word32 usernameSz = (word32)(sizeof(username) - 1);
const word32 serviceNameSz = (word32)(sizeof(serviceName) - 1);
const word32 authNameSz = (word32)(sizeof(authName) - 1);
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
MlDsaKey signingKey;
int signingKeyInit = 0;
WC_RNG rng;
int rngInit = 0;
Cert myCert;
WS_UserAuthData authData;
byte* certDER = NULL;
byte* rfcBlob = NULL; /* RFC6187 cert chain blob */
byte* sigBlob = NULL;
byte* dataToSign = NULL;
byte* checkData = NULL;
byte* sig = NULL;
word32 certDERSz = 0;
word32 rfcBlobSz = 0;
word32 sigBlobSz = 0;
word32 dataToSignSz = 0;
word32 checkDataSz = 0;
int sigSzInt;
word32 sigSz = 0;
int mldsaKeyType;
word32 off;
int result = 0;
int ret;
mldsaKeyType = (level == WC_ML_DSA_44) ? ML_DSA_44_TYPE :
(level == WC_ML_DSA_65) ? ML_DSA_65_TYPE : ML_DSA_87_TYPE;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL) return -850;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -851; goto done; }
ssh->sessionIdSz = 16;
WMEMSET(ssh->sessionId, 0xA5, ssh->sessionIdSz);
if (wc_InitRng(&rng) != 0) { result = -852; goto done; }
rngInit = 1;
if (wc_MlDsaKey_Init(&signingKey, NULL, INVALID_DEVID) != 0) {
result = -853; goto done;
}
signingKeyInit = 1;
if (wc_MlDsaKey_SetParams(&signingKey, level) != 0) {
result = -854; goto done;
}
if (wc_MlDsaKey_MakeKey(&signingKey, &rng) != 0) {
result = -855; goto done;
}
/* Generate a self-signed X.509 cert containing the ML-DSA public key.
* 16384 bytes is sufficient for the largest ML-DSA variant (ML-DSA-87). */
certDER = (byte*)WMALLOC(16384, NULL, 0);
if (certDER == NULL) { result = -856; goto done; }
wc_InitCert(&myCert);
WSTRNCPY(myCert.subject.commonName, "wolfSSH-mldsa-test",
CTC_NAME_SIZE - 1);
myCert.subject.commonNameEnc = CTC_UTF8;
WSTRNCPY(myCert.subject.country, "US", CTC_NAME_SIZE - 1);
myCert.daysValid = 365;
myCert.selfSigned = 1;
myCert.sigType = certSigType;
ret = wc_MakeCert_ex(&myCert, certDER, 16384, mldsaKeyType,
&signingKey, &rng);
if (ret <= 0) { result = -857; goto done; }
ret = wc_SignCert_ex(ret, certSigType, certDER, 16384, mldsaKeyType,
&signingKey, &rng);
if (ret <= 0) { result = -858; goto done; }
certDERSz = (word32)ret;
/* Build RFC6187 cert chain blob:
* string keyTypeName | uint32 certCount=1 | string certDER |
* uint32 ocspCount=0 */
rfcBlobSz = UINT32_SZ + keyTypeNameSz + UINT32_SZ +
UINT32_SZ + certDERSz + UINT32_SZ;
rfcBlob = (byte*)WMALLOC(rfcBlobSz, NULL, 0);
if (rfcBlob == NULL) { result = -859; goto done; }
off = 0;
MlDsaTest_PutLen(rfcBlob + off, keyTypeNameSz); off += UINT32_SZ;
WMEMCPY(rfcBlob + off, keyTypeName, keyTypeNameSz); off += keyTypeNameSz;
MlDsaTest_PutLen(rfcBlob + off, 1); off += UINT32_SZ;
MlDsaTest_PutLen(rfcBlob + off, certDERSz); off += UINT32_SZ;
WMEMCPY(rfcBlob + off, certDER, certDERSz); off += certDERSz;
MlDsaTest_PutLen(rfcBlob + off, 0); off += UINT32_SZ;
/* Build dataToSign; pubkey blob length uses RFC6187 blob size. */
dataToSignSz = UINT32_SZ * 5 + usernameSz + serviceNameSz + authNameSz +
1 + keyTypeNameSz + rfcBlobSz;
dataToSign = (byte*)WMALLOC(dataToSignSz, NULL, 0);
if (dataToSign == NULL) { result = -860; goto done; }
off = 0;
MlDsaTest_PutLen(dataToSign + off, usernameSz); off += UINT32_SZ;
WMEMCPY(dataToSign + off, username, usernameSz); off += usernameSz;
MlDsaTest_PutLen(dataToSign + off, serviceNameSz); off += UINT32_SZ;
WMEMCPY(dataToSign + off, serviceName, serviceNameSz); off += serviceNameSz;
MlDsaTest_PutLen(dataToSign + off, authNameSz); off += UINT32_SZ;
WMEMCPY(dataToSign + off, authName, authNameSz); off += authNameSz;
dataToSign[off++] = 1; /* hasSig */
MlDsaTest_PutLen(dataToSign + off, keyTypeNameSz); off += UINT32_SZ;
WMEMCPY(dataToSign + off, keyTypeName, keyTypeNameSz); off += keyTypeNameSz;
MlDsaTest_PutLen(dataToSign + off, rfcBlobSz); off += UINT32_SZ;
WMEMCPY(dataToSign + off, rfcBlob, rfcBlobSz); off += rfcBlobSz;
/* Build checkData and sign it. */
sigSzInt = wc_MlDsaKey_SigSize(&signingKey);
if (sigSzInt < 0) { result = -861; goto done; }
sigSz = (word32)sigSzInt;
sig = (byte*)WMALLOC(sigSz, NULL, 0);
if (sig == NULL) { result = -871; goto done; }
checkDataSz = UINT32_SZ + ssh->sessionIdSz + MSG_ID_SZ + dataToSignSz;
checkData = (byte*)WMALLOC(checkDataSz, NULL, 0);
if (checkData == NULL) { result = -862; goto done; }
off = 0;
MlDsaTest_PutLen(checkData + off, ssh->sessionIdSz); off += UINT32_SZ;
WMEMCPY(checkData + off, ssh->sessionId, ssh->sessionIdSz);
off += ssh->sessionIdSz;
checkData[off++] = MSGID_USERAUTH_REQUEST;
WMEMCPY(checkData + off, dataToSign, dataToSignSz);
if (wc_MlDsaKey_SignCtx(&signingKey, NULL, 0, sig, &sigSz, checkData,
checkDataSz, &rng) != 0) {
result = -863; goto done;
}
/* Build signature blob: string keyTypeName || string sig */
sigBlobSz = UINT32_SZ * 2 + keyTypeNameSz + sigSz;
sigBlob = (byte*)WMALLOC(sigBlobSz, NULL, 0);
if (sigBlob == NULL) { result = -864; goto done; }
off = 0;
MlDsaTest_PutLen(sigBlob + off, keyTypeNameSz); off += UINT32_SZ;
WMEMCPY(sigBlob + off, keyTypeName, keyTypeNameSz); off += keyTypeNameSz;
MlDsaTest_PutLen(sigBlob + off, sigSz); off += UINT32_SZ;
WMEMCPY(sigBlob + off, sig, sigSz); off += sigSz;
sigBlobSz = off;
/* DoUserAuthRequestMlDsa with isCert=1 expects pk->publicKey to be the
* leaf cert DER. Pass rfcBlobSz explicitly so dataToSign is sized from
* the wire blob length, not the cert DER length. */
WMEMSET(&authData, 0, sizeof(authData));
authData.type = WOLFSSH_USERAUTH_PUBLICKEY;
authData.username = (const byte*)username;
authData.usernameSz = usernameSz;
authData.serviceName = (const byte*)serviceName;
authData.serviceNameSz = serviceNameSz;
authData.authName = (const byte*)authName;
authData.authNameSz = authNameSz;
authData.sf.publicKey.dataToSign = dataToSign;
authData.sf.publicKey.publicKeyType = (const byte*)keyTypeName;
authData.sf.publicKey.publicKeyTypeSz = keyTypeNameSz;
authData.sf.publicKey.publicKey = certDER;
authData.sf.publicKey.publicKeySz = certDERSz;
authData.sf.publicKey.hasSignature = 1;
authData.sf.publicKey.isCert = 1;
authData.sf.publicKey.signature = sigBlob;
authData.sf.publicKey.signatureSz = sigBlobSz;
ret = wolfSSH_TestDoUserAuthRequestMlDsa(ssh, &authData, rfcBlobSz);
if (ret != WS_SUCCESS) {
printf("DoUserAuthRequestMlDsa cert-path valid (%s): "
"ret=%d expected %d\n",
keyTypeName, ret, WS_SUCCESS);
result = -865;
}
done:
if (signingKeyInit) wc_MlDsaKey_Free(&signingKey);
if (rngInit) wc_FreeRng(&rng);
if (certDER != NULL) WFREE(certDER, NULL, 0);
if (rfcBlob != NULL) WFREE(rfcBlob, NULL, 0);
if (sigBlob != NULL) WFREE(sigBlob, NULL, 0);
if (dataToSign != NULL) WFREE(dataToSign, NULL, 0);
if (checkData != NULL) WFREE(checkData, NULL, 0);
if (sig != NULL) WFREE(sig, NULL, 0);
if (ssh != NULL) wolfSSH_free(ssh);
if (ctx != NULL) wolfSSH_CTX_free(ctx);
return result;
}
/* Cross-level mismatch: cert has ML-DSA key at a different level than
* keyTypeName claims. PublicKeyDecode fails, should return WS_CRYPTO_FAILED.
* Requires both MLDSA44 (for the claimed type) and MLDSA65 (for the actual
* key embedded in the cert). */
#if !defined(WOLFSSH_NO_MLDSA44) && !defined(WOLFSSH_NO_MLDSA65)
static int test_DoUserAuthRequestMlDsa_CertPath_WrongLevel(void)
{
/* Claim ML-DSA-44 type but embed an ML-DSA-65 key in the cert. */
static const char keyTypeName[] = "x509v3-ssh-mldsa-44";
static const char username[] = "wolfssh";
static const char serviceName[] = "ssh-connection";
static const char authName[] = "publickey";
const word32 keyTypeNameSz = (word32)WSTRLEN(keyTypeName);
const word32 usernameSz = (word32)(sizeof(username) - 1);
const word32 serviceNameSz = (word32)(sizeof(serviceName) - 1);
const word32 authNameSz = (word32)(sizeof(authName) - 1);
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
MlDsaKey signingKey;
int signingKeyInit = 0;
WC_RNG rng;
int rngInit = 0;
Cert myCert;
WS_UserAuthData authData;
byte* certDER = NULL;
byte* sigBlob = NULL;
byte* dataToSign = NULL;
word32 certDERSz = 0;
word32 dataToSignSz = 0;
word32 off;
int result = 0;
int ret;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL) return -880;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -881; goto done; }
ssh->sessionIdSz = 16;
WMEMSET(ssh->sessionId, 0xA5, ssh->sessionIdSz);
if (wc_InitRng(&rng) != 0) { result = -882; goto done; }
rngInit = 1;
if (wc_MlDsaKey_Init(&signingKey, NULL, INVALID_DEVID) != 0) {
result = -883; goto done;
}
signingKeyInit = 1;
if (wc_MlDsaKey_SetParams(&signingKey, WC_ML_DSA_65) != 0) {
result = -884; goto done;
}
if (wc_MlDsaKey_MakeKey(&signingKey, &rng) != 0) {
result = -885; goto done;
}
certDER = (byte*)WMALLOC(16384, NULL, 0);
if (certDER == NULL) { result = -886; goto done; }
wc_InitCert(&myCert);
WSTRNCPY(myCert.subject.commonName, "wolfSSH-mldsa-test",
CTC_NAME_SIZE - 1);
myCert.subject.commonNameEnc = CTC_UTF8;
WSTRNCPY(myCert.subject.country, "US", CTC_NAME_SIZE - 1);
myCert.daysValid = 365;
myCert.selfSigned = 1;
myCert.sigType = CTC_ML_DSA_65;
ret = wc_MakeCert_ex(&myCert, certDER, 16384, ML_DSA_65_TYPE,
&signingKey, &rng);
if (ret <= 0) { result = -887; goto done; }
ret = wc_SignCert_ex(ret, CTC_ML_DSA_65, certDER, 16384,
ML_DSA_65_TYPE, &signingKey, &rng);
if (ret <= 0) { result = -888; goto done; }
certDERSz = (word32)ret;
/* Dummy sig blob: keyTypeName || one zero byte. */
sigBlob = (byte*)WMALLOC(UINT32_SZ * 2 + keyTypeNameSz + 1, NULL, 0);
if (sigBlob == NULL) { result = -889; goto done; }
off = 0;
MlDsaTest_PutLen(sigBlob + off, keyTypeNameSz); off += UINT32_SZ;
WMEMCPY(sigBlob + off, keyTypeName, keyTypeNameSz); off += keyTypeNameSz;
MlDsaTest_PutLen(sigBlob + off, 1); off += UINT32_SZ;
sigBlob[off] = 0x00;
/* Sized to match the checkData formula in DoUserAuthRequestMlDsa with
* pubKeyBlobSz=0. Populated with zeros - not a valid payload, but
* non-NULL so that if key-level enforcement ever relaxes, execution fails
* at sig verify rather than crashing on a NULL deref. */
dataToSignSz = UINT32_SZ * 5 + usernameSz + serviceNameSz + authNameSz +
BOOLEAN_SZ + keyTypeNameSz;
dataToSign = (byte*)WMALLOC(dataToSignSz, NULL, 0);
if (dataToSign == NULL) { result = -890; goto done; }
WMEMSET(dataToSign, 0, dataToSignSz);
WMEMSET(&authData, 0, sizeof(authData));
authData.type = WOLFSSH_USERAUTH_PUBLICKEY;
authData.username = (const byte*)username;
authData.usernameSz = usernameSz;
authData.serviceName = (const byte*)serviceName;
authData.serviceNameSz = serviceNameSz;
authData.authName = (const byte*)authName;
authData.authNameSz = authNameSz;
authData.sf.publicKey.publicKeyType = (const byte*)keyTypeName;
authData.sf.publicKey.publicKeyTypeSz = keyTypeNameSz;
authData.sf.publicKey.publicKey = certDER;
authData.sf.publicKey.publicKeySz = certDERSz;
authData.sf.publicKey.hasSignature = 1;
authData.sf.publicKey.isCert = 1;
authData.sf.publicKey.dataToSign = dataToSign;
authData.sf.publicKey.signature = sigBlob;
authData.sf.publicKey.signatureSz = UINT32_SZ * 2 + keyTypeNameSz + 1;
ret = wolfSSH_TestDoUserAuthRequestMlDsa(ssh, &authData, 0);
if (ret == WS_SUCCESS) {
printf("DoUserAuthRequestMlDsa cert-path wrong-level: "
"wrongfully accepted\n");
result = -891;
}
else if (ret != WS_CRYPTO_FAILED) {
printf("DoUserAuthRequestMlDsa cert-path wrong-level: "
"ret=%d expected %d\n",
ret, WS_CRYPTO_FAILED);
result = -892;
}
done:
if (signingKeyInit) wc_MlDsaKey_Free(&signingKey);
if (rngInit) wc_FreeRng(&rng);
if (certDER != NULL) WFREE(certDER, NULL, 0);
if (sigBlob != NULL) WFREE(sigBlob, NULL, 0);
if (dataToSign != NULL) WFREE(dataToSign, NULL, 0);
if (ssh != NULL) wolfSSH_free(ssh);
if (ctx != NULL) wolfSSH_CTX_free(ctx);
return result;
}
#endif /* WOLFSSH_NO_MLDSA44 && WOLFSSH_NO_MLDSA65 */
#endif /* WOLFSSH_CERTS && WOLFSSL_CERT_GEN */
#endif /* WOLFSSH_CERTS */
#ifdef WOLFSSH_KEYGEN
static int test_PrepareUserAuthRequestMlDsa_Params(word32 keygenLevel,
byte keyId, int derBufSz)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WS_UserAuthData authData;
WS_KeySignature keySig;
byte* derKey = NULL;
word32 payloadSz;
int derKeySz;
int result = 0;
int ret;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL) return -900;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -901; goto done; }
derKey = (byte*)WMALLOC(derBufSz, NULL, 0);
if (derKey == NULL) { result = -902; goto done; }
derKeySz = wolfSSH_MakeMlDsaKey(derKey, (word32)derBufSz, keygenLevel);
if (derKeySz < 0) { result = -903; goto done; }
/* DER success path */
WMEMSET(&authData, 0, sizeof(authData));
WMEMSET(&keySig, 0, sizeof(keySig));
payloadSz = 0;
authData.sf.publicKey.privateKey = derKey;
authData.sf.publicKey.privateKeySz = (word32)derKeySz;
authData.sf.publicKey.hasSignature = 0;
keySig.keyId = keyId;
keySig.heap = NULL;
ret = wolfSSH_TestPrepareUserAuthRequestMlDsa(ssh, &payloadSz,
&authData, &keySig);
if (ret != WS_SUCCESS) { result = -904; goto done; }
wc_MlDsaKey_Free(&keySig.ks.mldsa.key);
/* Fallback path: garbage fails PrivateKeyDecode, then fails OpenSSH
* magic check; function must return an error (not leak the Init'd key). */
{
static const byte badKey[] = { 0xFF, 0xFE, 0x00, 0x01 };
WMEMSET(&authData, 0, sizeof(authData));
WMEMSET(&keySig, 0, sizeof(keySig));
payloadSz = 0;
authData.sf.publicKey.privateKey = badKey;
authData.sf.publicKey.privateKeySz = sizeof(badKey);
authData.sf.publicKey.hasSignature = 0;
keySig.keyId = keyId;
keySig.heap = NULL;
ret = wolfSSH_TestPrepareUserAuthRequestMlDsa(ssh, &payloadSz,
&authData, &keySig);
if (ret == WS_SUCCESS) {
wc_MlDsaKey_Free(&keySig.ks.mldsa.key);
result = -905;
goto done;
}
}
/* hasSignature=1 path: exercises payload-size accumulation and sigSz. */
{
WMEMSET(&authData, 0, sizeof(authData));
WMEMSET(&keySig, 0, sizeof(keySig));
payloadSz = 0;
authData.sf.publicKey.privateKey = derKey;
authData.sf.publicKey.privateKeySz = (word32)derKeySz;
authData.sf.publicKey.hasSignature = 1;
keySig.keyId = keyId;
keySig.heap = NULL;
ret = wolfSSH_TestPrepareUserAuthRequestMlDsa(ssh, &payloadSz,
&authData, &keySig);
/* On failure the function frees the key internally; only free on
* success paths where the key was left initialized for the caller. */
if (ret != WS_SUCCESS) { result = -906; goto done; }
if (keySig.sigSz == 0) {
wc_MlDsaKey_Free(&keySig.ks.mldsa.key);
result = -907; goto done;
}
if (payloadSz == 0) {
wc_MlDsaKey_Free(&keySig.ks.mldsa.key);
result = -908; goto done;
}
wc_MlDsaKey_Free(&keySig.ks.mldsa.key);
}
done:
WFREE(derKey, NULL, 0);
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* WOLFSSH_KEYGEN */
static int test_DoUserAuthRequestMlDsa(void)
{
int ret;
#ifndef WOLFSSH_NO_MLDSA44
ret = test_DoUserAuthRequestMlDsa_Params("ssh-mldsa-44", WC_ML_DSA_44);
if (ret != 0) return ret;
#endif
#ifndef WOLFSSH_NO_MLDSA65
ret = test_DoUserAuthRequestMlDsa_Params("ssh-mldsa-65", WC_ML_DSA_65);
if (ret != 0) return ret;
#endif
#ifndef WOLFSSH_NO_MLDSA87
ret = test_DoUserAuthRequestMlDsa_Params("ssh-mldsa-87", WC_ML_DSA_87);
if (ret != 0) return ret;
#endif
ret = test_DoUserAuthRequestMlDsa_BadAlgo();
if (ret != 0) return ret;
#ifdef WOLFSSH_CERTS
#ifndef WOLFSSH_NO_MLDSA44
ret = test_DoUserAuthRequestMlDsa_CertPath("x509v3-ssh-mldsa-44");
if (ret != 0) return ret;
#endif
#ifndef WOLFSSH_NO_MLDSA65
ret = test_DoUserAuthRequestMlDsa_CertPath("x509v3-ssh-mldsa-65");
if (ret != 0) return ret;
#endif
#ifndef WOLFSSH_NO_MLDSA87
ret = test_DoUserAuthRequestMlDsa_CertPath("x509v3-ssh-mldsa-87");
if (ret != 0) return ret;
#endif
#ifdef WOLFSSL_CERT_GEN
#ifndef WOLFSSH_NO_MLDSA44
ret = test_DoUserAuthRequestMlDsa_CertPath_Valid(
"x509v3-ssh-mldsa-44", WC_ML_DSA_44, CTC_ML_DSA_44);
if (ret != 0) return ret;
#endif
#ifndef WOLFSSH_NO_MLDSA65
ret = test_DoUserAuthRequestMlDsa_CertPath_Valid(
"x509v3-ssh-mldsa-65", WC_ML_DSA_65, CTC_ML_DSA_65);
if (ret != 0) return ret;
#endif
#ifndef WOLFSSH_NO_MLDSA87
ret = test_DoUserAuthRequestMlDsa_CertPath_Valid(
"x509v3-ssh-mldsa-87", WC_ML_DSA_87, CTC_ML_DSA_87);
if (ret != 0) return ret;
#endif
#if !defined(WOLFSSH_NO_MLDSA44) && !defined(WOLFSSH_NO_MLDSA65)
ret = test_DoUserAuthRequestMlDsa_CertPath_WrongLevel();
if (ret != 0) return ret;
#endif
#endif /* WOLFSSL_CERT_GEN */
#endif /* WOLFSSH_CERTS */
return 0;
}
#ifndef WOLFSSH_NO_MLDSA44
/* Host key blob parse for ssh-mldsa-44. The format identifier must match
* the negotiated algorithm (RFC 4253 section 6.6). */
static int test_ParseMlDsaPubKey(void)
{
static const char keyTypeName[] = "ssh-mldsa-44";
const word32 keyTypeNameSz = (word32)(sizeof(keyTypeName) - 1);
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
MlDsaKey key;
int keyInit = 0;
WC_RNG rng;
int rngInit = 0;
byte blob[UINT32_SZ * 2 + sizeof(keyTypeName) - 1
+ WC_MLDSA_44_PUB_KEY_SIZE];
word32 pubSz = WC_MLDSA_44_PUB_KEY_SIZE;
word32 blobSz;
int ret;
int result = 0;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -780;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
result = -781;
goto done;
}
if (wc_InitRng(&rng) != 0) {
result = -782;
goto done;
}
rngInit = 1;
if (wc_MlDsaKey_Init(&key, NULL, INVALID_DEVID) != 0) {
result = -783;
goto done;
}
keyInit = 1;
if (wc_MlDsaKey_SetParams(&key, WC_ML_DSA_44) != 0
|| wc_MlDsaKey_MakeKey(&key, &rng) != 0) {
result = -784;
goto done;
}
/* string "ssh-mldsa-44" || string pubkey */
PutU32BE(blob, keyTypeNameSz);
WMEMCPY(blob + UINT32_SZ, keyTypeName, keyTypeNameSz);
if (wc_MlDsaKey_ExportPubRaw(&key,
blob + UINT32_SZ * 2 + keyTypeNameSz, &pubSz) != 0) {
result = -785;
goto done;
}
PutU32BE(blob + UINT32_SZ + keyTypeNameSz, pubSz);
blobSz = UINT32_SZ * 2 + keyTypeNameSz + pubSz;
ret = wolfSSH_TestParseMlDsaPubKey(ssh, blob, blobSz, ID_MLDSA44);
if (ret != WS_SUCCESS) {
fprintf(stderr, "\t\"valid\" FAIL: got %d, expected %d\n",
ret, WS_SUCCESS);
result = -786;
goto done;
}
ret = wolfSSH_TestParseMlDsaPubKey(ssh, blob, blobSz - 4, ID_MLDSA44);
if (ret == WS_SUCCESS) {
fprintf(stderr, "\t\"truncated\" FAIL: got %d\n", ret);
result = -787;
goto done;
}
/* format identifier other than "ssh-mldsa-44" */
blob[UINT32_SZ + keyTypeNameSz - 1] = '5';
ret = wolfSSH_TestParseMlDsaPubKey(ssh, blob, blobSz, ID_MLDSA44);
if (ret != WS_INVALID_ALGO_ID) {
fprintf(stderr, "\t\"format mismatch\" FAIL: got %d, expected %d\n",
ret, WS_INVALID_ALGO_ID);
result = -788;
goto done;
}
done:
if (keyInit)
wc_MlDsaKey_Free(&key);
if (rngInit)
wc_FreeRng(&rng);
if (ssh != NULL)
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* !WOLFSSH_NO_MLDSA44 */
/* tamperSig: 0 = no tampering, 1 = flip a byte in the trad-algorithm
* signature component, 2 = flip a byte in the ML-DSA signature component,
* 3 = claim a composite signature length shorter than the ML-DSA half
* alone, 4 = claim a composite signature length far longer than what was
* produced. All tamper modes must be rejected by verification. */
#ifndef WOLFSSH_NO_MLDSA_COMPOSITES
static int test_DoUserAuthRequestMlDsaComposite_Params(const char* keyTypeName,
byte keyId, int tamperSig)
{
static const char username[] = "wolfssh";
static const char serviceName[] = "ssh-connection";
static const char authName[] = "publickey";
const word32 keyTypeNameSz = (word32)(WSTRLEN(keyTypeName));
const word32 usernameSz = (word32)(sizeof(username) - 1);
const word32 serviceNameSz = (word32)(sizeof(serviceName) - 1);
const word32 authNameSz = (word32)(sizeof(authName) - 1);
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
MlDsaKey signingKey;
int signingKeyInit = 0;
#ifndef WOLFSSH_NO_ECDSA
ecc_key eccKey;
int eccInit = 0;
#endif
#ifndef WOLFSSH_NO_ED25519
ed25519_key ed25519Key;
int ed25519Init = 0;
#endif
#ifdef WOLFSSH_HAVE_COMPOSITE_ED448
ed448_key ed448Key;
int ed448Init = 0;
#endif
WC_RNG rng;
int rngInit = 0;
WS_UserAuthData authData;
CompositeParams params;
byte* pubKeyBlob = NULL;
byte* sigBlob = NULL;
byte* dataToSign = NULL;
byte* checkData = NULL;
byte* pubRaw = NULL;
byte* tradPub = NULL;
byte* mldsaSig = NULL;
byte* tradSig = NULL;
byte* hash = NULL;
byte* m_prime = NULL;
word32 pubKeyBlobSz = 0;
word32 sigBlobSz = 0;
word32 dataToSignSz = 0;
word32 checkDataSz = 0;
word32 off;
word32 mldsaSigSz;
word32 tradSigSz = 0;
word32 m_prime_len;
int result = 0;
int ret;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL) return -700;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -701; goto done; }
/* Stub a session id so the verify hash has something to absorb. */
ssh->sessionIdSz = 16;
WMEMSET(ssh->sessionId, 0xA5, ssh->sessionIdSz);
if (wc_InitRng(&rng) != 0) {
result = -702;
goto done;
}
rngInit = 1;
ret = WS_GetCompositeParams(keyId, &params);
if (ret != WS_SUCCESS) { result = -703; goto done; }
if (wc_MlDsaKey_Init(&signingKey, NULL,
INVALID_DEVID) != 0) { result = -704; goto done; }
signingKeyInit = 1;
if (wc_MlDsaKey_SetParams(&signingKey,
params.mldsaLevel) != 0) { result = -705; goto done; }
if (wc_MlDsaKey_MakeKey(&signingKey,
&rng) != 0) { result = -706; goto done; }
if (params.tradType == TRAD_TYPE_ED25519) {
#ifndef WOLFSSH_NO_ED25519
if (wc_ed25519_init(&ed25519Key) != 0) { result = -707; goto done; }
ed25519Init = 1;
if (wc_ed25519_make_key(&rng, ED25519_KEY_SIZE,
&ed25519Key) != 0) { result = -708; goto done; }
#else
result = -709; goto done;
#endif
}
else if (params.tradType == TRAD_TYPE_ED448) {
#ifdef WOLFSSH_HAVE_COMPOSITE_ED448
if (wc_ed448_init(&ed448Key) != 0) { result = -710; goto done; }
ed448Init = 1;
if (wc_ed448_make_key(&rng, 57,
&ed448Key) != 0) { result = -711; goto done; }
#else
result = -712; goto done;
#endif
}
else if (params.tradType == TRAD_TYPE_ECC) {
#ifndef WOLFSSH_NO_ECDSA
if (wc_ecc_init(&eccKey) != 0) { result = -713; goto done; }
eccInit = 1;
if (wc_ecc_make_key_ex(&rng, (int)params.tradPrivSz, &eccKey,
params.eccCurveId) != 0) { result = -714; goto done; }
#else
result = -715; goto done;
#endif
}
pubRaw = (byte*)WMALLOC(params.mldsaPubSz, NULL, 0);
if (pubRaw == NULL) { result = -716; goto done; }
{
word32 sz = params.mldsaPubSz;
if (wc_MlDsaKey_ExportPubRaw(&signingKey, pubRaw,
&sz) != 0 || sz != params.mldsaPubSz) { result = -717; goto done; }
}
tradPub = (byte*)WMALLOC(params.tradPubSz, NULL, 0);
if (tradPub == NULL) { result = -718; goto done; }
if (params.tradType == TRAD_TYPE_ED25519) {
#ifndef WOLFSSH_NO_ED25519
word32 sz = params.tradPubSz;
if (wc_ed25519_export_public(&ed25519Key, tradPub,
&sz) != 0 || sz != params.tradPubSz) { result = -719; goto done; }
#endif
}
else if (params.tradType == TRAD_TYPE_ED448) {
#ifdef WOLFSSH_HAVE_COMPOSITE_ED448
word32 sz = params.tradPubSz;
if (wc_ed448_export_public(&ed448Key, tradPub,
&sz) != 0 || sz != params.tradPubSz) { result = -720; goto done; }
#endif
}
else if (params.tradType == TRAD_TYPE_ECC) {
#ifndef WOLFSSH_NO_ECDSA
word32 sz = params.tradPubSz;
if (wc_ecc_export_x963(&eccKey, tradPub,
&sz) != 0 || sz != params.tradPubSz) { result = -721; goto done; }
#endif
}
pubKeyBlobSz = UINT32_SZ * 2 + keyTypeNameSz + params.mldsaPubSz +
params.tradPubSz;
pubKeyBlob = (byte*)WMALLOC(pubKeyBlobSz, NULL, 0);
if (pubKeyBlob == NULL) { result = -722; goto done; }
off = 0;
MlDsaTest_PutLen(pubKeyBlob + off, keyTypeNameSz); off += UINT32_SZ;
WMEMCPY(pubKeyBlob + off, keyTypeName, keyTypeNameSz); off += keyTypeNameSz;
MlDsaTest_PutLen(pubKeyBlob + off,
params.mldsaPubSz + params.tradPubSz); off += UINT32_SZ;
WMEMCPY(pubKeyBlob + off, pubRaw,
params.mldsaPubSz); off += params.mldsaPubSz;
WMEMCPY(pubKeyBlob + off, tradPub,
params.tradPubSz); off += params.tradPubSz;
dataToSignSz = UINT32_SZ * 5 + usernameSz + serviceNameSz +
authNameSz + 1 + keyTypeNameSz + pubKeyBlobSz;
dataToSign = (byte*)WMALLOC(dataToSignSz, NULL, 0);
if (dataToSign == NULL) { result = -723; goto done; }
off = 0;
MlDsaTest_PutLen(dataToSign + off, usernameSz); off += UINT32_SZ;
WMEMCPY(dataToSign + off, username, usernameSz); off += usernameSz;
MlDsaTest_PutLen(dataToSign + off, serviceNameSz); off += UINT32_SZ;
WMEMCPY(dataToSign + off, serviceName, serviceNameSz); off += serviceNameSz;
MlDsaTest_PutLen(dataToSign + off, authNameSz); off += UINT32_SZ;
WMEMCPY(dataToSign + off, authName, authNameSz); off += authNameSz;
dataToSign[off++] = 1;
MlDsaTest_PutLen(dataToSign + off, keyTypeNameSz); off += UINT32_SZ;
WMEMCPY(dataToSign + off, keyTypeName, keyTypeNameSz); off += keyTypeNameSz;
MlDsaTest_PutLen(dataToSign + off, pubKeyBlobSz); off += UINT32_SZ;
WMEMCPY(dataToSign + off, pubKeyBlob, pubKeyBlobSz); off += pubKeyBlobSz;
checkDataSz = UINT32_SZ + ssh->sessionIdSz + MSG_ID_SZ + dataToSignSz;
checkData = (byte*)WMALLOC(checkDataSz, NULL, 0);
if (checkData == NULL) { result = -724; goto done; }
off = 0;
MlDsaTest_PutLen(checkData + off, ssh->sessionIdSz); off += UINT32_SZ;
WMEMCPY(checkData + off, ssh->sessionId,
ssh->sessionIdSz); off += ssh->sessionIdSz;
checkData[off++] = MSGID_USERAUTH_REQUEST;
WMEMCPY(checkData + off, dataToSign, dataToSignSz);
mldsaSig = (byte*)WMALLOC(params.mldsaSigSz, NULL, 0);
tradSig = (byte*)WMALLOC(params.tradSigSz + 256, NULL, 0);
mldsaSigSz = params.mldsaSigSz;
if (mldsaSig == NULL || tradSig == NULL) { result = -725; goto done; }
hash = (byte*)WMALLOC(params.tradHashSz, NULL, 0);
m_prime_len = COMPOSITE_DOMAIN_PREFIX_SZ + params.labelSz + 1 +
params.tradHashSz;
m_prime = (byte*)WMALLOC(m_prime_len, NULL, 0);
if (hash == NULL || m_prime == NULL) { result = -726; goto done; }
ret = WS_Hash_Helper(params.tradHashId, checkData, checkDataSz, hash,
params.tradHashSz);
if (ret != 0) { result = -727; goto done; }
WMEMCPY(m_prime, COMPOSITE_DOMAIN_PREFIX, COMPOSITE_DOMAIN_PREFIX_SZ);
WMEMCPY(m_prime + COMPOSITE_DOMAIN_PREFIX_SZ, params.label, params.labelSz);
m_prime[COMPOSITE_DOMAIN_PREFIX_SZ + params.labelSz] = 0;
WMEMCPY(m_prime + COMPOSITE_DOMAIN_PREFIX_SZ + params.labelSz + 1, hash,
params.tradHashSz);
if (wc_MlDsaKey_SignCtx(&signingKey, (const byte*)params.label,
params.labelSz, mldsaSig, &mldsaSigSz, m_prime, m_prime_len,
&rng) != 0) {
result = -728; goto done;
}
if (params.tradType == TRAD_TYPE_ED25519) {
#ifndef WOLFSSH_NO_ED25519
tradSigSz = ED25519_SIG_SIZE;
if (wc_ed25519_sign_msg(m_prime, m_prime_len, tradSig, &tradSigSz,
&ed25519Key) != 0) { result = -729; goto done; }
#endif
}
else if (params.tradType == TRAD_TYPE_ED448) {
#ifdef WOLFSSH_HAVE_COMPOSITE_ED448
tradSigSz = 114;
if (wc_ed448_sign_msg(m_prime, m_prime_len, tradSig, &tradSigSz,
&ed448Key, NULL, 0) != 0) { result = -730; goto done; }
#endif
}
else if (params.tradType == TRAD_TYPE_ECC) {
#ifndef WOLFSSH_NO_ECDSA
byte asnSig[ECDSA_ASN_SIG_SZ];
word32 asnSigSz = sizeof(asnSig);
byte digest[WC_MAX_DIGEST_SIZE];
word32 rSz = MAX_ECC_BYTES + ECC_MAX_PAD_SZ,
sSz = MAX_ECC_BYTES + ECC_MAX_PAD_SZ;
byte rBuf[MAX_ECC_BYTES + ECC_MAX_PAD_SZ];
byte sBuf[MAX_ECC_BYTES + ECC_MAX_PAD_SZ];
ret = WS_Hash_Helper(params.tradHashId, m_prime, m_prime_len, digest,
params.tradHashSz);
if (ret != 0) { result = -737; goto done; }
if (wc_ecc_sign_hash(digest, params.tradHashSz, asnSig, &asnSigSz,
&rng, &eccKey) != 0) { result = -731; goto done; }
if (wc_ecc_sig_to_rs(asnSig, asnSigSz, rBuf, &rSz, sBuf,
&sSz) != 0) { result = -734; goto done; }
{
/* mpint pad, mirroring CompositeEccSign()'s wire format. */
byte rPad = (rBuf[0] & 0x80) ? 1 : 0;
byte sPad = (sBuf[0] & 0x80) ? 1 : 0;
off = 0;
MlDsaTest_PutLen(tradSig + off, rSz + rPad); off += UINT32_SZ;
if (rPad)
tradSig[off++] = 0;
WMEMCPY(tradSig + off, rBuf, rSz); off += rSz;
MlDsaTest_PutLen(tradSig + off, sSz + sPad); off += UINT32_SZ;
if (sPad)
tradSig[off++] = 0;
WMEMCPY(tradSig + off, sBuf, sSz); off += sSz;
tradSigSz = off;
}
#endif
}
/* extra padding so tamperSig==4's oversized claimed length reads
* initialized (zeroed) memory instead of running off the allocation */
sigBlobSz = UINT32_SZ * 2 + keyTypeNameSz + mldsaSigSz + tradSigSz + 64;
sigBlob = (byte*)WMALLOC(sigBlobSz, NULL, 0);
if (sigBlob == NULL) { result = -735; goto done; }
WMEMSET(sigBlob, 0, sigBlobSz);
off = 0;
MlDsaTest_PutLen(sigBlob + off, keyTypeNameSz); off += UINT32_SZ;
WMEMCPY(sigBlob + off, keyTypeName, keyTypeNameSz); off += keyTypeNameSz;
{
word32 sigLenOff = off;
MlDsaTest_PutLen(sigBlob + off, mldsaSigSz + tradSigSz);
off += UINT32_SZ;
WMEMCPY(sigBlob + off, mldsaSig, mldsaSigSz); off += mldsaSigSz;
WMEMCPY(sigBlob + off, tradSig, tradSigSz); off += tradSigSz;
if (tamperSig == 3) {
/* Claim a composite signature shorter than the ML-DSA half
* alone; must be rejected by VerifyMlDsaComposite()'s
* "sigSz < params.mldsaSigSz" underflow guard. */
MlDsaTest_PutLen(sigBlob + sigLenOff, mldsaSigSz - 1);
}
else if (tamperSig == 4) {
/* Claim a composite signature far longer than what was
* actually produced; must be rejected by
* VerifyMlDsaComposite()'s trad-region bound checks rather
* than reading past the real signature data. */
MlDsaTest_PutLen(sigBlob + sigLenOff,
mldsaSigSz + tradSigSz + 32);
}
}
if (tamperSig == 1) {
/* Flip a byte in the trad-algorithm component of the signature
* (last byte of the real content, before the padding added for
* tamperSig==4) and confirm verification rejects it rather than
* accepting a corrupted composite signature. */
sigBlob[off - 1] ^= 0xFF;
}
else if (tamperSig == 2) {
/* Flip the first byte of the ML-DSA component of the signature
* and confirm verification rejects it too; a bug that verifies
* only the trad half (or mis-slices the combined signature)
* would let this slip through. */
word32 mldsaOff = UINT32_SZ * 2 + keyTypeNameSz;
sigBlob[mldsaOff] ^= 0xFF;
}
WMEMSET(&authData, 0, sizeof(authData));
authData.type = WOLFSSH_USERAUTH_PUBLICKEY;
authData.username = (const byte*)username;
authData.usernameSz = usernameSz;
authData.serviceName = (const byte*)serviceName;
authData.serviceNameSz = serviceNameSz;
authData.authName = (const byte*)authName;
authData.authNameSz = authNameSz;
authData.sf.publicKey.dataToSign = dataToSign;
authData.sf.publicKey.publicKeyType = (const byte*)keyTypeName;
authData.sf.publicKey.publicKeyTypeSz = keyTypeNameSz;
authData.sf.publicKey.publicKey = pubKeyBlob;
authData.sf.publicKey.publicKeySz = pubKeyBlobSz;
authData.sf.publicKey.signature = sigBlob;
/* sigBlobSz (not off) so tamperSig==4's inflated claimed length still
* passes DoUserAuthRequestMlDsaComposite's GetSize() bound check
* against the remaining buffer and reaches VerifyMlDsaComposite's own
* trad-region bound checks instead of being rejected earlier. */
authData.sf.publicKey.signatureSz = sigBlobSz;
ret = wolfSSH_TestDoUserAuthRequestMlDsaComposite(ssh, &authData, keyId,
pubKeyBlobSz);
if (tamperSig) {
if (ret == WS_SUCCESS) {
printf("DoUserAuthRequestMlDsaComposite (%s) tampered sig "
"incorrectly verified as valid\n", keyTypeName);
result = -738;
}
}
else if (ret != WS_SUCCESS) {
printf("DoUserAuthRequestMlDsaComposite (%s) failed: ret=%d\n",
keyTypeName, ret);
result = -736;
}
done:
if (signingKeyInit) wc_MlDsaKey_Free(&signingKey);
#ifndef WOLFSSH_NO_ECDSA
if (eccInit) wc_ecc_free(&eccKey);
#endif
#ifndef WOLFSSH_NO_ED25519
if (ed25519Init) wc_ed25519_free(&ed25519Key);
#endif
#ifdef WOLFSSH_HAVE_COMPOSITE_ED448
if (ed448Init) wc_ed448_free(&ed448Key);
#endif
if (rngInit) wc_FreeRng(&rng);
if (pubKeyBlob != NULL) WFREE(pubKeyBlob, NULL, 0);
if (sigBlob != NULL) WFREE(sigBlob, NULL, 0);
if (dataToSign != NULL) WFREE(dataToSign, NULL, 0);
if (checkData != NULL) WFREE(checkData, NULL, 0);
if (pubRaw != NULL) WFREE(pubRaw, NULL, 0);
if (tradPub != NULL) WFREE(tradPub, NULL, 0);
if (mldsaSig != NULL) WFREE(mldsaSig, NULL, 0);
if (tradSig != NULL) WFREE(tradSig, NULL, 0);
if (hash != NULL) WFREE(hash, NULL, 0);
if (m_prime != NULL) WFREE(m_prime, NULL, 0);
if (ssh != NULL) wolfSSH_free(ssh);
if (ctx != NULL) wolfSSH_CTX_free(ctx);
return result;
}
/* Exercise SignHMlDsaComposite() buffer limits. */
static int test_SignHMlDsaComposite_Params(const char* label, byte keyId)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
CompositeParams params;
byte sig[WC_MLDSA_87_SIG_SIZE + 256];
word32 sigSz;
int ret, result = 0;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL) return -900;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -901; goto done; }
ssh->hSz = WC_SHA256_DIGEST_SIZE;
WMEMSET(ssh->h, 0xA5, ssh->hSz);
if (WS_GetCompositeParams(keyId, &params) != WS_SUCCESS) {
result = -902; goto done;
}
/* Verify worst-case buffer sizing succeeds. */
{
word32 minSigSz = params.mldsaSigSz + params.tradSigSz;
if (params.tradType == TRAD_TYPE_ECC) {
minSigSz -= (minSigSz > 4) ? 4 : minSigSz;
}
sigSz = params.mldsaSigSz + params.tradSigSz;
ret = wolfSSH_TestSignHMlDsaComposite(ssh, sig, &sigSz, keyId);
if (ret != WS_SUCCESS || sigSz < minSigSz ||
sigSz > (params.mldsaSigSz + params.tradSigSz)) {
printf("SignHMlDsaComposite (%s) worst-case-size sign failed: "
"ret=%d sigSz=%u min=%u max=%u\n", label, ret, sigSz,
minSigSz, params.mldsaSigSz + params.tradSigSz);
result = -903; goto done;
}
}
/* Reject undersized buffer. */
sigSz = params.mldsaSigSz + 1;
ret = wolfSSH_TestSignHMlDsaComposite(ssh, sig, &sigSz, keyId);
if (ret != WS_BAD_ARGUMENT) {
printf("SignHMlDsaComposite (%s) undersized buffer not rejected: "
"ret=%d\n", label, ret);
result = -904; goto done;
}
/* Historical KEX_SIG_SIZE reserved only 64 bytes of trad headroom,
* too small for P-384/Ed448. Exercises the same generic tradSigSz
* check as above, not the KEX_SIG_SIZE constant itself. */
if (params.tradSigSz > 64) {
sigSz = params.mldsaSigSz + 64;
ret = wolfSSH_TestSignHMlDsaComposite(ssh, sig, &sigSz, keyId);
if (ret != WS_BAD_ARGUMENT) {
printf("SignHMlDsaComposite (%s) 64-byte trad headroom not "
"rejected: ret=%d\n", label, ret);
result = -905; goto done;
}
}
done:
if (ssh != NULL) wolfSSH_free(ssh);
if (ctx != NULL) wolfSSH_CTX_free(ctx);
return result;
}
static int test_SignHMlDsaComposite(void)
{
int ret = 0;
#ifndef WOLFSSH_NO_MLDSA44_ES256
ret = test_SignHMlDsaComposite_Params("ssh-mldsa44-es256@wolfssl.com",
ID_MLDSA44_ES256);
if (ret != 0) return ret;
#endif
#ifndef WOLFSSH_NO_MLDSA65_ES256
ret = test_SignHMlDsaComposite_Params("ssh-mldsa65-es256@wolfssl.com",
ID_MLDSA65_ES256);
if (ret != 0) return ret;
#endif
#ifndef WOLFSSH_NO_MLDSA87_ES384
ret = test_SignHMlDsaComposite_Params("ssh-mldsa87-es384@wolfssl.com",
ID_MLDSA87_ES384);
if (ret != 0) return ret;
#endif
#ifndef WOLFSSH_NO_MLDSA44_ED25519
ret = test_SignHMlDsaComposite_Params("ssh-mldsa44-ed25519@openssh.com",
ID_MLDSA44_ED25519);
if (ret != 0) return ret;
#endif
#ifndef WOLFSSH_NO_MLDSA65_ED25519
ret = test_SignHMlDsaComposite_Params("ssh-mldsa65-ed25519@wolfssl.com",
ID_MLDSA65_ED25519);
if (ret != 0) return ret;
#endif
#ifndef WOLFSSH_NO_MLDSA87_ED448
ret = test_SignHMlDsaComposite_Params("ssh-mldsa87-ed448@wolfssl.com",
ID_MLDSA87_ED448);
if (ret != 0) return ret;
#endif
return 0;
}
#ifndef WOLFSSH_NO_MLDSA44_ED25519
/* Reset a WS_KeySignature to a clean slate before (re)using it as an
* ID_MLDSA44_ED25519 decode target. */
static void MlDsaTest_ResetKeySig(WS_KeySignature* keySig)
{
WMEMSET(keySig, 0, sizeof(*keySig));
keySig->keyId = ID_MLDSA44_ED25519;
keySig->heap = NULL;
}
#endif
/* E2E parser test with minimal OpenSSH-key-v1 envelope. */
static int test_PrepareUserAuthRequestMlDsaComposite_OpenSshEnvelope(void)
{
#ifndef WOLFSSH_NO_MLDSA44_ED25519
static const char keyTypeName[] = "ssh-mldsa44-ed25519@openssh.com";
static const char magic[] = "openssh-key-v1";
static const char none[] = "none";
static const char comment[] = "";
const word32 keyTypeNameSz = (word32)(sizeof(keyTypeName) - 1);
const word32 noneSz = (word32)(sizeof(none) - 1);
const word32 commentSz = (word32)(sizeof(comment) - 1);
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WC_RNG rng;
int rngInit = 0;
CompositeParams params;
WS_KeySignature keySig;
WS_UserAuthData authData;
MlDsaKey signingKey;
int signingKeyInit = 0;
ed25519_key ed25519Key;
int ed25519Init = 0;
int result = 0;
int ret;
byte mldsaSeed[MLDSA_SEED_SZ];
byte ed25519Seed[ED25519_KEY_SIZE];
byte* mldsaPub = NULL;
byte* ed25519Pub = NULL;
word32 mldsaPubSz = 0;
word32 ed25519PubSz = ED25519_PUB_KEY_SIZE;
byte roundTripPub[WC_MLDSA_44_PUB_KEY_SIZE];
word32 roundTripPubSz;
byte* file = NULL;
word32 fileSz;
word32 off;
word32 pubBlobSz, compositePubSz, compositePrivSz, privKeysStrSz, padSz, i;
word32 compPubOff2 = 0, compPrivOff = 0;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL) return -950;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -951; goto done; }
if (wc_InitRng(&rng) != 0) { result = -952; goto done; }
rngInit = 1;
ret = WS_GetCompositeParams(ID_MLDSA44_ED25519, &params);
if (ret != WS_SUCCESS) { result = -953; goto done; }
/* Generate real seed-based keys, per the composite draft's
* seed-based KeyGen_internal requirement (draft section 4.1). */
if (wc_RNG_GenerateBlock(&rng, mldsaSeed, sizeof(mldsaSeed)) != 0) {
result = -954; goto done;
}
if (wc_MlDsaKey_Init(&signingKey, NULL,
INVALID_DEVID) != 0) { result = -955; goto done; }
signingKeyInit = 1;
if (wc_MlDsaKey_SetParams(&signingKey,
params.mldsaLevel) != 0) { result = -956; goto done; }
if (wc_MlDsaKey_MakeKeyFromSeed(&signingKey,
mldsaSeed) != 0) { result = -957; goto done; }
mldsaPub = (byte*)WMALLOC(params.mldsaPubSz, NULL, 0);
if (mldsaPub == NULL) { result = -958; goto done; }
mldsaPubSz = params.mldsaPubSz;
if (wc_MlDsaKey_ExportPubRaw(&signingKey, mldsaPub, &mldsaPubSz) != 0
|| mldsaPubSz != params.mldsaPubSz) {
result = -959; goto done;
}
if (wc_RNG_GenerateBlock(&rng, ed25519Seed, sizeof(ed25519Seed)) != 0) {
result = -960; goto done;
}
if (wc_ed25519_init(&ed25519Key) != 0) { result = -961; goto done; }
ed25519Init = 1;
if (wc_ed25519_import_private_only(ed25519Seed, sizeof(ed25519Seed),
&ed25519Key) != 0) {
result = -962; goto done;
}
ed25519Pub = (byte*)WMALLOC(ED25519_PUB_KEY_SIZE, NULL, 0);
if (ed25519Pub == NULL) { result = -963; goto done; }
if (wc_ed25519_make_public(&ed25519Key, ed25519Pub, ed25519PubSz) != 0) {
result = -964; goto done;
}
/* wc_ed25519_make_public() alone doesn't mark the key as having a
* public part for later use; import the full pair explicitly. */
wc_ed25519_free(&ed25519Key);
ed25519Init = 0;
if (wc_ed25519_init(&ed25519Key) != 0) { result = -965; goto done; }
ed25519Init = 1;
if (wc_ed25519_import_private_key(ed25519Seed, sizeof(ed25519Seed),
ed25519Pub, ed25519PubSz, &ed25519Key) != 0) {
result = -966; goto done;
}
/* Build the OpenSSH-key-v1 envelope:
* magic "openssh-key-v1\0", string ciphername, string kdfname,
* string kdfoptions, uint32 keycount, string pubkeyblob,
* string { checkint1, checkint2, { string type, string pub,
* string priv, string comment } x keycount, padding } */
compositePubSz = params.mldsaPubSz + params.tradPubSz;
compositePrivSz = MLDSA_SEED_SZ + ED25519_KEY_SIZE;
pubBlobSz = UINT32_SZ + keyTypeNameSz + UINT32_SZ + compositePubSz;
privKeysStrSz = UINT32_SZ * 2 /* checkints */
+ UINT32_SZ + keyTypeNameSz
+ UINT32_SZ + compositePubSz
+ UINT32_SZ + compositePrivSz
+ UINT32_SZ + commentSz;
padSz = (MIN_BLOCK_SZ - (privKeysStrSz % MIN_BLOCK_SZ)) % MIN_BLOCK_SZ;
privKeysStrSz += padSz;
fileSz = (word32)WSTRLEN(magic) + 1
+ UINT32_SZ + noneSz /* ciphername */
+ UINT32_SZ + noneSz /* kdfname */
+ UINT32_SZ /* kdfoptions (empty) */
+ UINT32_SZ /* keycount */
+ UINT32_SZ + pubBlobSz
+ UINT32_SZ + privKeysStrSz;
file = (byte*)WMALLOC(fileSz, NULL, 0);
if (file == NULL) { result = -967; goto done; }
off = 0;
WMEMCPY(file + off, magic, WSTRLEN(magic) + 1); off += (word32)WSTRLEN(
magic) + 1;
MlDsaTest_PutLen(file + off, noneSz); off += UINT32_SZ;
WMEMCPY(file + off, none, noneSz); off += noneSz;
MlDsaTest_PutLen(file + off, noneSz); off += UINT32_SZ;
WMEMCPY(file + off, none, noneSz); off += noneSz;
MlDsaTest_PutLen(file + off, 0); off += UINT32_SZ; /* kdfoptions */
MlDsaTest_PutLen(file + off, 1); off += UINT32_SZ; /* keycount */
MlDsaTest_PutLen(file + off, pubBlobSz); off += UINT32_SZ;
MlDsaTest_PutLen(file + off, keyTypeNameSz); off += UINT32_SZ;
WMEMCPY(file + off, keyTypeName, keyTypeNameSz); off += keyTypeNameSz;
MlDsaTest_PutLen(file + off, compositePubSz); off += UINT32_SZ;
WMEMCPY(file + off, mldsaPub, mldsaPubSz); off += mldsaPubSz;
WMEMCPY(file + off, ed25519Pub, ed25519PubSz); off += ed25519PubSz;
MlDsaTest_PutLen(file + off, privKeysStrSz); off += UINT32_SZ;
MlDsaTest_PutLen(file + off, 0xC0FFEEEE); off += UINT32_SZ; /* checkint1 */
MlDsaTest_PutLen(file + off, 0xC0FFEEEE); off += UINT32_SZ; /* checkint2 */
MlDsaTest_PutLen(file + off, keyTypeNameSz); off += UINT32_SZ;
WMEMCPY(file + off, keyTypeName, keyTypeNameSz); off += keyTypeNameSz;
compPubOff2 = off;
MlDsaTest_PutLen(file + off, compositePubSz); off += UINT32_SZ;
WMEMCPY(file + off, mldsaPub, mldsaPubSz); off += mldsaPubSz;
WMEMCPY(file + off, ed25519Pub, ed25519PubSz); off += ed25519PubSz;
compPrivOff = off;
MlDsaTest_PutLen(file + off, compositePrivSz); off += UINT32_SZ;
WMEMCPY(file + off, mldsaSeed, MLDSA_SEED_SZ); off += MLDSA_SEED_SZ;
WMEMCPY(file + off, ed25519Seed, ED25519_KEY_SIZE); off += ED25519_KEY_SIZE;
MlDsaTest_PutLen(file + off, commentSz); off += UINT32_SZ;
for (i = 1; i <= padSz; i++) {
file[off++] = (byte)i;
}
if (off != fileSz) { result = -968; goto done; }
MlDsaTest_ResetKeySig(&keySig);
WMEMSET(&authData, 0, sizeof(authData));
authData.sf.publicKey.privateKey = file;
authData.sf.publicKey.privateKeySz = fileSz;
authData.sf.publicKey.hasSignature = 0;
{
word32 payloadSz = 0;
ret = wolfSSH_TestPrepareUserAuthRequestMlDsaComposite(ssh, &payloadSz,
&authData, &keySig);
}
if (ret != WS_SUCCESS) {
printf("PrepareUserAuthRequestMlDsaComposite OpenSSH envelope "
"decode failed: ret=%d\n", ret);
result = -969; goto done;
}
/* Confirm the decoded key is the one that was actually encoded, not
* just that decoding didn't crash. */
roundTripPubSz = sizeof(roundTripPub);
if (wc_MlDsaKey_ExportPubRaw(&keySig.ks.mldsa_composite.mldsa,
roundTripPub, &roundTripPubSz) != 0
|| roundTripPubSz != mldsaPubSz
|| WMEMCMP(roundTripPub, mldsaPub, mldsaPubSz) != 0) {
printf("PrepareUserAuthRequestMlDsaComposite OpenSSH envelope: "
"ML-DSA public key round-trip mismatch\n");
result = -970;
}
wolfSSH_KEY_clean(&keySig);
/* Negative test: shrinking compositePubSz by 1 in the private section's copy */
MlDsaTest_PutLen(file + compPubOff2, compositePubSz - 1);
{
word32 payloadSz = 0;
MlDsaTest_ResetKeySig(&keySig);
ret = wolfSSH_TestPrepareUserAuthRequestMlDsaComposite(ssh, &payloadSz,
&authData, &keySig);
if (ret >= 0) {
printf("PrepareUserAuthRequestMlDsaComposite: expected failure for shrunken pub blob, got %d\n", ret);
result = -971;
}
/* A parse failure can still leave a partially-initialized sub-key;
* clean unconditionally so it can't leak into the next call. */
wolfSSH_KEY_clean(&keySig);
}
MlDsaTest_PutLen(file + compPubOff2, compositePubSz); /* restore */
/* Negative test: extending compositePrivSz by 1 in the private section */
MlDsaTest_PutLen(file + compPrivOff, compositePrivSz + 1);
{
word32 payloadSz = 0;
MlDsaTest_ResetKeySig(&keySig);
ret = wolfSSH_TestPrepareUserAuthRequestMlDsaComposite(ssh, &payloadSz,
&authData, &keySig);
if (ret >= 0) {
printf("PrepareUserAuthRequestMlDsaComposite: expected failure for enlarged priv blob, got %d\n", ret);
result = -972;
}
wolfSSH_KEY_clean(&keySig);
}
MlDsaTest_PutLen(file + compPrivOff, compositePrivSz); /* restore */
done:
if (signingKeyInit) wc_MlDsaKey_Free(&signingKey);
if (ed25519Init) wc_ed25519_free(&ed25519Key);
if (rngInit) wc_FreeRng(&rng);
if (mldsaPub != NULL) WFREE(mldsaPub, NULL, 0);
if (ed25519Pub != NULL) WFREE(ed25519Pub, NULL, 0);
if (file != NULL) WFREE(file, NULL, 0);
if (ssh != NULL) wolfSSH_free(ssh);
if (ctx != NULL) wolfSSH_CTX_free(ctx);
return result;
#else
return 0;
#endif
}
#endif /* WOLFSSH_NO_MLDSA_COMPOSITES */
/* Test client signer against server parser. */
#ifdef WOLFSSH_KEYGEN
#ifndef WOLFSSH_NO_MLDSA_COMPOSITES
static int test_BuildUserAuthRequestMlDsaComposite_Params(
const char* keyTypeName, word32 level, word32 tradType, byte keyId)
{
static const char username[] = "wolfssh";
static const char serviceName[] = "ssh-connection";
static const char authName[] = "publickey";
const word32 keyTypeNameSz = (word32)(WSTRLEN(keyTypeName));
const word32 usernameSz = (word32)(sizeof(username) - 1);
const word32 serviceNameSz = (word32)(sizeof(serviceName) - 1);
const word32 authNameSz = (word32)(sizeof(authName) - 1);
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
CompositeParams params;
WS_KeySignature keySig;
WS_UserAuthData authData;
const CompositeTradOps* ops;
int prepared = 0;
byte* privKey = NULL;
word32 privKeySz;
byte* mldsaPub = NULL;
byte* tradPub = NULL;
byte* pubKeyBlob = NULL;
byte* packet = NULL;
word32 pubKeyBlobSz = 0;
word32 dataToSignSz = 0;
word32 packetSz;
word32 packetBufSz;
word32 off;
word32 pubBlobTagOff;
word32 payloadSz = 0;
word32 idx;
int result = 0;
int ret;
WMEMSET(&keySig, 0, sizeof(keySig));
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL) return -980;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -981; goto done; }
ssh->sessionIdSz = 16;
WMEMSET(ssh->sessionId, 0xA5, ssh->sessionIdSz);
ret = WS_GetCompositeParams(keyId, &params);
if (ret != WS_SUCCESS) { result = -982; goto done; }
privKey = (byte*)WMALLOC(8192, NULL, 0);
if (privKey == NULL) { result = -983; goto done; }
ret = wolfSSH_MakeMlDsaCompositeKey(privKey, 8192, level, tradType);
if (ret < 0) { result = -984; goto done; }
privKeySz = (word32)ret;
{
byte* decodedPrivKey = NULL;
word32 decodedPrivKeySz = 0;
const byte* outType = NULL;
word32 outTypeSz = 0;
ret = wolfSSH_ReadKey_buffer(privKey, privKeySz, WOLFSSH_FORMAT_OPENSSH,
&decodedPrivKey, &decodedPrivKeySz, &outType, &outTypeSz, NULL);
if (ret != WS_SUCCESS) {
printf("BuildUserAuthRequestMlDsaComposite (%s): "
"ReadKey_buffer failed ret=%d\n", keyTypeName, ret);
result = -984; goto done;
}
WMEMCPY(privKey, decodedPrivKey, decodedPrivKeySz);
privKeySz = decodedPrivKeySz;
WFREE(decodedPrivKey, NULL, DYNTYPE_PRIVKEY);
}
keySig.keyId = keyId;
keySig.heap = NULL;
WMEMSET(&authData, 0, sizeof(authData));
authData.sf.publicKey.privateKey = privKey;
authData.sf.publicKey.privateKeySz = privKeySz;
authData.sf.publicKey.hasSignature = 1;
authData.sf.publicKey.publicKeyType = (const byte*)keyTypeName;
authData.sf.publicKey.publicKeyTypeSz = keyTypeNameSz;
ret = wolfSSH_TestPrepareUserAuthRequestMlDsaComposite(ssh, &payloadSz,
&authData, &keySig);
if (ret != WS_SUCCESS) {
printf("BuildUserAuthRequestMlDsaComposite (%s): prepare failed "
"ret=%d\n", keyTypeName, ret);
result = -985; goto done;
}
prepared = 1;
mldsaPub = (byte*)WMALLOC(params.mldsaPubSz, NULL, 0);
tradPub = (byte*)WMALLOC(params.tradPubSz, NULL, 0);
if (mldsaPub == NULL || tradPub == NULL) { result = -986; goto done; }
{
word32 sz = params.mldsaPubSz;
if (wc_MlDsaKey_ExportPubRaw(&keySig.ks.mldsa_composite.mldsa,
mldsaPub, &sz) != 0 || sz != params.mldsaPubSz) {
result = -987; goto done;
}
}
ops = WS_GetTradOps(params.tradType);
if (ops == NULL) { result = -988; goto done; }
{
word32 sz = params.tradPubSz;
if (ops->exportPub(&keySig.ks.mldsa_composite.trad, tradPub, &sz)
!= 0 || sz != params.tradPubSz) {
result = -989; goto done;
}
}
pubKeyBlobSz = UINT32_SZ * 2 + keyTypeNameSz +
params.mldsaPubSz + params.tradPubSz;
pubKeyBlob = (byte*)WMALLOC(pubKeyBlobSz, NULL, 0);
if (pubKeyBlob == NULL) { result = -990; goto done; }
off = 0;
MlDsaTest_PutLen(pubKeyBlob + off, keyTypeNameSz); off += UINT32_SZ;
WMEMCPY(pubKeyBlob + off, keyTypeName, keyTypeNameSz);
off += keyTypeNameSz;
pubBlobTagOff = off;
MlDsaTest_PutLen(pubKeyBlob + off, params.mldsaPubSz + params.tradPubSz);
off += UINT32_SZ;
WMEMCPY(pubKeyBlob + off, mldsaPub, params.mldsaPubSz);
off += params.mldsaPubSz;
WMEMCPY(pubKeyBlob + off, tradPub, params.tradPubSz);
off += params.tradPubSz;
dataToSignSz = UINT32_SZ * 5 + usernameSz + serviceNameSz + authNameSz +
1 + keyTypeNameSz + pubKeyBlobSz;
packetSz = MSG_ID_SZ + dataToSignSz;
packetBufSz = packetSz + UINT32_SZ * 2 + keyTypeNameSz + keySig.sigSz
+ 32;
packet = (byte*)WMALLOC(packetBufSz, NULL, 0);
if (packet == NULL) { result = -991; goto done; }
off = 0;
packet[off++] = MSGID_USERAUTH_REQUEST;
MlDsaTest_PutLen(packet + off, usernameSz); off += UINT32_SZ;
WMEMCPY(packet + off, username, usernameSz); off += usernameSz;
MlDsaTest_PutLen(packet + off, serviceNameSz); off += UINT32_SZ;
WMEMCPY(packet + off, serviceName, serviceNameSz); off += serviceNameSz;
MlDsaTest_PutLen(packet + off, authNameSz); off += UINT32_SZ;
WMEMCPY(packet + off, authName, authNameSz); off += authNameSz;
packet[off++] = 1;
MlDsaTest_PutLen(packet + off, keyTypeNameSz); off += UINT32_SZ;
WMEMCPY(packet + off, keyTypeName, keyTypeNameSz); off += keyTypeNameSz;
MlDsaTest_PutLen(packet + off, pubKeyBlobSz); off += UINT32_SZ;
WMEMCPY(packet + off, pubKeyBlob, pubKeyBlobSz); off += pubKeyBlobSz;
if (off != packetSz) { result = -992; goto done; }
idx = packetSz;
ret = wolfSSH_TestBuildUserAuthRequestMlDsaComposite(ssh, packet, &idx,
&authData, packet, 0, &keySig);
if (ret != WS_SUCCESS) {
printf("BuildUserAuthRequestMlDsaComposite (%s): build failed "
"ret=%d\n", keyTypeName, ret);
result = -993; goto done;
}
/* Build appends string(string(type) + string(sig)); Do expects
* pk->signature to be the inner content, without that outer length
* prefix. */
authData.username = (const byte*)username;
authData.usernameSz = usernameSz;
authData.serviceName = (const byte*)serviceName;
authData.serviceNameSz = serviceNameSz;
authData.authName = (const byte*)authName;
authData.authNameSz = authNameSz;
authData.sf.publicKey.dataToSign = packet + MSG_ID_SZ;
authData.sf.publicKey.publicKey = pubKeyBlob;
authData.sf.publicKey.publicKeySz = pubKeyBlobSz;
authData.sf.publicKey.signature = packet + packetSz + LENGTH_SZ;
authData.sf.publicKey.signatureSz = idx - packetSz - LENGTH_SZ;
ret = wolfSSH_TestDoUserAuthRequestMlDsaComposite(ssh, &authData, keyId,
pubKeyBlobSz);
if (ret != WS_SUCCESS) {
printf("BuildUserAuthRequestMlDsaComposite (%s): verify of built "
"signature failed ret=%d\n", keyTypeName, ret);
result = -994;
}
/* Negative test: shrink composite pub key length tag */
MlDsaTest_PutLen(pubKeyBlob + pubBlobTagOff, params.mldsaPubSz + params.tradPubSz - 1);
ret = wolfSSH_TestDoUserAuthRequestMlDsaComposite(ssh, &authData, keyId,
pubKeyBlobSz);
if (ret >= 0) {
printf("BuildUserAuthRequestMlDsaComposite (%s): verify of shrunken "
"blob succeeded\n", keyTypeName);
result = -995;
}
MlDsaTest_PutLen(pubKeyBlob + pubBlobTagOff, params.mldsaPubSz + params.tradPubSz);
done:
if (prepared) {
wolfSSH_KEY_clean(&keySig);
}
if (privKey != NULL) WFREE(privKey, NULL, 0);
if (mldsaPub != NULL) WFREE(mldsaPub, NULL, 0);
if (tradPub != NULL) WFREE(tradPub, NULL, 0);
if (pubKeyBlob != NULL) WFREE(pubKeyBlob, NULL, 0);
if (packet != NULL) WFREE(packet, NULL, 0);
if (ssh != NULL) wolfSSH_free(ssh);
if (ctx != NULL) wolfSSH_CTX_free(ctx);
return result;
}
static int test_BuildUserAuthRequestMlDsaComposite(void)
{
int ret = 0;
#ifndef WOLFSSH_NO_MLDSA44_ES256
ret = test_BuildUserAuthRequestMlDsaComposite_Params(
"ssh-mldsa44-es256@wolfssl.com", WOLFSSH_MLDSAKEY_44,
WOLFSSH_COMPOSITE_TRAD_ECDSA, ID_MLDSA44_ES256);
if (ret != 0) return ret;
#endif
#ifndef WOLFSSH_NO_MLDSA65_ES256
ret = test_BuildUserAuthRequestMlDsaComposite_Params(
"ssh-mldsa65-es256@wolfssl.com", WOLFSSH_MLDSAKEY_65,
WOLFSSH_COMPOSITE_TRAD_ECDSA, ID_MLDSA65_ES256);
if (ret != 0) return ret;
#endif
#ifndef WOLFSSH_NO_MLDSA87_ES384
ret = test_BuildUserAuthRequestMlDsaComposite_Params(
"ssh-mldsa87-es384@wolfssl.com", WOLFSSH_MLDSAKEY_87,
WOLFSSH_COMPOSITE_TRAD_ECDSA, ID_MLDSA87_ES384);
if (ret != 0) return ret;
#endif
#ifndef WOLFSSH_NO_MLDSA44_ED25519
ret = test_BuildUserAuthRequestMlDsaComposite_Params(
"ssh-mldsa44-ed25519@openssh.com", WOLFSSH_MLDSAKEY_44,
WOLFSSH_COMPOSITE_TRAD_ED25519, ID_MLDSA44_ED25519);
if (ret != 0) return ret;
#endif
#ifndef WOLFSSH_NO_MLDSA65_ED25519
ret = test_BuildUserAuthRequestMlDsaComposite_Params(
"ssh-mldsa65-ed25519@wolfssl.com", WOLFSSH_MLDSAKEY_65,
WOLFSSH_COMPOSITE_TRAD_ED25519, ID_MLDSA65_ED25519);
if (ret != 0) return ret;
#endif
#ifndef WOLFSSH_NO_MLDSA87_ED448
ret = test_BuildUserAuthRequestMlDsaComposite_Params(
"ssh-mldsa87-ed448@wolfssl.com", WOLFSSH_MLDSAKEY_87,
WOLFSSH_COMPOSITE_TRAD_ED448, ID_MLDSA87_ED448);
if (ret != 0) return ret;
#endif
return 0;
}
#endif /* WOLFSSH_NO_MLDSA_COMPOSITES */
#endif /* WOLFSSH_KEYGEN */
#ifndef WOLFSSH_NO_MLDSA_COMPOSITES
static int test_DoUserAuthRequestMlDsaComposite(void)
{
int ret = 0;
#ifndef WOLFSSH_NO_MLDSA44_ES256
ret = test_DoUserAuthRequestMlDsaComposite_Params("ssh-mldsa44-es256@wolfssl.com",
ID_MLDSA44_ES256, 0);
if (ret != 0) return ret;
ret = test_DoUserAuthRequestMlDsaComposite_Params("ssh-mldsa44-es256@wolfssl.com",
ID_MLDSA44_ES256, 1);
if (ret != 0) return ret;
ret = test_DoUserAuthRequestMlDsaComposite_Params("ssh-mldsa44-es256@wolfssl.com",
ID_MLDSA44_ES256, 2);
if (ret != 0) return ret;
ret = test_DoUserAuthRequestMlDsaComposite_Params("ssh-mldsa44-es256@wolfssl.com",
ID_MLDSA44_ES256, 3);
if (ret != 0) return ret;
ret = test_DoUserAuthRequestMlDsaComposite_Params("ssh-mldsa44-es256@wolfssl.com",
ID_MLDSA44_ES256, 4);
if (ret != 0) return ret;
#endif
#ifndef WOLFSSH_NO_MLDSA65_ES256
ret = test_DoUserAuthRequestMlDsaComposite_Params("ssh-mldsa65-es256@wolfssl.com",
ID_MLDSA65_ES256, 0);
if (ret != 0) return ret;
ret = test_DoUserAuthRequestMlDsaComposite_Params("ssh-mldsa65-es256@wolfssl.com",
ID_MLDSA65_ES256, 1);
if (ret != 0) return ret;
ret = test_DoUserAuthRequestMlDsaComposite_Params("ssh-mldsa65-es256@wolfssl.com",
ID_MLDSA65_ES256, 2);
if (ret != 0) return ret;
ret = test_DoUserAuthRequestMlDsaComposite_Params("ssh-mldsa65-es256@wolfssl.com",
ID_MLDSA65_ES256, 3);
if (ret != 0) return ret;
ret = test_DoUserAuthRequestMlDsaComposite_Params("ssh-mldsa65-es256@wolfssl.com",
ID_MLDSA65_ES256, 4);
if (ret != 0) return ret;
#endif
#ifndef WOLFSSH_NO_MLDSA87_ES384
ret = test_DoUserAuthRequestMlDsaComposite_Params("ssh-mldsa87-es384@wolfssl.com",
ID_MLDSA87_ES384, 0);
if (ret != 0) return ret;
ret = test_DoUserAuthRequestMlDsaComposite_Params("ssh-mldsa87-es384@wolfssl.com",
ID_MLDSA87_ES384, 1);
if (ret != 0) return ret;
ret = test_DoUserAuthRequestMlDsaComposite_Params("ssh-mldsa87-es384@wolfssl.com",
ID_MLDSA87_ES384, 2);
if (ret != 0) return ret;
ret = test_DoUserAuthRequestMlDsaComposite_Params("ssh-mldsa87-es384@wolfssl.com",
ID_MLDSA87_ES384, 3);
if (ret != 0) return ret;
ret = test_DoUserAuthRequestMlDsaComposite_Params("ssh-mldsa87-es384@wolfssl.com",
ID_MLDSA87_ES384, 4);
if (ret != 0) return ret;
#endif
#ifndef WOLFSSH_NO_MLDSA44_ED25519
ret = test_DoUserAuthRequestMlDsaComposite_Params(
"ssh-mldsa44-ed25519@openssh.com", ID_MLDSA44_ED25519, 0);
if (ret != 0) return ret;
ret = test_DoUserAuthRequestMlDsaComposite_Params(
"ssh-mldsa44-ed25519@openssh.com", ID_MLDSA44_ED25519, 1);
if (ret != 0) return ret;
ret = test_DoUserAuthRequestMlDsaComposite_Params(
"ssh-mldsa44-ed25519@openssh.com", ID_MLDSA44_ED25519, 2);
if (ret != 0) return ret;
ret = test_DoUserAuthRequestMlDsaComposite_Params(
"ssh-mldsa44-ed25519@openssh.com", ID_MLDSA44_ED25519, 3);
if (ret != 0) return ret;
ret = test_DoUserAuthRequestMlDsaComposite_Params(
"ssh-mldsa44-ed25519@openssh.com", ID_MLDSA44_ED25519, 4);
if (ret != 0) return ret;
#endif
#ifndef WOLFSSH_NO_MLDSA65_ED25519
ret = test_DoUserAuthRequestMlDsaComposite_Params("ssh-mldsa65-ed25519@wolfssl.com",
ID_MLDSA65_ED25519, 0);
if (ret != 0) return ret;
ret = test_DoUserAuthRequestMlDsaComposite_Params("ssh-mldsa65-ed25519@wolfssl.com",
ID_MLDSA65_ED25519, 1);
if (ret != 0) return ret;
ret = test_DoUserAuthRequestMlDsaComposite_Params("ssh-mldsa65-ed25519@wolfssl.com",
ID_MLDSA65_ED25519, 2);
if (ret != 0) return ret;
ret = test_DoUserAuthRequestMlDsaComposite_Params("ssh-mldsa65-ed25519@wolfssl.com",
ID_MLDSA65_ED25519, 3);
if (ret != 0) return ret;
ret = test_DoUserAuthRequestMlDsaComposite_Params("ssh-mldsa65-ed25519@wolfssl.com",
ID_MLDSA65_ED25519, 4);
if (ret != 0) return ret;
#endif
#ifndef WOLFSSH_NO_MLDSA87_ED448
ret = test_DoUserAuthRequestMlDsaComposite_Params("ssh-mldsa87-ed448@wolfssl.com",
ID_MLDSA87_ED448, 0);
if (ret != 0) return ret;
ret = test_DoUserAuthRequestMlDsaComposite_Params("ssh-mldsa87-ed448@wolfssl.com",
ID_MLDSA87_ED448, 1);
if (ret != 0) return ret;
ret = test_DoUserAuthRequestMlDsaComposite_Params("ssh-mldsa87-ed448@wolfssl.com",
ID_MLDSA87_ED448, 2);
if (ret != 0) return ret;
ret = test_DoUserAuthRequestMlDsaComposite_Params("ssh-mldsa87-ed448@wolfssl.com",
ID_MLDSA87_ED448, 3);
if (ret != 0) return ret;
ret = test_DoUserAuthRequestMlDsaComposite_Params("ssh-mldsa87-ed448@wolfssl.com",
ID_MLDSA87_ED448, 4);
if (ret != 0) return ret;
#endif
return 0;
}
#endif /* WOLFSSH_NO_MLDSA_COMPOSITES */
#ifdef WOLFSSH_KEYGEN
static int test_PrepareUserAuthRequestMlDsa(void)
{
int ret = 0;
#ifndef WOLFSSH_NO_MLDSA44
ret = test_PrepareUserAuthRequestMlDsa_Params(WOLFSSH_MLDSAKEY_44,
ID_MLDSA44, WC_MLDSA_44_BOTH_KEY_DER_SIZE);
if (ret != 0) return ret;
#endif
#ifndef WOLFSSH_NO_MLDSA65
ret = test_PrepareUserAuthRequestMlDsa_Params(WOLFSSH_MLDSAKEY_65,
ID_MLDSA65, WC_MLDSA_65_BOTH_KEY_DER_SIZE);
if (ret != 0) return ret;
#endif
#ifndef WOLFSSH_NO_MLDSA87
ret = test_PrepareUserAuthRequestMlDsa_Params(WOLFSSH_MLDSAKEY_87,
ID_MLDSA87, WC_MLDSA_87_BOTH_KEY_DER_SIZE);
if (ret != 0) return ret;
#endif
(void)ret;
return 0;
}
#ifdef WOLFSSH_CERTS
static int test_PrepareUserAuthRequestMlDsaCert_Params(word32 keygenLevel,
byte keyId, int derBufSz)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WS_UserAuthData authData;
WS_KeySignature keySig;
byte* derKey = NULL;
word32 payloadSz;
int derKeySz;
int result = 0;
int ret;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL) return -920;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -921; goto done; }
derKey = (byte*)WMALLOC(derBufSz, NULL, 0);
if (derKey == NULL) { result = -922; goto done; }
derKeySz = wolfSSH_MakeMlDsaKey(derKey, (word32)derBufSz, keygenLevel);
if (derKeySz < 0) { result = -923; goto done; }
/* Success path: good key, hasSignature=0 */
WMEMSET(&authData, 0, sizeof(authData));
WMEMSET(&keySig, 0, sizeof(keySig));
payloadSz = 0;
authData.sf.publicKey.privateKey = derKey;
authData.sf.publicKey.privateKeySz = (word32)derKeySz;
authData.sf.publicKey.hasSignature = 0;
keySig.keyId = keyId;
keySig.heap = NULL;
ret = wolfSSH_TestPrepareUserAuthRequestMlDsaCert(ssh, &payloadSz,
&authData, &keySig);
if (ret != WS_SUCCESS) { result = -924; goto done; }
wc_MlDsaKey_Free(&keySig.ks.mldsa.key);
/* Bad key: exercises the PrivateKeyDecode failure free path */
{
static const byte badKey[] = { 0xFF, 0xFE, 0x00, 0x01 };
WMEMSET(&authData, 0, sizeof(authData));
WMEMSET(&keySig, 0, sizeof(keySig));
payloadSz = 0;
authData.sf.publicKey.privateKey = badKey;
authData.sf.publicKey.privateKeySz = sizeof(badKey);
authData.sf.publicKey.hasSignature = 0;
keySig.keyId = keyId;
keySig.heap = NULL;
ret = wolfSSH_TestPrepareUserAuthRequestMlDsaCert(ssh, &payloadSz,
&authData, &keySig);
if (ret == WS_SUCCESS) { result = -925; goto done; }
}
/* hasSignature=1 path: exercises sigSz accumulation */
{
WMEMSET(&authData, 0, sizeof(authData));
WMEMSET(&keySig, 0, sizeof(keySig));
payloadSz = 0;
authData.sf.publicKey.privateKey = derKey;
authData.sf.publicKey.privateKeySz = (word32)derKeySz;
authData.sf.publicKey.hasSignature = 1;
keySig.keyId = keyId;
keySig.heap = NULL;
ret = wolfSSH_TestPrepareUserAuthRequestMlDsaCert(ssh, &payloadSz,
&authData, &keySig);
if (ret != WS_SUCCESS) {
wc_MlDsaKey_Free(&keySig.ks.mldsa.key);
result = -926; goto done;
}
if (keySig.sigSz == 0) {
wc_MlDsaKey_Free(&keySig.ks.mldsa.key);
result = -927; goto done;
}
if (payloadSz == 0) {
wc_MlDsaKey_Free(&keySig.ks.mldsa.key);
result = -928; goto done;
}
wc_MlDsaKey_Free(&keySig.ks.mldsa.key);
}
done:
WFREE(derKey, NULL, 0);
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
static int test_PrepareUserAuthRequestMlDsaCert(void)
{
int ret = 0;
#ifndef WOLFSSH_NO_MLDSA44
ret = test_PrepareUserAuthRequestMlDsaCert_Params(WOLFSSH_MLDSAKEY_44,
ID_X509V3_MLDSA44, WC_MLDSA_44_BOTH_KEY_DER_SIZE);
if (ret != 0) return ret;
#endif
#ifndef WOLFSSH_NO_MLDSA65
ret = test_PrepareUserAuthRequestMlDsaCert_Params(WOLFSSH_MLDSAKEY_65,
ID_X509V3_MLDSA65, WC_MLDSA_65_BOTH_KEY_DER_SIZE);
if (ret != 0) return ret;
#endif
#ifndef WOLFSSH_NO_MLDSA87
ret = test_PrepareUserAuthRequestMlDsaCert_Params(WOLFSSH_MLDSAKEY_87,
ID_X509V3_MLDSA87, WC_MLDSA_87_BOTH_KEY_DER_SIZE);
if (ret != 0) return ret;
#endif
(void)ret;
return 0;
}
#endif /* WOLFSSH_CERTS */
#endif /* WOLFSSH_KEYGEN */
static int test_BuildUserAuthRequestMlDsa(void)
{
#ifndef WOLFSSH_NO_MLDSA44
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WS_KeySignature keySig;
WS_UserAuthData authData;
byte output[MLDSA_MAX_SIG_SIZE + 256];
word32 idx = 0;
word32 idx0 = 0;
word32 idxBefore = 0;
int sigSz;
int result = 0;
int ret;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL) { result = -700; goto done; }
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -701; goto done; }
ssh->sessionIdSz = 16;
WMEMSET(ssh->sessionId, 0xA5, ssh->sessionIdSz);
WMEMSET(&keySig, 0, sizeof(keySig));
keySig.keyId = ID_MLDSA44;
keySig.heap = NULL;
ret = wc_MlDsaKey_Init(&keySig.ks.mldsa.key, NULL, INVALID_DEVID);
if (ret != 0) { result = -702; goto done; }
{
word32 kidx = 0;
ret = wc_MlDsaKey_PrivateKeyDecode(&keySig.ks.mldsa.key,
unitTestMlDsaPrivKey,
(word32)sizeof(unitTestMlDsaPrivKey), &kidx);
}
if (ret != 0) {
wc_MlDsaKey_Free(&keySig.ks.mldsa.key);
result = -703;
goto done;
}
sigSz = wc_MlDsaKey_SigSize(&keySig.ks.mldsa.key);
if (sigSz < 0) {
wc_MlDsaKey_Free(&keySig.ks.mldsa.key);
result = -704;
goto done;
}
keySig.sigSz = (word32)sigSz;
WMEMSET(&authData, 0, sizeof(authData));
authData.sf.publicKey.hasSignature = 1;
authData.sf.publicKey.publicKeyType = (const byte*)"ssh-mldsa-44";
authData.sf.publicKey.publicKeyTypeSz = 12;
/* Write minimal auth-request header so (begin - sigStartIdx) > 0. */
{
static const char testUser[] = "user";
static const char testSvc[] = "ssh-connection";
static const char testMethod[] = "publickey";
output[idx++] = MSGID_USERAUTH_REQUEST;
MlDsaTest_PutLen(output + idx, (word32)WSTRLEN(testUser));
idx += UINT32_SZ;
WMEMCPY(output + idx, testUser, WSTRLEN(testUser));
idx += (word32)WSTRLEN(testUser);
MlDsaTest_PutLen(output + idx, (word32)WSTRLEN(testSvc));
idx += UINT32_SZ;
WMEMCPY(output + idx, testSvc, WSTRLEN(testSvc));
idx += (word32)WSTRLEN(testSvc);
MlDsaTest_PutLen(output + idx, (word32)WSTRLEN(testMethod));
idx += UINT32_SZ;
WMEMCPY(output + idx, testMethod, WSTRLEN(testMethod));
idx += (word32)WSTRLEN(testMethod);
}
idxBefore = idx;
ret = wolfSSH_TestBuildUserAuthRequestMlDsa(ssh, output, &idx,
&authData, output, idx0, &keySig);
wc_MlDsaKey_Free(&keySig.ks.mldsa.key);
if (ret != WS_SUCCESS) {
printf("BuildUserAuthRequestMlDsa failed: %d\n", ret);
result = -705;
}
else {
/* 3 length fields + algo name + sig bytes */
word32 nameSz = (word32)WSTRLEN("ssh-mldsa-44");
word32 expAdv = 3 * UINT32_SZ + nameSz + (word32)sigSz;
if (idx - idxBefore != expAdv) {
printf("BuildUserAuthRequestMlDsa idx advance wrong:"
" got %d expected %d\n",
(int)(idx - idxBefore), (int)expAdv);
result = -706;
}
}
done:
if (ssh) wolfSSH_free(ssh);
if (ctx) wolfSSH_CTX_free(ctx);
return result;
#else
return 0;
#endif
}
#endif
#if !defined(WOLFSSH_NO_ECDSA) && defined(HAVE_ECC_KEY_EXPORT)
/* Private-only SEC1 DER (public point omitted): must succeed as cert may supply
* public key later. Shared across P-256/P-384/P-521.
* Return codes -667..-674 */
static int test_IdentifyAsn1Key_EccPrivOnlyDer(int curveSz,
int expectedKeyId, const char* curveName)
{
int ret;
ecc_key eccKey;
WC_RNG eccRng;
byte* eccDer = NULL;
int eccDerSz;
WMEMSET(&eccKey, 0, sizeof(eccKey));
if (wc_ecc_init(&eccKey) != 0) {
return -667;
}
if (wc_InitRng(&eccRng) != 0) {
wc_ecc_free(&eccKey);
return -668;
}
if (wc_ecc_make_key(&eccRng, curveSz, &eccKey) != 0) {
wc_FreeRng(&eccRng);
wc_ecc_free(&eccKey);
return -669;
}
wc_FreeRng(&eccRng);
eccDerSz = wc_EccKeyDerSize(&eccKey, 0);
if (eccDerSz <= 0) {
wc_ecc_free(&eccKey);
return -670;
}
eccDer = (byte*)WMALLOC((word32)eccDerSz, NULL, 0);
if (eccDer == NULL) {
wc_ecc_free(&eccKey);
return -671;
}
eccDerSz = wc_EccPrivateKeyToDer(&eccKey, eccDer, (word32)eccDerSz);
wc_ecc_free(&eccKey);
if (eccDerSz <= 0) {
WFREE(eccDer, NULL, 0);
return -672;
}
ret = IdentifyAsn1Key(eccDer, (word32)eccDerSz, 1, NULL, NULL);
if (ret != expectedKeyId) {
WFREE(eccDer, NULL, 0);
printf("IdentifyAsn1Key: private-only ECC %s DER expected "
"keyId %d, got %d\n", curveName, expectedKeyId, ret);
return -673;
}
/* Requesting populated WS_KeySignature confirms key object survives. */
{
WS_KeySignature* eccKeySig = NULL;
ret = IdentifyAsn1Key(eccDer, (word32)eccDerSz, 1, NULL,
&eccKeySig);
WFREE(eccDer, NULL, 0);
if (ret != expectedKeyId || eccKeySig == NULL ||
eccKeySig->keyId != expectedKeyId) {
printf("IdentifyAsn1Key: private-only ECC %s DER pkey-out "
"variant failed, ret=%d\n", curveName, ret);
if (eccKeySig != NULL) {
wolfSSH_KEY_clean(eccKeySig);
WFREE(eccKeySig, NULL, DYNTYPE_PRIVKEY);
}
return -674;
}
wolfSSH_KEY_clean(eccKeySig);
WFREE(eccKeySig, NULL, DYNTYPE_PRIVKEY);
}
return 0;
}
static int test_IdentifyAsn1Key_EccPrivOnlyDerFailure(int curveSz,
const char* curveName)
{
int ret;
ecc_key eccKey;
WC_RNG eccRng;
byte* eccDer = NULL;
int eccDerSz;
int i;
int expected = WS_CRYPTO_FAILED;
WMEMSET(&eccKey, 0, sizeof(eccKey));
if (wc_ecc_init(&eccKey) != 0) {
return -6932;
}
if (wc_InitRng(&eccRng) != 0) {
wc_ecc_free(&eccKey);
return -6933;
}
if (wc_ecc_make_key(&eccRng, curveSz, &eccKey) != 0) {
wc_FreeRng(&eccRng);
wc_ecc_free(&eccKey);
return -6934;
}
wc_FreeRng(&eccRng);
eccDerSz = wc_EccKeyDerSize(&eccKey, 0);
if (eccDerSz <= 0) {
wc_ecc_free(&eccKey);
return -6935;
}
eccDer = (byte*)WMALLOC((word32)eccDerSz, NULL, 0);
if (eccDer == NULL) {
wc_ecc_free(&eccKey);
return -6936;
}
eccDerSz = wc_EccPrivateKeyToDer(&eccKey, eccDer, (word32)eccDerSz);
wc_ecc_free(&eccKey);
if (eccDerSz <= 0) {
WFREE(eccDer, NULL, 0);
return -6937;
}
/* Corrupt the private scalar to force a wc_ecc_make_pub failure during
* pubkey derivation in IdentifyAsn1Key. */
for (i = 0; i < eccDerSz - curveSz - 2; i++) {
if (eccDer[i] == 0x04 && eccDer[i+1] == curveSz) {
WMEMSET(eccDer + i + 2, 0, curveSz);
break;
}
}
/* Some wolfSSL builds reject the zeroed scalar while decoding the DER,
* so IdentifyAsn1Key never reaches the derivation and reports the key
* as unidentified. Ask this build which rejection to expect. */
{
ecc_key probeKey;
word32 probeIdx = 0;
if (wc_ecc_init(&probeKey) != 0) {
WFREE(eccDer, NULL, 0);
return -6939;
}
if (wc_EccPrivateKeyDecode(eccDer, &probeIdx, &probeKey,
(word32)eccDerSz) != 0) {
expected = WS_UNIMPLEMENTED_E;
}
wc_ecc_free(&probeKey);
}
ret = IdentifyAsn1Key(eccDer, (word32)eccDerSz, 1, NULL, NULL);
WFREE(eccDer, NULL, 0);
if (ret != expected) {
printf("IdentifyAsn1Key: private-only ECC %s DER rejection expected "
"%d, got %d\n", curveName, expected, ret);
return -6938;
}
return 0;
}
#endif
#if !defined(WOLFSSH_NO_ED25519) && defined(HAVE_ED25519) && \
defined(HAVE_ED25519_MAKE_KEY) && defined(HAVE_ED25519_KEY_EXPORT)
/* Private-only DER: Ed25519 public key is deterministically derivable, so
* IdentifyAsn1Key must load it successfully.
* Return codes -675..-681 */
static int test_IdentifyAsn1Key_Ed25519PrivOnlyDer(void)
{
int ret;
ed25519_key edKey;
WC_RNG edRng;
byte* edDer = NULL;
int edDerSz;
if (wc_ed25519_init(&edKey) != 0) {
return -675;
}
if (wc_InitRng(&edRng) != 0) {
wc_ed25519_free(&edKey);
return -676;
}
if (wc_ed25519_make_key(&edRng, ED25519_KEY_SIZE, &edKey) != 0) {
wc_FreeRng(&edRng);
wc_ed25519_free(&edKey);
return -677;
}
wc_FreeRng(&edRng);
edDerSz = wc_Ed25519PrivateKeyToDer(&edKey, NULL, 0);
if (edDerSz <= 0) {
wc_ed25519_free(&edKey);
return -678;
}
edDer = (byte*)WMALLOC((word32)edDerSz, NULL, 0);
if (edDer == NULL) {
wc_ed25519_free(&edKey);
return -679;
}
edDerSz = wc_Ed25519PrivateKeyToDer(&edKey, edDer, (word32)edDerSz);
wc_ed25519_free(&edKey);
if (edDerSz <= 0) {
WFREE(edDer, NULL, 0);
return -680;
}
{
WS_KeySignature* edKeySig = NULL;
ret = IdentifyAsn1Key(edDer, (word32)edDerSz, 1, NULL, &edKeySig);
WFREE(edDer, NULL, 0);
if (ret != ID_ED25519 || edKeySig == NULL ||
edKeySig->keyId != ID_ED25519) {
printf("IdentifyAsn1Key: private-only Ed25519 DER expected "
"ID_ED25519, got %d\n", ret);
if (edKeySig != NULL) {
wolfSSH_KEY_clean(edKeySig);
WFREE(edKeySig, NULL, DYNTYPE_PRIVKEY);
}
return -681;
}
wolfSSH_KEY_clean(edKeySig);
WFREE(edKeySig, NULL, DYNTYPE_PRIVKEY);
}
return 0;
}
#endif
#if !defined(WOLFSSH_NO_ED25519) && defined(HAVE_ED25519) && \
!defined(HAVE_ED25519_MAKE_KEY)
/* Private-only Ed25519 DER must be rejected if no HAVE_ED25519_MAKE_KEY.
* Hardcoded PKCS8 DER since make_key is unavailable. */
static int test_IdentifyAsn1Key_Ed25519PrivOnlyDerNoMakeKey(void)
{
int ret;
/* SEQUENCE { version 0, AlgorithmIdentifier{Ed25519 OID},
* OCTET STRING { OCTET STRING <32-byte seed> } } */
static const byte edDer[] = {
0x30, 0x2E,
0x02, 0x01, 0x00,
0x30, 0x05, 0x06, 0x03, 0x2B, 0x65, 0x70,
0x04, 0x22,
0x04, 0x20,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10,
0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20
};
WS_KeySignature* edKeySig = NULL;
ret = IdentifyAsn1Key(edDer, (word32)sizeof(edDer), 1, NULL, &edKeySig);
if (ret != WS_CRYPTO_FAILED) {
printf("IdentifyAsn1Key: private-only Ed25519 DER expected "
"WS_CRYPTO_FAILED without HAVE_ED25519_MAKE_KEY, got %d\n",
ret);
if (edKeySig != NULL) {
wolfSSH_KEY_clean(edKeySig);
WFREE(edKeySig, NULL, DYNTYPE_PRIVKEY);
}
return -682;
}
if (edKeySig != NULL) {
printf("IdentifyAsn1Key: expected NULL keySig on rejection\n");
wolfSSH_KEY_clean(edKeySig);
WFREE(edKeySig, NULL, DYNTYPE_PRIVKEY);
return -683;
}
return 0;
}
#endif
#if !defined(WOLFSSH_NO_ED25519) && defined(HAVE_ED25519) && \
defined(HAVE_ED25519_MAKE_KEY) && defined(HAVE_ED25519_KEY_EXPORT) && \
defined(HAVE_ED25519_SIGN) && defined(HAVE_ED25519_VERIFY)
/* Mirrors KEX host-key signing fallback: decode private-only DER, let
* export_public fail, derive public key, and confirm signing/verification.
* This only proves the underlying wolfCrypt sequence; the real regression
* guard for SendKexGetSigningKey's derive fallback (Ed25519 and ECDSA) is
* the end-to-end test_pubkey_auth_ed25519_privonly_hostkey /
* test_pubkey_auth_ecdsa_privonly_hostkey in tests/auth.c.
* Return codes -682..-691. Mutually exclusive with
* test_IdentifyAsn1Key_Ed25519PrivOnlyDerNoMakeKey, which reuses -682/-683. */
static int test_Ed25519KexDeriveFallback(void)
{
ed25519_key edKey;
WC_RNG edRng;
byte der[128];
int derSz;
word32 idx = 0;
ed25519_key kexKey;
byte q[ED25519_PUB_KEY_SIZE];
word32 qSz = sizeof(q);
byte sig[ED25519_SIG_SIZE];
word32 sigSz = sizeof(sig);
const byte msg[] = "wolfSSH KEX derive-fallback test message";
int verifyRes = 0;
WMEMSET(&edKey, 0, sizeof(edKey));
if (wc_ed25519_init(&edKey) != 0) {
return -682;
}
if (wc_InitRng(&edRng) != 0) {
wc_ed25519_free(&edKey);
return -683;
}
if (wc_ed25519_make_key(&edRng, ED25519_KEY_SIZE, &edKey) != 0) {
wc_FreeRng(&edRng);
wc_ed25519_free(&edKey);
return -684;
}
wc_FreeRng(&edRng);
derSz = wc_Ed25519PrivateKeyToDer(&edKey, der, sizeof(der));
wc_ed25519_free(&edKey);
if (derSz <= 0) {
return -685;
}
/* KEX sequence: fresh decode, export_public, then fallback. */
WMEMSET(&kexKey, 0, sizeof(kexKey));
if (wc_ed25519_init(&kexKey) != 0) {
return -686;
}
if (wc_Ed25519PrivateKeyDecode(der, &idx, &kexKey,
(word32)derSz) != 0) {
wc_ed25519_free(&kexKey);
return -687;
}
if (wc_ed25519_export_public(&kexKey, q, &qSz) == 0) {
/* Public key derived during decode; fallback not needed. */
wc_ed25519_free(&kexKey);
return 0;
}
/* trusted=1: matches production (src/internal.c). */
if (wc_ed25519_make_public(&kexKey, q, ED25519_PUB_KEY_SIZE) != 0 ||
wc_ed25519_import_public_ex(q, ED25519_PUB_KEY_SIZE, &kexKey,
1) != 0) {
wc_ed25519_free(&kexKey);
printf("test_Ed25519KexDeriveFallback: derive/import failed\n");
return -689;
}
if (wc_ed25519_sign_msg(msg, sizeof(msg), sig, &sigSz, &kexKey) != 0) {
wc_ed25519_free(&kexKey);
printf("test_Ed25519KexDeriveFallback: sign failed\n");
return -690;
}
if (wc_ed25519_verify_msg(sig, sigSz, msg, sizeof(msg), &verifyRes,
&kexKey) != 0 || verifyRes != 1) {
wc_ed25519_free(&kexKey);
printf("test_Ed25519KexDeriveFallback: verify failed\n");
return -691;
}
wc_ed25519_free(&kexKey);
return 0;
}
/* Failure path: wc_ed25519_make_public() must fail cleanly (not fabricate
* a key) when handed an undersized output buffer.
* Return codes -6920..-6926 */
static int test_Ed25519KexDeriveFallbackFailure(void)
{
ed25519_key edKey;
WC_RNG edRng;
byte der[128];
int derSz;
word32 idx = 0;
ed25519_key kexKey;
byte q[ED25519_PUB_KEY_SIZE];
word32 qSz = sizeof(q);
WMEMSET(&edKey, 0, sizeof(edKey));
if (wc_ed25519_init(&edKey) != 0) {
return -6920;
}
if (wc_InitRng(&edRng) != 0) {
wc_ed25519_free(&edKey);
return -6921;
}
if (wc_ed25519_make_key(&edRng, ED25519_KEY_SIZE, &edKey) != 0) {
wc_FreeRng(&edRng);
wc_ed25519_free(&edKey);
return -6922;
}
wc_FreeRng(&edRng);
derSz = wc_Ed25519PrivateKeyToDer(&edKey, der, sizeof(der));
wc_ed25519_free(&edKey);
if (derSz <= 0) {
return -6923;
}
WMEMSET(&kexKey, 0, sizeof(kexKey));
if (wc_ed25519_init(&kexKey) != 0) {
return -6924;
}
if (wc_Ed25519PrivateKeyDecode(der, &idx, &kexKey,
(word32)derSz) != 0) {
wc_ed25519_free(&kexKey);
return -6925;
}
if (wc_ed25519_export_public(&kexKey, q, &qSz) == 0) {
/* Public key derived during decode; fallback not exercised. */
wc_ed25519_free(&kexKey);
return 0;
}
if (wc_ed25519_make_public(&kexKey, q, 0) == 0) {
wc_ed25519_free(&kexKey);
printf("test_Ed25519KexDeriveFallbackFailure: expected failure on "
"undersized buffer, got success\n");
return -6926;
}
wc_ed25519_free(&kexKey);
return 0;
}
#endif
#ifndef WOLFSSH_NO_ECDSA
/* Failure path counterpart for ECDSA: wc_ecc_make_pub() must fail cleanly
* when a key has no private scalar loaded, mirroring the guard added in
* IdentifyAsn1Key and the fallback in SendKexGetSigningKey.
* Return codes -6930..-6931 */
static int test_ECCKexDeriveFallbackFailure(void)
{
ecc_key eccKey;
int ret;
WMEMSET(&eccKey, 0, sizeof(eccKey));
if (wc_ecc_init(&eccKey) != 0) {
return -6930;
}
ret = wc_ecc_make_pub(&eccKey, NULL);
wc_ecc_free(&eccKey);
if (ret == 0) {
printf("test_ECCKexDeriveFallbackFailure: expected failure on key "
"with no private scalar, got success\n");
return -6931;
}
return 0;
}
#endif
#if !defined(WOLFSSH_NO_MLDSA) && defined(WOLFSSL_MLDSA_PRIVATE_KEY) && \
!defined(WOLFSSL_MLDSA_NO_ASN1) && \
!defined(WOLFSSL_MLDSA_NO_MAKE_KEY) && \
(!defined(WOLFSSH_NO_MLDSA44) || !defined(WOLFSSH_NO_MLDSA65) || \
!defined(WOLFSSH_NO_MLDSA87))
/* FIPS 204 expanded private key: rho || K || tr || ... */
#define MLDSA_TEST_RHO_SZ 32
#define MLDSA_TEST_K_SZ 32
#define MLDSA_TEST_TR_SZ 64
/* Private-only DER: the public key is derived at decode time where wolfSSL
* supports it, otherwise rejected there. Shared across 44/65/87 levels.
* Return codes -692..-703 */
static int test_IdentifyAsn1Key_MlDsaPrivOnlyDer(byte level,
word32 derBufSz, int expectedKeyId, const char* levelName)
{
#ifdef WOLFSSH_HAVE_MLDSA_DERIVE_PUB
const int expect = expectedKeyId;
#else
const int expect = WS_CRYPTO_FAILED;
#endif
int ret;
MlDsaKey mlKey;
WC_RNG mlRng;
byte* mlDer = NULL;
int mlDerSz;
#ifdef WOLFSSH_HAVE_MLDSA_DERIVE_PUB
byte origPub[WOLFSSH_MLDSA_MAX_PUB_KEY_SZ];
word32 origPubSz = sizeof(origPub);
#endif
#ifndef WOLFSSH_HAVE_MLDSA_DERIVE_PUB
WOLFSSH_UNUSED(expectedKeyId);
#endif
WMEMSET(&mlKey, 0, sizeof(mlKey));
if (wc_MlDsaKey_Init(&mlKey, NULL, INVALID_DEVID) != 0) {
return -692;
}
if (wc_MlDsaKey_SetParams(&mlKey, level) != 0) {
wc_MlDsaKey_Free(&mlKey);
return -693;
}
if (wc_InitRng(&mlRng) != 0) {
wc_MlDsaKey_Free(&mlKey);
return -694;
}
if (wc_MlDsaKey_MakeKey(&mlKey, &mlRng) != 0) {
wc_FreeRng(&mlRng);
wc_MlDsaKey_Free(&mlKey);
return -695;
}
wc_FreeRng(&mlRng);
mlDer = (byte*)WMALLOC(derBufSz, NULL, 0);
if (mlDer == NULL) {
wc_MlDsaKey_Free(&mlKey);
return -696;
}
mlDerSz = wc_MlDsaKey_PrivateKeyToDer(&mlKey, mlDer, derBufSz);
#ifdef WOLFSSH_HAVE_MLDSA_DERIVE_PUB
/* Keep the generated public key so the derived one can be compared
* against it; deriving the wrong key would still set pubKeySet. */
if (wc_MlDsaKey_ExportPubRaw(&mlKey, origPub, &origPubSz) != 0) {
wc_MlDsaKey_Free(&mlKey);
WMEMSET(mlDer, 0, derBufSz);
WFREE(mlDer, NULL, 0);
return -700;
}
#endif
wc_MlDsaKey_Free(&mlKey);
if (mlDerSz <= 0) {
WMEMSET(mlDer, 0, derBufSz);
WFREE(mlDer, NULL, 0);
return -697;
}
ret = IdentifyAsn1Key(mlDer, (word32)mlDerSz, 1, NULL, NULL);
if (ret != expect) {
WMEMSET(mlDer, 0, mlDerSz);
WFREE(mlDer, NULL, 0);
printf("IdentifyAsn1Key: private-only MlDsa %s DER expected "
"%d, got %d\n", levelName, expect, ret);
return -698;
}
#ifdef WOLFSSH_HAVE_MLDSA_DERIVE_PUB
/* A key whose stored tr does not match the derived public key is
* rejected. rho also opens the public key, so find it in the DER rather
* than assume the layout. */
{
word32 trIdx = 0, i;
int rhoHits = 0;
WS_KeySignature* badSig = NULL;
for (i = 0; i + MLDSA_TEST_RHO_SZ + MLDSA_TEST_K_SZ +
MLDSA_TEST_TR_SZ <= (word32)mlDerSz; i++) {
if (WMEMCMP(mlDer + i, origPub, MLDSA_TEST_RHO_SZ) == 0) {
trIdx = i + MLDSA_TEST_RHO_SZ + MLDSA_TEST_K_SZ;
rhoHits++;
}
}
/* A changed encoding would otherwise hollow out this test. */
if (rhoHits != 1) {
WMEMSET(mlDer, 0, mlDerSz);
WFREE(mlDer, NULL, 0);
printf("IdentifyAsn1Key: private-only MlDsa %s DER has no "
"expanded key (%d rho matches)\n", levelName, rhoHits);
return -702;
}
mlDer[trIdx] ^= 0x5A;
ret = IdentifyAsn1Key(mlDer, (word32)mlDerSz, 1, NULL, &badSig);
mlDer[trIdx] ^= 0x5A;
if (ret != WS_CRYPTO_FAILED || badSig != NULL) {
if (badSig != NULL) {
wolfSSH_KEY_clean(badSig);
WFREE(badSig, NULL, DYNTYPE_PRIVKEY);
}
WMEMSET(mlDer, 0, mlDerSz);
WFREE(mlDer, NULL, 0);
printf("IdentifyAsn1Key: private-only MlDsa %s DER with a bad "
"tr expected WS_CRYPTO_FAILED, got %d\n", levelName, ret);
return -701;
}
}
#endif
/* wolfSSH_ReadKey_buffer() takes the same path for a client key. */
{
byte* out = NULL;
word32 outSz = 0;
const byte* outType = NULL;
word32 outTypeSz = 0;
char name[16];
int bad;
WSNPRINTF(name, sizeof(name), "ssh-mldsa-%s", levelName);
ret = wolfSSH_ReadKey_buffer(mlDer, (word32)mlDerSz,
WOLFSSH_FORMAT_ASN1, &out, &outSz, &outType, &outTypeSz,
NULL);
#ifdef WOLFSSH_HAVE_MLDSA_DERIVE_PUB
bad = ret != WS_SUCCESS || out == NULL
|| outSz != (word32)mlDerSz
|| WMEMCMP(out, mlDer, mlDerSz) != 0
|| outTypeSz != (word32)WSTRLEN(name)
|| WMEMCMP(outType, name, outTypeSz) != 0;
#else
bad = ret != WS_CRYPTO_FAILED || out != NULL;
#endif
if (out != NULL) {
WMEMSET(out, 0, outSz);
WFREE(out, NULL, DYNTYPE_PRIVKEY);
}
if (bad) {
WMEMSET(mlDer, 0, mlDerSz);
WFREE(mlDer, NULL, 0);
printf("wolfSSH_ReadKey_buffer: private-only MlDsa %s DER "
"failed, ret=%d\n", levelName, ret);
return -703;
}
}
/* On the derive path *pkey comes back with the public key set; on the
* reject path it stays NULL. */
{
WS_KeySignature* mlKeySig = NULL;
int bad;
ret = IdentifyAsn1Key(mlDer, (word32)mlDerSz, 1, NULL,
&mlKeySig);
WMEMSET(mlDer, 0, mlDerSz);
WFREE(mlDer, NULL, 0);
#ifdef WOLFSSH_HAVE_MLDSA_DERIVE_PUB
bad = (ret != expect) || mlKeySig == NULL ||
mlKeySig->keyId != expectedKeyId ||
!mlKeySig->ks.mldsa.key.pubKeySet;
if (!bad) {
byte derivedPub[WOLFSSH_MLDSA_MAX_PUB_KEY_SZ];
word32 derivedPubSz = sizeof(derivedPub);
bad = wc_MlDsaKey_ExportPubRaw(&mlKeySig->ks.mldsa.key,
derivedPub, &derivedPubSz) != 0
|| derivedPubSz != origPubSz
|| WMEMCMP(derivedPub, origPub, origPubSz) != 0;
if (bad) {
printf("IdentifyAsn1Key: private-only MlDsa %s derived "
"public key does not match the original\n",
levelName);
}
}
#else
bad = (ret != expect) || mlKeySig != NULL;
#endif
if (mlKeySig != NULL) {
wolfSSH_KEY_clean(mlKeySig);
WFREE(mlKeySig, NULL, DYNTYPE_PRIVKEY);
}
if (bad) {
printf("IdentifyAsn1Key: private-only MlDsa %s DER pkey-out "
"variant failed, ret=%d\n", levelName, ret);
return -699;
}
}
return 0;
}
#endif
/* Set when at least one test_ReadPublicKeyAsn1 sub-test is compiled in. The
* blob helpers below are unused otherwise, which -Werror rejects. */
#if !defined(WOLFSSH_NO_RSA) || \
(!defined(WOLFSSH_NO_ECDSA) && defined(HAVE_ECC_KEY_EXPORT)) || \
(!defined(WOLFSSH_NO_ED25519) && defined(HAVE_ED25519) && \
defined(HAVE_ED25519_MAKE_KEY) && defined(HAVE_ED25519_KEY_EXPORT)) || \
(!defined(WOLFSSH_NO_MLDSA) && !defined(WOLFSSL_DILITHIUM_NO_MAKE_KEY))
#define WOLFSSH_TEST_PUBKEY_ASN1
#endif
#ifdef WOLFSSH_TEST_PUBKEY_ASN1
/* Reads the 4-byte big-endian length prefix of an SSH wire string. */
static word32 ReadPubBlobLen(const byte* b)
{
return ((word32)b[0] << 24) | ((word32)b[1] << 16) |
((word32)b[2] << 8) | ((word32)b[3]);
}
/* Compares the SSH string at *idx in blob against expect, then advances
* *idx past it. Returns 0 on match, -1 otherwise. */
static int CheckPubBlobStr(const byte* blob, word32 blobSz, word32* idx,
const byte* expect, word32 expectSz)
{
word32 len;
if (*idx + LENGTH_SZ > blobSz) {
return -1;
}
len = ReadPubBlobLen(blob + *idx);
*idx += LENGTH_SZ;
if (len != expectSz || len > blobSz - *idx) {
return -1;
}
if (WMEMCMP(blob + *idx, expect, len) != 0) {
return -1;
}
*idx += len;
return 0;
}
#endif /* WOLFSSH_TEST_PUBKEY_ASN1 */
#if !defined(WOLFSSH_NO_ECDSA) && defined(HAVE_ECC_KEY_EXPORT)
/* An SPKI public key must produce an ecdsa-sha2-nistpXXX blob with the curve
* name and x963 point, not an ssh-rsa blob. Return codes -6940..-6949 */
static int test_ReadPublicKeyAsn1Ecc(int curveSz, const char* keyName,
const char* curveName)
{
int result = 0;
int ret;
int derSz = 0;
ecc_key eccKey;
WC_RNG rng;
byte* der = NULL;
byte* blob = NULL;
word32 blobSz = 0;
const byte* blobType = NULL;
word32 blobTypeSz = 0;
byte q[257];
word32 qSz = (word32)sizeof(q);
word32 idx = 0;
WMEMSET(&eccKey, 0, sizeof(eccKey));
if (wc_ecc_init(&eccKey) != 0) {
return -6940;
}
if (wc_InitRng(&rng) != 0) {
wc_ecc_free(&eccKey);
return -6941;
}
if (wc_ecc_make_key(&rng, curveSz, &eccKey) != 0) {
result = -6942;
}
wc_FreeRng(&rng);
if (result == 0) {
derSz = wc_EccPublicKeyDerSize(&eccKey, 1);
if (derSz <= 0) {
result = -6943;
}
}
if (result == 0) {
der = (byte*)WMALLOC((word32)derSz, NULL, 0);
if (der == NULL) {
result = -6944;
}
}
if (result == 0) {
derSz = wc_EccPublicKeyToDer(&eccKey, der, (word32)derSz, 1);
if (derSz <= 0) {
result = -6945;
}
}
if (result == 0) {
if (wc_ecc_export_x963(&eccKey, q, &qSz) != 0) {
result = -6946;
}
}
if (result == 0) {
ret = wolfSSH_ReadPublicKey_buffer(der, (word32)derSz,
WOLFSSH_FORMAT_ASN1, &blob, &blobSz, &blobType, &blobTypeSz,
NULL);
if (ret != WS_SUCCESS || blob == NULL) {
printf("ReadPublicKeyAsn1: ECC %s read failed, ret=%d\n",
curveName, ret);
result = -6947;
}
}
if (result == 0) {
if (blobTypeSz != (word32)WSTRLEN(keyName) ||
WMEMCMP(blobType, keyName, blobTypeSz) != 0) {
printf("ReadPublicKeyAsn1: ECC %s expected type %s\n",
curveName, keyName);
result = -6948;
}
}
if (result == 0) {
if (CheckPubBlobStr(blob, blobSz, &idx,
(const byte*)keyName, (word32)WSTRLEN(keyName)) != 0 ||
CheckPubBlobStr(blob, blobSz, &idx,
(const byte*)curveName, (word32)WSTRLEN(curveName)) != 0 ||
CheckPubBlobStr(blob, blobSz, &idx, q, qSz) != 0 ||
idx != blobSz) {
printf("ReadPublicKeyAsn1: ECC %s blob malformed\n", curveName);
result = -6949;
}
}
if (blob != NULL) {
WFREE(blob, NULL, DYNTYPE_PRIVKEY);
}
if (der != NULL) {
WFREE(der, NULL, 0);
}
wc_ecc_free(&eccKey);
return result;
}
#endif /* !WOLFSSH_NO_ECDSA && HAVE_ECC_KEY_EXPORT */
#if !defined(WOLFSSH_NO_ED25519) && defined(HAVE_ED25519) && \
defined(HAVE_ED25519_MAKE_KEY) && defined(HAVE_ED25519_KEY_EXPORT)
/* An SPKI public key must produce an ssh-ed25519 blob carrying the raw
* public key, not an ssh-rsa blob built from the overlaid union storage.
* Return codes -6950..-6957 */
static int test_ReadPublicKeyAsn1Ed25519(void)
{
static const char keyName[] = "ssh-ed25519";
int result = 0;
int ret;
int derSz = 0;
ed25519_key edKey;
WC_RNG rng;
byte der[128];
byte* blob = NULL;
word32 blobSz = 0;
const byte* blobType = NULL;
word32 blobTypeSz = 0;
byte q[ED25519_PUB_KEY_SIZE];
word32 qSz = (word32)sizeof(q);
word32 idx = 0;
if (wc_ed25519_init(&edKey) != 0) {
return -6950;
}
if (wc_InitRng(&rng) != 0) {
wc_ed25519_free(&edKey);
return -6951;
}
if (wc_ed25519_make_key(&rng, ED25519_KEY_SIZE, &edKey) != 0) {
result = -6952;
}
wc_FreeRng(&rng);
if (result == 0) {
derSz = wc_Ed25519PublicKeyToDer(&edKey, der, (word32)sizeof(der), 1);
if (derSz <= 0) {
result = -6953;
}
}
if (result == 0) {
if (wc_ed25519_export_public(&edKey, q, &qSz) != 0) {
result = -6954;
}
}
if (result == 0) {
ret = wolfSSH_ReadPublicKey_buffer(der, (word32)derSz,
WOLFSSH_FORMAT_ASN1, &blob, &blobSz, &blobType, &blobTypeSz,
NULL);
if (ret != WS_SUCCESS || blob == NULL) {
printf("ReadPublicKeyAsn1: Ed25519 read failed, ret=%d\n", ret);
result = -6955;
}
}
if (result == 0) {
if (blobTypeSz != (word32)WSTRLEN(keyName) ||
WMEMCMP(blobType, keyName, blobTypeSz) != 0) {
printf("ReadPublicKeyAsn1: Ed25519 expected type %s\n", keyName);
result = -6956;
}
}
if (result == 0) {
if (CheckPubBlobStr(blob, blobSz, &idx,
(const byte*)keyName, (word32)WSTRLEN(keyName)) != 0 ||
CheckPubBlobStr(blob, blobSz, &idx, q, qSz) != 0 ||
idx != blobSz) {
printf("ReadPublicKeyAsn1: Ed25519 blob malformed\n");
result = -6957;
}
}
if (blob != NULL) {
WFREE(blob, NULL, DYNTYPE_PRIVKEY);
}
wc_ed25519_free(&edKey);
return result;
}
#endif /* !WOLFSSH_NO_ED25519 && HAVE_ED25519 && ... */
#if !defined(WOLFSSH_NO_MLDSA) && !defined(WOLFSSL_DILITHIUM_NO_MAKE_KEY)
/* A raw ML-DSA public key must produce an ssh-mldsa-NN blob carrying that
* same raw key. Return codes -6970..-6977 */
static int test_ReadPublicKeyAsn1MlDsa(byte level, const char* keyName,
word32 rawSz)
{
int result = 0;
int ret;
MlDsaKey mlKey;
WC_RNG rng;
byte* raw = NULL;
word32 gotSz = rawSz;
byte* blob = NULL;
word32 blobSz = 0;
const byte* blobType = NULL;
word32 blobTypeSz = 0;
word32 idx = 0;
if (wc_MlDsaKey_Init(&mlKey, NULL, INVALID_DEVID) != 0) {
return -6970;
}
if (wc_InitRng(&rng) != 0) {
wc_MlDsaKey_Free(&mlKey);
return -6971;
}
if (wc_MlDsaKey_SetParams(&mlKey, level) != 0) {
result = -6972;
}
if (result == 0) {
if (wc_MlDsaKey_MakeKey(&mlKey, &rng) != 0) {
result = -6973;
}
}
wc_FreeRng(&rng);
if (result == 0) {
raw = (byte*)WMALLOC(rawSz, NULL, 0);
if (raw == NULL) {
result = -6974;
}
}
if (result == 0) {
if (wc_MlDsaKey_ExportPubRaw(&mlKey, raw, &gotSz) != 0 ||
gotSz != rawSz) {
result = -6975;
}
}
/* IdentifyAsn1Key falls back to a raw-length probe when the bytes are
* not an SPKI, which is what routes this to the ML-DSA arm. */
if (result == 0) {
ret = wolfSSH_ReadPublicKey_buffer(raw, rawSz, WOLFSSH_FORMAT_ASN1,
&blob, &blobSz, &blobType, &blobTypeSz, NULL);
if (ret != WS_SUCCESS || blob == NULL) {
printf("ReadPublicKeyAsn1: %s read failed, ret=%d\n",
keyName, ret);
result = -6976;
}
}
if (result == 0) {
if (blobTypeSz != (word32)WSTRLEN(keyName) ||
WMEMCMP(blobType, keyName, blobTypeSz) != 0 ||
CheckPubBlobStr(blob, blobSz, &idx,
(const byte*)keyName, (word32)WSTRLEN(keyName)) != 0 ||
CheckPubBlobStr(blob, blobSz, &idx, raw, rawSz) != 0 ||
idx != blobSz) {
printf("ReadPublicKeyAsn1: %s blob malformed\n", keyName);
result = -6977;
}
}
if (blob != NULL) {
WFREE(blob, NULL, DYNTYPE_PRIVKEY);
}
if (raw != NULL) {
WFREE(raw, NULL, 0);
}
wc_MlDsaKey_Free(&mlKey);
return result;
}
#endif /* !WOLFSSH_NO_MLDSA && !WOLFSSL_DILITHIUM_NO_MAKE_KEY */
#ifndef WOLFSSH_NO_RSA
/* Regression guard: the RSA public path must keep producing an ssh-rsa blob
* of three strings once it is gated on its own key ID.
* Return codes -6960..-6967 */
static int test_ReadPublicKeyAsn1Rsa(void)
{
static const char keyName[] = "ssh-rsa";
int result = 0;
int ret;
RsaKey rsaKey;
byte e[8];
byte n[RSA_MAX_SIZE / 8 + 1];
word32 eSz = (word32)sizeof(e);
word32 nSz = (word32)sizeof(n) - 1;
byte* blob = NULL;
word32 blobSz = 0;
const byte* blobType = NULL;
word32 blobTypeSz = 0;
word32 idx = 0;
/* Recover the expected e and n the same way DoAsn1Key does, so the blob
* is checked against real key material and not just its framing. */
if (wc_InitRsaKey(&rsaKey, NULL) != 0) {
return -6960;
}
idx = 0;
if (wc_RsaPublicKeyDecode(unitTestRsaPubKey, &idx, &rsaKey,
unitTestRsaPubKeySz) != 0) {
result = -6961;
}
if (result == 0) {
if (wc_RsaFlattenPublicKey(&rsaKey, e, &eSz, n + 1, &nSz) != 0) {
result = -6962;
}
}
/* DoAsn1Key prepends a zero byte when the modulus MSB is set, so the
* mpint stays positive. Mirror that to compare bytes. */
if (result == 0) {
if (n[1] & 0x80) {
n[0] = 0;
nSz++;
}
else {
WMEMMOVE(n, n + 1, nSz);
}
}
if (result == 0) {
ret = wolfSSH_ReadPublicKey_buffer(unitTestRsaPubKey,
unitTestRsaPubKeySz,
WOLFSSH_FORMAT_ASN1, &blob, &blobSz, &blobType, &blobTypeSz,
NULL);
if (ret != WS_SUCCESS || blob == NULL) {
printf("ReadPublicKeyAsn1: RSA read failed, ret=%d\n", ret);
result = -6963;
}
}
if (result == 0) {
if (blobTypeSz != (word32)WSTRLEN(keyName) ||
WMEMCMP(blobType, keyName, blobTypeSz) != 0) {
printf("ReadPublicKeyAsn1: RSA expected type %s\n", keyName);
result = -6964;
}
}
if (result == 0) {
idx = 0;
if (CheckPubBlobStr(blob, blobSz, &idx,
(const byte*)keyName, (word32)WSTRLEN(keyName)) != 0) {
printf("ReadPublicKeyAsn1: RSA blob name malformed\n");
result = -6965;
}
}
if (result == 0) {
if (CheckPubBlobStr(blob, blobSz, &idx, e, eSz) != 0) {
printf("ReadPublicKeyAsn1: RSA exponent mismatch\n");
result = -6966;
}
}
if (result == 0) {
if (CheckPubBlobStr(blob, blobSz, &idx, n, nSz) != 0 ||
idx != blobSz) {
printf("ReadPublicKeyAsn1: RSA modulus mismatch\n");
result = -6967;
}
}
if (blob != NULL) {
WFREE(blob, NULL, DYNTYPE_PRIVKEY);
}
wc_FreeRsaKey(&rsaKey);
return result;
}
#endif /* WOLFSSH_NO_RSA */
/* wolfSSH_ReadPublicKey_buffer() with WOLFSSH_FORMAT_ASN1 must dispatch on the
* identified key type instead of assuming every DER public key is RSA. */
static int test_ReadPublicKeyAsn1(void)
{
int result = 0;
#ifndef WOLFSSH_NO_RSA
result = test_ReadPublicKeyAsn1Rsa();
#endif
#if !defined(WOLFSSH_NO_ECDSA) && defined(HAVE_ECC_KEY_EXPORT)
#ifndef WOLFSSH_NO_ECDSA_SHA2_NISTP256
if (result == 0) {
result = test_ReadPublicKeyAsn1Ecc(32, "ecdsa-sha2-nistp256",
"nistp256");
}
#endif
#ifndef WOLFSSH_NO_ECDSA_SHA2_NISTP384
if (result == 0) {
result = test_ReadPublicKeyAsn1Ecc(48, "ecdsa-sha2-nistp384",
"nistp384");
}
#endif
#ifndef WOLFSSH_NO_ECDSA_SHA2_NISTP521
if (result == 0) {
result = test_ReadPublicKeyAsn1Ecc(66, "ecdsa-sha2-nistp521",
"nistp521");
}
#endif
#endif /* !WOLFSSH_NO_ECDSA && HAVE_ECC_KEY_EXPORT */
#if !defined(WOLFSSH_NO_ED25519) && defined(HAVE_ED25519) && \
defined(HAVE_ED25519_MAKE_KEY) && defined(HAVE_ED25519_KEY_EXPORT)
if (result == 0) {
result = test_ReadPublicKeyAsn1Ed25519();
}
#endif
#if !defined(WOLFSSH_NO_MLDSA) && !defined(WOLFSSL_DILITHIUM_NO_MAKE_KEY)
#ifndef WOLFSSH_NO_MLDSA44
if (result == 0) {
result = test_ReadPublicKeyAsn1MlDsa(WC_ML_DSA_44, "ssh-mldsa-44",
WC_MLDSA_44_PUB_KEY_SIZE);
}
#endif
#ifndef WOLFSSH_NO_MLDSA65
if (result == 0) {
result = test_ReadPublicKeyAsn1MlDsa(WC_ML_DSA_65, "ssh-mldsa-65",
WC_MLDSA_65_PUB_KEY_SIZE);
}
#endif
#ifndef WOLFSSH_NO_MLDSA87
if (result == 0) {
result = test_ReadPublicKeyAsn1MlDsa(WC_ML_DSA_87, "ssh-mldsa-87",
WC_MLDSA_87_PUB_KEY_SIZE);
}
#endif
#endif /* !WOLFSSH_NO_MLDSA && !WOLFSSL_DILITHIUM_NO_MAKE_KEY */
return result;
}
/* IdentifyAsn1Key unit test
*
* Exercises every new wc_Free* error-path added in IdentifyAsn1Key:
* - wc_FreeRsaKey on RSA decode failure
* - wc_ecc_free on ECC decode failure
* - wc_ecc_free in the default: branch (unsupported curve)
* - wc_ed25519_free on Ed25519 decode failure
* Each happy-path call implicitly exercises the failure-path frees for the
* other key types.
*/
static int test_IdentifyAsn1Key(void)
{
int result = 0;
int ret;
#ifndef WOLFSSH_NO_RSA
ret = IdentifyAsn1Key(unitTestRsaPrivKey, unitTestRsaPrivKeySz,
1, NULL, NULL);
if (ret != ID_SSH_RSA) {
printf("IdentifyAsn1Key: RSA priv failed, ret=%d\n", ret);
result = -600; goto done;
}
#endif
#ifndef WOLFSSH_NO_ECDSA_SHA2_NISTP256
ret = IdentifyAsn1Key(unitTestEcc256PrivKey,
(word32)sizeof(unitTestEcc256PrivKey),
1, NULL, NULL);
if (ret != ID_ECDSA_SHA2_NISTP256) {
printf("IdentifyAsn1Key: ECC P-256 priv failed, ret=%d\n", ret);
result = -601; goto done;
}
#ifdef HAVE_ECC_KEY_EXPORT
ret = test_IdentifyAsn1Key_EccPrivOnlyDer(32, ID_ECDSA_SHA2_NISTP256,
"P-256");
if (ret != 0) {
result = ret; goto done;
}
ret = test_IdentifyAsn1Key_EccPrivOnlyDerFailure(32, "P-256");
if (ret != 0) {
result = ret; goto done;
}
#endif
#endif
#ifndef WOLFSSH_NO_ECDSA_SHA2_NISTP384
ret = IdentifyAsn1Key(unitTestEcc384PrivKey,
(word32)sizeof(unitTestEcc384PrivKey),
1, NULL, NULL);
if (ret != ID_ECDSA_SHA2_NISTP384) {
printf("IdentifyAsn1Key: ECC P-384 priv failed, ret=%d\n", ret);
result = -602; goto done;
}
#ifdef HAVE_ECC_KEY_EXPORT
ret = test_IdentifyAsn1Key_EccPrivOnlyDer(48, ID_ECDSA_SHA2_NISTP384,
"P-384");
if (ret != 0) {
result = ret; goto done;
}
ret = test_IdentifyAsn1Key_EccPrivOnlyDerFailure(48, "P-384");
if (ret != 0) {
result = ret; goto done;
}
#endif
#endif
#ifndef WOLFSSH_NO_ECDSA_SHA2_NISTP521
ret = IdentifyAsn1Key(unitTestEcc521PrivKey,
(word32)sizeof(unitTestEcc521PrivKey),
1, NULL, NULL);
if (ret != ID_ECDSA_SHA2_NISTP521) {
printf("IdentifyAsn1Key: ECC P-521 priv failed, ret=%d\n", ret);
result = -603; goto done;
}
#ifdef HAVE_ECC_KEY_EXPORT
ret = test_IdentifyAsn1Key_EccPrivOnlyDer(66, ID_ECDSA_SHA2_NISTP521,
"P-521");
if (ret != 0) {
result = ret; goto done;
}
ret = test_IdentifyAsn1Key_EccPrivOnlyDerFailure(66, "P-521");
if (ret != 0) {
result = ret; goto done;
}
#endif
#endif
#if !defined(WOLFSSH_NO_ED25519)
ret = IdentifyAsn1Key(unitTestEd25519PrivKey,
(word32)sizeof(unitTestEd25519PrivKey),
1, NULL, NULL);
if (ret != ID_ED25519) {
printf("IdentifyAsn1Key: Ed25519 priv failed, ret=%d\n", ret);
result = -604; goto done;
}
#if defined(HAVE_ED25519) && defined(HAVE_ED25519_MAKE_KEY) && \
defined(HAVE_ED25519_KEY_EXPORT)
ret = test_IdentifyAsn1Key_Ed25519PrivOnlyDer();
if (ret != 0) {
result = ret; goto done;
}
#endif
#if defined(HAVE_ED25519) && !defined(HAVE_ED25519_MAKE_KEY)
ret = test_IdentifyAsn1Key_Ed25519PrivOnlyDerNoMakeKey();
if (ret != 0) {
result = ret; goto done;
}
#endif
#if defined(HAVE_ED25519) && defined(HAVE_ED25519_MAKE_KEY) && \
defined(HAVE_ED25519_KEY_EXPORT) && defined(HAVE_ED25519_SIGN) && \
defined(HAVE_ED25519_VERIFY)
ret = test_Ed25519KexDeriveFallback();
if (ret != 0) {
result = ret; goto done;
}
ret = test_Ed25519KexDeriveFallbackFailure();
if (ret != 0) {
result = ret; goto done;
}
#endif
#endif
#ifndef WOLFSSH_NO_ECDSA
ret = test_ECCKexDeriveFallbackFailure();
if (ret != 0) {
result = ret; goto done;
}
#endif
#if !defined(WOLFSSH_NO_MLDSA) && !defined(WOLFSSH_NO_MLDSA44)
ret = IdentifyAsn1Key(unitTestMlDsaPrivKey,
(word32)sizeof(unitTestMlDsaPrivKey),
1, NULL, NULL);
/* unitTestMlDsaPrivKey encodes a level-44 key; the private-key decode
* path determines keyId purely from the decoded key's level (see
* IdentifyAsn1Key), not from WOLFSSH_NO_MLDSA44, so this must always
* be ID_MLDSA44 regardless of which individual levels are compiled in. */
if (ret != ID_MLDSA44) {
printf("IdentifyAsn1Key: MlDsa priv failed, ret=%d\n", ret);
result = -606;
goto done;
}
/* Raw public key probe path: extract the public key from the private key
* test vector, then pass the raw bytes (no SPKI wrapper) to
* IdentifyAsn1Key. This exercises the level-probing fallback added for
* certificate-extracted public keys. */
{
MlDsaKey mlKey;
byte* mlPub = NULL;
word32 mlPubSz = 0;
word32 mlIdx = 0;
if (wc_MlDsaKey_Init(&mlKey, NULL, INVALID_DEVID) != 0) {
result = -607; goto done;
}
if (wc_MlDsaKey_PrivateKeyDecode(&mlKey, unitTestMlDsaPrivKey,
sizeof(unitTestMlDsaPrivKey),
&mlIdx) != 0) {
wc_MlDsaKey_Free(&mlKey);
result = -608; goto done;
}
{
int mlPubSzInt = wc_MlDsaKey_PubSize(&mlKey);
if (mlPubSzInt < 0) {
wc_MlDsaKey_Free(&mlKey);
result = -609; goto done;
}
mlPubSz = (word32)mlPubSzInt;
}
mlPub = (byte*)WMALLOC(mlPubSz, NULL, 0);
if (mlPub == NULL) {
wc_MlDsaKey_Free(&mlKey);
result = -619; goto done;
}
if (wc_MlDsaKey_ExportPubRaw(&mlKey, mlPub, &mlPubSz) != 0) {
WFREE(mlPub, NULL, 0);
wc_MlDsaKey_Free(&mlKey);
result = -610; goto done;
}
wc_MlDsaKey_Free(&mlKey);
ret = IdentifyAsn1Key(mlPub, mlPubSz, 0, NULL, NULL);
WFREE(mlPub, NULL, 0);
if (ret != ID_MLDSA44) {
printf("IdentifyAsn1Key: MlDsa raw pub probe failed, ret=%d\n",
ret);
result = -611; goto done;
}
}
#if defined(WOLFSSL_MLDSA_PRIVATE_KEY) && !defined(WOLFSSL_MLDSA_NO_ASN1) && \
!defined(WOLFSSL_MLDSA_NO_MAKE_KEY)
ret = test_IdentifyAsn1Key_MlDsaPrivOnlyDer(WC_ML_DSA_44,
WC_MLDSA_44_PRV_KEY_DER_SIZE, ID_MLDSA44, "44");
if (ret != 0) {
result = ret; goto done;
}
#endif
#endif
#if !defined(WOLFSSH_NO_MLDSA) && !defined(WOLFSSH_NO_MLDSA65) && \
defined(WOLFSSL_MLDSA_PRIVATE_KEY) && !defined(WOLFSSL_MLDSA_NO_ASN1) && \
!defined(WOLFSSL_MLDSA_NO_MAKE_KEY)
ret = test_IdentifyAsn1Key_MlDsaPrivOnlyDer(WC_ML_DSA_65,
WC_MLDSA_65_PRV_KEY_DER_SIZE, ID_MLDSA65, "65");
if (ret != 0) {
result = ret; goto done;
}
#endif
#if !defined(WOLFSSH_NO_MLDSA) && !defined(WOLFSSH_NO_MLDSA87) && \
defined(WOLFSSL_MLDSA_PRIVATE_KEY) && !defined(WOLFSSL_MLDSA_NO_ASN1) && \
!defined(WOLFSSL_MLDSA_NO_MAKE_KEY)
ret = test_IdentifyAsn1Key_MlDsaPrivOnlyDer(WC_ML_DSA_87,
WC_MLDSA_87_PRV_KEY_DER_SIZE, ID_MLDSA87, "87");
if (ret != 0) {
result = ret; goto done;
}
#endif
/* Unsupported ECC curve: triggers wc_ecc_free in the default: branch
* (wolfSSL has P-192) or the else branch (wolfSSL lacks P-192).
* Either way the key must be freed and WS_UNIMPLEMENTED_E returned. */
#ifndef WOLFSSH_NO_ECDSA
ret = IdentifyAsn1Key(unitTestEccUnsupportedCurveKey,
(word32)sizeof(unitTestEccUnsupportedCurveKey),
1, NULL, NULL);
if (ret != WS_UNIMPLEMENTED_E) {
printf("IdentifyAsn1Key: unsupported ECC curve expected "
"WS_UNIMPLEMENTED_E, got %d\n", ret);
result = -605; goto done;
}
#endif
/* Garbage: all decode attempts fail, all wc_Free* cleanup paths hit */
{
static const byte garbage[] = {0x00, 0x01, 0x02, 0x03};
ret = IdentifyAsn1Key(garbage, (word32)sizeof(garbage), 1, NULL, NULL);
if (ret != WS_UNIMPLEMENTED_E) {
printf("IdentifyAsn1Key: garbage expected WS_UNIMPLEMENTED_E, "
"got %d\n", ret);
result = -606; goto done;
}
}
done:
return result;
}
#endif /* WOLFSSH_TEST_INTERNAL */
/* The cert manager tests below use only public API, so they are outside the
* WOLFSSH_TEST_INTERNAL section. Each carries its own feature guard;
* WOLFSSH_TEST_CERTMAN_PROMOTE still implies WOLFSSH_TEST_INTERNAL. */
/* Guard by the actual users, to avoid -Wunused-function: the promote tests,
* the root CA half of test_SetCertManager(), and test_ParseECCPubKeyCert().
* That last one needs WOLFSSH_TEST_INTERNAL, which ide/winvs does not
* define, so it does not build there. */
#if defined(WOLFSSH_TEST_CERTMAN_PROMOTE) || \
(defined(WOLFSSH_TEST_SET_CERTMAN) && \
defined(WOLFSSH_TEST_CERTMAN_ROOTCA)) || \
(defined(WOLFSSH_TEST_INTERNAL) && defined(WOLFSSH_CERTS) && \
!defined(NO_FILESYSTEM) && !defined(WOLFSSH_NO_ECDSA_SHA2_NISTP256))
/* Read a whole file into a freshly malloc'd buffer. Caller frees *buf. */
static int certmanLoadFile(const char* fn, byte** buf, word32* bufSz)
{
FILE* f;
long sz;
size_t rd;
*buf = NULL;
*bufSz = 0;
f = fopen(fn, "rb");
if (f == NULL)
return -1;
if (fseek(f, 0, SEEK_END) != 0 || (sz = ftell(f)) < 0) {
fclose(f);
return -1;
}
#if LONG_MAX > 0xFFFFFFFFL
/* The size is later stored in a word32; reject anything that would not
* round-trip so *bufSz stays consistent with the allocated/read size. */
if (sz > 0xFFFFFFFFL) {
fclose(f);
return -1;
}
#endif
if (fseek(f, 0, SEEK_SET) != 0) {
fclose(f);
return -1;
}
*buf = (byte*)malloc((size_t)sz);
if (*buf == NULL) {
fclose(f);
return -1;
}
rd = fread(*buf, 1, (size_t)sz, f);
fclose(f);
if (rd != (size_t)sz) {
free(*buf);
*buf = NULL;
return -1;
}
*bufSz = (word32)sz;
return 0;
}
#endif /* WOLFSSH_TEST_CERTMAN_PROMOTE ||
* (WOLFSSH_TEST_SET_CERTMAN && WOLFSSH_TEST_CERTMAN_ROOTCA) ||
* (WOLFSSH_TEST_INTERNAL && WOLFSSH_CERTS && !NO_FILESYSTEM &&
* !WOLFSSH_NO_ECDSA_SHA2_NISTP256) */
#ifdef WOLFSSH_TEST_CERTMAN_PROMOTE
/* Forge an end-entity cert whose issuer is the supplied cert and which is
* signed with the supplied (non-CA) key. Fills der/derSz on success. */
static int certmanForgeChild(const byte* issuerCert, word32 issuerCertSz,
const byte* issuerKey, word32 issuerKeySz, byte* der, word32* derSz)
{
ecc_key key;
WC_RNG rng;
Cert cert;
word32 idx = 0;
int ret;
int sz;
int haveKey = 0, haveRng = 0;
ret = wc_ecc_init(&key);
if (ret == 0) {
haveKey = 1;
ret = wc_InitRng(&rng);
}
if (ret == 0) {
haveRng = 1;
ret = wc_EccPrivateKeyDecode(issuerKey, &idx, &key, issuerKeySz);
}
if (ret == 0)
ret = wc_InitCert(&cert);
if (ret == 0) {
WSTRNCPY(cert.subject.country, "US", CTC_NAME_SIZE);
WSTRNCPY(cert.subject.commonName, "Mallory", CTC_NAME_SIZE);
cert.sigType = CTC_SHA256wECDSA;
cert.daysValid = 365;
cert.isCA = 0;
ret = wc_SetIssuerBuffer(&cert, issuerCert, (int)issuerCertSz);
}
if (ret == 0) {
/* Reuse the issuer key as the subject key; only the issuer and the
* signature matter for the signer lookup under test. */
sz = wc_MakeCert(&cert, der, *derSz, NULL, &key, &rng);
if (sz < 0)
ret = sz;
}
if (ret == 0) {
sz = wc_SignCert(cert.bodySz, cert.sigType, der, *derSz, NULL, &key,
&rng);
if (sz < 0)
ret = sz;
else
*derSz = (word32)sz;
}
if (haveRng)
wc_FreeRng(&rng);
if (haveKey)
wc_ecc_free(&key);
return ret;
}
/* Forge a cert with the given subject CN, or with issuerCert's subject name
* when cn is NULL (a self-issued cert). When isCA is set the cert asserts
* basicConstraints CA=TRUE. When keyUsage is non-NULL the cert carries a
* KeyUsage extension with the named usage(s) (e.g. "keyCertSign" or
* "digitalSignature"); NULL omits the extension entirely. extKeyUsage does
* the same for ExtendedKeyUsage, taking wc_SetExtKeyUsage() names
* ("serverAuth", "clientAuth", "any", ...) or, with WOLFSSL_EKU_OID, a
* dotted OID. The issuer name is taken from issuerCert, the subject public
* key from subjectKey, and the cert is signed with issuerKey. keyIds of
* CERTMAN_NO_SKID or CERTMAN_NO_AKID leaves out that key ID, and a non-NULL
* akidKey takes the authority key ID from that key instead of from
* issuerCert: by RFC 5280 method 1, or with CERTMAN_AKID_SPKI as the SHA-1
* of its whole SubjectPublicKeyInfo, the ID wolfSSL derives for a cert
* without a subject key ID. Fills der/derSz on success. */
#define CERTMAN_NO_SKID 0x01
#define CERTMAN_NO_AKID 0x02
#define CERTMAN_AKID_SPKI 0x04
static int certmanForgeCertKeyIds(const char* cn, int isCA,
const char* keyUsage, const char* extKeyUsage,
const byte* issuerCert, word32 issuerCertSz,
ecc_key* issuerKey, ecc_key* subjectKey, int keyIds,
ecc_key* akidKey, byte* der, word32* derSz)
{
WC_RNG rng;
Cert cert;
int ret;
int sz;
int haveRng = 0;
ret = wc_InitRng(&rng);
if (ret == 0) {
haveRng = 1;
ret = wc_InitCert(&cert);
}
if (ret == 0) {
/* wc_InitCert zeroed the struct, so leaving the final byte untouched
* keeps the name NUL-terminated and avoids a strncpy truncation
* warning on the runtime cn pointer. */
if (cn != NULL) {
WSTRNCPY(cert.subject.country, "US", CTC_NAME_SIZE - 1);
WSTRNCPY(cert.subject.commonName, cn, CTC_NAME_SIZE - 1);
}
else {
ret = wc_SetSubjectBuffer(&cert, issuerCert, (int)issuerCertSz);
}
cert.sigType = CTC_SHA256wECDSA;
cert.daysValid = 365;
cert.isCA = isCA;
if (ret == 0 && keyUsage != NULL) {
#ifdef WOLFSSL_CERT_EXT
ret = wc_SetKeyUsage(&cert, keyUsage);
#else
ret = BAD_FUNC_ARG;
#endif
}
}
if (ret == 0 && extKeyUsage != NULL) {
#ifdef WOLFSSL_CERT_EXT
if (WSTRCHR(extKeyUsage, '.') == NULL) {
ret = wc_SetExtKeyUsage(&cert, extKeyUsage);
}
else {
#ifdef WOLFSSL_EKU_OID
ret = wc_SetExtKeyUsageOID(&cert, extKeyUsage,
(word32)WSTRLEN(extKeyUsage), 0, NULL);
#else
ret = BAD_FUNC_ARG;
#endif
}
#else
ret = BAD_FUNC_ARG;
#endif
}
if (ret == 0)
ret = wc_SetIssuerBuffer(&cert, issuerCert, (int)issuerCertSz);
#ifdef WOLFSSL_CERT_EXT
/* Key ids make the signer lookup go by key, not by the issuer name,
* which a self-issued intermediate shares with the root. */
if (ret == 0 && !(keyIds & CERTMAN_NO_SKID))
ret = wc_SetSubjectKeyIdFromPublicKey_ex(&cert, ECC_TYPE, subjectKey);
if (ret == 0 && !(keyIds & CERTMAN_NO_AKID)) {
if (akidKey != NULL && (keyIds & CERTMAN_AKID_SPKI)) {
byte spki[256];
sz = wc_EccPublicKeyToDer(akidKey, spki, sizeof(spki), 1);
if (sz < 0)
ret = sz;
else
ret = wc_ShaHash(spki, (word32)sz, cert.akid);
cert.akidSz = WC_SHA_DIGEST_SIZE;
}
else if (akidKey != NULL)
ret = wc_SetAuthKeyIdFromPublicKey_ex(&cert, ECC_TYPE, akidKey);
else
ret = wc_SetAuthKeyIdFromCert(&cert, issuerCert,
(int)issuerCertSz);
}
#else
(void)keyIds;
(void)akidKey;
#endif
if (ret == 0) {
sz = wc_MakeCert(&cert, der, *derSz, NULL, subjectKey, &rng);
if (sz < 0)
ret = sz;
}
if (ret == 0) {
sz = wc_SignCert(cert.bodySz, cert.sigType, der, *derSz, NULL,
issuerKey, &rng);
if (sz < 0)
ret = sz;
else
*derSz = (word32)sz;
}
if (haveRng)
wc_FreeRng(&rng);
return ret;
}
static int certmanForgeCert(const char* cn, int isCA, const char* keyUsage,
const char* extKeyUsage,
const byte* issuerCert, word32 issuerCertSz,
ecc_key* issuerKey, ecc_key* subjectKey, byte* der, word32* derSz)
{
return certmanForgeCertKeyIds(cn, isCA, keyUsage, extKeyUsage,
issuerCert, issuerCertSz, issuerKey, subjectKey, 0, NULL,
der, derSz);
}
static void certmanPutU32(byte* p, word32 v)
{
p[0] = (byte)(v >> 24);
p[1] = (byte)(v >> 16);
p[2] = (byte)(v >> 8);
p[3] = (byte)(v);
}
/* Append a length-prefixed cert (the framing VerifyCerts_buffer expects).
* chainCap is the capacity of chain; on insufficient space the chain is left
* unchanged so a cert-size regression surfaces as a failed assertion rather
* than memory corruption. The subtractions are ordered to avoid word32
* underflow. */
static word32 certmanAppendCert(byte* chain, word32 chainCap, word32 chainSz,
const byte* cert, word32 certSz)
{
if (chainSz > chainCap ||
certSz > chainCap - chainSz ||
UINT32_SZ > chainCap - chainSz - certSz) {
return chainSz;
}
certmanPutU32(chain + chainSz, certSz);
chainSz += UINT32_SZ;
WMEMCPY(chain + chainSz, cert, certSz);
chainSz += certSz;
return chainSz;
}
/* Regression test: a peer-supplied end-entity (non-CA)
* certificate presented at an intermediate position in a chain must not be
* promoted into the cert manager's trust store. If it were, the holder of any
* ordinary leaf cert issued by a trusted root could then forge certs binding
* arbitrary SSH principals.
*
* Fred's cert is a non-CA leaf issued by the test root (ca-cert-ecc). We forge
* a child ("Mallory") issued by Fred and signed with Fred's key, then:
* 1. Sanity: with Fred explicitly trusted as a CA, the forged child gets
* past the no-signer stage, proving the child is well-formed and chains
* to Fred -- so the regression check below cannot pass vacuously.
* 2. Regression: run the attack chain [child, fred] through verify (a
* vulnerable build promotes Fred here), then confirm the store was not
* mutated -- verifying the child alone must now fail with
* WS_CERT_NO_SIGNER_E. */
static int test_CertMan_NoPromoteNonCaIntermediate(void)
{
int result = 0;
int ret;
byte* root = NULL;
byte* fred = NULL;
byte* fredKey = NULL;
word32 rootSz = 0, fredSz = 0, fredKeySz = 0;
byte child[2048];
word32 childSz = sizeof(child);
byte chain[6144];
word32 chainSz;
WOLFSSH_CERTMAN* cm = NULL;
if (certmanLoadFile("./keys/ca-cert-ecc.der", &root, &rootSz) != 0) {
printf("CertMan: can't load root cert\n");
result = -900; goto done;
}
if (certmanLoadFile("./keys/fred-cert.der", &fred, &fredSz) != 0) {
printf("CertMan: can't load fred cert\n");
result = -901; goto done;
}
if (certmanLoadFile("./keys/fred-key.der", &fredKey, &fredKeySz) != 0) {
printf("CertMan: can't load fred key\n");
result = -902; goto done;
}
ret = certmanForgeChild(fred, fredSz, fredKey, fredKeySz, child, &childSz);
if (ret != 0) {
printf("CertMan: forge child failed, ret=%d\n", ret);
result = -903; goto done;
}
/* 1. Sanity: with Fred explicitly trusted, the child chains to Fred. */
cm = wolfSSH_CERTMAN_new(NULL);
if (cm == NULL) {
result = -904; goto done;
}
if (wolfSSH_CERTMAN_LoadRootCA_buffer(cm, root, rootSz) != WS_SUCCESS) {
result = -905; goto done;
}
if (wolfSSH_CERTMAN_LoadRootCA_buffer(cm, fred, fredSz) != WS_SUCCESS) {
result = -906; goto done;
}
chainSz = certmanAppendCert(chain, (word32)sizeof(chain), 0,
child, childSz);
ret = wolfSSH_CERTMAN_VerifyCerts_buffer(cm, chain, chainSz, 1);
if (ret == WS_CERT_NO_SIGNER_E) {
printf("CertMan: sanity check failed, child didn't chain to Fred\n");
result = -907; goto done;
}
wolfSSH_CERTMAN_free(cm);
cm = NULL;
/* 2. Regression: Fred NOT explicitly trusted. Run the attack chain so a
* vulnerable build would promote Fred, then confirm the store was not
* mutated. */
cm = wolfSSH_CERTMAN_new(NULL);
if (cm == NULL) {
result = -908; goto done;
}
if (wolfSSH_CERTMAN_LoadRootCA_buffer(cm, root, rootSz) != WS_SUCCESS) {
result = -909; goto done;
}
chainSz = certmanAppendCert(chain, (word32)sizeof(chain), 0,
child, childSz);
chainSz = certmanAppendCert(chain, (word32)sizeof(chain), chainSz,
fred, fredSz);
/* The attack chain itself must be rejected. */
ret = wolfSSH_CERTMAN_VerifyCerts_buffer(cm, chain, chainSz, 2);
if (ret == WS_SUCCESS) {
printf("CertMan: attack chain unexpectedly verified\n");
result = -910; goto done;
}
/* The trust store must be unchanged: verifying the forged child alone must
* now fail with no available signer, proving Fred was not promoted. */
chainSz = certmanAppendCert(chain, (word32)sizeof(chain), 0,
child, childSz);
ret = wolfSSH_CERTMAN_VerifyCerts_buffer(cm, chain, chainSz, 1);
if (ret != WS_CERT_NO_SIGNER_E) {
printf("CertMan: non-CA intermediate was promoted! ret=%d\n", ret);
result = -911; goto done;
}
done:
if (cm != NULL)
wolfSSH_CERTMAN_free(cm);
free(root);
free(fred);
free(fredKey);
return result;
}
/* Returns 1 when der's issuer name equals its subject name. Compares the name
* hashes, since DecodedCert.selfSigned also requires a self-signature in
* some wolfSSL versions. */
static int certmanIsSelfIssued(const byte* der, word32 derSz)
{
DecodedCert decoded;
int ret = 0;
wc_InitDecodedCert(&decoded, der, derSz, NULL);
if (wc_ParseCert(&decoded, CERT_TYPE, NO_VERIFY, NULL) == 0 &&
WMEMCMP(decoded.issuerHash, decoded.subjectHash,
sizeof(decoded.subjectHash)) == 0) {
ret = 1;
}
wc_FreeDecodedCert(&decoded);
return ret;
}
/* Drives CertManIntermediateIsCA through a forged [leaf <- intermediate] chain
* with only the root trusted, so the intermediate CA must be promoted for the
* leaf to find a signer.
*
* interKeyUsage selects the intermediate's KeyUsage extension:
* NULL omits KeyUsage entirely. Pins the extKeyUsageSet guard:
* without it the intermediate (extKeyUsage==0) would be
* wrongly demoted to non-CA.
* "keyCertSign" the RFC 5280 conforming CA case (needs cert-ext support).
* "digitalSignature" has KeyUsage but lacks keyCertSign: intermediate
* CA must be demoted (keyCertSign-rejection branch).
*
* selfIssued gives the intermediate the root's subject name while it keeps its
* own key and the root's signature, the shape of a CA key rollover cert.
*
* appendRoot also sends the trusted root at the end of the chain, so it goes
* through CertManIntermediateIsCA too and must stay trusted afterwards.
*
* expectPromote==1 asserts the intermediate was promoted and the leaf
* verified through it: verify returns WS_SUCCESS, or WS_CERT_PROFILE_E when
* FPKI profile enforcement (--enable-all) rejects the synthetic leaf after the
* chain verified. ==0 asserts it was not promoted (verify returns
* WS_CERT_NO_SIGNER_E). */
static int certmanCheckIntermediate(const char* interKeyUsage, int selfIssued,
int appendRoot, int expectPromote)
{
int result = 0;
int ret;
byte* root = NULL;
byte* rootKeyBuf = NULL;
word32 rootSz = 0, rootKeySz = 0;
byte inter[2048];
word32 interSz = sizeof(inter);
byte leaf[2048];
word32 leafSz = sizeof(leaf);
byte chain[6144];
word32 chainSz;
word32 idx;
ecc_key rootKey, interKey, leafKey;
int haveRootKey = 0, haveInterKey = 0, haveLeafKey = 0;
WC_RNG rng;
int haveRng = 0;
WOLFSSH_CERTMAN* cm = NULL;
if (certmanLoadFile("./keys/ca-cert-ecc.der", &root, &rootSz) != 0) {
printf("CertMan: can't load root cert\n");
result = -920; goto done;
}
if (certmanLoadFile("./keys/ca-key-ecc.der",
&rootKeyBuf, &rootKeySz) != 0) {
printf("CertMan: can't load root key\n");
result = -921; goto done;
}
if (wc_InitRng(&rng) != 0) {
result = -922; goto done;
}
haveRng = 1;
/* Only the root key must match the trusted root cert; the intermediate and
* leaf use freshly generated keys. */
if (wc_ecc_init(&rootKey) != 0) {
result = -923; goto done;
}
haveRootKey = 1;
idx = 0;
if (wc_EccPrivateKeyDecode(rootKeyBuf, &idx, &rootKey, rootKeySz) != 0) {
result = -924; goto done;
}
if (wc_ecc_init(&interKey) != 0) {
result = -925; goto done;
}
haveInterKey = 1;
if (wc_ecc_make_key(&rng, 32, &interKey) != 0) {
result = -926; goto done;
}
if (wc_ecc_init(&leafKey) != 0) {
result = -927; goto done;
}
haveLeafKey = 1;
if (wc_ecc_make_key(&rng, 32, &leafKey) != 0) {
result = -928; goto done;
}
/* Intermediate CA signed by the root. */
ret = certmanForgeCert(selfIssued ? NULL : "IntermediateCA", 1,
interKeyUsage, NULL, root, rootSz, &rootKey, &interKey, inter,
&interSz);
if (ret != 0) {
printf("CertMan: forge intermediate failed, ret=%d\n", ret);
result = -929; goto done;
}
if (selfIssued && !certmanIsSelfIssued(inter, interSz)) {
printf("CertMan: forged intermediate is not self-issued\n");
result = -935; goto done;
}
/* Leaf signed by the intermediate. */
ret = certmanForgeCert("ValidLeaf", 0, NULL, NULL, inter, interSz,
&interKey, &leafKey, leaf, &leafSz);
if (ret != 0) {
printf("CertMan: forge leaf failed, ret=%d\n", ret);
result = -930; goto done;
}
/* Trust only the root; the valid intermediate CA must be promoted so the
* leaf chains all the way up. */
cm = wolfSSH_CERTMAN_new(NULL);
if (cm == NULL) {
result = -931; goto done;
}
if (wolfSSH_CERTMAN_LoadRootCA_buffer(cm, root, rootSz) != WS_SUCCESS) {
result = -932; goto done;
}
chainSz = certmanAppendCert(chain, (word32)sizeof(chain), 0,
leaf, leafSz);
chainSz = certmanAppendCert(chain, (word32)sizeof(chain), chainSz,
inter, interSz);
if (appendRoot) {
chainSz = certmanAppendCert(chain, (word32)sizeof(chain), chainSz,
root, rootSz);
}
ret = wolfSSH_CERTMAN_VerifyCerts_buffer(cm, chain, chainSz,
appendRoot ? 3 : 2);
if (expectPromote && ret != WS_SUCCESS && ret != WS_CERT_PROFILE_E) {
printf("CertMan: chain did not verify through the intermediate CA, "
"ret=%d\n", ret);
result = -933; goto done;
}
if (!expectPromote && ret != WS_CERT_NO_SIGNER_E) {
printf("CertMan: intermediate CA without keyCertSign was promoted, "
"ret=%d\n", ret);
result = -934; goto done;
}
if (expectPromote) {
/* The intermediate stays in the manager, so the leaf alone now
* finds its signer. */
chainSz = certmanAppendCert(chain, (word32)sizeof(chain), 0,
leaf, leafSz);
ret = wolfSSH_CERTMAN_VerifyCerts_buffer(cm, chain, chainSz, 1);
if (ret != WS_SUCCESS && ret != WS_CERT_PROFILE_E) {
printf("CertMan: promoted intermediate CA not kept, ret=%d\n",
ret);
result = -936; goto done;
}
}
done:
if (cm != NULL)
wolfSSH_CERTMAN_free(cm);
if (haveRootKey)
wc_ecc_free(&rootKey);
if (haveInterKey)
wc_ecc_free(&interKey);
if (haveLeafKey)
wc_ecc_free(&leafKey);
if (haveRng)
wc_FreeRng(&rng);
free(root);
free(rootKeyBuf);
return result;
}
static int test_CertMan_PromoteValidCaIntermediate(void)
{
int result;
/* A CA intermediate with no KeyUsage extension must still be promoted. */
result = certmanCheckIntermediate(NULL, 0, 0, 1);
/* A peer may send the trusted root too; it asserts keyCertSign, so it
* passes the CA check like any other cert above the leaf. */
if (result == 0)
result = certmanCheckIntermediate(NULL, 0, 1, 1);
#ifdef WOLFSSL_CERT_EXT
/* As must a CA intermediate that explicitly asserts keyCertSign. */
if (result == 0)
result = certmanCheckIntermediate("keyCertSign", 0, 0, 1);
if (result == 0)
result = certmanCheckIntermediate("keyCertSign", 1, 0, 1);
#ifndef ALLOW_INVALID_CERTSIGN
/* But a CA intermediate carrying a KeyUsage extension that omits
* keyCertSign must be rejected (the keyCertSign-rejection branch),
* self-issued or not. */
if (result == 0)
result = certmanCheckIntermediate("digitalSignature", 0, 0, 0);
if (result == 0)
result = certmanCheckIntermediate("digitalSignature", 1, 0, 0);
#endif
#endif
return result;
}
#ifdef WOLFSSL_CERT_EXT
/* An intermediate CA with no subject key ID extension is found as the
* signer of a leaf whose authority key ID is the key ID wolfSSL derives for
* it, the SHA-1 of its SubjectPublicKeyInfo. wolfSSL finds no signer for a
* leaf whose authority key ID is anything else, here the RFC 5280 method 1
* ID of the intermediate's key or the ID of another key, and does not fall
* back to the issuer name; the intermediate must then not be left in the
* manager, so a leaf without an authority key ID, found by issuer name
* alone, still has no signer afterwards. */
static int test_CertMan_IssuerWithoutSkid(void)
{
int result = 0;
int ret;
byte* root = NULL;
byte* rootKeyBuf = NULL;
word32 rootSz = 0, rootKeySz = 0;
byte inter[2048];
word32 interSz = sizeof(inter);
byte leaf[2048];
word32 leafSz;
byte chain[4096];
word32 chainSz;
word32 idx;
ecc_key rootKey, interKey, leafKey;
int haveRootKey = 0, haveInterKey = 0, haveLeafKey = 0;
WC_RNG rng;
int haveRng = 0;
WOLFSSH_CERTMAN* cm = NULL;
int i;
if (certmanLoadFile("./keys/ca-cert-ecc.der", &root, &rootSz) != 0 ||
certmanLoadFile("./keys/ca-key-ecc.der",
&rootKeyBuf, &rootKeySz) != 0) {
printf("CertMan: can't load test certs\n");
result = -980; goto done;
}
if (wc_InitRng(&rng) != 0) {
result = -981; goto done;
}
haveRng = 1;
if (wc_ecc_init(&rootKey) != 0) {
result = -982; goto done;
}
haveRootKey = 1;
idx = 0;
if (wc_EccPrivateKeyDecode(rootKeyBuf, &idx, &rootKey, rootKeySz) != 0) {
result = -983; goto done;
}
if (wc_ecc_init(&interKey) != 0) {
result = -984; goto done;
}
haveInterKey = 1;
if (wc_ecc_init(&leafKey) != 0) {
result = -985; goto done;
}
haveLeafKey = 1;
if (wc_ecc_make_key(&rng, 32, &interKey) != 0 ||
wc_ecc_make_key(&rng, 32, &leafKey) != 0) {
result = -986; goto done;
}
if (certmanForgeCertKeyIds("NoSkidCA", 1, NULL, NULL, root, rootSz,
&rootKey, &interKey, CERTMAN_NO_SKID, NULL,
inter, &interSz) != 0) {
result = -987; goto done;
}
/* 0: wolfSSL's ID for the intermediate, 1: the method 1 ID of its key,
* 2: an ID of another key */
for (i = 0; i < 3; i++) {
cm = wolfSSH_CERTMAN_new(NULL);
if (cm == NULL || wolfSSH_CERTMAN_LoadRootCA_buffer(cm, root, rootSz)
!= WS_SUCCESS) {
result = -988; goto done;
}
leafSz = sizeof(leaf);
if (certmanForgeCertKeyIds("NoSkidLeaf", 0, NULL, NULL, inter,
interSz, &interKey, &leafKey,
i == 0 ? CERTMAN_AKID_SPKI : 0,
i == 2 ? &leafKey : &interKey, leaf, &leafSz) != 0) {
result = -989; goto done;
}
chainSz = certmanAppendCert(chain, (word32)sizeof(chain), 0,
leaf, leafSz);
chainSz = certmanAppendCert(chain, (word32)sizeof(chain), chainSz,
inter, interSz);
ret = wolfSSH_CERTMAN_VerifyCerts_buffer(cm, chain, chainSz, 2);
if (i == 0 && ret != WS_SUCCESS && ret != WS_CERT_PROFILE_E) {
printf("CertMan: issuer without SKID not found, ret=%d\n", ret);
result = -990; goto done;
}
if (i > 0) {
if (ret != WS_CERT_NO_SIGNER_E) {
printf("CertMan: AKID case %d got %d\n", i, ret);
result = -991; goto done;
}
leafSz = sizeof(leaf);
if (certmanForgeCertKeyIds("NameLeaf", 0, NULL, NULL, inter,
interSz, &interKey, &leafKey, CERTMAN_NO_AKID, NULL,
leaf, &leafSz) != 0) {
result = -992; goto done;
}
chainSz = certmanAppendCert(chain, (word32)sizeof(chain), 0,
leaf, leafSz);
ret = wolfSSH_CERTMAN_VerifyCerts_buffer(cm, chain, chainSz, 1);
if (ret != WS_CERT_NO_SIGNER_E) {
printf("CertMan: intermediate left loaded, ret=%d\n", ret);
result = -993; goto done;
}
}
wolfSSH_CERTMAN_free(cm);
cm = NULL;
}
done:
if (cm != NULL)
wolfSSH_CERTMAN_free(cm);
if (haveRootKey)
wc_ecc_free(&rootKey);
if (haveInterKey)
wc_ecc_free(&interKey);
if (haveLeafKey)
wc_ecc_free(&leafKey);
if (haveRng)
wc_FreeRng(&rng);
free(root);
free(rootKeyBuf);
return result;
}
#endif /* WOLFSSL_CERT_EXT */
#ifdef WOLFSSH_TEST_SET_CERTMAN
/* Verifies chain and expects expected, then, after the application clears
* the chain CAs, expects goodLeaf, signed by the root, to still verify. */
static int certmanCheckRootKept(WOLFSSH_CERTMAN* cm, WOLFSSL_CERT_MANAGER* wcm,
const byte* chain, word32 chainSz, word32 count, int expected,
const byte* goodLeaf, word32 goodLeafSz)
{
byte one[2048 + UINT32_SZ];
word32 oneSz;
int ret;
ret = wolfSSH_CERTMAN_VerifyCerts_buffer(cm, chain, chainSz, count);
if (ret != expected) {
printf("CertMan: chain got %d, expected %d\n", ret, expected);
return -940;
}
#ifdef WOLFSSH_CERTMAN_CHAIN_CA
if (wolfSSL_CertManagerUnloadIntermediateCerts(wcm) != WOLFSSL_SUCCESS) {
printf("CertMan: unloading intermediate certs failed\n");
return -941;
}
#else
(void)wcm;
#endif
oneSz = certmanAppendCert(one, (word32)sizeof(one), 0,
goodLeaf, goodLeafSz);
ret = wolfSSH_CERTMAN_VerifyCerts_buffer(cm, one, oneSz, 1);
if (ret != WS_SUCCESS && ret != WS_CERT_PROFILE_E) {
printf("CertMan: trusted root lost, ret=%d\n", ret);
return -942;
}
return 0;
}
/* A peer chain that puts an already-trusted CA above a cert it does not
* sign must leave that CA a trusted root: wolfSSL's typed CA load retags
* an existing signer with the same key ID, which a later
* wolfSSL_CertManagerUnloadIntermediateCerts() would then remove.
* 1. [leaf not issued by the root, root]
* 2. [leaf, cert named as its issuer that shares the root's key ID]
* 3. a valid [leaf, intermediate] chain: the intermediate is a chain CA,
* cleared by the unload, while the root stays. Before that, it is not
* loaded above a leaf it did not issue, or above one the root signed. */
static int test_CertMan_TrustedRootNotRetagged(void)
{
int result = 0;
int ret;
byte* root = NULL;
byte* rootKeyBuf = NULL;
byte* fred = NULL;
word32 rootSz = 0, rootKeySz = 0, fredSz = 0;
byte goodLeaf[2048];
word32 goodLeafSz = sizeof(goodLeaf);
byte leaf[2048];
word32 leafSz;
byte ca[2048];
word32 caSz;
byte chain[6144];
word32 chainSz;
word32 idx;
ecc_key rootKey, leafKey;
int haveRootKey = 0, haveLeafKey = 0;
WC_RNG rng;
int haveRng = 0;
WOLFSSH_CTX* ctx = NULL;
WOLFSSL_CERT_MANAGER* wcm = NULL;
WOLFSSH_CERTMAN* cm = NULL;
if (certmanLoadFile("./keys/ca-cert-ecc.der", &root, &rootSz) != 0 ||
certmanLoadFile("./keys/ca-key-ecc.der",
&rootKeyBuf, &rootKeySz) != 0 ||
certmanLoadFile("./keys/fred-cert.der", &fred, &fredSz) != 0) {
printf("CertMan: can't load test certs\n");
result = -943; goto done;
}
if (wc_InitRng(&rng) != 0) {
result = -944; goto done;
}
haveRng = 1;
if (wc_ecc_init(&rootKey) != 0) {
result = -945; goto done;
}
haveRootKey = 1;
idx = 0;
if (wc_EccPrivateKeyDecode(rootKeyBuf, &idx, &rootKey, rootKeySz) != 0) {
result = -946; goto done;
}
if (wc_ecc_init(&leafKey) != 0) {
result = -947; goto done;
}
haveLeafKey = 1;
if (wc_ecc_make_key(&rng, 32, &leafKey) != 0) {
result = -948; goto done;
}
if (certmanForgeCert("GoodLeaf", 0, NULL, NULL, root, rootSz, &rootKey,
&leafKey, goodLeaf, &goodLeafSz) != 0) {
result = -949; goto done;
}
/* Import the wolfSSL manager so the test can unload from it. */
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
wcm = wolfSSL_CertManagerNew();
if (ctx == NULL || wcm == NULL ||
wolfSSH_SetCertManager(ctx, wcm) != WS_SUCCESS) {
result = -950; goto done;
}
cm = ctx->certMan;
if (wolfSSH_CERTMAN_LoadRootCA_buffer(cm, root, rootSz) != WS_SUCCESS) {
result = -951; goto done;
}
/* 1. A leaf issued under Fred's name, with the trusted root above. */
leafSz = sizeof(leaf);
if (certmanForgeCert("BogusLeaf", 0, NULL, NULL, fred, fredSz, &leafKey,
&leafKey, leaf, &leafSz) != 0) {
result = -952; goto done;
}
chainSz = certmanAppendCert(chain, (word32)sizeof(chain), 0,
leaf, leafSz);
chainSz = certmanAppendCert(chain, (word32)sizeof(chain), chainSz,
root, rootSz);
result = certmanCheckRootKept(cm, wcm, chain, chainSz, 2,
WS_CERT_NO_SIGNER_E, goodLeaf, goodLeafSz);
if (result != 0)
goto done;
#ifdef WOLFSSL_CERT_EXT
/* 2. A CA under a new name with the root's key, so the same key ID,
* signed by the root, above a leaf issued under that name. The root
* is the signer the load finds by that key ID. */
caSz = sizeof(ca);
if (certmanForgeCert("RenamedRoot", 1, NULL, NULL, root, rootSz,
&rootKey, &rootKey, ca, &caSz) != 0) {
result = -953; goto done;
}
leafSz = sizeof(leaf);
if (certmanForgeCert("RenamedLeaf", 0, NULL, NULL, ca, caSz, &rootKey,
&leafKey, leaf, &leafSz) != 0) {
result = -954; goto done;
}
{
DecodedCert a, b;
int same = 0;
wc_InitDecodedCert(&a, root, rootSz, NULL);
wc_InitDecodedCert(&b, ca, caSz, NULL);
if (wc_ParseCert(&a, CERT_TYPE, NO_VERIFY, NULL) == 0 &&
wc_ParseCert(&b, CERT_TYPE, NO_VERIFY, NULL) == 0) {
same = WMEMCMP(a.extSubjKeyId, b.extSubjKeyId,
sizeof(a.extSubjKeyId)) == 0;
}
wc_FreeDecodedCert(&b);
wc_FreeDecodedCert(&a);
if (!same) {
printf("CertMan: renamed root has its own key ID\n");
result = -955; goto done;
}
}
chainSz = certmanAppendCert(chain, (word32)sizeof(chain), 0,
leaf, leafSz);
chainSz = certmanAppendCert(chain, (word32)sizeof(chain), chainSz,
ca, caSz);
result = certmanCheckRootKept(cm, wcm, chain, chainSz, 2,
WS_CERT_NO_SIGNER_E, goodLeaf, goodLeafSz);
if (result != 0)
goto done;
#endif /* WOLFSSL_CERT_EXT */
/* 3. A valid intermediate, cleared by the unload. */
caSz = sizeof(ca);
if (certmanForgeCert("IntermediateCA", 1, NULL, NULL, root, rootSz,
&rootKey, &leafKey, ca, &caSz) != 0) {
result = -956; goto done;
}
leafSz = sizeof(leaf);
if (certmanForgeCert("InterLeaf", 0, NULL, NULL, ca, caSz, &leafKey,
&leafKey, leaf, &leafSz) != 0) {
result = -957; goto done;
}
/* Above a leaf it did not issue, the intermediate is not loaded. */
{
byte bogus[2048];
word32 bogusSz = sizeof(bogus);
if (certmanForgeCert("BogusLeaf", 0, NULL, NULL, fred, fredSz,
&leafKey, &leafKey, bogus, &bogusSz) != 0) {
result = -960; goto done;
}
chainSz = certmanAppendCert(chain, (word32)sizeof(chain), 0,
bogus, bogusSz);
chainSz = certmanAppendCert(chain, (word32)sizeof(chain), chainSz,
ca, caSz);
ret = wolfSSH_CERTMAN_VerifyCerts_buffer(cm, chain, chainSz, 2);
if (ret != WS_CERT_NO_SIGNER_E) {
printf("CertMan: bogus intermediate chain got %d\n", ret);
result = -961; goto done;
}
chainSz = certmanAppendCert(chain, (word32)sizeof(chain), 0,
leaf, leafSz);
ret = wolfSSH_CERTMAN_VerifyCerts_buffer(cm, chain, chainSz, 1);
if (ret != WS_CERT_NO_SIGNER_E) {
printf("CertMan: intermediate loaded for a cert it did not "
"issue, ret=%d\n", ret);
result = -962; goto done;
}
}
/* Nor above a leaf that has a signer without it. */
chainSz = certmanAppendCert(chain, (word32)sizeof(chain), 0,
goodLeaf, goodLeafSz);
chainSz = certmanAppendCert(chain, (word32)sizeof(chain), chainSz,
ca, caSz);
ret = wolfSSH_CERTMAN_VerifyCerts_buffer(cm, chain, chainSz, 2);
if (ret != WS_SUCCESS && ret != WS_CERT_PROFILE_E) {
printf("CertMan: root-signed leaf under an intermediate got %d\n",
ret);
result = -963; goto done;
}
chainSz = certmanAppendCert(chain, (word32)sizeof(chain), 0,
leaf, leafSz);
ret = wolfSSH_CERTMAN_VerifyCerts_buffer(cm, chain, chainSz, 1);
if (ret != WS_CERT_NO_SIGNER_E) {
printf("CertMan: intermediate loaded for a leaf with a signer, "
"ret=%d\n", ret);
result = -964; goto done;
}
chainSz = certmanAppendCert(chain, (word32)sizeof(chain), 0,
leaf, leafSz);
chainSz = certmanAppendCert(chain, (word32)sizeof(chain), chainSz,
ca, caSz);
ret = wolfSSH_CERTMAN_VerifyCerts_buffer(cm, chain, chainSz, 2);
if (ret != WS_SUCCESS && ret != WS_CERT_PROFILE_E) {
printf("CertMan: intermediate chain failed, ret=%d\n", ret);
result = -958; goto done;
}
result = certmanCheckRootKept(cm, wcm, chain, chainSz, 2, ret,
goodLeaf, goodLeafSz);
if (result != 0)
goto done;
#ifdef WOLFSSH_CERTMAN_CHAIN_CA
chainSz = certmanAppendCert(chain, (word32)sizeof(chain), 0,
leaf, leafSz);
ret = wolfSSH_CERTMAN_VerifyCerts_buffer(cm, chain, chainSz, 1);
if (ret != WS_CERT_NO_SIGNER_E) {
printf("CertMan: chain CA survived the unload, ret=%d\n", ret);
result = -959; goto done;
}
#endif
done:
if (ctx != NULL)
wolfSSH_CTX_free(ctx);
if (wcm != NULL)
wolfSSL_CertManagerFree(wcm);
if (haveRootKey)
wc_ecc_free(&rootKey);
if (haveLeafKey)
wc_ecc_free(&leafKey);
if (haveRng)
wc_FreeRng(&rng);
free(root);
free(rootKeyBuf);
free(fred);
return result;
}
#ifdef WOLFSSH_CERTMAN_CHAIN_CA
/* A valid intermediate loaded for a leaf whose signature is bad must still
* be a chain CA, cleared by wolfSSL_CertManagerUnloadIntermediateCerts(),
* or any peer could leave it trusted as a root. */
static int test_CertMan_BadSigChildChainCA(void)
{
int result = 0;
int ret;
byte* root = NULL;
byte* rootKeyBuf = NULL;
word32 rootSz = 0, rootKeySz = 0;
byte goodLeaf[2048];
word32 goodLeafSz = sizeof(goodLeaf);
byte leaf[2048];
word32 leafSz = sizeof(leaf);
byte badLeaf[2048];
word32 badLeafSz = sizeof(badLeaf);
byte ca[2048];
word32 caSz = sizeof(ca);
byte chain[6144];
word32 chainSz;
word32 idx = 0;
ecc_key rootKey, caKey, leafKey;
int haveRootKey = 0, haveCaKey = 0, haveLeafKey = 0;
WC_RNG rng;
int haveRng = 0;
WOLFSSH_CTX* ctx = NULL;
WOLFSSL_CERT_MANAGER* wcm = NULL;
WOLFSSH_CERTMAN* cm = NULL;
if (certmanLoadFile("./keys/ca-cert-ecc.der", &root, &rootSz) != 0 ||
certmanLoadFile("./keys/ca-key-ecc.der",
&rootKeyBuf, &rootKeySz) != 0) {
printf("CertMan: can't load test certs\n");
result = -1134; goto done;
}
if (wc_InitRng(&rng) != 0) {
result = -1135; goto done;
}
haveRng = 1;
if (wc_ecc_init(&rootKey) != 0) {
result = -1136; goto done;
}
haveRootKey = 1;
if (wc_EccPrivateKeyDecode(rootKeyBuf, &idx, &rootKey, rootKeySz) != 0) {
result = -1137; goto done;
}
if (wc_ecc_init(&caKey) != 0) {
result = -1138; goto done;
}
haveCaKey = 1;
if (wc_ecc_init(&leafKey) != 0) {
result = -1139; goto done;
}
haveLeafKey = 1;
if (wc_ecc_make_key(&rng, 32, &caKey) != 0 ||
wc_ecc_make_key(&rng, 32, &leafKey) != 0) {
result = -1140; goto done;
}
/* badLeaf names the intermediate as issuer but is signed by leafKey. */
if (certmanForgeCert("GoodLeaf", 0, NULL, NULL, root, rootSz, &rootKey,
&leafKey, goodLeaf, &goodLeafSz) != 0 ||
certmanForgeCert("IntermediateCA", 1, NULL, NULL, root, rootSz,
&rootKey, &caKey, ca, &caSz) != 0 ||
certmanForgeCert("InterLeaf", 0, NULL, NULL, ca, caSz, &caKey,
&leafKey, leaf, &leafSz) != 0 ||
certmanForgeCert("BadSigLeaf", 0, NULL, NULL, ca, caSz,
&leafKey, &leafKey, badLeaf, &badLeafSz) != 0) {
result = -1141; goto done;
}
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
wcm = wolfSSL_CertManagerNew();
if (ctx == NULL || wcm == NULL ||
wolfSSH_SetCertManager(ctx, wcm) != WS_SUCCESS) {
result = -1142; goto done;
}
cm = ctx->certMan;
if (wolfSSH_CERTMAN_LoadRootCA_buffer(cm, root, rootSz) != WS_SUCCESS) {
result = -1143; goto done;
}
chainSz = certmanAppendCert(chain, (word32)sizeof(chain), 0,
badLeaf, badLeafSz);
chainSz = certmanAppendCert(chain, (word32)sizeof(chain), chainSz,
ca, caSz);
ret = wolfSSH_CERTMAN_VerifyCerts_buffer(cm, chain, chainSz, 2);
if (ret != WS_CERT_SIG_CONFIRM_E) {
printf("CertMan: bad signature leaf got %d\n", ret);
result = -1144; goto done;
}
/* The intermediate is loaded... */
chainSz = certmanAppendCert(chain, (word32)sizeof(chain), 0,
leaf, leafSz);
ret = wolfSSH_CERTMAN_VerifyCerts_buffer(cm, chain, chainSz, 1);
if (ret != WS_SUCCESS && ret != WS_CERT_PROFILE_E) {
printf("CertMan: intermediate not loaded, ret=%d\n", ret);
result = -1145; goto done;
}
/* ...as a chain CA: the unload clears it and keeps the root. */
result = certmanCheckRootKept(cm, wcm, chain, chainSz, 1, ret,
goodLeaf, goodLeafSz);
if (result != 0)
goto done;
ret = wolfSSH_CERTMAN_VerifyCerts_buffer(cm, chain, chainSz, 1);
if (ret != WS_CERT_NO_SIGNER_E) {
printf("CertMan: intermediate survived the unload, ret=%d\n", ret);
result = -1146; goto done;
}
done:
if (ctx != NULL)
wolfSSH_CTX_free(ctx);
if (wcm != NULL)
wolfSSL_CertManagerFree(wcm);
if (haveRootKey)
wc_ecc_free(&rootKey);
if (haveCaKey)
wc_ecc_free(&caKey);
if (haveLeafKey)
wc_ecc_free(&leafKey);
if (haveRng)
wc_FreeRng(&rng);
free(root);
free(rootKeyBuf);
return result;
}
#endif /* WOLFSSH_CERTMAN_CHAIN_CA */
#if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSH_CERTMAN_CHAIN_CA) && \
!defined(WOLFSSL_STATIC_MEMORY) && !defined(WOLFSSL_DEBUG_MEMORY)
static int certmanAllocNth;
static int certmanAllocHits;
static void* certmanFailMalloc(size_t size)
{
if (++certmanAllocHits == certmanAllocNth) {
return NULL;
}
return malloc(size);
}
static void* certmanFailRealloc(void* p, size_t size)
{
if (++certmanAllocHits == certmanAllocNth) {
return NULL;
}
return realloc(p, size);
}
/* An allocation failure while verifying a chain must not retag a trusted
* root. The chain puts a CA sharing the root's key ID above a leaf issued
* under its name, so loading it adds nothing; if the leaf's verification
* then fails for another reason, a typed load would retag the root. Fail
* each allocation of the chain in turn: every time, the root must survive
* wolfSSL_CertManagerUnloadIntermediateCerts(). */
static int test_CertMan_AllocFailKeepsRoot(void)
{
int result = 0;
int ret;
int nth;
byte* root = NULL;
byte* rootKeyBuf = NULL;
word32 rootSz = 0, rootKeySz = 0;
byte goodLeaf[2048];
word32 goodLeafSz = sizeof(goodLeaf);
byte leaf[2048];
word32 leafSz = sizeof(leaf);
byte ca[2048];
word32 caSz = sizeof(ca);
byte chain[6144];
word32 chainSz;
byte one[2048 + UINT32_SZ];
word32 oneSz;
word32 idx = 0;
ecc_key rootKey, leafKey;
int haveRootKey = 0, haveLeafKey = 0;
WC_RNG rng;
int haveRng = 0;
WOLFSSH_CTX* ctx = NULL;
WOLFSSL_CERT_MANAGER* wcm = NULL;
wolfSSL_Malloc_cb mf;
wolfSSL_Free_cb ff;
wolfSSL_Realloc_cb rf;
if (certmanLoadFile("./keys/ca-cert-ecc.der", &root, &rootSz) != 0 ||
certmanLoadFile("./keys/ca-key-ecc.der",
&rootKeyBuf, &rootKeySz) != 0) {
printf("CertMan: can't load test certs\n");
result = -1000; goto done;
}
if (wc_InitRng(&rng) != 0) {
result = -1001; goto done;
}
haveRng = 1;
if (wc_ecc_init(&rootKey) != 0) {
result = -1002; goto done;
}
haveRootKey = 1;
if (wc_EccPrivateKeyDecode(rootKeyBuf, &idx, &rootKey, rootKeySz) != 0) {
result = -1003; goto done;
}
if (wc_ecc_init(&leafKey) != 0) {
result = -1004; goto done;
}
haveLeafKey = 1;
if (wc_ecc_make_key(&rng, 32, &leafKey) != 0) {
result = -1005; goto done;
}
if (certmanForgeCert("GoodLeaf", 0, NULL, NULL, root, rootSz, &rootKey,
&leafKey, goodLeaf, &goodLeafSz) != 0 ||
certmanForgeCert("RenamedRoot", 1, NULL, NULL, root, rootSz,
&rootKey, &rootKey, ca, &caSz) != 0 ||
certmanForgeCert("RenamedLeaf", 0, NULL, NULL, ca, caSz,
&rootKey, &leafKey, leaf, &leafSz) != 0) {
result = -1006; goto done;
}
chainSz = certmanAppendCert(chain, (word32)sizeof(chain), 0,
leaf, leafSz);
chainSz = certmanAppendCert(chain, (word32)sizeof(chain), chainSz,
ca, caSz);
if (wolfSSL_GetAllocators(&mf, &ff, &rf) != 0) {
result = -1007; goto done;
}
for (nth = 1; result == 0; nth++) {
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
wcm = wolfSSL_CertManagerNew();
if (ctx == NULL || wcm == NULL ||
wolfSSH_SetCertManager(ctx, wcm) != WS_SUCCESS ||
wolfSSH_CERTMAN_LoadRootCA_buffer(ctx->certMan,
root, rootSz) != WS_SUCCESS) {
result = -1008; goto done;
}
certmanAllocNth = nth;
certmanAllocHits = 0;
if (wolfSSL_SetAllocators(certmanFailMalloc, ff,
certmanFailRealloc) != 0) {
result = -1009; goto done;
}
ret = wolfSSH_CERTMAN_VerifyCerts_buffer(ctx->certMan, chain,
chainSz, 2);
wolfSSL_SetAllocators(mf, ff, rf);
if (ret == WS_SUCCESS) {
printf("CertMan: renamed-root chain verified, nth=%d\n", nth);
result = -1010; goto done;
}
if (wolfSSL_CertManagerUnloadIntermediateCerts(wcm)
!= WOLFSSL_SUCCESS) {
result = -1011; goto done;
}
oneSz = certmanAppendCert(one, (word32)sizeof(one), 0,
goodLeaf, goodLeafSz);
ret = wolfSSH_CERTMAN_VerifyCerts_buffer(ctx->certMan, one, oneSz, 1);
if (ret != WS_SUCCESS && ret != WS_CERT_PROFILE_E) {
printf("CertMan: root lost with allocation %d failed, ret=%d\n",
nth, ret);
result = -1012;
}
wolfSSH_CTX_free(ctx);
ctx = NULL;
wolfSSL_CertManagerFree(wcm);
wcm = NULL;
/* Stop once a pass completes without reaching the failure. */
if (certmanAllocHits < nth)
break;
}
done:
if (ctx != NULL)
wolfSSH_CTX_free(ctx);
if (wcm != NULL)
wolfSSL_CertManagerFree(wcm);
if (haveRootKey)
wc_ecc_free(&rootKey);
if (haveLeafKey)
wc_ecc_free(&leafKey);
if (haveRng)
wc_FreeRng(&rng);
free(root);
free(rootKeyBuf);
return result;
}
#endif /* WOLFSSL_CERT_EXT && WOLFSSH_CERTMAN_CHAIN_CA && ... */
#endif /* WOLFSSH_TEST_SET_CERTMAN */
#ifdef WOLFSSL_CERT_EXT
/* The FPKI profile check runs after the RFC 6187 usage check and never
* matches a forged leaf, so in an FPKI build a leaf that passes the usage
* check surfaces as WS_CERT_PROFILE_E rather than WS_SUCCESS. Either way it
* is distinct from WS_CERT_KEY_USAGE_E. */
#ifdef WOLFSSH_NO_FPKI
#define CERTMAN_LEAF_USAGE_OK WS_SUCCESS
#else
#define CERTMAN_LEAF_USAGE_OK WS_CERT_PROFILE_E
#endif
/* Forges a leaf signed by the test root carrying the given KeyUsage and
* ExtendedKeyUsage (NULL omits the extension), verifies it through a manager
* owned by a CTX of the given endpoint, or a standalone manager when side is
* -1, and compares the result with expected. */
static int certmanCheckLeafUsage(const char* keyUsage, const char* extKeyUsage,
int side, int expected)
{
int result = 0;
int ret;
byte* root = NULL;
byte* rootKeyBuf = NULL;
word32 rootSz = 0, rootKeySz = 0;
byte leaf[2048];
word32 leafSz = sizeof(leaf);
byte chain[4096];
word32 chainSz;
word32 idx;
ecc_key rootKey, leafKey;
int haveRootKey = 0, haveLeafKey = 0;
WC_RNG rng;
int haveRng = 0;
WOLFSSH_CTX* ctx = NULL;
WOLFSSH_CERTMAN* cm = NULL;
if (certmanLoadFile("./keys/ca-cert-ecc.der", &root, &rootSz) != 0) {
printf("CertMan: can't load root cert\n");
result = -940; goto done;
}
if (certmanLoadFile("./keys/ca-key-ecc.der",
&rootKeyBuf, &rootKeySz) != 0) {
printf("CertMan: can't load root key\n");
result = -941; goto done;
}
if (wc_InitRng(&rng) != 0) {
result = -942; goto done;
}
haveRng = 1;
if (wc_ecc_init(&rootKey) != 0) {
result = -943; goto done;
}
haveRootKey = 1;
idx = 0;
if (wc_EccPrivateKeyDecode(rootKeyBuf, &idx, &rootKey, rootKeySz) != 0) {
result = -944; goto done;
}
if (wc_ecc_init(&leafKey) != 0) {
result = -945; goto done;
}
haveLeafKey = 1;
if (wc_ecc_make_key(&rng, 32, &leafKey) != 0) {
result = -946; goto done;
}
ret = certmanForgeCert("UsageLeaf", 0, keyUsage, extKeyUsage,
root, rootSz, &rootKey, &leafKey, leaf, &leafSz);
if (ret != 0) {
printf("CertMan: forge leaf (KU %s, EKU %s) failed, ret=%d\n",
keyUsage ? keyUsage : "none",
extKeyUsage ? extKeyUsage : "none", ret);
result = -947; goto done;
}
if (side == WOLFSSH_ENDPOINT_SERVER || side == WOLFSSH_ENDPOINT_CLIENT) {
ctx = wolfSSH_CTX_new(side, NULL);
if (ctx == NULL) {
result = -948; goto done;
}
if (wolfSSH_CTX_AddRootCert_buffer(ctx, root, rootSz,
WOLFSSH_FORMAT_ASN1) != WS_SUCCESS) {
result = -949; goto done;
}
cm = ctx->certMan;
}
else {
cm = wolfSSH_CERTMAN_new(NULL);
if (cm == NULL) {
result = -950; goto done;
}
if (wolfSSH_CERTMAN_LoadRootCA_buffer(cm, root, rootSz)
!= WS_SUCCESS) {
result = -951; goto done;
}
}
chainSz = certmanAppendCert(chain, (word32)sizeof(chain), 0,
leaf, leafSz);
ret = wolfSSH_CERTMAN_VerifyCerts_buffer(cm, chain, chainSz, 1);
if (ret != expected) {
printf("CertMan: leaf KU %s, EKU %s, side %d: got %d, expected %d\n",
keyUsage ? keyUsage : "none",
extKeyUsage ? extKeyUsage : "none", side, ret, expected);
result = -952; goto done;
}
done:
if (ctx != NULL)
wolfSSH_CTX_free(ctx);
else if (cm != NULL)
wolfSSH_CERTMAN_free(cm);
if (haveRootKey)
wc_ecc_free(&rootKey);
if (haveLeafKey)
wc_ecc_free(&leafKey);
if (haveRng)
wc_FreeRng(&rng);
free(root);
free(rootKeyBuf);
return result;
}
/* RFC 6187 section 2.2: a leaf KeyUsage must assert digitalSignature and a
* leaf ExtendedKeyUsage must name a purpose for the role being verified.
* The server side verifies user certs (client purpose), the client side host
* certs (server purpose), and a standalone manager accepts either. */
static int test_CertMan_LeafKeyUsage(void)
{
static const struct {
const char* keyUsage;
const char* extKeyUsage;
int side;
int expected;
} tv[] = {
{ NULL, NULL, WOLFSSH_ENDPOINT_SERVER, CERTMAN_LEAF_USAGE_OK },
{ "digitalSignature", NULL, WOLFSSH_ENDPOINT_SERVER,
CERTMAN_LEAF_USAGE_OK },
{ "keyEncipherment", NULL, WOLFSSH_ENDPOINT_SERVER,
WS_CERT_KEY_USAGE_E },
{ "keyEncipherment", NULL, WOLFSSH_ENDPOINT_CLIENT,
WS_CERT_KEY_USAGE_E },
{ "keyEncipherment", "clientAuth", -1, WS_CERT_KEY_USAGE_E },
{ "digitalSignature", "any", WOLFSSH_ENDPOINT_SERVER,
CERTMAN_LEAF_USAGE_OK },
{ "digitalSignature", "any", WOLFSSH_ENDPOINT_CLIENT,
CERTMAN_LEAF_USAGE_OK },
{ "digitalSignature", "clientAuth", WOLFSSH_ENDPOINT_SERVER,
CERTMAN_LEAF_USAGE_OK },
{ "digitalSignature", "clientAuth", WOLFSSH_ENDPOINT_CLIENT,
WS_CERT_KEY_USAGE_E },
{ "digitalSignature", "serverAuth", WOLFSSH_ENDPOINT_SERVER,
WS_CERT_KEY_USAGE_E },
{ "digitalSignature", "serverAuth", WOLFSSH_ENDPOINT_CLIENT,
CERTMAN_LEAF_USAGE_OK },
{ "digitalSignature", "serverAuth", -1, CERTMAN_LEAF_USAGE_OK },
{ "digitalSignature", "serverAuth,clientAuth",
WOLFSSH_ENDPOINT_SERVER, CERTMAN_LEAF_USAGE_OK },
{ "digitalSignature", "codeSigning", WOLFSSH_ENDPOINT_SERVER,
WS_CERT_KEY_USAGE_E },
{ "digitalSignature", "codeSigning", WOLFSSH_ENDPOINT_CLIENT,
WS_CERT_KEY_USAGE_E },
{ "digitalSignature", "codeSigning", -1, WS_CERT_KEY_USAGE_E },
{ "digitalSignature", "emailProtection", WOLFSSH_ENDPOINT_SERVER,
WS_CERT_KEY_USAGE_E },
{ NULL, "emailProtection", WOLFSSH_ENDPOINT_SERVER,
WS_CERT_KEY_USAGE_E },
#ifdef WOLFSSL_EKU_OID
/* id-kp-secureShellClient and id-kp-secureShellServer */
{ "digitalSignature", "1.3.6.1.5.5.7.3.21", WOLFSSH_ENDPOINT_SERVER,
CERTMAN_LEAF_USAGE_OK },
{ "digitalSignature", "1.3.6.1.5.5.7.3.21", WOLFSSH_ENDPOINT_CLIENT,
WS_CERT_KEY_USAGE_E },
{ "digitalSignature", "1.3.6.1.5.5.7.3.22", WOLFSSH_ENDPOINT_CLIENT,
CERTMAN_LEAF_USAGE_OK },
{ "digitalSignature", "1.3.6.1.5.5.7.3.22", WOLFSSH_ENDPOINT_SERVER,
WS_CERT_KEY_USAGE_E },
#endif
};
int result = 0;
word32 i;
for (i = 0; result == 0 && i < sizeof(tv) / sizeof(tv[0]); i++) {
result = certmanCheckLeafUsage(tv[i].keyUsage, tv[i].extKeyUsage,
tv[i].side, tv[i].expected);
}
return result;
}
#if !defined(WOLFSSH_NO_FPKI) && defined(WOLFSSL_SUBJ_DIR_ATTR)
/* A leaf that names its issuer as its own subject is self-issued, so the
* NO_VERIFY parse before CheckProfile() looks up no signer for it. Give it
* what the FPKI worksheet 6 profile checks ahead of the issuer-DN match and
* expect WS_CERT_PROFILE_E, not a NULL dereference. wolfSSL cannot write a
* subjectDirectoryAttributes extension, so the leaf carries the
* countryOfCitizenship value as a CRL distribution points extension whose
* OID is rewritten to 2.5.29.9 before signing. */
static int test_CertMan_ProfileLeafNoSigner(void)
{
static const byte sda[] = {
0x30, 0x12, 0x30, 0x10,
0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x09, 0x04,
0x31, 0x04, 0x13, 0x02, 'U', 'S'
};
static const byte crlDpOid[] = { 0x06, 0x03, 0x55, 0x1d, 0x1f };
int result = 0;
int ret;
int sz;
byte* root = NULL;
byte* rootKeyBuf = NULL;
word32 rootSz = 0, rootKeySz = 0;
byte leaf[2048];
word32 leafSz = 0;
byte chain[4096];
word32 chainSz;
word32 idx;
ecc_key rootKey, leafKey;
int haveRootKey = 0, haveLeafKey = 0;
WC_RNG rng;
int haveRng = 0;
Cert cert;
DecodedCert decoded;
WOLFSSH_CERTMAN* cm = NULL;
if (certmanLoadFile("./keys/ca-cert-ecc.der", &root, &rootSz) != 0 ||
certmanLoadFile("./keys/ca-key-ecc.der",
&rootKeyBuf, &rootKeySz) != 0) {
printf("CertMan: can't load test certs\n");
result = -970; goto done;
}
if (wc_InitRng(&rng) != 0) {
result = -971; goto done;
}
haveRng = 1;
if (wc_ecc_init(&rootKey) != 0) {
result = -972; goto done;
}
haveRootKey = 1;
idx = 0;
if (wc_EccPrivateKeyDecode(rootKeyBuf, &idx, &rootKey, rootKeySz) != 0) {
result = -973; goto done;
}
if (wc_ecc_init(&leafKey) != 0) {
result = -974; goto done;
}
haveLeafKey = 1;
if (wc_ecc_make_key(&rng, 32, &leafKey) != 0) {
result = -975; goto done;
}
ret = wc_InitCert(&cert);
if (ret == 0)
ret = wc_SetSubjectBuffer(&cert, root, (int)rootSz);
if (ret == 0)
ret = wc_SetIssuerBuffer(&cert, root, (int)rootSz);
if (ret == 0)
ret = wc_SetKeyUsage(&cert, "digitalSignature");
if (ret == 0)
ret = wc_SetSubjectKeyIdFromPublicKey_ex(&cert, ECC_TYPE, &leafKey);
if (ret == 0)
ret = wc_SetAuthKeyIdFromCert(&cert, root, (int)rootSz);
if (ret == 0) {
cert.sigType = CTC_SHA256wECDSA;
cert.daysValid = 365;
cert.isCA = 0;
WSTRNCPY(cert.certPolicies[0], "2.16.840.1.101.3.2.1.3.13",
CTC_MAX_CERTPOL_SZ - 1);
cert.certPoliciesNb = 1;
WMEMCPY(cert.crlInfo, sda, sizeof(sda));
cert.crlInfoSz = (int)sizeof(sda);
sz = wc_MakeCert(&cert, leaf, sizeof(leaf), NULL, &leafKey, &rng);
if (sz < 0)
ret = sz;
}
if (ret == 0) {
ret = -1;
for (idx = 0; idx + sizeof(crlDpOid) <= (word32)cert.bodySz; idx++) {
if (WMEMCMP(leaf + idx, crlDpOid, sizeof(crlDpOid)) == 0) {
leaf[idx + sizeof(crlDpOid) - 1] = 0x09;
ret = 0;
break;
}
}
}
if (ret == 0) {
sz = wc_SignCert(cert.bodySz, cert.sigType, leaf, sizeof(leaf), NULL,
&rootKey, &rng);
if (sz < 0)
ret = sz;
else
leafSz = (word32)sz;
}
if (ret != 0) {
printf("CertMan: forge profile leaf failed, ret=%d\n", ret);
result = -976; goto done;
}
/* The leaf must get as far as the issuer-DN match. */
wc_InitDecodedCert(&decoded, leaf, leafSz, NULL);
ret = wc_ParseCert(&decoded, CERT_TYPE, NO_VERIFY, NULL);
if (ret == 0 && WSTRCMP(decoded.countryOfCitizenship, "US") != 0) {
ret = -1;
}
wc_FreeDecodedCert(&decoded);
if (ret != 0 || !certmanIsSelfIssued(leaf, leafSz)) {
printf("CertMan: forged profile leaf is not as intended\n");
result = -977; goto done;
}
cm = wolfSSH_CERTMAN_new(NULL);
if (cm == NULL ||
wolfSSH_CERTMAN_LoadRootCA_buffer(cm, root, rootSz) != WS_SUCCESS) {
result = -978; goto done;
}
chainSz = certmanAppendCert(chain, (word32)sizeof(chain), 0,
leaf, leafSz);
ret = wolfSSH_CERTMAN_VerifyCerts_buffer(cm, chain, chainSz, 1);
if (ret != WS_CERT_PROFILE_E) {
printf("CertMan: self-issued profile leaf got %d\n", ret);
result = -979; goto done;
}
done:
if (cm != NULL)
wolfSSH_CERTMAN_free(cm);
if (haveRootKey)
wc_ecc_free(&rootKey);
if (haveLeafKey)
wc_ecc_free(&leafKey);
if (haveRng)
wc_FreeRng(&rng);
free(root);
free(rootKeyBuf);
return result;
}
#endif /* !WOLFSSH_NO_FPKI && WOLFSSL_SUBJ_DIR_ATTR */
#endif /* WOLFSSL_CERT_EXT */
#endif /* WOLFSSH_TEST_CERTMAN_PROMOTE */
#ifdef WOLFSSH_TEST_SET_CERTMAN
/* wolfSSH_SetCertManager imports a WOLFSSL_CERT_MANAGER by reference into
* the wolfSSH context. Test argument checking, importing the same manager
* twice (a reference leak there is only observable under the sanitizer or
* leak-checking builds, not by these return-value checks), replacing an
* already-imported manager, and the reference counting on both sides of
* the import: the imported manager must outlive the reference it was
* created with, and must outlive the wolfSSH context. Each of those is
* checked by loading a root CA through the manager afterwards, so a
* missing up_ref shows up as a failure or as a use-after-free under the
* sanitizer builds. */
static int test_SetCertManager(void)
{
int result = 0;
WOLFSSH_CTX* ctx = NULL;
WOLFSSL_CERT_MANAGER* cm = NULL;
WOLFSSL_CERT_MANAGER* cm2 = NULL;
#ifdef WOLFSSH_TEST_CERTMAN_ROOTCA
byte* root = NULL;
word32 rootSz = 0;
int haveRoot;
/* Autotools builds link keys/ca-cert-ecc.der into the build tree, but
* other runners (e.g. the VS unit-test.exe) may not run from a tree with
* ./keys. The argument and reference-count checks below need no file, so
* treat a missing cert as a SKIP of the root-CA half, not a failure. The
* skip is reported by returning 1 so it cannot pass as a full SUCCESS. */
haveRoot = (certmanLoadFile("./keys/ca-cert-ecc.der", &root, &rootSz)
== 0);
if (!haveRoot) {
printf("SetCertManager: SKIP root cert checks, "
"./keys/ca-cert-ecc.der not readable\n");
}
#endif
if (result == 0) {
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
result = -2;
}
if (result == 0) {
cm = wolfSSL_CertManagerNew();
if (cm == NULL)
result = -3;
}
/* bad arguments */
if (result == 0 && wolfSSH_SetCertManager(NULL, cm) != WS_BAD_ARGUMENT)
result = -4;
if (result == 0 && wolfSSH_SetCertManager(ctx, NULL) != WS_BAD_ARGUMENT)
result = -5;
/* import, then import the same manager again */
if (result == 0 && wolfSSH_SetCertManager(ctx, cm) != WS_SUCCESS)
result = -6;
if (result == 0 && wolfSSH_SetCertManager(ctx, cm) != WS_SUCCESS)
result = -7;
/* the context holds its own reference: dropping the creating reference
* must leave the imported manager usable */
if (result == 0) {
wolfSSL_CertManagerFree(cm);
cm = NULL;
}
#ifdef WOLFSSH_TEST_CERTMAN_ROOTCA
if (result == 0 && haveRoot &&
wolfSSH_CTX_AddRootCert_buffer(ctx, root, rootSz,
WOLFSSH_FORMAT_ASN1) != WS_SUCCESS)
result = -8;
#endif
/* replacing the imported manager releases the reference on the old one */
if (result == 0) {
cm2 = wolfSSL_CertManagerNew();
if (cm2 == NULL)
result = -9;
else if (wolfSSH_SetCertManager(ctx, cm2) != WS_SUCCESS)
result = -10;
}
#ifdef WOLFSSH_TEST_CERTMAN_ROOTCA
if (result == 0 && haveRoot &&
wolfSSH_CTX_AddRootCert_buffer(ctx, root, rootSz,
WOLFSSH_FORMAT_ASN1) != WS_SUCCESS)
result = -11;
#endif
/* the caller's reference outlives the context that imported it */
if (ctx != NULL)
wolfSSH_CTX_free(ctx);
#ifdef WOLFSSH_TEST_CERTMAN_ROOTCA
if (result == 0 && haveRoot && cm2 != NULL &&
wolfSSL_CertManagerLoadCABuffer(cm2, root, rootSz,
WOLFSSL_FILETYPE_ASN1) != WOLFSSL_SUCCESS)
result = -12;
#endif
if (cm != NULL)
wolfSSL_CertManagerFree(cm);
if (cm2 != NULL)
wolfSSL_CertManagerFree(cm2);
#ifdef WOLFSSH_TEST_CERTMAN_ROOTCA
if (root != NULL)
free(root);
if (result == 0 && !haveRoot)
result = 1;
#else
/* The reference-counting behaviour is only observable through the
* root-CA loads; without them this run verified the argument checks
* only, so report SKIPPED rather than a full SUCCESS. */
if (result == 0)
result = 1;
#endif
return result;
}
#endif /* WOLFSSH_TEST_SET_CERTMAN */
#ifdef WOLFSSH_WINDOWS_CERT_STORE
/* Check one wolfSSH_ParseCertStoreSpec call against expected results.
* expRet is the expected return value; the name/flag expectations are only
* checked when expRet is WS_SUCCESS. */
static int certStoreSpecCheck(const char* spec, int expRet,
const wchar_t* expStore, const wchar_t* expSubject, word32 expFlags)
{
int ret;
int result = 0;
wchar_t* wStoreName = NULL;
wchar_t* wSubjectName = NULL;
word32 dwFlags = 0;
ret = wolfSSH_ParseCertStoreSpec(spec, &wStoreName, &wSubjectName,
&dwFlags, NULL);
if (ret != expRet) {
printf("ParseCertStoreSpec(%s): ret %d, expected %d\n",
spec != NULL ? spec : "(null)", ret, expRet);
result = -1;
}
if (result == 0 && ret == WS_SUCCESS) {
if (wcscmp(wStoreName, expStore) != 0)
result = -2;
else if (wcscmp(wSubjectName, expSubject) != 0)
result = -3;
else if (dwFlags != expFlags)
result = -4;
}
/* on failure the parser must not hand back allocations */
if (result == 0 && ret != WS_SUCCESS &&
(wStoreName != NULL || wSubjectName != NULL)) {
result = -5;
}
wolfSSH_FreeCertStoreSpec(wStoreName, wSubjectName, NULL);
return result;
}
static int test_ParseCertStoreSpec(void)
{
int result;
wchar_t* wStoreName = NULL;
wchar_t* wSubjectName = NULL;
word32 dwFlags = 0;
/* bad arguments; the out pointers are seeded with a garbage sentinel so
* the documented "any non-NULL out-pointer is NULLed on failure"
* contract is actually observed, not just vacuously satisfied */
result = certStoreSpecCheck(NULL, WS_BAD_ARGUMENT, NULL, NULL, 0);
wSubjectName = (wchar_t*)(size_t)1;
if (result == 0 && wolfSSH_ParseCertStoreSpec("My:server", NULL,
&wSubjectName, &dwFlags, NULL) != WS_BAD_ARGUMENT)
result = -10;
if (result == 0 && wSubjectName != NULL)
result = -13;
wStoreName = (wchar_t*)(size_t)1;
if (result == 0 && wolfSSH_ParseCertStoreSpec("My:server", &wStoreName,
NULL, &dwFlags, NULL) != WS_BAD_ARGUMENT)
result = -11;
if (result == 0 && wStoreName != NULL)
result = -14;
wStoreName = (wchar_t*)(size_t)1;
wSubjectName = (wchar_t*)(size_t)1;
if (result == 0 && wolfSSH_ParseCertStoreSpec("My:server", &wStoreName,
&wSubjectName, NULL, NULL) != WS_BAD_ARGUMENT)
result = -12;
if (result == 0 && (wStoreName != NULL || wSubjectName != NULL))
result = -15;
wStoreName = NULL;
wSubjectName = NULL;
/* full spec with every named flag value, short form */
if (result == 0)
result = certStoreSpecCheck("My:server:LOCAL_MACHINE", WS_SUCCESS,
L"My", L"server", CERT_SYSTEM_STORE_LOCAL_MACHINE);
if (result == 0)
result = certStoreSpecCheck("My:server:CURRENT_USER", WS_SUCCESS,
L"My", L"server", CERT_SYSTEM_STORE_CURRENT_USER);
if (result == 0)
result = certStoreSpecCheck("My:server:USERS", WS_SUCCESS,
L"My", L"server", CERT_SYSTEM_STORE_USERS);
if (result == 0)
result = certStoreSpecCheck("My:server:CURRENT_SERVICE", WS_SUCCESS,
L"My", L"server", CERT_SYSTEM_STORE_CURRENT_SERVICE);
if (result == 0)
result = certStoreSpecCheck("My:server:SERVICES", WS_SUCCESS,
L"My", L"server", CERT_SYSTEM_STORE_SERVICES);
if (result == 0)
result = certStoreSpecCheck("My:server:CURRENT_USER_GROUP_POLICY",
WS_SUCCESS, L"My", L"server",
CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY);
if (result == 0)
result = certStoreSpecCheck("My:server:LOCAL_MACHINE_GROUP_POLICY",
WS_SUCCESS, L"My", L"server",
CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY);
if (result == 0)
result = certStoreSpecCheck("My:server:LOCAL_MACHINE_ENTERPRISE",
WS_SUCCESS, L"My", L"server",
CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE);
/* the long CERT_SYSTEM_STORE_* spellings are accepted too */
if (result == 0)
result = certStoreSpecCheck(
"My:server:CERT_SYSTEM_STORE_LOCAL_MACHINE", WS_SUCCESS,
L"My", L"server", CERT_SYSTEM_STORE_LOCAL_MACHINE);
if (result == 0)
result = certStoreSpecCheck(
"My:server:CERT_SYSTEM_STORE_CURRENT_USER", WS_SUCCESS,
L"My", L"server", CERT_SYSTEM_STORE_CURRENT_USER);
/* flags default to CURRENT_USER when not given */
if (result == 0)
result = certStoreSpecCheck("My:server", WS_SUCCESS,
L"My", L"server", CERT_SYSTEM_STORE_CURRENT_USER);
/* a subject may carry the CN= prefix and a fourth field is rejected */
if (result == 0)
result = certStoreSpecCheck("My:CN=host:LOCAL_MACHINE", WS_SUCCESS,
L"My", L"CN=host", CERT_SYSTEM_STORE_LOCAL_MACHINE);
if (result == 0)
result = certStoreSpecCheck("My:server:CURRENT_USER:extra",
WS_BAD_ARGUMENT, NULL, NULL, 0);
/* numeric flags: only system-store location bits are accepted */
if (result == 0)
result = certStoreSpecCheck("My:server:393216", WS_SUCCESS,
L"My", L"server", CERT_SYSTEM_STORE_USERS);
if (result == 0)
result = certStoreSpecCheck("My:server:12345", WS_BAD_ARGUMENT,
NULL, NULL, 0);
/* location plus a control flag (CERT_STORE_DELETE_FLAG) is rejected */
if (result == 0)
result = certStoreSpecCheck("My:server:65552", WS_BAD_ARGUMENT,
NULL, NULL, 0);
/* an unassigned location id (0x00030000) is rejected */
if (result == 0)
result = certStoreSpecCheck("My:server:0x00030000", WS_BAD_ARGUMENT,
NULL, NULL, 0);
/* an unrecognized name falls to the numeric parser and is rejected */
if (result == 0)
result = certStoreSpecCheck("My:server:BOGUS", WS_BAD_ARGUMENT,
NULL, NULL, 0);
/* strtoul()'s sign and whitespace forms must not sneak through */
if (result == 0)
result = certStoreSpecCheck("My:server:+65536", WS_BAD_ARGUMENT,
NULL, NULL, 0);
if (result == 0)
result = certStoreSpecCheck("My:server:-0xFFFF0000", WS_BAD_ARGUMENT,
NULL, NULL, 0);
if (result == 0)
result = certStoreSpecCheck("My:server: 65536", WS_BAD_ARGUMENT,
NULL, NULL, 0);
/* trailing junk after the number is rejected */
if (result == 0)
result = certStoreSpecCheck("My:server:65536x", WS_BAD_ARGUMENT,
NULL, NULL, 0);
/* invalid UTF-8 in a name fails the wide conversion */
if (result == 0)
result = certStoreSpecCheck("My\xC3:server", WS_FATAL_ERROR,
NULL, NULL, 0);
/* missing or empty fields are rejected */
if (result == 0)
result = certStoreSpecCheck("My", WS_BAD_ARGUMENT, NULL, NULL, 0);
if (result == 0)
result = certStoreSpecCheck("My:", WS_BAD_ARGUMENT, NULL, NULL, 0);
if (result == 0)
result = certStoreSpecCheck(":server", WS_BAD_ARGUMENT, NULL, NULL, 0);
if (result == 0)
result = certStoreSpecCheck("My:server:", WS_BAD_ARGUMENT, NULL, NULL,
0);
if (result == 0)
result = certStoreSpecCheck("", WS_BAD_ARGUMENT, NULL, NULL, 0);
return result;
}
/* Store-independent argument and no-side-effect checks for
* wolfSSH_CTX_UsePrivateKey_fromStore(): the NULL-argument and bad-dwFlags
* rejections run before any store is opened, and every failure must leave
* the context's key table untouched per the documented contract. */
static int test_UsePrivateKeyFromStoreArgs(void)
{
int result = 0;
WOLFSSH_CTX* ctx;
word32 keyCountBefore;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1;
keyCountBefore = ctx->privateKeyCount;
if (wolfSSH_CTX_UsePrivateKey_fromStore(NULL, L"My",
CERT_SYSTEM_STORE_CURRENT_USER, L"unit") != WS_BAD_ARGUMENT)
result = -2;
if (result == 0 && wolfSSH_CTX_UsePrivateKey_fromStore(ctx, NULL,
CERT_SYSTEM_STORE_CURRENT_USER, L"unit") != WS_BAD_ARGUMENT)
result = -3;
if (result == 0 && wolfSSH_CTX_UsePrivateKey_fromStore(ctx, L"My",
CERT_SYSTEM_STORE_CURRENT_USER, NULL) != WS_BAD_ARGUMENT)
result = -4;
/* zero and location-plus-control-flag values are not store locations */
if (result == 0 && wolfSSH_CTX_UsePrivateKey_fromStore(ctx, L"My", 0,
L"unit") != WS_BAD_ARGUMENT)
result = -5;
if (result == 0 && wolfSSH_CTX_UsePrivateKey_fromStore(ctx, L"My",
0x00010010, L"unit") != WS_BAD_ARGUMENT)
result = -6;
/* a store that cannot exist fails to open (read-only, open-existing) */
if (result == 0 && wolfSSH_CTX_UsePrivateKey_fromStore(ctx,
L"wolfSSHUnitTestNoSuchStore", CERT_SYSTEM_STORE_CURRENT_USER,
L"unit") != WS_BAD_FILE_E)
result = -7;
/* on every failure the context is left unchanged */
if (result == 0 && ctx->privateKeyCount != keyCountBefore)
result = -8;
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* WOLFSSH_WINDOWS_CERT_STORE */
#ifdef WOLFSSH_TEST_INTERNAL
/* Tests below install a custom allocator via wolfSSL_SetAllocators, which
* wolfSSL defines only under USE_WOLFSSL_MEMORY. The
* wolfSSL_Malloc_cb / wolfSSL_Free_cb / wolfSSL_Realloc_cb typedefs gain
* extra parameters when wolfSSL is built with WOLFSSL_STATIC_MEMORY or
* WOLFSSL_DEBUG_MEMORY, so the capturing-allocator tests only compile
* against the default signature. */
#if defined(USE_WOLFSSL_MEMORY) && !defined(WOLFSSL_STATIC_MEMORY) && \
!defined(WOLFSSL_DEBUG_MEMORY)
#define WOLFSSH_TEST_CAPTURING_ALLOCATOR
/* Retain-on-free allocator. Pass-through malloc/realloc; the free
* callback unconditionally diverts the pointer onto a retain list so
* the buffer's contents can be inspected after the API under test
* has called free on it. Install only across the narrow window of
* interest so allocations made before/after use the default allocator
* and can be paired with default free. */
typedef struct RetainedBuf {
void* ptr;
struct RetainedBuf* next;
} RetainedBuf;
static RetainedBuf* retainedFrees = NULL;
/* Set retainWatchSz to have RetainMalloc record in retainWatchPtr the first
* block of that size, for a buffer the code under test allocates and frees
* without handing it back. */
static size_t retainWatchSz = 0;
static void* retainWatchPtr = NULL;
static void* RetainMalloc(size_t size)
{
void* p = malloc(size);
if (p != NULL && retainWatchSz != 0 && size == retainWatchSz
&& retainWatchPtr == NULL)
retainWatchPtr = p;
return p;
}
static void RetainFree(void* ptr)
{
RetainedBuf* node;
if (ptr == NULL)
return;
node = (RetainedBuf*)malloc(sizeof(*node));
if (node == NULL) {
/* On bookkeeping failure, fall through to a real free; the
* test will not be able to inspect this buffer but we do not
* leak the underlying allocation. */
free(ptr);
return;
}
node->ptr = ptr;
node->next = retainedFrees;
retainedFrees = node;
}
static void* RetainRealloc(void* ptr, size_t size)
{
return realloc(ptr, size);
}
static int IsRetained(void* p)
{
RetainedBuf* r;
for (r = retainedFrees; r != NULL; r = r->next) {
if (r->ptr == p)
return 1;
}
return 0;
}
static void DrainRetained(void)
{
RetainedBuf* r = retainedFrees;
while (r != NULL) {
RetainedBuf* next = r->next;
free(r->ptr);
free(r);
r = next;
}
retainedFrees = NULL;
}
/* Verify SshResourceFree wipes secrets that live inside the WOLFSSH struct
* before the struct is released:
* - ssh->k: the DH/ECDH shared secret
* - ssh->keys: active session encryption + MAC keys (our direction)
* - ssh->peerKeys: active session encryption + MAC keys (peer direction)
* Mutation testing flagged each WS_FORCEZERO in SshResourceFree as having no
* coverage; removing any of them would leave key material in heap memory
* after wolfSSH_free. To inspect the bytes after free without touching
* freed memory, the test installs the retain-on-free allocator just
* around wolfSSH_free so its frees are diverted onto a retain list. */
static int test_SshResourceFree_zeroesSecrets(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
word32 markedSz;
word32 i;
const byte* keysBytes;
const byte* peerKeysBytes;
int result = 0;
wolfSSL_Malloc_cb prevMf = NULL;
wolfSSL_Free_cb prevFf = NULL;
wolfSSL_Realloc_cb prevRf = NULL;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -700;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
result = -701;
goto out;
}
markedSz = (word32)sizeof(ssh->k);
WMEMSET(ssh->k, 0xA5, markedSz);
ssh->kSz = markedSz;
WMEMSET(&ssh->keys, 0xA5, sizeof(ssh->keys));
WMEMSET(&ssh->peerKeys, 0xA5, sizeof(ssh->peerKeys));
wolfSSL_GetAllocators(&prevMf, &prevFf, &prevRf);
/* Allocators unchanged on failure; nothing to restore. */
if (wolfSSL_SetAllocators(RetainMalloc, RetainFree,
RetainRealloc) != 0) {
result = -702;
goto out;
}
wolfSSH_free(ssh);
wolfSSL_SetAllocators(prevMf, prevFf, prevRf);
if (!IsRetained(ssh)) {
result = -703;
goto out;
}
for (i = 0; i < markedSz; i++) {
if (ssh->k[i] != 0) {
result = -704;
goto out;
}
}
keysBytes = (const byte*)&ssh->keys;
for (i = 0; i < (word32)sizeof(ssh->keys); i++) {
if (keysBytes[i] != 0) {
result = -705;
goto out;
}
}
peerKeysBytes = (const byte*)&ssh->peerKeys;
for (i = 0; i < (word32)sizeof(ssh->peerKeys); i++) {
if (peerKeysBytes[i] != 0) {
result = -706;
goto out;
}
}
out:
DrainRetained();
if (ctx != NULL)
wolfSSH_CTX_free(ctx);
return result;
}
/* Verify ChannelDelete wipes the peer's exec/subsystem command line before
* releasing it. A command can carry a password or token in its arguments,
* and the buffer sits right below the inputBuffer this function already
* scrubs. The retain-on-free allocator is installed just around
* ChannelDelete so the freed bytes can be read back without touching
* freed memory. */
static int test_ChannelDelete_zeroesCommand(void)
{
static const char command[] = "sh -c 'login --password hunter2'";
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* channel = NULL;
const byte* commandBytes;
word32 commandSz;
word32 i;
int result = 0;
wolfSSL_Malloc_cb prevMf = NULL;
wolfSSL_Free_cb prevFf = NULL;
wolfSSL_Realloc_cb prevRf = NULL;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -710;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
result = -711;
goto out;
}
channel = ChannelNew(ssh, ID_CHANTYPE_SESSION,
DEFAULT_WINDOW_SZ, DEFAULT_MAX_PACKET_SZ);
if (channel == NULL) {
result = -712;
goto out;
}
commandSz = (word32)WSTRLEN(command);
channel->command = (char*)WMALLOC(commandSz + 1, NULL, DYNTYPE_STRING);
if (channel->command == NULL) {
result = -713;
goto out;
}
WMEMCPY(channel->command, command, commandSz + 1);
channel->commandSz = commandSz;
commandBytes = (const byte*)channel->command;
wolfSSL_GetAllocators(&prevMf, &prevFf, &prevRf);
/* Allocators unchanged on failure; nothing to restore. */
if (wolfSSL_SetAllocators(RetainMalloc, RetainFree,
RetainRealloc) != 0) {
result = -714;
goto out;
}
ChannelDelete(channel, NULL);
wolfSSL_SetAllocators(prevMf, prevFf, prevRf);
channel = NULL;
if (!IsRetained((void*)commandBytes)) {
result = -715;
goto out;
}
for (i = 0; i < commandSz; i++) {
if (commandBytes[i] != 0) {
result = -716;
goto out;
}
}
out:
DrainRetained();
/* Only the setup-failure paths reach here with a channel; it is never
* on ssh->channelList, so wolfSSH_free() would not release it. */
if (channel != NULL)
ChannelDelete(channel, ssh->ctx->heap);
if (ssh != NULL)
wolfSSH_free(ssh);
if (ctx != NULL)
wolfSSH_CTX_free(ctx);
return result;
}
/* Store a command line as the client's exec channel name and return the
* buffer holding it, or NULL. */
static const byte* SetExecName(WOLFSSH* ssh, const char* command)
{
if (wolfSSH_SetChannelType(ssh, WOLFSSH_SESSION_EXEC, (byte*)command,
(word32)WSTRLEN(command)) != WS_SUCCESS)
return NULL;
return ssh->channelName;
}
static int IsWiped(const byte* p, word32 sz)
{
word32 i;
if (p == NULL || !IsRetained((void*)p))
return 0;
for (i = 0; i < sz; i++) {
if (p[i] != 0)
return 0;
}
return 1;
}
/* Verify every release of the client's exec command line in
* ssh->channelName wipes it first: switching to shell or terminal,
* replacing it with another command, and wolfSSH_free(). The
* retain-on-free allocator is installed just around each release so the
* freed bytes can be read back. */
static int test_ChannelName_zeroedOnFree(void)
{
static const char command[] = "sh -c 'login --password hunter2'";
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
const byte* name;
word32 commandSz = (word32)WSTRLEN(command);
int result = 0;
wolfSSL_Malloc_cb prevMf = NULL;
wolfSSL_Free_cb prevFf = NULL;
wolfSSL_Realloc_cb prevRf = NULL;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -740;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
result = -741;
goto out;
}
wolfSSL_GetAllocators(&prevMf, &prevFf, &prevRf);
/* exec to shell */
if ((name = SetExecName(ssh, command)) == NULL) {
result = -742;
goto out;
}
if (wolfSSL_SetAllocators(RetainMalloc, RetainFree,
RetainRealloc) != 0) {
result = -743;
goto out;
}
wolfSSH_SetChannelType(ssh, WOLFSSH_SESSION_SHELL, NULL, 0);
wolfSSL_SetAllocators(prevMf, prevFf, prevRf);
if (!IsWiped(name, commandSz)) {
result = -744;
goto out;
}
DrainRetained();
/* exec replaced by another exec */
if ((name = SetExecName(ssh, command)) == NULL) {
result = -745;
goto out;
}
if (wolfSSL_SetAllocators(RetainMalloc, RetainFree,
RetainRealloc) != 0) {
result = -746;
goto out;
}
wolfSSH_SetChannelType(ssh, WOLFSSH_SESSION_EXEC, (byte*)"ls", 2);
wolfSSL_SetAllocators(prevMf, prevFf, prevRf);
if (!IsWiped(name, commandSz)) {
result = -747;
goto out;
}
DrainRetained();
#ifdef WOLFSSH_TERM
/* exec to terminal */
if ((name = SetExecName(ssh, command)) == NULL) {
result = -748;
goto out;
}
if (wolfSSL_SetAllocators(RetainMalloc, RetainFree,
RetainRealloc) != 0) {
result = -749;
goto out;
}
wolfSSH_SetChannelType(ssh, WOLFSSH_SESSION_TERMINAL, NULL, 0);
wolfSSL_SetAllocators(prevMf, prevFf, prevRf);
if (!IsWiped(name, commandSz)) {
result = -750;
goto out;
}
DrainRetained();
#endif
/* wolfSSH_free() */
if ((name = SetExecName(ssh, command)) == NULL) {
result = -751;
goto out;
}
if (wolfSSL_SetAllocators(RetainMalloc, RetainFree,
RetainRealloc) != 0) {
result = -752;
goto out;
}
wolfSSH_free(ssh);
wolfSSL_SetAllocators(prevMf, prevFf, prevRf);
ssh = NULL;
if (!IsWiped(name, commandSz)) {
result = -753;
goto out;
}
out:
DrainRetained();
if (ssh != NULL)
wolfSSH_free(ssh);
if (ctx != NULL)
wolfSSH_CTX_free(ctx);
return result;
}
#ifdef WOLFSSH_TEST_INTERNAL
/* [uint32 channelId][string "exec"][byte wantReply][string command] */
static word32 BuildExecRequestPayload(byte* out, word32 outSz,
const char* command)
{
word32 commandSz = (word32)WSTRLEN(command);
word32 idx = 0;
if (outSz < 17 + commandSz)
return 0;
PutU32BE(out + idx, 0); idx += UINT32_SZ;
PutU32BE(out + idx, 4); idx += UINT32_SZ;
WMEMCPY(out + idx, "exec", 4); idx += 4;
out[idx++] = 1;
PutU32BE(out + idx, commandSz); idx += UINT32_SZ;
WMEMCPY(out + idx, command, commandSz); idx += commandSz;
return idx;
}
/* Verify a refused second exec request wipes the command line it carried.
* The channel already has a session, so the request is read into a buffer
* of its own and freed; without the scrub the command, credentials and
* all, stays readable in the freed block. The retain-on-free allocator is
* installed just around the second request, watching for the command's
* allocation, so the freed bytes can be read back. */
static int test_DoChannelRequest_zeroesRefusedCommand(void)
{
static const char second[] = "sh -c 'login --password hunter2'";
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
const byte* refused;
byte payload[128];
word32 payloadSz;
word32 secondSz = (word32)WSTRLEN(second);
word32 idx;
word32 i;
int result = 0;
wolfSSL_Malloc_cb prevMf = NULL;
wolfSSL_Free_cb prevFf = NULL;
wolfSSL_Realloc_cb prevRf = NULL;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -720;
wolfSSH_SetIOSend(ctx, CaptureIoSendChanReq);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
result = -721;
goto out;
}
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION,
DEFAULT_WINDOW_SZ, DEFAULT_MAX_PACKET_SZ);
if (ch == NULL) {
result = -722;
goto out;
}
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -723;
goto out;
}
idx = 0;
payloadSz = BuildExecRequestPayload(payload, sizeof(payload), "ls");
if (payloadSz == 0) {
result = -724;
goto out;
}
if (wolfSSH_TestDoChannelRequest(ssh, payload, payloadSz, &idx)
!= WS_SUCCESS || !ch->sessionGranted) {
result = -725;
goto out;
}
idx = 0;
payloadSz = BuildExecRequestPayload(payload, sizeof(payload), second);
if (payloadSz == 0) {
result = -726;
goto out;
}
wolfSSL_GetAllocators(&prevMf, &prevFf, &prevRf);
retainWatchSz = secondSz + 1;
retainWatchPtr = NULL;
/* Allocators unchanged on failure; nothing to restore. */
if (wolfSSL_SetAllocators(RetainMalloc, RetainFree,
RetainRealloc) != 0) {
retainWatchSz = 0;
result = -727;
goto out;
}
result = wolfSSH_TestDoChannelRequest(ssh, payload, payloadSz, &idx);
wolfSSL_SetAllocators(prevMf, prevFf, prevRf);
retainWatchSz = 0;
refused = (const byte*)retainWatchPtr;
if (result != WS_SUCCESS) {
result = -728;
goto out;
}
result = 0;
if (refused == NULL || !IsRetained((void*)refused)) {
result = -729;
goto out;
}
for (i = 0; i < secondSz; i++) {
if (refused[i] != 0) {
result = -730;
goto out;
}
}
/* The refusal left the granted command whole. */
if (ch->command == NULL || WSTRCMP(ch->command, "ls") != 0
|| ch->commandSz != 2) {
result = -731;
goto out;
}
out:
DrainRetained();
retainWatchPtr = NULL;
if (ssh != NULL)
wolfSSH_free(ssh);
if (ctx != NULL)
wolfSSH_CTX_free(ctx);
return result;
}
#ifdef WOLFSSH_SCP
/* Allocates a DEFAULT_SCP_BUFFER_SZ scpFileBuffer filled with 0xA5 whose
* scpFileBufferSz is chunkSz, as a sink run leaves it. */
static int ScpFillFileBuffer(WOLFSSH* ssh, word32 chunkSz)
{
ssh->scpFileBuffer = (byte*)WMALLOC(DEFAULT_SCP_BUFFER_SZ, ssh->ctx->heap,
DYNTYPE_BUFFER);
if (ssh->scpFileBuffer == NULL)
return -1;
WMEMSET(ssh->scpFileBuffer, 0xA5, DEFAULT_SCP_BUFFER_SZ);
ssh->scpFileBufferSz = chunkSz;
return 0;
}
static int ScpBufferIsZero(const byte* buf)
{
word32 i;
for (i = 0; i < DEFAULT_SCP_BUFFER_SZ; i++) {
if (buf[i] != 0)
return 0;
}
return 1;
}
/* Verify the SCP transfer buffer is wiped across its whole allocation when
* it is released, both by SshResourceFree and by ScpSourceInit replacing it,
* even though scpFileBufferSz holds only a sink chunk length (or zero). */
static int test_ScpFileBuffer_zeroedOnFree(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
const byte* buf;
int result = 0;
wolfSSL_Malloc_cb prevMf = NULL;
wolfSSL_Free_cb prevFf = NULL;
wolfSSL_Realloc_cb prevRf = NULL;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -720;
/* SshResourceFree, chunk length already reset to zero */
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
result = -721;
goto out;
}
if (ScpFillFileBuffer(ssh, 0) != 0) {
result = -722;
goto out;
}
buf = ssh->scpFileBuffer;
wolfSSL_GetAllocators(&prevMf, &prevFf, &prevRf);
if (wolfSSL_SetAllocators(RetainMalloc, RetainFree,
RetainRealloc) != 0) {
result = -723;
goto out;
}
wolfSSH_free(ssh);
wolfSSL_SetAllocators(prevMf, prevFf, prevRf);
ssh = NULL;
if (!IsRetained((void*)buf))
result = -724;
else if (!ScpBufferIsZero(buf))
result = -725;
DrainRetained();
if (result != 0)
goto out;
/* ScpSourceInit replacing a buffer holding a short sink chunk */
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
result = -726;
goto out;
}
if (ScpFillFileBuffer(ssh, 16) != 0) {
result = -727;
goto out;
}
buf = ssh->scpFileBuffer;
ssh->scpState = SCP_SOURCE_INIT;
if (wolfSSL_SetAllocators(RetainMalloc, RetainFree,
RetainRealloc) != 0) {
result = -728;
goto out;
}
/* fails reading the confirmation with no channel, after the init */
(void)wolfSSH_TestDoScpSource(ssh);
wolfSSL_SetAllocators(prevMf, prevFf, prevRf);
if (ssh->scpFileBuffer == buf)
result = -729;
else if (!IsRetained((void*)buf))
result = -730;
else if (!ScpBufferIsZero(buf))
result = -731;
out:
DrainRetained();
if (ssh != NULL)
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* WOLFSSH_SCP */
#endif /* WOLFSSH_TEST_INTERNAL */
#endif /* WOLFSSH_TEST_CAPTURING_ALLOCATOR */
#ifndef WOLFSSH_NO_DH
/* Verify KeyAgreeDh_client zeroes the ephemeral DH private key
* ssh->handshake->x before returning. The WS_FORCEZERO is unconditional in
* the function (runs even if wc_DhAgree fails), so the test does not need
* to feed a valid peer public key - it just needs to observe that x is
* wiped after the call returns. The test hook wolfSSH_TestKeyAgreeDh_client
* exposes the static function. */
static int test_KeyAgreeDh_client_zeroesEphemeralPrivKey(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
HandshakeInfo* hs = NULL;
byte bogusF[256];
word32 markedSz;
word32 i;
int result = 0;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -710;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return -711;
}
/* wolfSSH_new already allocated and zero-initialised ssh->handshake;
* use it directly. wolfSSH_free will release it via HandshakeInfoFree. */
hs = ssh->handshake;
if (hs == NULL) {
result = -712;
goto cleanup;
}
if (wc_InitDhKey(&hs->privKey.dh) != 0) {
result = -713;
goto cleanup;
}
markedSz = (word32)sizeof(hs->x);
WMEMSET(hs->x, 0xA5, markedSz);
hs->xSz = markedSz;
/* No prime group is set, so wc_DhCheckPubKey fails before wc_DhAgree is
* reached. The WS_FORCEZERO on x is unconditional and runs regardless. */
WMEMSET(bogusF, 0xCC, sizeof(bogusF));
(void)wolfSSH_TestKeyAgreeDh_client(ssh, WC_HASH_TYPE_SHA256,
bogusF, (word32)sizeof(bogusF));
/* wc_FreeDhKey was called inside the test hook; do not free again. */
for (i = 0; i < markedSz; i++) {
if (hs->x[i] != 0) {
result = -714;
break;
}
}
cleanup:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* Verify KeyAgreeDh_server rejects a degenerate peer DH public key.
* The peer public 'e' is read from ssh->handshake->e; a value of 1 sits at
* the low end of RFC 4253 section 8's permitted [1, p-1] range, but it is a
* weak/degenerate value that wc_DhCheckPubKey rejects (stricter than the
* RFC's bare minimum) before the shared secret is computed. Without that
* guard wc_DhAgree would happily derive the degenerate secret 1. */
static int test_KeyAgreeDh_server_rejectsBadPeerPublic(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
byte f[MAX_KEX_KEY_SZ];
word32 fSz = (word32)sizeof(f);
int result = 0;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -730;
ssh = wolfSSH_new(ctx);
if (ssh == NULL || ssh->handshake == NULL) {
result = -731;
goto out;
}
#ifndef WOLFSSH_NO_DH_GROUP14_SHA256
ssh->handshake->kexId = ID_DH_GROUP14_SHA256;
#elif !defined(WOLFSSH_NO_DH_GROUP16_SHA512)
ssh->handshake->kexId = ID_DH_GROUP16_SHA512;
#elif !defined(WOLFSSH_NO_DH_GROUP14_SHA1)
ssh->handshake->kexId = ID_DH_GROUP14_SHA1;
#elif !defined(WOLFSSH_NO_DH_GROUP1_SHA1)
ssh->handshake->kexId = ID_DH_GROUP1_SHA1;
#else
/* No fixed DH group enabled; fail rather than silently pass without
* exercising the peer-key check. */
result = -733;
goto out;
#endif
/* Degenerate peer public key e = 1 (yields the shared secret 1). */
ssh->handshake->e[0] = 0x01;
ssh->handshake->eSz = 1;
if (wolfSSH_TestKeyAgreeDh_server(ssh, WC_HASH_TYPE_SHA256, f, &fSz) == 0) {
/* The degenerate peer public must not be accepted. */
result = -732;
}
out:
if (ssh != NULL)
wolfSSH_free(ssh);
if (ctx != NULL)
wolfSSH_CTX_free(ctx);
return result;
}
/* Verify KeyAgreeDh_client rejects a degenerate peer DH public key. The
* peer public 'f' is passed straight to the function; a value of 1 sits at the
* low end of RFC 4253 section 8's permitted [1, p-1] range, but it is a
* weak/degenerate value that the wc_DhCheckPubKey guard rejects (stricter than
* the RFC's bare minimum) before the shared secret is used.
* wolfSSH_TestSetDhKexKey installs the prime
* group and generates a real ephemeral key pair first, mirroring SendKexDhInit,
* so the rejection is driven by the bad peer key rather than a missing private
* exponent. This guard is defense-in-depth: wc_DhAgree in wolfCrypt also
* enforces the same range, so the test confirms the client rejection behavior
* but does not isolate the wolfSSH check from the underlying wolfCrypt one. */
static int test_KeyAgreeDh_client_rejectsBadPeerPublic(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
byte f[1];
int result = 0;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -750;
ssh = wolfSSH_new(ctx);
if (ssh == NULL || ssh->handshake == NULL) {
result = -751;
goto out;
}
#ifndef WOLFSSH_NO_DH_GROUP14_SHA256
ssh->handshake->kexId = ID_DH_GROUP14_SHA256;
#elif !defined(WOLFSSH_NO_DH_GROUP16_SHA512)
ssh->handshake->kexId = ID_DH_GROUP16_SHA512;
#elif !defined(WOLFSSH_NO_DH_GROUP14_SHA1)
ssh->handshake->kexId = ID_DH_GROUP14_SHA1;
#elif !defined(WOLFSSH_NO_DH_GROUP1_SHA1)
ssh->handshake->kexId = ID_DH_GROUP1_SHA1;
#else
/* No fixed DH group enabled; fail rather than silently pass without
* exercising the peer-key check. */
result = -754;
goto out;
#endif
/* Install the prime group on the client's ephemeral DH key, as the client
* KEX path does before KeyAgreeDh_client runs. */
if (wolfSSH_TestSetDhKexKey(ssh) != 0) {
result = -752;
goto out;
}
/* Degenerate peer public key f = 1 (yields the shared secret 1). */
f[0] = 0x01;
if (wolfSSH_TestKeyAgreeDh_client(ssh, WC_HASH_TYPE_SHA256, f,
(word32)sizeof(f)) == 0) {
/* The degenerate peer public must not be accepted. */
result = -753;
}
out:
if (ssh != NULL)
wolfSSH_free(ssh);
if (ctx != NULL)
wolfSSH_CTX_free(ctx);
return result;
}
#if defined(WOLFSSH_SMALL_STACK) && defined(WOLFSSH_TEST_CAPTURING_ALLOCATOR)
/* Size-tracked, poisoning capture allocator. AllocHeader stores the
* user-requested size in front of each allocation so tests can filter
* captured buffers by size after the API under test has freed them.
* Every fresh allocation is stamped with 0xCC so tests can tell "byte
* was untouched" apart from "byte was written and later zeroed". The
* free callback unconditionally diverts the pointer (with its size)
* onto a capture list. Install only across the narrow window of the
* call under test so allocations made outside use the default allocator
* and don't need header-aware free on exit. */
typedef struct AllocHeader {
size_t size;
/* sizeof(AllocHeader) is 2 * sizeof(size_t), which preserves the
* alignment that the system malloc returns (16 on 64-bit, 8 on
* 32-bit) for the user pointer that follows. */
size_t pad;
} AllocHeader;
typedef struct CapturedBuf {
void* ptr;
size_t size;
struct CapturedBuf* next;
} CapturedBuf;
static CapturedBuf* capturedFrees = NULL;
static void* CaptureMalloc(size_t size)
{
AllocHeader* h = (AllocHeader*)malloc(size + sizeof(AllocHeader));
if (h == NULL)
return NULL;
h->size = size;
WMEMSET((void*)(h + 1), 0xCC, size);
return (void*)(h + 1);
}
static void CaptureFree(void* ptr)
{
AllocHeader* h;
CapturedBuf* node;
if (ptr == NULL)
return;
h = (AllocHeader*)ptr - 1;
node = (CapturedBuf*)malloc(sizeof(*node));
if (node == NULL) {
/* On bookkeeping failure, fall through to a real free; the
* test will not be able to inspect this buffer but we do not
* leak the underlying allocation. */
free(h);
return;
}
node->ptr = ptr;
node->size = h->size;
node->next = capturedFrees;
capturedFrees = node;
}
static void* CaptureRealloc(void* ptr, size_t size)
{
AllocHeader* h;
AllocHeader* h2;
size_t oldSize;
if (ptr == NULL)
return CaptureMalloc(size);
h = (AllocHeader*)ptr - 1;
oldSize = h->size;
h2 = (AllocHeader*)realloc(h, size + sizeof(AllocHeader));
if (h2 == NULL)
return NULL;
h2->size = size;
if (size > oldSize)
WMEMSET((byte*)(h2 + 1) + oldSize, 0xCC, size - oldSize);
return (void*)(h2 + 1);
}
static void DrainCaptured(void)
{
CapturedBuf* c = capturedFrees;
while (c != NULL) {
CapturedBuf* next = c->next;
free((AllocHeader*)c->ptr - 1);
free(c);
c = next;
}
capturedFrees = NULL;
}
/* Verify KeyAgreeDh_server zeroes the ephemeral DH private key buffer
* y_ptr before WFREE returns it to the heap. y_ptr is a stack array in
* the default build but a heap allocation under WOLFSSH_SMALL_STACK, so
* the test installs the capturing allocator and inspects the captured
* buffer afterwards.
*
* wc_DhGenerateKeyPair writes only the leading ySz bytes of the
* MAX_KEX_KEY_SZ allocation (ySz is typically the prime-group size, well
* below MAX_KEX_KEY_SZ), and WS_FORCEZERO only wipes those same ySz bytes -
* so the tail of the buffer is never written by the function under test.
* The capture allocator stamps every fresh allocation with 0xCC so that
* after the call:
* - present WS_FORCEZERO -> [0x00 * ySz] [0xCC * (MAX - ySz)]
* - removed WS_FORCEZERO -> [priv-key * ySz] [0xCC * (MAX - ySz)]
* The check requires a captured MAX_KEX_KEY_SZ buffer whose bytes are all
* either 0x00 or 0xCC AND that contains at least one 0x00. The DH private
* key emitted by wc_DhGenerateKeyPair is overwhelmingly unlikely to be
* entirely composed of 0x00 / 0xCC bytes, so this catches the mutation
* while staying deterministic regardless of underlying malloc state.
*
* The peer value ssh->handshake->e is left zero, so the new
* wc_DhCheckPubKey now fails between wc_DhGenerateKeyPair and wc_DhAgree;
* the WS_FORCEZERO on y_ptr is unconditional and still runs, so the buffer
* assertion above is unaffected. */
static int test_KeyAgreeDh_server_zeroesEphemeralPrivKey(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
byte f[MAX_KEX_KEY_SZ];
word32 fSz = (word32)sizeof(f);
int result = 0;
CapturedBuf* c;
int foundYPtr = 0;
int captureInstalled = 0;
wolfSSL_Malloc_cb prevMf = NULL;
wolfSSL_Free_cb prevFf = NULL;
wolfSSL_Realloc_cb prevRf = NULL;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -720;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
result = -721;
goto out;
}
if (ssh->handshake == NULL) {
result = -722;
goto out;
}
#ifndef WOLFSSH_NO_DH_GROUP14_SHA256
ssh->handshake->kexId = ID_DH_GROUP14_SHA256;
#elif !defined(WOLFSSH_NO_DH_GROUP16_SHA512)
ssh->handshake->kexId = ID_DH_GROUP16_SHA512;
#elif !defined(WOLFSSH_NO_DH_GROUP14_SHA1)
ssh->handshake->kexId = ID_DH_GROUP14_SHA1;
#elif !defined(WOLFSSH_NO_DH_GROUP1_SHA1)
ssh->handshake->kexId = ID_DH_GROUP1_SHA1;
#else
/* No fixed DH group enabled; nothing to exercise. */
result = -725;
goto out;
#endif
wolfSSL_GetAllocators(&prevMf, &prevFf, &prevRf);
/* Allocators unchanged on failure; nothing to restore. */
if (wolfSSL_SetAllocators(CaptureMalloc, CaptureFree,
CaptureRealloc) != 0) {
result = -723;
goto out;
}
captureInstalled = 1;
(void)wolfSSH_TestKeyAgreeDh_server(ssh, WC_HASH_TYPE_SHA256, f, &fSz);
wolfSSL_SetAllocators(prevMf, prevFf, prevRf);
captureInstalled = 0;
for (c = capturedFrees; c != NULL; c = c->next) {
const byte* bytes;
word32 i;
int hasZero = 0;
int hasOther = 0;
if (c->size != MAX_KEX_KEY_SZ)
continue;
bytes = (const byte*)c->ptr;
for (i = 0; i < MAX_KEX_KEY_SZ; i++) {
if (bytes[i] == 0x00) {
hasZero = 1;
}
else if (bytes[i] != 0xCC) {
hasOther = 1;
break;
}
}
if (hasZero && !hasOther) {
foundYPtr = 1;
break;
}
}
if (!foundYPtr) {
result = -724;
}
out:
if (captureInstalled)
wolfSSL_SetAllocators(prevMf, prevFf, prevRf);
DrainCaptured();
if (ssh != NULL)
wolfSSH_free(ssh);
if (ctx != NULL)
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* WOLFSSH_SMALL_STACK && WOLFSSH_TEST_CAPTURING_ALLOCATOR */
/* Verify KeyAgreeDh_server rejects an out-of-range peer public value.
* The server hook loads the SSH prime group from kexId itself, so feeding
* ssh->handshake->e a value of 0 or 1 (outside [2, p-2]) must make
* wc_DhCheckPubKey fail and the call return non-WS_SUCCESS instead of
* deriving a known shared secret. On a wolfSSL whose wc_DhAgree already
* validates the peer key this is an equivalent guard; its value is
* defense-in-depth for builds whose wc_DhAgree does not validate. */
static int test_KeyAgreeDh_server_rejectsOutOfRangePeer(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
HandshakeInfo* hs = NULL;
byte f[MAX_KEX_KEY_SZ];
word32 fSz;
word32 c;
int result = 0;
static const byte badVals[2] = { 0x00, 0x01 };
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -740;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return -741;
}
hs = ssh->handshake;
if (hs == NULL) {
result = -742;
goto cleanup;
}
#ifndef WOLFSSH_NO_DH_GROUP14_SHA256
hs->kexId = ID_DH_GROUP14_SHA256;
#elif !defined(WOLFSSH_NO_DH_GROUP16_SHA512)
hs->kexId = ID_DH_GROUP16_SHA512;
#elif !defined(WOLFSSH_NO_DH_GROUP14_SHA1)
hs->kexId = ID_DH_GROUP14_SHA1;
#elif !defined(WOLFSSH_NO_DH_GROUP1_SHA1)
hs->kexId = ID_DH_GROUP1_SHA1;
#else
/* No fixed DH group enabled; fail rather than silently pass. */
result = -744;
goto cleanup;
#endif
for (c = 0; c < (word32)sizeof(badVals); c++) {
int ret;
hs->e[0] = badVals[c];
hs->eSz = 1;
fSz = (word32)sizeof(f);
ret = wolfSSH_TestKeyAgreeDh_server(ssh, WC_HASH_TYPE_SHA256, f, &fSz);
if (ret != WS_CRYPTO_FAILED) {
result = -743;
break;
}
}
cleanup:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#ifdef HAVE_FFDHE_2048
/* Verify KeyAgreeDh_client rejects an out-of-range peer public value.
* A real prime group is loaded into ssh->handshake->privKey.dh so that an
* f of 0 or 1 (outside [2, p-2]) is caught by wc_DhCheckPubKey before key
* agreement, yielding WS_CRYPTO_FAILED rather than a known shared secret.
* Equivalent-mutant caveat as in the server case above: it is a regression
* guard for builds whose wc_DhAgree does not validate the peer key. */
static int test_KeyAgreeDh_client_rejectsOutOfRangePeer(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
HandshakeInfo* hs = NULL;
byte badF[1];
word32 c;
int result = 0;
static const byte badVals[2] = { 0x00, 0x01 };
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -750;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return -751;
}
hs = ssh->handshake;
if (hs == NULL) {
result = -752;
goto cleanup;
}
for (c = 0; c < (word32)sizeof(badVals); c++) {
int ret;
/* The hook frees privKey.dh on return, so re-init each iteration. */
if (wc_InitDhKey(&hs->privKey.dh) != 0) {
result = -753;
break;
}
if (wc_DhSetNamedKey(&hs->privKey.dh, WC_FFDHE_2048) != 0) {
wc_FreeDhKey(&hs->privKey.dh);
result = -754;
break;
}
/* x is unused on the reject path but WS_FORCEZERO still runs over it. */
hs->xSz = 0;
badF[0] = badVals[c];
ret = wolfSSH_TestKeyAgreeDh_client(ssh, WC_HASH_TYPE_SHA256,
badF, (word32)sizeof(badF));
if (ret != WS_CRYPTO_FAILED) {
result = -755;
break;
}
}
cleanup:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* HAVE_FFDHE_2048 */
/* Verify both DH key agreement sides reject a peer public value encoded
* as a negative mpint (RFC 4251 section 5). 0x80 is 128 read unsigned,
* inside [2, p-2], so only the sign check can reject it; 0x00 0x80 is
* the same value encoded correctly and must be accepted. */
static int test_KeyAgreeDh_rejectsNegativePeer(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
HandshakeInfo* hs = NULL;
byte f[MAX_KEX_KEY_SZ];
word32 fSz;
int ret;
int result = 0;
static const byte negPeer[1] = { 0x80 };
static const byte posPeer[2] = { 0x00, 0x80 };
byte kexId;
/* server: the peer value is the client's e */
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -760;
ssh = wolfSSH_new(ctx);
if (ssh == NULL || ssh->handshake == NULL) {
result = -761;
goto cleanup;
}
#ifndef WOLFSSH_NO_DH_GROUP14_SHA256
kexId = ID_DH_GROUP14_SHA256;
#elif !defined(WOLFSSH_NO_DH_GROUP16_SHA512)
kexId = ID_DH_GROUP16_SHA512;
#elif !defined(WOLFSSH_NO_DH_GROUP14_SHA1)
kexId = ID_DH_GROUP14_SHA1;
#elif !defined(WOLFSSH_NO_DH_GROUP1_SHA1)
kexId = ID_DH_GROUP1_SHA1;
#else
/* No fixed DH group enabled; fail rather than silently pass. */
result = -762;
goto cleanup;
#endif
hs = ssh->handshake;
hs->kexId = kexId;
WMEMCPY(hs->e, negPeer, sizeof(negPeer));
hs->eSz = (word32)sizeof(negPeer);
fSz = (word32)sizeof(f);
ret = wolfSSH_TestKeyAgreeDh_server(ssh, WC_HASH_TYPE_SHA256, f, &fSz);
if (ret != WS_CRYPTO_FAILED) {
result = -763;
goto cleanup;
}
WMEMCPY(hs->e, posPeer, sizeof(posPeer));
hs->eSz = (word32)sizeof(posPeer);
fSz = (word32)sizeof(f);
ret = wolfSSH_TestKeyAgreeDh_server(ssh, WC_HASH_TYPE_SHA256, f, &fSz);
if (ret != WS_SUCCESS) {
result = -764;
goto cleanup;
}
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
/* client: the peer value is the server's f */
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -765;
ssh = wolfSSH_new(ctx);
if (ssh == NULL || ssh->handshake == NULL) {
result = -766;
goto cleanup;
}
ssh->handshake->kexId = kexId;
/* The hook frees the DH key on return, so set it up for each call. */
if (wolfSSH_TestSetDhKexKey(ssh) != 0) {
result = -767;
goto cleanup;
}
ret = wolfSSH_TestKeyAgreeDh_client(ssh, WC_HASH_TYPE_SHA256,
negPeer, (word32)sizeof(negPeer));
if (ret != WS_CRYPTO_FAILED) {
result = -768;
goto cleanup;
}
if (wolfSSH_TestSetDhKexKey(ssh) != 0) {
result = -769;
goto cleanup;
}
ret = wolfSSH_TestKeyAgreeDh_client(ssh, WC_HASH_TYPE_SHA256,
posPeer, (word32)sizeof(posPeer));
if (ret != WS_SUCCESS) {
result = -770;
goto cleanup;
}
cleanup:
if (ssh != NULL)
wolfSSH_free(ssh);
if (ctx != NULL)
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* !WOLFSSH_NO_DH */
#if !defined(WOLFSSH_NO_ECDH) && !defined(WOLFSSH_NO_ECDH_SHA2_NISTP256)
/* Verify KeyAgreeEcdh_server rejects an off-curve peer ECC point. The peer
* point is read from ssh->handshake->e as an X9.63 uncompressed point; (1, 1)
* is a well-formed encoding that is not on P-256. In builds without
* WOLFSSL_VALIDATE_ECC_IMPORT (the common embedded case this hardening targets)
* wc_ecc_import_x963 accepts the coordinates, so the wc_ecc_check_key call in
* the shared EccCheckPeerKey helper is what rejects it before
* wc_ecc_shared_secret is reached; with WOLFSSL_VALIDATE_ECC_IMPORT the import
* itself rejects it. Either way the function must fail. P-256 has cofactor 1,
* so an off-curve point (not a wrong-subgroup one) is the meaningful test. */
static int test_KeyAgreeEcdh_server_rejectsOffCurvePoint(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
byte f[MAX_KEX_KEY_SZ];
word32 fSz = (word32)sizeof(f);
int result = 0;
/* X9.63 uncompressed point for P-256: 0x04 || X(32) || Y(32), here the
* off-curve point (X=1, Y=1). */
byte point[1 + 32 + 32];
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -740;
ssh = wolfSSH_new(ctx);
if (ssh == NULL || ssh->handshake == NULL) {
result = -741;
goto out;
}
ssh->handshake->kexId = ID_ECDH_SHA2_NISTP256;
WMEMSET(point, 0, sizeof(point));
point[0] = 0x04; /* uncompressed */
point[32] = 0x01; /* X = 1 (big-endian, last byte) */
point[64] = 0x01; /* Y = 1 */
WMEMCPY(ssh->handshake->e, point, sizeof(point));
ssh->handshake->eSz = (word32)sizeof(point);
if (wolfSSH_TestKeyAgreeEcdh_server(ssh, WC_HASH_TYPE_SHA256, f, &fSz)
== 0) {
/* The off-curve peer point must not be accepted. */
result = -742;
}
out:
if (ssh != NULL)
wolfSSH_free(ssh);
if (ctx != NULL)
wolfSSH_CTX_free(ctx);
return result;
}
/* Verify KeyAgreeEcdh_client rejects an off-curve peer ECC point. The peer
* point 'f' is an X9.63 uncompressed encoding; (1, 1) is well-formed but is
* not on P-256. In builds without WOLFSSL_VALIDATE_ECC_IMPORT (the common
* embedded case this hardening targets) wc_ecc_import_x963 accepts the
* coordinates, so the wc_ecc_check_key call in the shared EccCheckPeerKey
* helper is what rejects it before wc_ecc_shared_secret is reached; with
* WOLFSSL_VALIDATE_ECC_IMPORT the import itself rejects it. Either way the
* function must fail. P-256 has cofactor 1, so an off-curve point (not a
* wrong-subgroup one) is the meaningful test. */
static int test_KeyAgreeEcdh_client_rejectsOffCurvePoint(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
int result = 0;
/* X9.63 uncompressed point for P-256: 0x04 || X(32) || Y(32), here the
* off-curve point (X=1, Y=1). */
byte point[1 + 32 + 32];
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -770;
ssh = wolfSSH_new(ctx);
if (ssh == NULL || ssh->handshake == NULL) {
result = -771;
goto out;
}
ssh->handshake->kexId = ID_ECDH_SHA2_NISTP256;
/* Generate a real client ephemeral P-256 key, as SendKexDhInit() does
* before KeyAgreeEcdh_client() runs. With a live private key in place the
* only way the call can fail is the peer point validation, so the test
* actually exercises the wc_ecc_check_key guard rather than tripping over a
* missing private key. KeyAgreeEcdh_client() frees privKey.ecc on the way
* out, so the cleanup path stays well defined. */
if (wc_ecc_init(&ssh->handshake->privKey.ecc) != 0) {
result = -772;
goto out;
}
ssh->handshake->useEcdh = 1;
#ifdef HAVE_WC_ECC_SET_RNG
if (wc_ecc_set_rng(&ssh->handshake->privKey.ecc, ssh->rng) != 0) {
result = -774;
goto out;
}
#endif
if (wc_ecc_make_key_ex(ssh->rng, 32, &ssh->handshake->privKey.ecc,
ECC_SECP256R1) != 0) {
result = -775;
goto out;
}
WMEMSET(point, 0, sizeof(point));
point[0] = 0x04; /* uncompressed */
point[32] = 0x01; /* X = 1 (big-endian, last byte) */
point[64] = 0x01; /* Y = 1 */
if (wolfSSH_TestKeyAgreeEcdh_client(ssh, WC_HASH_TYPE_SHA256, point,
(word32)sizeof(point)) == 0) {
/* The off-curve peer point must not be accepted. */
result = -773;
}
out:
if (ssh != NULL)
wolfSSH_free(ssh);
if (ctx != NULL)
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* !WOLFSSH_NO_ECDH && !WOLFSSH_NO_ECDH_SHA2_NISTP256 */
#if defined(WOLFSSH_SMALL_STACK) && \
defined(WOLFSSH_TEST_CAPTURING_ALLOCATOR) && \
((!defined(WOLFSSH_NO_ECDH) && \
!defined(WOLFSSH_NO_ECDH_SHA2_NISTP256)) || \
!defined(WOLFSSH_NO_CURVE25519_SHA256))
/* Fault-injecting allocator: the failAt'th allocation after install
* returns NULL, and every other one is filled with 0xCC so storage that
* was never initialized looks like garbage, not zeros. The other one of
* the first two allocations is never initialized; the free checks it is
* still all 0xCC, so a wolfCrypt free that touched it (the Curve25519
* free zeroes the key) is caught. */
#define FAIL_NTH_PROBE_SZ 2
static int failAllocAt = 0;
static int failAllocCount = 0;
static void* failNthPtr[FAIL_NTH_PROBE_SZ];
static size_t failNthSz[FAIL_NTH_PROBE_SZ];
static int failAllocTouched = 0;
static void* FailNthMalloc(size_t size)
{
void* p;
if (++failAllocCount == failAllocAt)
return NULL;
p = malloc(size);
if (p != NULL)
WMEMSET(p, 0xCC, size);
if (failAllocCount <= FAIL_NTH_PROBE_SZ) {
failNthPtr[failAllocCount - 1] = p;
failNthSz[failAllocCount - 1] = size;
}
return p;
}
static void FailNthFree(void* ptr)
{
size_t i, j;
for (i = 0; ptr != NULL && i < FAIL_NTH_PROBE_SZ; i++) {
if (ptr == failNthPtr[i]) {
for (j = 0; j < failNthSz[i]; j++) {
if (((byte*)ptr)[j] != 0xCC) {
failAllocTouched = 1;
break;
}
}
failNthPtr[i] = NULL;
}
}
free(ptr);
}
static void* FailNthRealloc(void* ptr, size_t size)
{
return realloc(ptr, size);
}
typedef int (*KeyAgreeServerFn)(WOLFSSH* ssh, byte hashId,
byte* f, word32* fSz);
/* Verify the server ECDH and Curve25519 KeyAgree functions survive a
* failed allocation of either temporary key under WOLFSSH_SMALL_STACK.
* When one allocation fails, the other key was allocated but never
* initialized; it must not be handed to the wolfCrypt free, so it must
* reach WFREE still holding the allocator's fill. */
static int test_KeyAgree_server_allocFailCleanup(void)
{
static const struct {
byte kexId;
KeyAgreeServerFn fn;
} cases[] = {
#if !defined(WOLFSSH_NO_ECDH) && !defined(WOLFSSH_NO_ECDH_SHA2_NISTP256)
{ ID_ECDH_SHA2_NISTP256, wolfSSH_TestKeyAgreeEcdh_server },
#endif
#ifndef WOLFSSH_NO_CURVE25519_SHA256
{ ID_CURVE25519_SHA256, wolfSSH_TestKeyAgreeCurve25519_server },
#endif
};
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
byte f[MAX_KEX_KEY_SZ];
word32 fSz;
word32 i;
int failAt;
int ret;
int result = 0;
wolfSSL_Malloc_cb prevMf = NULL;
wolfSSL_Free_cb prevFf = NULL;
wolfSSL_Realloc_cb prevRf = NULL;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -790;
ssh = wolfSSH_new(ctx);
if (ssh == NULL || ssh->handshake == NULL) {
result = -791;
goto out;
}
wolfSSL_GetAllocators(&prevMf, &prevFf, &prevRf);
for (i = 0; i < (word32)(sizeof(cases) / sizeof(cases[0])); i++) {
/* The two temporary keys are the first two allocations. */
for (failAt = 1; failAt <= 2; failAt++) {
ssh->handshake->kexId = cases[i].kexId;
fSz = (word32)sizeof(f);
failAllocAt = failAt;
failAllocCount = 0;
failAllocTouched = 0;
WMEMSET(failNthPtr, 0, sizeof(failNthPtr));
if (wolfSSL_SetAllocators(FailNthMalloc, FailNthFree,
FailNthRealloc) != 0) {
result = -792;
goto out;
}
ret = cases[i].fn(ssh, WC_HASH_TYPE_SHA256, f, &fSz);
wolfSSL_SetAllocators(prevMf, prevFf, prevRf);
if (ret != WS_MEMORY_E) {
result = -793;
goto out;
}
if (failAllocTouched) {
result = -794;
goto out;
}
}
}
out:
if (ssh != NULL)
wolfSSH_free(ssh);
if (ctx != NULL)
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* WOLFSSH_SMALL_STACK && WOLFSSH_TEST_CAPTURING_ALLOCATOR && ... */
#if !defined(WOLFSSH_NO_NISTP256_MLKEM768_SHA256) || \
!defined(WOLFSSH_NO_NISTP384_MLKEM1024_SHA384) || \
!defined(WOLFSSH_NO_CURVE25519_MLKEM768_SHA256)
typedef struct {
byte kexId;
int mlKemType;
enum wc_HashType hashId;
word32 classicSz; /* classical shared secret size */
} MlKemClientCase;
static const MlKemClientCase mlKemClientCases[] = {
#ifndef WOLFSSH_NO_CURVE25519_MLKEM768_SHA256
{ ID_CURVE25519_MLKEM768_SHA256, WC_ML_KEM_768, WC_HASH_TYPE_SHA256,
CURVE25519_KEYSIZE },
#endif
#ifndef WOLFSSH_NO_NISTP256_MLKEM768_SHA256
{ ID_NISTP256_MLKEM768_SHA256, WC_ML_KEM_768, WC_HASH_TYPE_SHA256, 32 },
#endif
#ifndef WOLFSSH_NO_NISTP384_MLKEM1024_SHA384
{ ID_NISTP384_MLKEM1024_SHA384, WC_ML_KEM_1024, WC_HASH_TYPE_SHA384, 48 },
#endif
};
/* Largest classical public key in f: an uncompressed P-384 point. */
#define MLKEM_CLIENT_PEER_SZ (1 + 2 * 48)
/* Run KeyAgreeEcdhMlKem_client for tc with a fresh client key pair, ssh->kSz
* set to kSz on entry. With corrupt set, one byte of the encoded private
* key's stored H(ek) is flipped and *decodeRet gets what
* wc_MlKemKey_DecodePrivateKey returns for those bytes. *kMatch is set when
* ssh->k is Hash(ss || classical secret), the secrets computed peer side. */
static int mlKemClientAgree(const MlKemClientCase* tc, word32 kSz,
int corrupt, int* agreeRet, int* decodeRet, int* kMatch)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
MlKemKey kem;
MlKemKey scratch;
byte f[WC_ML_KEM_MAX_CIPHER_TEXT_SIZE + MLKEM_CLIENT_PEER_SZ];
byte cPub[MLKEM_CLIENT_PEER_SZ];
byte expected[WC_ML_KEM_SS_SZ + MLKEM_CLIENT_PEER_SZ];
byte digest[WC_MAX_DIGEST_SIZE];
word32 ctSz = 0, privSz = 0;
word32 pubSz = MLKEM_CLIENT_PEER_SZ, cPubSz = sizeof(cPub);
word32 classicSz = MLKEM_CLIENT_PEER_SZ;
int digestSz;
int kemInit = 0;
int result = 0;
#ifndef WOLFSSH_NO_CURVE25519_MLKEM768_SHA256
curve25519_key peer25519, client25519;
int peer25519Init = 0, client25519Init = 0;
#endif
#if !defined(WOLFSSH_NO_NISTP256_MLKEM768_SHA256) || \
!defined(WOLFSSH_NO_NISTP384_MLKEM1024_SHA384)
ecc_key peerEcc, clientEcc;
int peerEccInit = 0, clientEccInit = 0;
int curveId = (tc->classicSz == 48) ? ECC_SECP384R1 : ECC_SECP256R1;
#endif
*agreeRet = WS_FATAL_ERROR;
*decodeRet = 0;
*kMatch = 0;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -7300;
ssh = wolfSSH_new(ctx);
if (ssh == NULL || ssh->handshake == NULL) {
result = -7301;
goto out;
}
ssh->handshake->kexId = tc->kexId;
ssh->handshake->useMlKem = 1;
/* Client ML-KEM key, encoded into handshake->x. */
if (wc_MlKemKey_Init(&kem, tc->mlKemType, NULL, INVALID_DEVID) != 0) {
result = -7303;
goto out;
}
kemInit = 1;
if (wc_MlKemKey_MakeKey(&kem, ssh->rng) != 0
|| wc_MlKemKey_PrivateKeySize(&kem, &privSz) != 0
|| wc_MlKemKey_CipherTextSize(&kem, &ctSz) != 0
|| privSz > sizeof(ssh->handshake->x)
|| wc_MlKemKey_EncodePrivateKey(&kem, ssh->handshake->x,
privSz) != 0
|| wc_MlKemKey_Encapsulate(&kem, f, expected, ssh->rng) != 0) {
result = -7304;
goto out;
}
ssh->handshake->xSz = privSz;
/* Client ephemeral classical key, as SendKexDhInit makes it, and the
* peer key whose public part follows the ciphertext in f. The expected
* classical secret is computed from the peer side. */
#ifndef WOLFSSH_NO_CURVE25519_MLKEM768_SHA256
if (tc->kexId == ID_CURVE25519_MLKEM768_SHA256) {
ssh->handshake->useCurve25519 = 1;
if (wc_curve25519_init(&ssh->handshake->privKey.curve25519) != 0
|| wc_curve25519_make_key(ssh->rng, CURVE25519_KEYSIZE,
&ssh->handshake->privKey.curve25519) != 0) {
result = -7302;
goto out;
}
if (wc_curve25519_init(&peer25519) != 0) {
result = -7305;
goto out;
}
peer25519Init = 1;
if (wc_curve25519_init(&client25519) != 0) {
result = -7305;
goto out;
}
client25519Init = 1;
if (wc_curve25519_make_key(ssh->rng, CURVE25519_KEYSIZE,
&peer25519) != 0
|| wc_curve25519_export_public_ex(&peer25519, f + ctSz,
&pubSz, EC25519_LITTLE_ENDIAN) != 0
|| wc_curve25519_export_public_ex(
&ssh->handshake->privKey.curve25519, cPub, &cPubSz,
EC25519_LITTLE_ENDIAN) != 0
|| wc_curve25519_import_public_ex(cPub, cPubSz,
&client25519, EC25519_LITTLE_ENDIAN) != 0
|| wc_curve25519_shared_secret_ex(&peer25519, &client25519,
expected + WC_ML_KEM_SS_SZ, &classicSz,
EC25519_LITTLE_ENDIAN) != 0) {
result = -7306;
goto out;
}
}
else
#endif
{
#if !defined(WOLFSSH_NO_NISTP256_MLKEM768_SHA256) || \
!defined(WOLFSSH_NO_NISTP384_MLKEM1024_SHA384)
ssh->handshake->useEcdh = 1;
if (wc_ecc_init(&ssh->handshake->privKey.ecc) != 0) {
result = -7302;
goto out;
}
#ifdef HAVE_WC_ECC_SET_RNG
if (wc_ecc_set_rng(&ssh->handshake->privKey.ecc, ssh->rng) != 0) {
result = -7302;
goto out;
}
#endif
if (wc_ecc_make_key_ex(ssh->rng, (int)tc->classicSz,
&ssh->handshake->privKey.ecc, curveId) != 0) {
result = -7302;
goto out;
}
if (wc_ecc_init(&peerEcc) != 0) {
result = -7305;
goto out;
}
peerEccInit = 1;
if (wc_ecc_init(&clientEcc) != 0) {
result = -7305;
goto out;
}
clientEccInit = 1;
#ifdef HAVE_WC_ECC_SET_RNG
if (wc_ecc_set_rng(&peerEcc, ssh->rng) != 0) {
result = -7305;
goto out;
}
#endif
if (wc_ecc_make_key_ex(ssh->rng, (int)tc->classicSz, &peerEcc,
curveId) != 0
|| wc_ecc_export_x963(&peerEcc, f + ctSz, &pubSz) != 0
|| wc_ecc_export_x963(&ssh->handshake->privKey.ecc, cPub,
&cPubSz) != 0
|| wc_ecc_import_x963_ex(cPub, cPubSz, &clientEcc,
curveId) != 0
|| wc_ecc_shared_secret(&peerEcc, &clientEcc,
expected + WC_ML_KEM_SS_SZ, &classicSz) != 0) {
result = -7306;
goto out;
}
#endif
}
if (classicSz != tc->classicSz) {
result = -7308;
goto out;
}
if (corrupt) {
/* dk ends with H(ek) || z; flip a byte of H(ek). */
ssh->handshake->x[privSz - 2 * WC_ML_KEM_SYM_SZ] ^= 0x01;
if (wc_MlKemKey_Init(&scratch, tc->mlKemType, NULL,
INVALID_DEVID) != 0) {
result = -7307;
goto out;
}
*decodeRet = wc_MlKemKey_DecodePrivateKey(&scratch,
ssh->handshake->x, privSz);
wc_MlKemKey_Free(&scratch);
}
ssh->kSz = kSz;
*agreeRet = wolfSSH_TestKeyAgreeEcdhMlKem_client(ssh, (byte)tc->hashId,
f, ctSz + pubSz);
digestSz = wc_HashGetDigestSize(tc->hashId);
if (digestSz <= 0 || wc_Hash(tc->hashId, expected,
WC_ML_KEM_SS_SZ + classicSz, digest, (word32)digestSz) != 0) {
result = -7309;
goto out;
}
*kMatch = (ssh->kSz == (word32)digestSz)
&& (WMEMCMP(ssh->k, digest, (word32)digestSz) == 0);
out:
#ifndef WOLFSSH_NO_CURVE25519_MLKEM768_SHA256
if (peer25519Init)
wc_curve25519_free(&peer25519);
if (client25519Init)
wc_curve25519_free(&client25519);
#endif
#if !defined(WOLFSSH_NO_NISTP256_MLKEM768_SHA256) || \
!defined(WOLFSSH_NO_NISTP384_MLKEM1024_SHA384)
if (peerEccInit)
wc_ecc_free(&peerEcc);
if (clientEccInit)
wc_ecc_free(&clientEcc);
#endif
if (kemInit)
wc_MlKemKey_Free(&kem);
if (ssh != NULL)
wolfSSH_free(ssh);
if (ctx != NULL)
wolfSSH_CTX_free(ctx);
return result;
}
/* The classical secret lands after the ML-KEM secret in ssh->k, so only the
* remaining capacity may be offered to it, and a private-key decode failure
* must be the error returned rather than a later decapsulation error. */
static int test_KeyAgreeEcdhMlKem_client(void)
{
word32 i;
int agreeRet;
int decodeRet;
int kMatch;
int ret;
for (i = 0; i < sizeof(mlKemClientCases) / sizeof(mlKemClientCases[0]);
i++) {
const MlKemClientCase* tc = &mlKemClientCases[i];
word32 fitSz = WC_ML_KEM_SS_SZ + tc->classicSz;
/* Control: full capacity agrees. */
ret = mlKemClientAgree(tc, MAX_KEX_KEY_SZ, 0, &agreeRet, &decodeRet,
&kMatch);
if (ret != 0)
return ret;
if (agreeRet != WS_SUCCESS || !kMatch)
return -7310;
/* Exact fit for both secrets agrees. */
ret = mlKemClientAgree(tc, fitSz, 0, &agreeRet, &decodeRet, &kMatch);
if (ret != 0)
return ret;
if (agreeRet != WS_SUCCESS || !kMatch)
return -7311;
/* No room past the ML-KEM secret is rejected before any agreement. */
ret = mlKemClientAgree(tc, WC_ML_KEM_SS_SZ, 0, &agreeRet, &decodeRet,
&kMatch);
if (ret != 0)
return ret;
if (agreeRet != WS_BUFFER_E)
return -7314;
ret = mlKemClientAgree(tc, 0, 0, &agreeRet, &decodeRet, &kMatch);
if (ret != 0)
return ret;
if (agreeRet != WS_BUFFER_E)
return -7315;
/* One byte short for the classical secret must fail. */
ret = mlKemClientAgree(tc, fitSz - 1, 0, &agreeRet, &decodeRet,
&kMatch);
if (ret != 0)
return ret;
if (agreeRet == WS_SUCCESS)
return -7312;
/* Corrupt private key: a decode error is returned as is. A decode
* that does not check H(ek) leaves decapsulation to reject
* implicitly, which agrees on a different secret. */
ret = mlKemClientAgree(tc, MAX_KEX_KEY_SZ, 1, &agreeRet, &decodeRet,
&kMatch);
if (ret != 0)
return ret;
if (kMatch || (decodeRet != 0 ? agreeRet != decodeRet
: agreeRet != WS_SUCCESS))
return -7313;
}
return 0;
}
#endif
#if defined(WOLFSSH_SCP) && !defined(WOLFSSH_SCP_USER_CALLBACKS) && \
!defined(NO_FILESYSTEM) && !defined(WOLFSSL_NUCLEUS) && \
!defined(_WIN32) && !defined(WOLFSSH_ZEPHYR)
#ifndef PATH_MAX
#define PATH_MAX 4096
#endif
static int scpTestSnprintfOk(int n, size_t bufSz)
{
return (n >= 0 && (size_t)n < bufSz);
}
static int pathsMatch(const char* a, const char* b)
{
char* aResolved = realpath(a, NULL);
char* bResolved = realpath(b, NULL);
int match = 0;
if (aResolved != NULL && bResolved != NULL)
match = (WSTRCMP(aResolved, bResolved) == 0);
free(aResolved);
free(bResolved);
return match;
}
static int test_ScpRecvCallback_EndDirDepthGuard(void)
{
char tmpDir[] = "/tmp/wolfssh_scpXXXXXX";
char basePathRaw[PATH_MAX];
char evilPath[PATH_MAX];
char evilFileInBase[PATH_MAX];
char subPath[PATH_MAX];
char cwd[PATH_MAX];
char origCwd[PATH_MAX];
char* basePath = NULL;
char* tmpResolved = NULL;
struct stat st;
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
int pathsReady = 0;
int baseMkdirDone = 0;
int subdirCreated = 0;
int origCwdSaved = 0;
int ret;
int result = 0;
basePathRaw[0] = '\0';
evilPath[0] = '\0';
evilFileInBase[0] = '\0';
subPath[0] = '\0';
if (getcwd(origCwd, sizeof(origCwd)) == NULL)
return -799;
origCwdSaved = 1;
if (mkdtemp(tmpDir) == NULL)
return -800;
ret = snprintf(basePathRaw, sizeof(basePathRaw), "%s/scp_target", tmpDir);
if (!scpTestSnprintfOk(ret, sizeof(basePathRaw))) {
result = -801;
goto cleanup;
}
if (mkdir(basePathRaw, 0755) != 0) {
result = -802;
goto cleanup;
}
baseMkdirDone = 1;
basePath = realpath(basePathRaw, NULL);
tmpResolved = realpath(tmpDir, NULL);
if (basePath == NULL || tmpResolved == NULL) {
result = -803;
goto cleanup;
}
ret = snprintf(evilPath, sizeof(evilPath), "%s/EVIL_FILE.txt", tmpResolved);
if (!scpTestSnprintfOk(ret, sizeof(evilPath))) {
result = -804;
goto cleanup;
}
ret = snprintf(evilFileInBase, sizeof(evilFileInBase), "%s/EVIL_FILE.txt",
basePath);
if (!scpTestSnprintfOk(ret, sizeof(evilFileInBase))) {
result = -804;
goto cleanup;
}
ret = snprintf(subPath, sizeof(subPath), "%s/subdir", basePath);
if (!scpTestSnprintfOk(ret, sizeof(subPath))) {
result = -804;
goto cleanup;
}
pathsReady = 1;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL) {
result = -805;
goto cleanup;
}
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
result = -806;
goto cleanup;
}
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_NEW_REQUEST, basePath,
NULL, 0, 0, 0, 0, NULL, 0, 0, NULL);
if (ret != WS_SCP_CONTINUE) {
result = -807;
goto cleanup;
}
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_END_DIR, basePath,
NULL, 0, 0, 0, 0, NULL, 0, 0, NULL);
if (ret != WS_SCP_ABORT) {
result = -808;
goto cleanup;
}
if (ssh->scpDirDepth != 0) {
result = -809;
goto cleanup;
}
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_NEW_FILE, basePath,
"EVIL_FILE.txt", 0644, 0, 0, 0, NULL, 0, 0, NULL);
if (ret == WS_SCP_CONTINUE) {
(void)wsScpRecvCallback(ssh, WOLFSSH_SCP_FILE_DONE, basePath,
"EVIL_FILE.txt", 0644, 0, 0, 0, NULL, 0, 0,
wolfSSH_GetScpRecvCtx(ssh));
}
if (stat(evilPath, &st) == 0) {
(void)remove(evilPath);
result = -810;
goto cleanup;
}
/* the callback keeps its destination per session, never in the process
* working directory */
if (getcwd(cwd, sizeof(cwd)) == NULL || !pathsMatch(cwd, origCwd)) {
result = -811;
goto cleanup;
}
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_NEW_DIR, basePath,
"subdir", 0755, 0, 0, 0, NULL, 0, 0, NULL);
if (ret != WS_SCP_CONTINUE) {
result = -812;
goto cleanup;
}
subdirCreated = 1;
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_END_DIR, basePath,
NULL, 0, 0, 0, 0, NULL, 0, 0, NULL);
if (ret != WS_SCP_CONTINUE || ssh->scpDirDepth != 0) {
result = -813;
goto cleanup;
}
if (getcwd(cwd, sizeof(cwd)) == NULL || !pathsMatch(cwd, origCwd)) {
result = -814;
goto cleanup;
}
cleanup:
if (ssh != NULL)
wolfSSH_free(ssh);
if (ctx != NULL)
wolfSSH_CTX_free(ctx);
free(basePath);
free(tmpResolved);
if (pathsReady) {
(void)remove(evilPath);
(void)remove(evilFileInBase);
}
if (subdirCreated)
(void)rmdir(subPath);
if (baseMkdirDone)
(void)rmdir(basePathRaw);
(void)rmdir(tmpDir);
if (origCwdSaved && chdir(origCwd) != 0 && result == 0)
result = -815;
return result;
}
static int test_ScpRecvCallback_NewDirEnterFail(void)
{
char tmpDir[] = "/tmp/wolfssh_scpXXXXXX";
char basePathRaw[PATH_MAX];
char noexecSubPath[PATH_MAX];
char plainFilePath[PATH_MAX];
char origCwd[PATH_MAX];
char* basePath = NULL;
struct stat st;
FILE* plainFp;
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
int baseMkdirDone = 0;
int noexecCreated = 0;
int plainCreated = 0;
int origCwdSaved = 0;
int ret;
int result = 0;
basePathRaw[0] = '\0';
noexecSubPath[0] = '\0';
plainFilePath[0] = '\0';
if (getcwd(origCwd, sizeof(origCwd)) == NULL)
return -820;
origCwdSaved = 1;
if (mkdtemp(tmpDir) == NULL)
return -821;
ret = snprintf(basePathRaw, sizeof(basePathRaw), "%s/scp_target", tmpDir);
if (!scpTestSnprintfOk(ret, sizeof(basePathRaw))) {
result = -822;
goto cleanup;
}
if (mkdir(basePathRaw, 0755) != 0) {
result = -823;
goto cleanup;
}
baseMkdirDone = 1;
basePath = realpath(basePathRaw, NULL);
if (basePath == NULL) {
result = -824;
goto cleanup;
}
ret = snprintf(noexecSubPath, sizeof(noexecSubPath), "%s/noexec_sub",
basePath);
if (!scpTestSnprintfOk(ret, sizeof(noexecSubPath))) {
result = -825;
goto cleanup;
}
ret = snprintf(plainFilePath, sizeof(plainFilePath), "%s/plain",
basePath);
if (!scpTestSnprintfOk(ret, sizeof(plainFilePath))) {
result = -834;
goto cleanup;
}
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL) {
result = -826;
goto cleanup;
}
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
result = -827;
goto cleanup;
}
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_NEW_REQUEST, basePath,
NULL, 0, 0, 0, 0, NULL, 0, 0, NULL);
if (ret != WS_SCP_CONTINUE) {
result = -828;
goto cleanup;
}
/* a regular file of the directory's name is nothing to enter, however
* mkdir reports it */
plainFp = fopen(plainFilePath, "wb");
if (plainFp == NULL) {
result = -835;
goto cleanup;
}
fclose(plainFp);
plainCreated = 1;
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_NEW_DIR, basePath,
"plain", 0755, 0, 0, 0, NULL, 0, 0, NULL);
if (ret != WS_SCP_ABORT) {
result = -836;
goto cleanup;
}
if (ssh->scpDirDepth != 0) {
result = -837;
goto cleanup;
}
if (stat(plainFilePath, &st) != 0 || !S_ISREG(st.st_mode)) {
result = -838;
goto cleanup;
}
/* pre-create noexec_sub with mode 0000 so the directory cannot be
* entered after mkdir gets EEXIST and continues */
if (mkdir(noexecSubPath, 0000) != 0) {
result = -829;
goto cleanup;
}
noexecCreated = 1;
/* root bypasses directory permission checks; skip the enter-fail
* sub-test to avoid a false failure */
if (geteuid() == 0)
goto cleanup;
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_NEW_DIR, basePath,
"noexec_sub", 0755, 0, 0, 0, NULL, 0, 0, NULL);
#ifdef WOLFSSH_HAVE_DIRFD
if (ret != WS_SCP_ABORT) {
result = -830;
goto cleanup;
}
#else
/* the path-based fallback does not enter directories, so the refusal
* only comes with the first create below it */
if (ret != WS_SCP_CONTINUE) {
result = -830;
goto cleanup;
}
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_NEW_FILE, basePath,
"f.txt", 0644, 0, 0, 0, NULL, 0, 0, NULL);
if (ret != WS_SCP_ABORT) {
result = -832;
goto cleanup;
}
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_END_DIR, basePath,
NULL, 0, 0, 0, 0, NULL, 0, 0, NULL);
if (ret != WS_SCP_CONTINUE) {
result = -833;
goto cleanup;
}
#endif
if (ssh->scpDirDepth != 0) {
result = -831;
goto cleanup;
}
cleanup:
if (ssh != NULL)
wolfSSH_free(ssh);
if (ctx != NULL)
wolfSSH_CTX_free(ctx);
free(basePath);
if (noexecCreated) {
(void)chmod(noexecSubPath, 0755);
(void)rmdir(noexecSubPath);
}
if (plainCreated)
(void)remove(plainFilePath);
if (baseMkdirDone)
(void)rmdir(basePathRaw);
(void)rmdir(tmpDir);
if (origCwdSaved && chdir(origCwd) != 0 && result == 0)
result = -839;
return result;
}
/* A pre-existing symlink in the destination directory must not be followed
* out of that directory, neither when entering it as a directory nor when
* opening it as a file. */
static int test_ScpRecvCallback_SymlinkGuard(void)
{
#ifndef WOLFSSH_HAVE_SYMLINK
/* symlink rejection is compiled out on this configuration */
return 0;
#else
char tmpDir[] = "/tmp/wolfssh_scpXXXXXX";
char basePathRaw[PATH_MAX];
char outsidePath[PATH_MAX];
char linkDirPath[PATH_MAX];
char linkFilePath[PATH_MAX];
char leakedPath[PATH_MAX];
char linkBasePath[PATH_MAX];
char origCwd[PATH_MAX];
char* basePath = NULL;
struct stat st;
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
int baseMkdirDone = 0;
int outsideMkdirDone = 0;
int linkDirDone = 0;
int linkFileDone = 0;
int linkBaseDone = 0;
int origCwdSaved = 0;
int ret;
int result = 0;
basePathRaw[0] = '\0';
outsidePath[0] = '\0';
linkDirPath[0] = '\0';
linkFilePath[0] = '\0';
leakedPath[0] = '\0';
linkBasePath[0] = '\0';
if (getcwd(origCwd, sizeof(origCwd)) == NULL)
return -840;
origCwdSaved = 1;
if (mkdtemp(tmpDir) == NULL)
return -841;
ret = snprintf(basePathRaw, sizeof(basePathRaw), "%s/scp_target", tmpDir);
if (!scpTestSnprintfOk(ret, sizeof(basePathRaw))) {
result = -842;
goto cleanup;
}
if (mkdir(basePathRaw, 0755) != 0) {
result = -843;
goto cleanup;
}
baseMkdirDone = 1;
ret = snprintf(outsidePath, sizeof(outsidePath), "%s/outside", tmpDir);
if (!scpTestSnprintfOk(ret, sizeof(outsidePath))) {
result = -844;
goto cleanup;
}
if (mkdir(outsidePath, 0755) != 0) {
result = -845;
goto cleanup;
}
outsideMkdirDone = 1;
basePath = realpath(basePathRaw, NULL);
if (basePath == NULL) {
result = -846;
goto cleanup;
}
ret = snprintf(linkDirPath, sizeof(linkDirPath), "%s/linkdir", basePath);
if (!scpTestSnprintfOk(ret, sizeof(linkDirPath))) {
result = -847;
goto cleanup;
}
ret = snprintf(linkFilePath, sizeof(linkFilePath), "%s/linkfile", basePath);
if (!scpTestSnprintfOk(ret, sizeof(linkFilePath))) {
result = -858;
goto cleanup;
}
ret = snprintf(leakedPath, sizeof(leakedPath),
"%s/leaked.txt", outsidePath);
if (!scpTestSnprintfOk(ret, sizeof(leakedPath))) {
result = -859;
goto cleanup;
}
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL) {
result = -848;
goto cleanup;
}
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
result = -849;
goto cleanup;
}
/* NEW_REQUEST takes basePath as the destination */
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_NEW_REQUEST, basePath,
NULL, 0, 0, 0, 0, NULL, 0, 0, NULL);
if (ret != WS_SCP_CONTINUE) {
result = -850;
goto cleanup;
}
/* plant a directory symlink pointing outside basePath */
if (symlink(outsidePath, linkDirPath) != 0) {
result = -851;
goto cleanup;
}
linkDirDone = 1;
/* mkdir returns EEXIST for the existing symlink; the callback must
* refuse to enter it rather than escape basePath */
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_NEW_DIR, basePath,
"linkdir", 0755, 0, 0, 0, NULL, 0, 0, NULL);
if (ret != WS_SCP_ABORT) {
result = -852;
goto cleanup;
}
if (ssh->scpDirDepth != 0) {
result = -853;
goto cleanup;
}
/* plant a (dangling) file symlink pointing outside basePath */
if (symlink(leakedPath, linkFilePath) != 0) {
result = -854;
goto cleanup;
}
linkFileDone = 1;
/* the callback must refuse to open the symlink rather than write through
* it to the outside target */
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_NEW_FILE, basePath,
"linkfile", 0644, 0, 0, 0, NULL, 0, 0, NULL);
if (ret != WS_SCP_ABORT) {
result = -855;
goto cleanup;
}
if (stat(leakedPath, &st) == 0) {
(void)remove(leakedPath);
result = -856;
goto cleanup;
}
/* a destination whose leaf is a symlink is refused when the request
* arrives, as the request parser refuses it, so a link swapped in
* between the two is not followed; the refusal leaves no destination
* behind for a file to land in */
ret = snprintf(linkBasePath, sizeof(linkBasePath), "%s/linkbase",
tmpDir);
if (!scpTestSnprintfOk(ret, sizeof(linkBasePath))) {
result = -860;
goto cleanup;
}
if (symlink(outsidePath, linkBasePath) != 0) {
result = -861;
goto cleanup;
}
linkBaseDone = 1;
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_NEW_REQUEST, linkBasePath,
NULL, 0, 0, 0, 0, NULL, 0, 0, NULL);
if (ret != WS_SCP_ABORT) {
result = -862;
goto cleanup;
}
if (ssh->scpRecvPath != NULL) {
result = -863;
goto cleanup;
}
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_NEW_FILE, linkBasePath,
"leaked.txt", 0644, 0, 0, 0, NULL, 0, 0, NULL);
if (ret != WS_SCP_ABORT) {
result = -864;
goto cleanup;
}
if (stat(leakedPath, &st) == 0) {
(void)remove(leakedPath);
result = -865;
goto cleanup;
}
cleanup:
if (ssh != NULL)
wolfSSH_free(ssh);
if (ctx != NULL)
wolfSSH_CTX_free(ctx);
free(basePath);
/* the callback must not have moved the process out of its directory */
if (origCwdSaved && chdir(origCwd) != 0 && result == 0)
result = -857;
if (linkDirDone)
(void)remove(linkDirPath);
if (linkFileDone)
(void)remove(linkFilePath);
if (linkBaseDone)
(void)remove(linkBasePath);
if (outsideMkdirDone)
(void)rmdir(outsidePath);
if (baseMkdirDone)
(void)rmdir(basePathRaw);
(void)rmdir(tmpDir);
return result;
#endif /* WOLFSSH_HAVE_SYMLINK */
}
/* A recursive receive must land each file in the directory last entered
* without the callback touching the process working directory, which every
* session in the process shares. A directory moved out from under the
* transfer must not carry the rest of it along. */
static int test_ScpRecvCallback_SessionPath(void)
{
char tmpDir[] = "/tmp/wolfssh_scpXXXXXX";
char origCwd[PATH_MAX];
char cwd[PATH_MAX];
char outerPath[PATH_MAX];
char innerPath[PATH_MAX];
char innerFile[PATH_MAX];
char baseFile[PATH_MAX];
char otherPath[PATH_MAX];
char movedOuter[PATH_MAX];
char movedInner[PATH_MAX];
char movedFile[PATH_MAX];
char strayFile[PATH_MAX];
char hFile[PATH_MAX];
char* basePath = NULL;
const char data[] = "nested";
struct stat st;
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
int baseReady = 0;
int ret;
int result = 0;
outerPath[0] = '\0';
innerPath[0] = '\0';
innerFile[0] = '\0';
baseFile[0] = '\0';
otherPath[0] = '\0';
movedOuter[0] = '\0';
movedInner[0] = '\0';
movedFile[0] = '\0';
strayFile[0] = '\0';
hFile[0] = '\0';
if (getcwd(origCwd, sizeof(origCwd)) == NULL)
return -870;
if (mkdtemp(tmpDir) == NULL)
return -871;
baseReady = 1;
basePath = realpath(tmpDir, NULL);
if (basePath == NULL) {
result = -872;
goto cleanup;
}
ret = snprintf(outerPath, sizeof(outerPath), "%s/outer", basePath);
if (!scpTestSnprintfOk(ret, sizeof(outerPath))) {
result = -873;
goto cleanup;
}
ret = snprintf(innerPath, sizeof(innerPath), "%s/inner", outerPath);
if (!scpTestSnprintfOk(ret, sizeof(innerPath))) {
result = -874;
goto cleanup;
}
ret = snprintf(innerFile, sizeof(innerFile), "%s/f.txt", innerPath);
if (!scpTestSnprintfOk(ret, sizeof(innerFile))) {
result = -875;
goto cleanup;
}
ret = snprintf(baseFile, sizeof(baseFile), "%s/g.txt", basePath);
if (!scpTestSnprintfOk(ret, sizeof(baseFile))) {
result = -876;
goto cleanup;
}
ret = snprintf(otherPath, sizeof(otherPath), "%s/other", basePath);
if (!scpTestSnprintfOk(ret, sizeof(otherPath))) {
result = -892;
goto cleanup;
}
ret = snprintf(movedOuter, sizeof(movedOuter), "%s/outer", otherPath);
if (!scpTestSnprintfOk(ret, sizeof(movedOuter))) {
result = -893;
goto cleanup;
}
ret = snprintf(movedInner, sizeof(movedInner), "%s/inner", movedOuter);
if (!scpTestSnprintfOk(ret, sizeof(movedInner))) {
result = -894;
goto cleanup;
}
ret = snprintf(movedFile, sizeof(movedFile), "%s/f.txt", movedInner);
if (!scpTestSnprintfOk(ret, sizeof(movedFile))) {
result = -903;
goto cleanup;
}
ret = snprintf(strayFile, sizeof(strayFile), "%s/h.txt", otherPath);
if (!scpTestSnprintfOk(ret, sizeof(strayFile))) {
result = -896;
goto cleanup;
}
ret = snprintf(hFile, sizeof(hFile), "%s/h.txt", basePath);
if (!scpTestSnprintfOk(ret, sizeof(hFile))) {
result = -904;
goto cleanup;
}
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL) {
result = -877;
goto cleanup;
}
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
result = -878;
goto cleanup;
}
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_NEW_REQUEST, basePath,
NULL, 0, 0, 0, 0, NULL, 0, 0, NULL);
if (ret != WS_SCP_CONTINUE) {
result = -879;
goto cleanup;
}
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_NEW_DIR, basePath,
"outer", 0755, 0, 0, 0, NULL, 0, 0, NULL);
if (ret != WS_SCP_CONTINUE) {
result = -880;
goto cleanup;
}
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_NEW_DIR, basePath,
"inner", 0755, 0, 0, 0, NULL, 0, 0, NULL);
if (ret != WS_SCP_CONTINUE || ssh->scpDirDepth != 2) {
result = -881;
goto cleanup;
}
/* a file two levels down */
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_NEW_FILE, basePath,
"f.txt", 0644, 0, 0, sizeof(data) - 1, NULL, 0, 0, NULL);
if (ret != WS_SCP_CONTINUE) {
result = -882;
goto cleanup;
}
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_FILE_PART, basePath,
"f.txt", 0644, 0, 0, sizeof(data) - 1, (byte*)data,
sizeof(data) - 1, 0, wolfSSH_GetScpRecvCtx(ssh));
if (ret != WS_SCP_CONTINUE) {
result = -883;
goto cleanup;
}
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_FILE_DONE, basePath,
"f.txt", 0644, 0, 0, sizeof(data) - 1, NULL, 0, 0,
wolfSSH_GetScpRecvCtx(ssh));
if (ret != WS_SCP_CONTINUE) {
result = -884;
goto cleanup;
}
if (stat(innerFile, &st) != 0 || st.st_size != (off_t)(sizeof(data) - 1)) {
result = -885;
goto cleanup;
}
/* back up to the base, where the next file lands */
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_END_DIR, basePath,
NULL, 0, 0, 0, 0, NULL, 0, 0, NULL);
if (ret != WS_SCP_CONTINUE) {
result = -886;
goto cleanup;
}
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_END_DIR, basePath,
NULL, 0, 0, 0, 0, NULL, 0, 0, NULL);
if (ret != WS_SCP_CONTINUE || ssh->scpDirDepth != 0) {
result = -887;
goto cleanup;
}
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_NEW_FILE, basePath,
"g.txt", 0644, 0, 0, 0, NULL, 0, 0, NULL);
if (ret != WS_SCP_CONTINUE) {
result = -888;
goto cleanup;
}
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_FILE_DONE, basePath,
"g.txt", 0644, 0, 0, 0, NULL, 0, 0, wolfSSH_GetScpRecvCtx(ssh));
if (ret != WS_SCP_CONTINUE) {
result = -889;
goto cleanup;
}
if (stat(baseFile, &st) != 0) {
result = -890;
goto cleanup;
}
/* none of it moved the process working directory */
if (getcwd(cwd, sizeof(cwd)) == NULL || !pathsMatch(cwd, origCwd)) {
result = -891;
goto cleanup;
}
/* go back down, then move the tree being written out from under the
* callback: leaving inner still reaches outer, the directory it was
* entered from, but leaving outer no longer reaches the base */
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_NEW_DIR, basePath,
"outer", 0755, 0, 0, 0, NULL, 0, 0, NULL);
if (ret != WS_SCP_CONTINUE) {
result = -895;
goto cleanup;
}
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_NEW_DIR, basePath,
"inner", 0755, 0, 0, 0, NULL, 0, 0, NULL);
if (ret != WS_SCP_CONTINUE) {
result = -897;
goto cleanup;
}
if (mkdir(otherPath, 0755) != 0 || rename(outerPath, movedOuter) != 0) {
result = -898;
goto cleanup;
}
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_END_DIR, basePath,
NULL, 0, 0, 0, 0, NULL, 0, 0, NULL);
if (ret != WS_SCP_CONTINUE) {
result = -899;
goto cleanup;
}
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_END_DIR, basePath,
NULL, 0, 0, 0, 0, NULL, 0, 0, NULL);
#ifdef WOLFSSH_HAVE_DIRFD
/* the parent found is not the one entered from, so the transfer ends
* rather than carrying on in it */
if (ret != WS_SCP_ABORT || ssh->scpDirDepth != 1) {
result = -900;
goto cleanup;
}
#else
/* the path names the base throughout; the next file lands there, not
* where the moved directory's parent now is */
if (ret != WS_SCP_CONTINUE || ssh->scpDirDepth != 0) {
result = -900;
goto cleanup;
}
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_NEW_FILE, basePath,
"h.txt", 0644, 0, 0, 0, NULL, 0, 0, NULL);
if (ret != WS_SCP_CONTINUE) {
result = -901;
goto cleanup;
}
(void)wsScpRecvCallback(ssh, WOLFSSH_SCP_FILE_DONE, basePath,
"h.txt", 0644, 0, 0, 0, NULL, 0, 0, wolfSSH_GetScpRecvCtx(ssh));
if (stat(strayFile, &st) == 0) {
result = -902;
goto cleanup;
}
#endif
cleanup:
if (ssh != NULL)
wolfSSH_free(ssh);
if (ctx != NULL)
wolfSSH_CTX_free(ctx);
if (baseFile[0] != '\0')
(void)remove(baseFile);
if (hFile[0] != '\0')
(void)remove(hFile);
if (strayFile[0] != '\0')
(void)remove(strayFile);
if (innerFile[0] != '\0')
(void)remove(innerFile);
if (movedFile[0] != '\0')
(void)remove(movedFile);
if (innerPath[0] != '\0')
(void)rmdir(innerPath);
if (outerPath[0] != '\0')
(void)rmdir(outerPath);
if (movedInner[0] != '\0')
(void)rmdir(movedInner);
if (movedOuter[0] != '\0')
(void)rmdir(movedOuter);
if (otherPath[0] != '\0')
(void)rmdir(otherPath);
free(basePath);
if (baseReady)
(void)rmdir(tmpDir);
return result;
}
/* Drive the default SCP receive callback through a full single-file receive
* and confirm the peer-supplied modification/access times end up on the
* written file.
*
* Which code path applies the timestamp is decided at build time, not by this
* test: when futimens is detected (HAVE_FUTIMENS) the callback sets it on the
* open descriptor before the closing flush, otherwise it sets it by path after
* close. Both must yield the peer-supplied times, which is what this end-to-end
* test asserts. When the descriptor path is compiled in, this also guards its
* ordering relative to the closing flush: applying the timestamp before the
* buffered data was flushed would leave the modification time at the current
* time rather than the peer value. */
static int test_ScpRecvCallback_Timestamp(void)
{
char tmpDir[] = "/tmp/wolfssh_scptsXXXXXX";
char filePath[PATH_MAX];
char origCwd[PATH_MAX];
const char data[] = "wolfssh scp timestamp regression\n";
const word64 mTime = 1234567890; /* 2009-02-13 23:31:30 UTC */
const word64 aTime = 1000000000; /* 2001-09-09 01:46:40 UTC */
struct stat st;
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
char* basePath = NULL;
int origCwdSaved = 0;
int baseReady = 0;
int ret;
int result = 0;
filePath[0] = '\0';
if (getcwd(origCwd, sizeof(origCwd)) == NULL)
return -850;
origCwdSaved = 1;
if (mkdtemp(tmpDir) == NULL)
return -851;
baseReady = 1;
basePath = realpath(tmpDir, NULL);
if (basePath == NULL) {
result = -852;
goto cleanup;
}
ret = snprintf(filePath, sizeof(filePath), "%s/ts_file.txt", basePath);
if (!scpTestSnprintfOk(ret, sizeof(filePath))) {
result = -853;
goto cleanup;
}
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL) {
result = -854;
goto cleanup;
}
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
result = -855;
goto cleanup;
}
/* enter the destination directory */
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_NEW_REQUEST, basePath,
NULL, 0, 0, 0, 0, NULL, 0, 0, NULL);
if (ret != WS_SCP_CONTINUE) {
result = -856;
goto cleanup;
}
/* open the destination file */
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_NEW_FILE, basePath,
"ts_file.txt", 0644, mTime, aTime, sizeof(data) - 1, NULL, 0, 0,
NULL);
if (ret != WS_SCP_CONTINUE) {
result = -857;
goto cleanup;
}
/* write the file contents */
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_FILE_PART, basePath,
"ts_file.txt", 0644, mTime, aTime, sizeof(data) - 1,
(byte*)data, sizeof(data) - 1, 0, wolfSSH_GetScpRecvCtx(ssh));
if (ret != WS_SCP_CONTINUE) {
result = -858;
goto cleanup;
}
/* close the file and apply the peer-supplied timestamps */
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_FILE_DONE, basePath,
"ts_file.txt", 0644, mTime, aTime, sizeof(data) - 1, NULL, 0, 0,
wolfSSH_GetScpRecvCtx(ssh));
if (ret != WS_SCP_CONTINUE) {
result = -859;
goto cleanup;
}
/* the written file must carry the peer-supplied timestamps */
if (stat(filePath, &st) != 0) {
result = -860;
goto cleanup;
}
if ((word64)st.st_mtime != mTime) {
result = -861;
goto cleanup;
}
if ((word64)st.st_atime != aTime) {
result = -862;
goto cleanup;
}
#ifdef HAVE_FUTIMENS
/* Descriptor build only: a FILE_DONE carrying timestamps but no open file
* (NULL ctx) must abort rather than silently fall back to a path-based
* update that could follow a swapped symlink. Use distinct times and
* confirm the existing file's modification time is left untouched. */
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_FILE_DONE, basePath,
"ts_file.txt", 0644, mTime + 100, aTime + 100, 0, NULL, 0, 0,
NULL);
if (ret != WS_SCP_ABORT) {
result = -864;
goto cleanup;
}
if (stat(filePath, &st) != 0) {
result = -865;
goto cleanup;
}
if ((word64)st.st_mtime != mTime) {
result = -866;
goto cleanup;
}
#endif
cleanup:
if (ssh != NULL)
wolfSSH_free(ssh);
if (ctx != NULL)
wolfSSH_CTX_free(ctx);
if (filePath[0] != '\0')
(void)remove(filePath);
free(basePath);
if (origCwdSaved && chdir(origCwd) != 0 && result == 0)
result = -863;
if (baseReady)
(void)rmdir(tmpDir);
return result;
}
#if defined(HAVE_UTIMENSAT) && defined(WOLFSSH_HAVE_SYMLINK)
/* Exercise the no-follow path fallback (no descriptor-based call available).
* Setting times through a symlink must land on the symlink itself, not the
* target, so a swapped symlink cannot redirect a peer-supplied timestamp. */
static int test_ScpTimestamp_NoFollow(void)
{
char tmpDir[] = "/tmp/wolfssh_scpnfXXXXXX";
char canaryPath[PATH_MAX];
char linkPath[PATH_MAX];
const word64 mTime = 1222333444; /* distinct from the canary's own time */
const word64 aTime = 1100000000;
struct timeval tv[2];
struct stat st;
time_t canaryOrig;
int baseReady = 0;
int canaryReady = 0;
int linkReady = 0;
int ret;
int result = 0;
int fd;
canaryPath[0] = '\0';
linkPath[0] = '\0';
if (mkdtemp(tmpDir) == NULL)
return -870;
baseReady = 1;
ret = snprintf(canaryPath, sizeof(canaryPath), "%s/canary.txt", tmpDir);
if (!scpTestSnprintfOk(ret, sizeof(canaryPath))) {
result = -871;
goto cleanup;
}
ret = snprintf(linkPath, sizeof(linkPath), "%s/link", tmpDir);
if (!scpTestSnprintfOk(ret, sizeof(linkPath))) {
result = -872;
goto cleanup;
}
fd = open(canaryPath, O_CREAT | O_WRONLY | O_TRUNC, 0644);
if (fd < 0) {
result = -873;
goto cleanup;
}
canaryReady = 1;
if (write(fd, "canary\n", 7) != 7) {
close(fd);
result = -881;
goto cleanup;
}
close(fd);
if (stat(canaryPath, &st) != 0) {
result = -874;
goto cleanup;
}
canaryOrig = st.st_mtime;
if (symlink(canaryPath, linkPath) != 0) {
result = -875;
goto cleanup;
}
linkReady = 1;
tv[0].tv_sec = (time_t)aTime;
tv[0].tv_usec = 0;
tv[1].tv_sec = (time_t)mTime;
tv[1].tv_usec = 0;
if (WUTIMES_NOFOLLOW(linkPath, tv) != 0) {
result = -876;
goto cleanup;
}
/* the symlink's own modification time must carry the supplied value */
if (lstat(linkPath, &st) != 0) {
result = -877;
goto cleanup;
}
if ((word64)st.st_mtime != mTime) {
result = -878;
goto cleanup;
}
/* the target the symlink points at must be left untouched */
if (stat(canaryPath, &st) != 0) {
result = -879;
goto cleanup;
}
if (st.st_mtime != canaryOrig) {
result = -880;
goto cleanup;
}
cleanup:
if (linkReady)
(void)remove(linkPath);
if (canaryReady)
(void)remove(canaryPath);
if (baseReady)
(void)rmdir(tmpDir);
return result;
}
#endif /* HAVE_UTIMENSAT && WOLFSSH_HAVE_SYMLINK */
#endif /* WOLFSSH_SCP recv callback depth guard test */
#if defined(WOLFSSH_SCP) && !defined(WOLFSSH_SCP_USER_CALLBACKS) && \
defined(NO_FILESYSTEM)
static int scpSendTestStatus(WOLFSSH* ssh, const char* fileName,
enum WS_ScpFileStates state, ScpBuffer* file)
{
WOLFSSH_UNUSED(ssh);
WOLFSSH_UNUSED(fileName);
WOLFSSH_UNUSED(state);
WOLFSSH_UNUSED(file);
return WS_SUCCESS;
}
/* moves idx past fileSz, as a buggy status callback could */
static int scpSendTestStatusBadIdx(WOLFSSH* ssh, const char* fileName,
enum WS_ScpFileStates state, ScpBuffer* file)
{
WOLFSSH_UNUSED(ssh);
WOLFSSH_UNUSED(fileName);
if (state == WOLFSSH_SCP_SINGLE_FILE_REQUEST)
file->idx = 5;
return WS_SUCCESS;
}
static int scpSendTestStatusFail(WOLFSSH* ssh, const char* fileName,
enum WS_ScpFileStates state, ScpBuffer* file)
{
WOLFSSH_UNUSED(ssh);
WOLFSSH_UNUSED(fileName);
WOLFSSH_UNUSED(state);
WOLFSSH_UNUSED(file);
return WS_FATAL_ERROR;
}
/* The default no-filesystem send callback must accept an ScpBuffer whose
* bufferSz exactly equals fileSz, in both single- and multi-chunk transfers,
* and must still refuse a fileSz larger than the buffer. */
static int test_ScpSendCallback_ExactFitBuffer(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
ScpBuffer sendBuf;
byte data[16];
byte out[64];
char fileName[DEFAULT_SCP_FILE_NAME_SZ];
word64 mTime = 0;
word64 aTime = 0;
word32 totalSz = 0;
int fileMode = 0;
int result = 0;
int ret;
word32 i;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1500;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return -1501;
}
for (i = 0; i < (word32)sizeof(data); i++)
data[i] = (byte)i;
WMEMSET(&sendBuf, 0, sizeof(sendBuf));
WMEMCPY(sendBuf.name, "file.txt", WSTRLEN("file.txt") + 1);
sendBuf.nameSz = (word32)WSTRLEN(sendBuf.name);
sendBuf.buffer = data;
sendBuf.bufferSz = (word32)sizeof(data);
sendBuf.fileSz = (word32)sizeof(data);
sendBuf.status = scpSendTestStatus;
WMEMSET(fileName, 0, sizeof(fileName));
/* exact fit, single chunk: the whole file is returned, not aborted */
ret = wsScpSendCallback(ssh, WOLFSSH_SCP_SINGLE_FILE_REQUEST, "file.txt",
fileName, (word32)sizeof(fileName), &mTime, &aTime, &fileMode, 0,
&totalSz, out, (word32)sizeof(out), &sendBuf);
if (ret != (int)sendBuf.fileSz)
result = -1502;
if (result == 0 && sendBuf.idx != sendBuf.fileSz)
result = -1503;
if (result == 0 && totalSz != sendBuf.fileSz)
result = -1504;
if (result == 0 && WMEMCMP(out, data, sizeof(data)) != 0)
result = -1505;
/* exact fit, multi-chunk: final chunk lands on the buffer boundary */
if (result == 0) {
sendBuf.idx = 0;
ret = wsScpSendCallback(ssh, WOLFSSH_SCP_SINGLE_FILE_REQUEST,
"file.txt", fileName, (word32)sizeof(fileName), &mTime, &aTime,
&fileMode, 0, &totalSz, out, 10, &sendBuf);
if (ret != 10)
result = -1506;
}
if (result == 0) {
ret = wsScpSendCallback(ssh, WOLFSSH_SCP_CONTINUE_FILE_TRANSFER,
"file.txt", fileName, (word32)sizeof(fileName), &mTime, &aTime,
&fileMode, 10, &totalSz, out, 10, &sendBuf);
if (ret != 6)
result = -1507;
if (result == 0 && WMEMCMP(out, data + 10, 6) != 0)
result = -1508;
}
if (result == 0) {
/* transfer complete: a further continue reports EOF, not abort */
ret = wsScpSendCallback(ssh, WOLFSSH_SCP_CONTINUE_FILE_TRANSFER,
"file.txt", fileName, (word32)sizeof(fileName), &mTime, &aTime,
&fileMode, 16, &totalSz, out, 10, &sendBuf);
if (ret != WS_EOF)
result = -1509;
}
/* fileSz larger than the buffer is still refused before any copy */
if (result == 0) {
sendBuf.idx = 0;
sendBuf.fileSz = sendBuf.bufferSz + 1;
ret = wsScpSendCallback(ssh, WOLFSSH_SCP_SINGLE_FILE_REQUEST,
"file.txt", fileName, (word32)sizeof(fileName), &mTime, &aTime,
&fileMode, 0, &totalSz, out, (word32)sizeof(out), &sendBuf);
if (ret != WS_SCP_ABORT)
result = -1510;
sendBuf.fileSz = sendBuf.bufferSz;
}
/* file smaller than the buffer keeps working */
if (result == 0) {
sendBuf.idx = 0;
sendBuf.fileSz = 8;
ret = wsScpSendCallback(ssh, WOLFSSH_SCP_SINGLE_FILE_REQUEST,
"file.txt", fileName, (word32)sizeof(fileName), &mTime, &aTime,
&fileMode, 0, &totalSz, out, (word32)sizeof(out), &sendBuf);
if (ret != 8)
result = -1511;
sendBuf.fileSz = sendBuf.bufferSz;
}
/* a NULL status callback must not crash the continue state */
if (result == 0) {
sendBuf.idx = 0;
sendBuf.status = NULL;
ret = wsScpSendCallback(ssh, WOLFSSH_SCP_SINGLE_FILE_REQUEST,
"file.txt", fileName, (word32)sizeof(fileName), &mTime, &aTime,
&fileMode, 0, &totalSz, out, 10, &sendBuf);
if (ret != 10)
result = -1512;
if (result == 0) {
ret = wsScpSendCallback(ssh, WOLFSSH_SCP_CONTINUE_FILE_TRANSFER,
"file.txt", fileName, (word32)sizeof(fileName), &mTime,
&aTime, &fileMode, 10, &totalSz, out, 10, &sendBuf);
if (ret != 6)
result = -1513;
}
sendBuf.status = scpSendTestStatus;
}
/* idx one past the buffer end must abort, not report EOF; idx == fileSz
* keeps the inner guard out of play so only the top guard can reject */
if (result == 0) {
sendBuf.idx = sendBuf.bufferSz + 1;
sendBuf.fileSz = sendBuf.bufferSz + 1;
ret = wsScpSendCallback(ssh, WOLFSSH_SCP_CONTINUE_FILE_TRANSFER,
"file.txt", fileName, (word32)sizeof(fileName), &mTime, &aTime,
&fileMode, 0, &totalSz, out, 10, &sendBuf);
if (ret != WS_SCP_ABORT)
result = -1514;
sendBuf.idx = 0;
sendBuf.fileSz = sendBuf.bufferSz;
}
/* a chunk that would run past the buffer end mid-continue must abort */
if (result == 0) {
sendBuf.idx = 10;
sendBuf.fileSz = sendBuf.bufferSz + 4;
ret = wsScpSendCallback(ssh, WOLFSSH_SCP_CONTINUE_FILE_TRANSFER,
"file.txt", fileName, (word32)sizeof(fileName), &mTime, &aTime,
&fileMode, 10, &totalSz, out, 10, &sendBuf);
if (ret != WS_SCP_ABORT)
result = -1515;
sendBuf.idx = 0;
sendBuf.fileSz = sendBuf.bufferSz;
}
/* idx past fileSz mid-continue must abort; idx + bufSz stays inside
* bufferSz here, so only the underflow guard can reject */
if (result == 0) {
sendBuf.idx = 5;
sendBuf.fileSz = 4;
ret = wsScpSendCallback(ssh, WOLFSSH_SCP_CONTINUE_FILE_TRANSFER,
"file.txt", fileName, (word32)sizeof(fileName), &mTime, &aTime,
&fileMode, 0, &totalSz, out, 10, &sendBuf);
if (ret != WS_SCP_ABORT)
result = -1516;
sendBuf.idx = 0;
sendBuf.fileSz = sendBuf.bufferSz;
}
/* same underflow on a single file request; status moves idx */
if (result == 0) {
sendBuf.idx = 0;
sendBuf.fileSz = 4;
sendBuf.status = scpSendTestStatusBadIdx;
ret = wsScpSendCallback(ssh, WOLFSSH_SCP_SINGLE_FILE_REQUEST,
"file.txt", fileName, (word32)sizeof(fileName), &mTime, &aTime,
&fileMode, 0, &totalSz, out, 10, &sendBuf);
if (ret != WS_SCP_ABORT)
result = -1517;
sendBuf.idx = 0;
sendBuf.fileSz = sendBuf.bufferSz;
sendBuf.status = scpSendTestStatus;
}
/* a failing status callback aborts the continue state even after a
* successful copy */
if (result == 0) {
sendBuf.idx = 0;
sendBuf.status = scpSendTestStatusFail;
ret = wsScpSendCallback(ssh, WOLFSSH_SCP_CONTINUE_FILE_TRANSFER,
"file.txt", fileName, (word32)sizeof(fileName), &mTime, &aTime,
&fileMode, 0, &totalSz, out, 10, &sendBuf);
if (ret != WS_SCP_ABORT)
result = -1518;
sendBuf.idx = 0;
sendBuf.status = scpSendTestStatus;
}
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* The no-filesystem send callback aborts on an unparsable file name, not
* matching a stale or empty one. aTime is reported as mTime. */
static int test_ScpSendCallback_FileNameAndTimes(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
ScpBuffer sendBuf;
byte data[16];
byte out[64];
char fileName[DEFAULT_SCP_FILE_NAME_SZ];
word64 mTime = 0;
word64 aTime = 0;
word32 totalSz = 0;
int fileMode = 0;
int result = 0;
int ret;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1520;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return -1521;
}
WMEMSET(data, 0x5A, sizeof(data));
WMEMSET(&sendBuf, 0, sizeof(sendBuf));
WMEMCPY(sendBuf.name, "file.txt", WSTRLEN("file.txt") + 1);
sendBuf.nameSz = (word32)WSTRLEN(sendBuf.name);
sendBuf.buffer = data;
sendBuf.bufferSz = (word32)sizeof(data);
sendBuf.fileSz = (word32)sizeof(data);
sendBuf.mTime = 1234;
sendBuf.status = scpSendTestStatus;
/* name too long for the output buffer: the stale matching name already
* in fileName must not let the transfer proceed */
WMEMCPY(fileName, "file.txt", WSTRLEN("file.txt") + 1);
ret = wsScpSendCallback(ssh, WOLFSSH_SCP_SINGLE_FILE_REQUEST,
"dir/file.txt", fileName, 4, &mTime, &aTime, &fileMode, 0,
&totalSz, out, (word32)sizeof(out), &sendBuf);
if (ret != WS_SCP_ABORT)
result = -1522;
if (result == 0 && sendBuf.idx != 0)
result = -1523;
/* empty peer request against an empty configured name */
if (result == 0) {
WMEMSET(sendBuf.name, 0, sizeof(sendBuf.name));
sendBuf.nameSz = 0;
WMEMSET(fileName, 0, sizeof(fileName));
ret = wsScpSendCallback(ssh, WOLFSSH_SCP_SINGLE_FILE_REQUEST, "",
fileName, (word32)sizeof(fileName), &mTime, &aTime,
&fileMode, 0, &totalSz, out, (word32)sizeof(out), &sendBuf);
if (ret != WS_SCP_ABORT)
result = -1524;
if (result == 0 && sendBuf.idx != 0)
result = -1525;
WMEMCPY(sendBuf.name, "file.txt", WSTRLEN("file.txt") + 1);
sendBuf.nameSz = (word32)WSTRLEN(sendBuf.name);
}
/* a good request reports mTime as both times */
if (result == 0) {
mTime = 0;
aTime = 0;
ret = wsScpSendCallback(ssh, WOLFSSH_SCP_SINGLE_FILE_REQUEST,
"dir/file.txt", fileName, (word32)sizeof(fileName), &mTime,
&aTime, &fileMode, 0, &totalSz, out, (word32)sizeof(out),
&sendBuf);
if (ret != (int)sizeof(data))
result = -1526;
if (result == 0 && mTime != 1234)
result = -1527;
if (result == 0 && aTime != 1234)
result = -1528;
}
/* a reused ScpBuffer restarts at 0 */
if (result == 0) {
ret = wsScpSendCallback(ssh, WOLFSSH_SCP_CONTINUE_FILE_TRANSFER,
"dir/file.txt", fileName, (word32)sizeof(fileName), &mTime,
&aTime, &fileMode, (word32)sizeof(data), &totalSz, out,
(word32)sizeof(out), &sendBuf);
if (ret != WS_EOF)
result = -1529;
}
if (result == 0) {
WMEMSET(out, 0, sizeof(out));
ret = wsScpSendCallback(ssh, WOLFSSH_SCP_SINGLE_FILE_REQUEST,
"dir/file.txt", fileName, (word32)sizeof(fileName), &mTime,
&aTime, &fileMode, 0, &totalSz, out, (word32)sizeof(out),
&sendBuf);
if (ret != (int)sizeof(data))
result = -1544;
if (result == 0 && (totalSz != sizeof(data) ||
sendBuf.idx != sizeof(data) ||
WMEMCMP(out, data, sizeof(data)) != 0))
result = -1545;
}
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* The default no-filesystem receive callback must start each new file with a
* terminated name and fresh size and index, even when the previous file was
* abandoned before FILE_DONE. */
static int test_ScpRecvCallback_TwoFiles(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
ScpBuffer recvBuf;
byte store[16];
byte in[10];
int result = 0;
int ret;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -1530;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return -1531;
}
WMEMSET(in, 0x11, sizeof(in));
WMEMSET(&recvBuf, 0, sizeof(recvBuf));
recvBuf.buffer = store;
recvBuf.bufferSz = (word32)sizeof(store);
recvBuf.status = scpSendTestStatus;
/* first file, received completely */
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_NEW_FILE, NULL, "first.txt",
0644, 0, 0, 10, NULL, 0, 0, &recvBuf);
if (ret != WS_SCP_CONTINUE)
result = -1532;
if (result == 0 && (recvBuf.nameSz != 9 ||
WSTRCMP(recvBuf.name, "first.txt") != 0))
result = -1533;
if (result == 0) {
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_FILE_PART, NULL,
"first.txt", 0644, 0, 0, 10, in, 10, 0, &recvBuf);
if (ret != WS_SCP_CONTINUE || recvBuf.fileSz != 10)
result = -1534;
}
if (result == 0) {
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_FILE_DONE, NULL,
"first.txt", 0644, 0, 0, 10, NULL, 0, 10, &recvBuf);
if (ret != WS_SCP_CONTINUE)
result = -1535;
}
/* second, shorter name: no stale suffix, size starts over */
if (result == 0) {
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_NEW_FILE, NULL, "b", 0644,
0, 0, 4, NULL, 0, 0, &recvBuf);
if (ret != WS_SCP_CONTINUE)
result = -1536;
if (result == 0 && (recvBuf.nameSz != 1 ||
WSTRCMP(recvBuf.name, "b") != 0))
result = -1537;
if (result == 0 && (recvBuf.fileSz != 0 || recvBuf.idx != 0))
result = -1538;
}
if (result == 0) {
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_FILE_PART, NULL, "b", 0644,
0, 0, 4, in, 4, 0, &recvBuf);
if (ret != WS_SCP_CONTINUE || recvBuf.fileSz != 4 ||
recvBuf.idx != 4)
result = -1539;
}
/* third file after the second was abandoned without FILE_DONE */
if (result == 0) {
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_NEW_FILE, NULL, "c.bin",
0644, 0, 0, 16, NULL, 0, 0, &recvBuf);
if (ret != WS_SCP_CONTINUE)
result = -1540;
if (result == 0 && (recvBuf.nameSz != 5 ||
WSTRCMP(recvBuf.name, "c.bin") != 0))
result = -1541;
if (result == 0 && (recvBuf.fileSz != 0 || recvBuf.idx != 0))
result = -1542;
}
if (result == 0) {
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_FILE_PART, NULL, "c.bin",
0644, 0, 0, 16, in, 10, 0, &recvBuf);
if (ret != WS_SCP_CONTINUE || recvBuf.fileSz != 10)
result = -1543;
}
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* The no-filesystem receive callback aborts a file larger than the buffer. */
static int test_ScpRecvCallback_Oversize(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
ScpBuffer recvBuf;
byte store[16];
byte in[20];
int result = 0;
int ret;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -1550;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return -1551;
}
WMEMSET(in, 0x33, sizeof(in));
WMEMSET(&recvBuf, 0, sizeof(recvBuf));
recvBuf.buffer = store;
recvBuf.bufferSz = (word32)sizeof(store);
recvBuf.status = scpSendTestStatus;
/* oversize announced: refused */
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_NEW_FILE, NULL, "big", 0644,
0, 0, (word32)sizeof(store) + 1, NULL, 0, 0, &recvBuf);
if (ret != WS_SCP_ABORT)
result = -1552;
/* overrunning part: abort, copy nothing */
if (result == 0) {
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_NEW_FILE, NULL, "fit", 0644,
0, 0, (word32)sizeof(store), NULL, 0, 0, &recvBuf);
if (ret != WS_SCP_CONTINUE)
result = -1553;
}
if (result == 0) {
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_FILE_PART, NULL, "fit",
0644, 0, 0, (word32)sizeof(store), in, 10, 0, &recvBuf);
if (ret != WS_SCP_CONTINUE || recvBuf.fileSz != 10)
result = -1554;
}
if (result == 0) {
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_FILE_PART, NULL, "fit",
0644, 0, 0, (word32)sizeof(store), in, 7, 10, &recvBuf);
if (ret != WS_SCP_ABORT || recvBuf.fileSz != 10 ||
recvBuf.idx != 10)
result = -1555;
}
/* exact fit: accepted */
if (result == 0) {
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_FILE_PART, NULL, "fit",
0644, 0, 0, (word32)sizeof(store), in, 6, 10, &recvBuf);
if (ret != WS_SCP_CONTINUE || recvBuf.fileSz != sizeof(store))
result = -1556;
}
if (result == 0) {
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_FILE_PART, NULL, "fit",
0644, 0, 0, (word32)sizeof(store), NULL, 0,
(word32)sizeof(store), &recvBuf);
if (ret != WS_SCP_CONTINUE)
result = -1557;
}
if (result == 0) {
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_FILE_DONE, NULL, "fit",
0644, 0, 0, (word32)sizeof(store), NULL, 0,
(word32)sizeof(store), &recvBuf);
if (ret != WS_SCP_CONTINUE)
result = -1558;
}
/* one byte over in one part: abort */
if (result == 0) {
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_NEW_FILE, NULL, "fit", 0644,
0, 0, (word32)sizeof(store), NULL, 0, 0, &recvBuf);
if (ret == WS_SCP_CONTINUE)
ret = wsScpRecvCallback(ssh, WOLFSSH_SCP_FILE_PART, NULL, "fit",
0644, 0, 0, (word32)sizeof(store), in,
(word32)sizeof(store) + 1, 0, &recvBuf);
if (ret != WS_SCP_ABORT || recvBuf.fileSz != 0)
result = -1559;
}
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* WOLFSSH_SCP && !WOLFSSH_SCP_USER_CALLBACKS && NO_FILESYSTEM */
/* ParseECCPubKey() Unit Test */
#ifndef WOLFSSH_NO_ECDSA_SHA2_NISTP256
/* The payload of keys/gretel-key-ecc.pub:
* string "ecdsa-sha2-nistp256" | string "nistp256" | string Q
* ParseECCPubKey() must reject blobs whose algorithm name or curve name
* does not match the negotiated host key algorithm. A MitM must not be
* able to choose a different curve by lying in the blob. */
static const byte eccPubKeyBlob[] = {
0x00, 0x00, 0x00, 0x13, 0x65, 0x63, 0x64, 0x73, 0x61, 0x2D, 0x73, 0x68,
0x61, 0x32, 0x2D, 0x6E, 0x69, 0x73, 0x74, 0x70, 0x32, 0x35, 0x36, 0x00,
0x00, 0x00, 0x08, 0x6E, 0x69, 0x73, 0x74, 0x70, 0x32, 0x35, 0x36, 0x00,
0x00, 0x00, 0x41, 0x04, 0xA0, 0x2D, 0x1F, 0xC7, 0x2A, 0x68, 0x36, 0xED,
0x24, 0x58, 0xED, 0xBE, 0x22, 0xE8, 0x6C, 0x70, 0x66, 0x8C, 0x2B, 0x46,
0xE7, 0xA0, 0xCC, 0x90, 0xFE, 0x80, 0xE0, 0xCD, 0x87, 0xF7, 0x35, 0xF6,
0xFD, 0x80, 0xA0, 0xD6, 0x1F, 0x5B, 0x61, 0x2E, 0xD6, 0x1D, 0xDF, 0x54,
0x40, 0x3C, 0x17, 0x3B, 0x51, 0xE1, 0x21, 0x9C, 0xD1, 0x61, 0xE7, 0x17,
0x87, 0xB4, 0x86, 0xF4, 0xFE, 0x06, 0x85, 0x16,
};
/* Offsets of interest in eccPubKeyBlob. */
#define ECC_BLOB_ALGO_DIGITS 20 /* the "256" in "ecdsa-sha2-nistp256" */
#define ECC_BLOB_CURVE_DIGITS 32 /* the "256" in "nistp256" */
#define ECC_BLOB_POINT 39 /* leading byte (0x04) of Q */
#define ECC_BLOB_TRUNC_SZ 30 /* cuts the blob mid curve name */
static const byte eccBadPointFormat[] = { 0x05 };
typedef struct {
const char* name;
word32 patchIdx;
const byte* patch;
word32 patchSz; /* 0 = no patch */
word32 blobSz;
byte pubKeyId; /* negotiated host key algorithm */
int expected;
} ParseECCPubKeyTestVector;
static const ParseECCPubKeyTestVector parseECCPubKeyTestVectors[] = {
{ "valid nistp256 blob", 0, NULL, 0, sizeof(eccPubKeyBlob),
ID_ECDSA_SHA2_NISTP256, WS_SUCCESS },
{ "algo name mismatch", ECC_BLOB_ALGO_DIGITS, (const byte*)"384", 3,
sizeof(eccPubKeyBlob), ID_ECDSA_SHA2_NISTP256, WS_INVALID_ALGO_ID },
#ifndef WOLFSSH_NO_ECDSA_SHA2_NISTP384
{ "blob downgrades negotiated nistp384", 0, NULL, 0,
sizeof(eccPubKeyBlob), ID_ECDSA_SHA2_NISTP384, WS_INVALID_ALGO_ID },
#endif
{ "curve name mismatch", ECC_BLOB_CURVE_DIGITS, (const byte*)"384", 3,
sizeof(eccPubKeyBlob), ID_ECDSA_SHA2_NISTP256,
WS_INVALID_PRIME_CURVE },
{ "corrupt point format", ECC_BLOB_POINT, eccBadPointFormat, 1,
sizeof(eccPubKeyBlob), ID_ECDSA_SHA2_NISTP256, WS_ECC_E },
{ "truncated blob", 0, NULL, 0, ECC_BLOB_TRUNC_SZ,
ID_ECDSA_SHA2_NISTP256, WS_BUFFER_E },
};
static int test_ParseECCPubKey(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
const ParseECCPubKeyTestVector* tv;
int tc = (int)(sizeof(parseECCPubKeyTestVectors)
/ sizeof(parseECCPubKeyTestVectors[0]));
int i;
int ret;
int failures = 0;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return 1;
ssh = wolfSSH_new(ctx);
if (ssh == NULL || ssh->handshake == NULL) {
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return 1;
}
for (i = 0, tv = parseECCPubKeyTestVectors; i < tc; i++, tv++) {
byte blob[sizeof(eccPubKeyBlob)];
WMEMCPY(blob, eccPubKeyBlob, sizeof(eccPubKeyBlob));
if (tv->patchSz > 0)
WMEMCPY(blob + tv->patchIdx, tv->patch, tv->patchSz);
ssh->handshake->pubKeyId = tv->pubKeyId;
ret = wolfSSH_TestParseECCPubKey(ssh, blob, tv->blobSz);
if (ret != tv->expected) {
fprintf(stderr, "\t[%d] \"%s\" FAIL: got %d, expected %d\n",
i, tv->name, ret, tv->expected);
failures++;
}
}
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return failures;
}
#if defined(WOLFSSH_CERTS) && !defined(NO_FILESYSTEM)
/* Big-endian word32 store; c32toa is WOLFSSH_LOCAL and not linkable here. */
static void certChainPut32(word32 v, byte* c)
{
c[0] = (byte)((v >> 24) & 0xFF);
c[1] = (byte)((v >> 16) & 0xFF);
c[2] = (byte)((v >> 8) & 0xFF);
c[3] = (byte)( v & 0xFF);
}
/* ParseECCPubKeyCert() Unit Test: the certificate host-key sibling of
* test_ParseECCPubKey(). Feeds an RFC 6187 chain blob wrapping
* keys/server-cert.der (a P-256 leaf chaining to keys/ca-cert-ecc.der) and
* checks the curve binding: the P-256 certificate must be accepted for
* x509v3-ecdsa-sha2-nistp256 and rejected with WS_INVALID_PRIME_CURVE for a
* negotiated x509v3-ecdsa-sha2-nistp384, and an id wcPrimeForId() cannot
* map must be rejected up front with WS_INVALID_PRIME_CURVE, matching
* ParseECCPubKey() (checked first: it needs no chain verification).
* Skipped (returns 1) when the key files are not readable or, in an FPKI
* build, when the FPKI profile rejects the test leaf. */
static int test_ParseECCPubKeyCert(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
byte* ca = NULL;
byte* cert = NULL;
byte* blob = NULL;
word32 caSz = 0, certSz = 0, blobSz = 0, idx;
int result = 0;
int ret;
static const char algoName[] = "x509v3-ecdsa-sha2-nistp256";
if (certmanLoadFile("./keys/ca-cert-ecc.der", &ca, &caSz) != 0 ||
certmanLoadFile("./keys/server-cert.der", &cert, &certSz)
!= 0) {
printf("ParseECCPubKeyCert: SKIP, ./keys certs not readable\n");
free(ca);
free(cert);
return 1;
}
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
result = -1;
if (result == 0 && wolfSSH_CTX_AddRootCert_buffer(ctx, ca, caSz,
WOLFSSH_FORMAT_ASN1) != WS_SUCCESS)
result = -2;
if (result == 0) {
ssh = wolfSSH_new(ctx);
if (ssh == NULL || ssh->handshake == NULL)
result = -3;
}
/* string name | uint32 cert count | string cert | uint32 ocsp count */
if (result == 0) {
blobSz = LENGTH_SZ + (word32)WSTRLEN(algoName)
+ UINT32_SZ + LENGTH_SZ + certSz + UINT32_SZ;
blob = (byte*)WMALLOC(blobSz, NULL, DYNTYPE_BUFFER);
if (blob == NULL)
result = -4;
}
if (result == 0) {
idx = 0;
certChainPut32((word32)WSTRLEN(algoName), blob + idx);
idx += LENGTH_SZ;
WMEMCPY(blob + idx, algoName, WSTRLEN(algoName));
idx += (word32)WSTRLEN(algoName);
certChainPut32(1, blob + idx);
idx += UINT32_SZ;
certChainPut32(certSz, blob + idx);
idx += LENGTH_SZ;
WMEMCPY(blob + idx, cert, certSz);
idx += certSz;
certChainPut32(0, blob + idx);
}
/* an id with no curve mapping is rejected before the parse, so this
* works even in builds whose cert profile rejects the test chain */
if (result == 0) {
ssh->handshake->pubKeyId = ID_SSH_RSA;
ret = wolfSSH_TestParseECCPubKeyCert(ssh, blob, blobSz);
if (ret != WS_INVALID_PRIME_CURVE) {
printf("ParseECCPubKeyCert: unmapped id ret %d\n", ret);
result = -7;
}
}
/* matching curve accepted. The only tolerated failure is the FPKI
* profile rejecting keys/server-cert.der, which carries none of the
* FPKI extensions; anything else is a parser or verification
* regression and fails the test */
if (result == 0) {
ssh->handshake->pubKeyId = ID_X509V3_ECDSA_SHA2_NISTP256;
ret = wolfSSH_TestParseECCPubKeyCert(ssh, blob, blobSz);
#ifndef WOLFSSH_NO_FPKI
if (ret == WS_CERT_PROFILE_E) {
printf("ParseECCPubKeyCert: SKIP, test cert does not meet the "
"FPKI profile\n");
result = 1;
}
else
#endif
if (ret != WS_SUCCESS) {
printf("ParseECCPubKeyCert: control chain ret %d\n", ret);
result = -5;
}
}
#ifndef WOLFSSH_NO_ECDSA_SHA2_NISTP384
/* P-256 leaf offered for a negotiated P-384 algorithm is rejected */
if (result == 0) {
ssh->handshake->pubKeyId = ID_X509V3_ECDSA_SHA2_NISTP384;
ret = wolfSSH_TestParseECCPubKeyCert(ssh, blob, blobSz);
if (ret != WS_INVALID_PRIME_CURVE) {
printf("ParseECCPubKeyCert: curve mismatch ret %d\n", ret);
result = -6;
}
}
#endif
if (blob != NULL)
WFREE(blob, NULL, DYNTYPE_BUFFER);
/* cert and ca come from certmanLoadFile()'s malloc */
free(cert);
free(ca);
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* Write r or s as an SSH mpint (RFC 4251 Section 5): a set high bit gets
* a leading zero so the value stays positive. Returns the size written. */
static word32 eccCertSigMpint(byte* out, const byte* v, word32 vSz)
{
word32 pad = (vSz > 0 && (v[0] & 0x80)) ? 1 : 0;
certChainPut32(vSz + pad, out);
if (pad)
out[LENGTH_SZ] = 0;
WMEMCPY(out + LENGTH_SZ + pad, v, vSz);
return LENGTH_SZ + pad + vSz;
}
/* Build an x509v3-ecdsa USERAUTH signature blob, string name || string
* (mpint r || mpint s), into out. Returns its size. */
static word32 eccCertSigBlob(byte* out, const char* name, const byte* r,
word32 rSz, const byte* s, word32 sSz)
{
word32 nameSz = (word32)WSTRLEN(name);
word32 idx = 0;
word32 lenIdx;
certChainPut32(nameSz, out + idx);
idx += LENGTH_SZ;
WMEMCPY(out + idx, name, nameSz);
idx += nameSz;
lenIdx = idx;
idx += LENGTH_SZ;
idx += eccCertSigMpint(out + idx, r, rSz);
idx += eccCertSigMpint(out + idx, s, sSz);
certChainPut32(idx - lenIdx - LENGTH_SZ, out + lenIdx);
return idx;
}
/* DoUserAuthRequestEccCert() Unit Test: signs a digest with keys/fred-key.der
* and checks the signature's algorithm name against the declared
* x509v3-ecdsa-sha2-nistp256 (keys/fred-cert.der is P-256). The declared name
* and RFC 6187's ecdsa-sha2-nistp256 are accepted; any other name is
* WS_INVALID_ALGO_ID. Argument errors keep their own code. Returns 1 to skip
* when the key files are not readable. */
static int test_DoUserAuthRequestEccCert(void)
{
static const struct {
const char* name;
int expected;
} names[] = {
{ "x509v3-ecdsa-sha2-nistp256", WS_SUCCESS },
{ "ecdsa-sha2-nistp256", WS_SUCCESS },
{ "ecdsa-sha2-nistp384", WS_INVALID_ALGO_ID },
{ "x509v3-ecdsa-sha2-nistp384", WS_INVALID_ALGO_ID },
{ "ssh-rsa", WS_INVALID_ALGO_ID },
{ "", WS_INVALID_ALGO_ID },
};
static const char algoName[] = "x509v3-ecdsa-sha2-nistp256";
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
byte* cert = NULL;
byte* keyDer = NULL;
word32 certSz = 0, keyDerSz = 0, idx = 0;
ecc_key key;
WC_RNG rng;
int keyInit = 0, rngInit = 0;
byte digest[WC_SHA256_DIGEST_SIZE];
byte der[ECC_MAX_SIG_SIZE];
word32 derSz = (word32)sizeof(der);
byte r[MAX_ECC_BYTES], s[MAX_ECC_BYTES];
word32 rSz = (word32)sizeof(r), sSz = (word32)sizeof(s);
byte sigBlob[64 + ECC_MAX_SIG_SIZE];
WS_UserAuthData_PublicKey pk;
int result = 0;
int ret;
word32 i;
if (certmanLoadFile("./keys/fred-cert.der", &cert, &certSz) != 0 ||
certmanLoadFile("./keys/fred-key.der", &keyDer, &keyDerSz)
!= 0) {
printf("DoUserAuthRequestEccCert: SKIP, ./keys not readable\n");
free(cert);
free(keyDer);
return 1;
}
WMEMSET(digest, 0x5A, sizeof(digest));
if (wc_InitRng(&rng) != 0)
result = -1;
else
rngInit = 1;
if (result == 0) {
if (wc_ecc_init(&key) != 0)
result = -2;
else
keyInit = 1;
}
if (result == 0 && wc_EccPrivateKeyDecode(keyDer, &idx, &key,
keyDerSz) != 0)
result = -3;
if (result == 0 && wc_ecc_sign_hash(digest, sizeof(digest), der, &derSz,
&rng, &key) != 0)
result = -4;
if (result == 0 && wc_ecc_sig_to_rs(der, derSz, r, &rSz, s, &sSz) != 0)
result = -5;
if (result == 0) {
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx != NULL)
ssh = wolfSSH_new(ctx);
if (ssh == NULL)
result = -6;
}
WMEMSET(&pk, 0, sizeof(pk));
pk.publicKeyType = (const byte*)algoName;
pk.publicKeyTypeSz = (word32)WSTRLEN(algoName);
pk.publicKey = cert;
pk.publicKeySz = certSz;
pk.hasSignature = 1;
pk.signature = sigBlob;
for (i = 0; ssh != NULL && i < sizeof(names) / sizeof(names[0]); i++) {
pk.signatureSz = eccCertSigBlob(sigBlob, names[i].name,
r, rSz, s, sSz);
ret = wolfSSH_TestDoUserAuthRequestEccCert(ssh, &pk,
WC_HASH_TYPE_SHA256, digest, (word32)sizeof(digest));
if (ret != names[i].expected) {
printf("DoUserAuthRequestEccCert: sig name \"%s\" ret %d, "
"expected %d\n", names[i].name, ret, names[i].expected);
result = -7;
}
}
/* a signature over another digest fails the verify */
if (result == 0) {
pk.signatureSz = eccCertSigBlob(sigBlob, algoName, r, rSz, s, sSz);
digest[0] ^= 0x01;
ret = wolfSSH_TestDoUserAuthRequestEccCert(ssh, &pk,
WC_HASH_TYPE_SHA256, digest, (word32)sizeof(digest));
digest[0] ^= 0x01;
if (ret != WS_ECC_E) {
printf("DoUserAuthRequestEccCert: wrong digest ret %d\n", ret);
result = -8;
}
}
/* an argument error is not reported as a key decode failure */
if (result == 0) {
ret = wolfSSH_TestDoUserAuthRequestEccCert(ssh, &pk,
WC_HASH_TYPE_SHA256, digest, 0);
if (ret != WS_BAD_ARGUMENT) {
printf("DoUserAuthRequestEccCert: digestSz 0 ret %d\n", ret);
result = -9;
}
}
/* a certificate that does not parse is a key decode failure */
if (result == 0) {
pk.publicKeySz = 16;
ret = wolfSSH_TestDoUserAuthRequestEccCert(ssh, &pk,
WC_HASH_TYPE_SHA256, digest, (word32)sizeof(digest));
pk.publicKeySz = certSz;
if (ret != WS_CRYPTO_FAILED) {
printf("DoUserAuthRequestEccCert: bad cert ret %d\n", ret);
result = -10;
}
}
if (keyInit)
wc_ecc_free(&key);
if (rngInit)
wc_FreeRng(&rng);
/* cert and keyDer come from certmanLoadFile()'s malloc */
free(cert);
free(keyDer);
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* WOLFSSH_CERTS && !NO_FILESYSTEM */
#endif /* !WOLFSSH_NO_ECDSA_SHA2_NISTP256 */
/* DoUserAuthRequestRsa() Unit Test */
#if !defined(WOLFSSH_NO_RSA) && !defined(WOLFSSH_NO_SSH_RSA_SHA1)
/* RFC 4253 Section 6.6: the RSA signature blob is a string of raw
* signature bytes, not an mpint. The fixed signature below was made
* with keys/hansel-key-rsa.pem over the message
* "wolfSSH unit test message 1" (SHA-1, PKCS#1 v1.5) and its first
* byte (0xB7) has the high bit set. An mpint parse would reject it
* as negative, so this pins the string parse. */
/* string "ssh-rsa" | mpint e | mpint n, from keys/hansel-key-rsa.pem */
static const byte userAuthRsaPubKeyBlob[] = {
0x00, 0x00, 0x00, 0x07, 0x73, 0x73, 0x68, 0x2D, 0x72, 0x73, 0x61, 0x00,
0x00, 0x00, 0x03, 0x01, 0x00, 0x01, 0x00, 0x00, 0x01, 0x01, 0x00, 0xBD,
0x3F, 0x76, 0x45, 0xA3, 0x03, 0xAC, 0x38, 0xD5, 0xC7, 0x0F, 0x93, 0x30,
0x5A, 0x20, 0x9C, 0x89, 0x7C, 0xAD, 0x05, 0x16, 0x46, 0x86, 0x83, 0x0D,
0x8A, 0x2B, 0x16, 0x4A, 0x05, 0x2C, 0xE4, 0x77, 0x47, 0x70, 0x00, 0xAE,
0x1D, 0x83, 0xE2, 0xD9, 0x6E, 0x99, 0xD4, 0xF0, 0x45, 0x98, 0x15, 0x93,
0xF6, 0x87, 0x4E, 0xAC, 0x64, 0x63, 0xA1, 0x95, 0xC9, 0x7C, 0x30, 0xE8,
0x3E, 0x2F, 0xA3, 0xF1, 0x24, 0x9F, 0x0C, 0x6B, 0x1C, 0xFE, 0x1B, 0x02,
0x99, 0xCD, 0xC6, 0xA7, 0x6C, 0x84, 0x85, 0x46, 0x54, 0x12, 0x40, 0xE1,
0xB4, 0xE5, 0xF2, 0xAA, 0x39, 0xEC, 0xD6, 0x27, 0x24, 0x0B, 0xD1, 0xA1,
0xE2, 0xEF, 0x34, 0x69, 0x25, 0x6D, 0xC0, 0x74, 0x67, 0x25, 0x98, 0x7D,
0xC4, 0xF8, 0x52, 0xAB, 0x9B, 0x4B, 0x3A, 0x12, 0x1D, 0xE1, 0xE3, 0xFA,
0xD6, 0xCF, 0x9A, 0xE6, 0x9C, 0x23, 0x4E, 0x39, 0xC4, 0x84, 0x16, 0x88,
0x3D, 0x42, 0x4E, 0xD8, 0x2F, 0xCC, 0xD2, 0x91, 0x67, 0x9D, 0xB6, 0x71,
0x2A, 0x02, 0x65, 0x5F, 0xBB, 0x75, 0x0E, 0x8C, 0xBB, 0x87, 0x97, 0x97,
0xC6, 0xF8, 0xB2, 0x98, 0xE2, 0x2F, 0x68, 0x26, 0x4A, 0x53, 0xEC, 0x79,
0x3A, 0x8A, 0x5F, 0xCC, 0xCF, 0xF0, 0x16, 0x47, 0xB2, 0xD0, 0x43, 0xD6,
0x36, 0x6C, 0xC8, 0xE7, 0x2F, 0xFE, 0xA7, 0x35, 0x39, 0x69, 0xFB, 0x1D,
0x78, 0x45, 0x9D, 0x89, 0x00, 0xC8, 0x41, 0xCF, 0x34, 0x1F, 0xA3, 0xF3,
0xF1, 0xFB, 0x28, 0x14, 0xFB, 0xD8, 0x48, 0x6F, 0xAC, 0xE3, 0xFC, 0x33,
0xD1, 0xDB, 0xAE, 0xEF, 0x27, 0x9E, 0x57, 0x56, 0x29, 0xA2, 0x1A, 0x3A,
0xE5, 0x9A, 0xFE, 0xA4, 0x49, 0xC8, 0x7F, 0xB7, 0x4E, 0xD0, 0x1F, 0x04,
0x6E, 0x58, 0x16, 0xB7, 0xEB, 0x9D, 0xF8, 0x92, 0x3C, 0xC2, 0xB0, 0x21,
0x7C, 0x4E, 0x31,
};
/* SHA-1 of "wolfSSH unit test message 1" */
static const byte userAuthRsaDigest[] = {
0x2A, 0x43, 0xF5, 0x19, 0x09, 0xEE, 0x2D, 0x85, 0x89, 0xD3, 0xE0, 0xCE,
0xF8, 0xA6, 0x8A, 0xC4, 0xD3, 0x33, 0xB3, 0x30,
};
/* string "ssh-rsa" | string signature */
static const byte userAuthRsaSigBlob[] = {
0x00, 0x00, 0x00, 0x07, 0x73, 0x73, 0x68, 0x2D, 0x72, 0x73, 0x61, 0x00,
0x00, 0x01, 0x00, 0xB7, 0xFD, 0xC3, 0x7B, 0x4A, 0xAD, 0x4B, 0x04, 0x28,
0xD0, 0xAA, 0x41, 0x59, 0x4D, 0xFB, 0x37, 0xBD, 0x2F, 0xA4, 0x93, 0x63,
0x4D, 0x10, 0xCF, 0x95, 0x59, 0x4C, 0x37, 0xBE, 0x71, 0xF1, 0x3D, 0xF5,
0x8A, 0x72, 0x92, 0x22, 0xE3, 0x0F, 0xE9, 0xAE, 0x12, 0xA9, 0xD3, 0xC8,
0x6A, 0x78, 0x66, 0x65, 0x4C, 0xDB, 0xA0, 0xB2, 0x8B, 0x19, 0x0F, 0x05,
0xC4, 0x05, 0x69, 0x54, 0x13, 0x34, 0x17, 0xB2, 0xEE, 0x77, 0x41, 0x9B,
0x17, 0xD6, 0x52, 0xA7, 0x1C, 0x81, 0x84, 0xED, 0x60, 0x3D, 0x52, 0xEF,
0x57, 0xCD, 0xE8, 0x9D, 0x51, 0xCB, 0x38, 0xC8, 0xB2, 0x8E, 0x74, 0x2F,
0xFD, 0x32, 0xCB, 0x0D, 0x8B, 0xFB, 0x7B, 0xCC, 0x35, 0xFF, 0x75, 0x10,
0x89, 0x0A, 0x1E, 0xA8, 0x37, 0xC9, 0x39, 0xED, 0x9F, 0xDA, 0x5D, 0xC5,
0x38, 0xEA, 0xC3, 0xBA, 0x58, 0x89, 0x5A, 0xA0, 0x84, 0x4D, 0x5F, 0x73,
0xF9, 0x5A, 0xC8, 0xD2, 0xEA, 0xB5, 0x6D, 0x3D, 0xC0, 0x12, 0xA7, 0x79,
0x30, 0x16, 0xE3, 0x2F, 0xBC, 0xAB, 0x12, 0xA8, 0xA1, 0xAB, 0x4B, 0xB3,
0x07, 0xF1, 0xDA, 0x1E, 0x3E, 0x5F, 0x02, 0x4B, 0x73, 0x22, 0x26, 0xC5,
0x51, 0xFB, 0xD1, 0x81, 0x53, 0x3B, 0xBA, 0x5E, 0x36, 0x2A, 0xBF, 0xC2,
0xB2, 0x9A, 0x0C, 0x8C, 0xB2, 0xCB, 0x6B, 0x9F, 0x30, 0xC8, 0x63, 0xA5,
0x72, 0xAF, 0x1D, 0x96, 0xE7, 0xB6, 0x17, 0xC4, 0xEB, 0x5F, 0xFD, 0xA4,
0xFB, 0xF8, 0xE4, 0x69, 0xE4, 0xA3, 0x47, 0x59, 0x2D, 0x8F, 0x4F, 0xB3,
0xD2, 0xAA, 0xD2, 0xF3, 0xCA, 0x42, 0xD5, 0xF7, 0x25, 0x5B, 0xCD, 0x60,
0x17, 0xA2, 0x0C, 0xE0, 0xF4, 0xEE, 0xE0, 0xF6, 0xED, 0x41, 0xC9, 0x00,
0x1B, 0x5A, 0x24, 0xD4, 0x18, 0xBA, 0xAC, 0x40, 0xBD, 0x7F, 0xFD, 0x46,
0x2F, 0xC5, 0x19, 0xF9, 0xE6, 0x2F, 0x16,
};
/* Offsets of interest in userAuthRsaSigBlob. */
#define RSA_SIG_BLOB_ALGO 4 /* "ssh-rsa" */
#define RSA_SIG_BLOB_LEN 11 /* length of the signature string */
#define RSA_SIG_BLOB_SIG 15 /* first byte of the raw signature */
/* 257: one past the actual signature size */
static const byte userAuthRsaSigLenOverrun[] = { 0x00, 0x00, 0x01, 0x01 };
/* Offsets of interest in userAuthRsaPubKeyBlob. */
#define RSA_PUB_BLOB_ALGO 4 /* "ssh-rsa" */
#define RSA_PUB_BLOB_NLEN 18 /* length of the modulus mpint */
#define RSA_PUB_BLOB_N 23 /* first byte of the modulus, past the pad */
/* 129: the mpint pad byte plus a 1024 bit modulus */
static const byte userAuthRsaPubKeyNLen1024[] = { 0x00, 0x00, 0x00, 0x81 };
/* Clears the modulus' top bit, leaving 2047 bits in 256 bytes. */
static const byte userAuthRsaPubKeyMsb2047[] = { 0x7F };
typedef struct {
const char* name;
word32 patchIdx;
const byte* patch;
word32 patchSz; /* 0 = no patch */
word32 flipIdx; /* XOR 0x01 into this index; 0 = none */
word32 pubPatchIdx;
const byte* pubPatch;
word32 pubPatchSz; /* 0 = no patch */
int expected;
} UserAuthRsaTestVector;
static const UserAuthRsaTestVector userAuthRsaTestVectors[] = {
{ "high bit signature accepted", 0, NULL, 0, 0, 0, NULL, 0, WS_SUCCESS },
{ "corrupt signature rejected", 0, NULL, 0, RSA_SIG_BLOB_SIG + 128,
0, NULL, 0, WS_RSA_E },
{ "signature length overrun", RSA_SIG_BLOB_LEN, userAuthRsaSigLenOverrun,
4, 0, 0, NULL, 0, WS_BUFFER_E },
{ "signature algo name mismatch", RSA_SIG_BLOB_ALGO,
(const byte*)"ssh-dss", 7, 0, 0, NULL, 0, WS_INVALID_ALGO_ID },
{ "1024 bit key rejected", 0, NULL, 0, 0,
RSA_PUB_BLOB_NLEN, userAuthRsaPubKeyNLen1024, 4, WS_CERT_KEY_SIZE_E },
{ "2047 bit key rejected", 0, NULL, 0, 0,
RSA_PUB_BLOB_N, userAuthRsaPubKeyMsb2047, 1, WS_CERT_KEY_SIZE_E },
};
static int test_DoUserAuthRequestRsa(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
const UserAuthRsaTestVector* tv;
int tc = (int)(sizeof(userAuthRsaTestVectors)
/ sizeof(userAuthRsaTestVectors[0]));
int i;
int ret;
int failures = 0;
/* The point of the test is a signature whose leading byte has the
* high bit set. Guard against the vector being regenerated without
* that property. */
if ((userAuthRsaSigBlob[RSA_SIG_BLOB_SIG] & 0x80) == 0) {
fprintf(stderr, "\tuserAuthRsaSigBlob needs its high bit set\n");
return 1;
}
/* The key size vectors patch the modulus in place, so the offsets have
* to still point at a 257 byte mpint holding a 2048 bit modulus. */
if (userAuthRsaPubKeyBlob[RSA_PUB_BLOB_NLEN + 2] != 0x01
|| userAuthRsaPubKeyBlob[RSA_PUB_BLOB_NLEN + 3] != 0x01
|| (userAuthRsaPubKeyBlob[RSA_PUB_BLOB_N] & 0x80) == 0) {
fprintf(stderr, "\tuserAuthRsaPubKeyBlob offsets are stale\n");
return 1;
}
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return 1;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return 1;
}
for (i = 0, tv = userAuthRsaTestVectors; i < tc; i++, tv++) {
byte sigBlob[sizeof(userAuthRsaSigBlob)];
byte pubBlob[sizeof(userAuthRsaPubKeyBlob)];
byte digest[sizeof(userAuthRsaDigest)];
WS_UserAuthData_PublicKey pk;
WMEMCPY(sigBlob, userAuthRsaSigBlob, sizeof(sigBlob));
WMEMCPY(pubBlob, userAuthRsaPubKeyBlob, sizeof(pubBlob));
WMEMCPY(digest, userAuthRsaDigest, sizeof(digest));
if (tv->patchSz > 0)
WMEMCPY(sigBlob + tv->patchIdx, tv->patch, tv->patchSz);
if (tv->flipIdx > 0)
sigBlob[tv->flipIdx] ^= 0x01;
if (tv->pubPatchSz > 0)
WMEMCPY(pubBlob + tv->pubPatchIdx, tv->pubPatch, tv->pubPatchSz);
WMEMSET(&pk, 0, sizeof(pk));
pk.publicKeyType = (const byte*)"ssh-rsa";
pk.publicKeyTypeSz = 7;
pk.publicKey = pubBlob;
pk.publicKeySz = (word32)sizeof(pubBlob);
pk.hasSignature = 1;
pk.signature = sigBlob;
pk.signatureSz = (word32)sizeof(sigBlob);
ret = wolfSSH_TestDoUserAuthRequestRsa(ssh, &pk, WC_HASH_TYPE_SHA,
digest, (word32)sizeof(digest));
if (ret != tv->expected) {
fprintf(stderr, "\t[%d] \"%s\" FAIL: got %d, expected %d\n",
i, tv->name, ret, tv->expected);
failures++;
}
}
/* A hash wc_EncodeSignature() cannot encode is a crypto failure, not a
* bad signature. */
{
byte sigBlob[sizeof(userAuthRsaSigBlob)];
byte pubBlob[sizeof(userAuthRsaPubKeyBlob)];
byte digest[sizeof(userAuthRsaDigest)];
WS_UserAuthData_PublicKey pk;
WMEMCPY(sigBlob, userAuthRsaSigBlob, sizeof(sigBlob));
WMEMCPY(pubBlob, userAuthRsaPubKeyBlob, sizeof(pubBlob));
WMEMCPY(digest, userAuthRsaDigest, sizeof(digest));
WMEMSET(&pk, 0, sizeof(pk));
pk.publicKeyType = (const byte*)"ssh-rsa";
pk.publicKeyTypeSz = 7;
pk.publicKey = pubBlob;
pk.publicKeySz = (word32)sizeof(pubBlob);
pk.hasSignature = 1;
pk.signature = sigBlob;
pk.signatureSz = (word32)sizeof(sigBlob);
ret = wolfSSH_TestDoUserAuthRequestRsa(ssh, &pk, WC_HASH_TYPE_NONE,
digest, (word32)sizeof(digest));
if (ret != WS_CRYPTO_FAILED) {
fprintf(stderr, "\t\"unencodable hash\" FAIL: got %d, "
"expected %d\n", ret, WS_CRYPTO_FAILED);
failures++;
}
}
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return failures;
}
static int test_ParseRSAPubKey(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
byte blob[sizeof(userAuthRsaPubKeyBlob)];
int ret;
int failures = 0;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return 1;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return 1;
}
WMEMCPY(blob, userAuthRsaPubKeyBlob, sizeof(blob));
/* valid blob */
ret = wolfSSH_TestParseRSAPubKey(ssh, blob, (word32)sizeof(blob));
if (ret != WS_SUCCESS) {
fprintf(stderr, "\t\"valid\" FAIL: got %d, expected %d\n",
ret, WS_SUCCESS);
failures++;
}
/* truncated blob: fails after the key is initialized */
ret = wolfSSH_TestParseRSAPubKey(ssh, blob, (word32)(sizeof(blob) / 2));
if (ret != WS_BUFFER_E) {
fprintf(stderr, "\t\"truncated\" FAIL: got %d, expected %d\n",
ret, WS_BUFFER_E);
failures++;
}
/* host key under WOLFSSH_RSA_MIN_KEY_BITS */
WMEMCPY(blob + RSA_PUB_BLOB_NLEN, userAuthRsaPubKeyNLen1024,
sizeof(userAuthRsaPubKeyNLen1024));
ret = wolfSSH_TestParseRSAPubKey(ssh, blob, (word32)sizeof(blob));
if (ret != WS_CERT_KEY_SIZE_E) {
fprintf(stderr, "\t\"1024 bit\" FAIL: got %d, expected %d\n",
ret, WS_CERT_KEY_SIZE_E);
failures++;
}
WMEMCPY(blob, userAuthRsaPubKeyBlob, sizeof(blob));
WMEMCPY(blob + RSA_PUB_BLOB_N, userAuthRsaPubKeyMsb2047,
sizeof(userAuthRsaPubKeyMsb2047));
ret = wolfSSH_TestParseRSAPubKey(ssh, blob, (word32)sizeof(blob));
if (ret != WS_CERT_KEY_SIZE_E) {
fprintf(stderr, "\t\"2047 bit\" FAIL: got %d, expected %d\n",
ret, WS_CERT_KEY_SIZE_E);
failures++;
}
/* format identifier other than "ssh-rsa" */
WMEMCPY(blob, userAuthRsaPubKeyBlob, sizeof(blob));
WMEMCPY(blob + RSA_PUB_BLOB_ALGO, "ssh-dss", 7);
ret = wolfSSH_TestParseRSAPubKey(ssh, blob, (word32)sizeof(blob));
if (ret != WS_INVALID_ALGO_ID) {
fprintf(stderr, "\t\"format mismatch\" FAIL: got %d, expected %d\n",
ret, WS_INVALID_ALGO_ID);
failures++;
}
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return failures;
}
#ifdef WOLFSSH_CERTS
/* DoUserAuthRequestRsaCert() parses the signature blob the same way as
* DoUserAuthRequestRsa(), but takes the public key from an X.509
* certificate. This is a self-signed certificate made from
* keys/hansel-key-rsa.pem, the same key as the vectors above, so the
* digest and signature blob are reused. */
static const byte userAuthRsaCertDer[] = {
0x30, 0x82, 0x03, 0xFB, 0x30, 0x82, 0x02, 0xE3, 0xA0, 0x03, 0x02, 0x01,
0x02, 0x02, 0x14, 0x1C, 0x71, 0x06, 0xEC, 0x89, 0xF3, 0x37, 0x6F, 0xE7,
0xBB, 0x3C, 0xE2, 0x74, 0x54, 0x43, 0x1F, 0x75, 0x0A, 0xED, 0xD5, 0x30,
0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0B,
0x05, 0x00, 0x30, 0x81, 0x8C, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55,
0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03,
0x55, 0x04, 0x08, 0x0C, 0x02, 0x57, 0x41, 0x31, 0x10, 0x30, 0x0E, 0x06,
0x03, 0x55, 0x04, 0x07, 0x0C, 0x07, 0x53, 0x65, 0x61, 0x74, 0x74, 0x6C,
0x65, 0x31, 0x14, 0x30, 0x12, 0x06, 0x03, 0x55, 0x04, 0x0A, 0x0C, 0x0B,
0x77, 0x6F, 0x6C, 0x66, 0x53, 0x53, 0x4C, 0x20, 0x49, 0x6E, 0x63, 0x31,
0x14, 0x30, 0x12, 0x06, 0x03, 0x55, 0x04, 0x0B, 0x0C, 0x0B, 0x44, 0x65,
0x76, 0x65, 0x6C, 0x6F, 0x70, 0x6D, 0x65, 0x6E, 0x74, 0x31, 0x0F, 0x30,
0x0D, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0C, 0x06, 0x48, 0x61, 0x6E, 0x73,
0x65, 0x6C, 0x31, 0x21, 0x30, 0x1F, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86,
0xF7, 0x0D, 0x01, 0x09, 0x01, 0x16, 0x12, 0x68, 0x61, 0x6E, 0x73, 0x65,
0x6C, 0x40, 0x65, 0x78, 0x61, 0x6D, 0x70, 0x6C, 0x65, 0x2E, 0x63, 0x6F,
0x6D, 0x30, 0x1E, 0x17, 0x0D, 0x32, 0x36, 0x30, 0x36, 0x31, 0x32, 0x31,
0x37, 0x34, 0x35, 0x30, 0x39, 0x5A, 0x17, 0x0D, 0x34, 0x38, 0x30, 0x35,
0x30, 0x37, 0x31, 0x37, 0x34, 0x35, 0x30, 0x39, 0x5A, 0x30, 0x81, 0x8C,
0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55,
0x53, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0C, 0x02,
0x57, 0x41, 0x31, 0x10, 0x30, 0x0E, 0x06, 0x03, 0x55, 0x04, 0x07, 0x0C,
0x07, 0x53, 0x65, 0x61, 0x74, 0x74, 0x6C, 0x65, 0x31, 0x14, 0x30, 0x12,
0x06, 0x03, 0x55, 0x04, 0x0A, 0x0C, 0x0B, 0x77, 0x6F, 0x6C, 0x66, 0x53,
0x53, 0x4C, 0x20, 0x49, 0x6E, 0x63, 0x31, 0x14, 0x30, 0x12, 0x06, 0x03,
0x55, 0x04, 0x0B, 0x0C, 0x0B, 0x44, 0x65, 0x76, 0x65, 0x6C, 0x6F, 0x70,
0x6D, 0x65, 0x6E, 0x74, 0x31, 0x0F, 0x30, 0x0D, 0x06, 0x03, 0x55, 0x04,
0x03, 0x0C, 0x06, 0x48, 0x61, 0x6E, 0x73, 0x65, 0x6C, 0x31, 0x21, 0x30,
0x1F, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x01,
0x16, 0x12, 0x68, 0x61, 0x6E, 0x73, 0x65, 0x6C, 0x40, 0x65, 0x78, 0x61,
0x6D, 0x70, 0x6C, 0x65, 0x2E, 0x63, 0x6F, 0x6D, 0x30, 0x82, 0x01, 0x22,
0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01,
0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0F, 0x00, 0x30, 0x82, 0x01, 0x0A,
0x02, 0x82, 0x01, 0x01, 0x00, 0xBD, 0x3F, 0x76, 0x45, 0xA3, 0x03, 0xAC,
0x38, 0xD5, 0xC7, 0x0F, 0x93, 0x30, 0x5A, 0x20, 0x9C, 0x89, 0x7C, 0xAD,
0x05, 0x16, 0x46, 0x86, 0x83, 0x0D, 0x8A, 0x2B, 0x16, 0x4A, 0x05, 0x2C,
0xE4, 0x77, 0x47, 0x70, 0x00, 0xAE, 0x1D, 0x83, 0xE2, 0xD9, 0x6E, 0x99,
0xD4, 0xF0, 0x45, 0x98, 0x15, 0x93, 0xF6, 0x87, 0x4E, 0xAC, 0x64, 0x63,
0xA1, 0x95, 0xC9, 0x7C, 0x30, 0xE8, 0x3E, 0x2F, 0xA3, 0xF1, 0x24, 0x9F,
0x0C, 0x6B, 0x1C, 0xFE, 0x1B, 0x02, 0x99, 0xCD, 0xC6, 0xA7, 0x6C, 0x84,
0x85, 0x46, 0x54, 0x12, 0x40, 0xE1, 0xB4, 0xE5, 0xF2, 0xAA, 0x39, 0xEC,
0xD6, 0x27, 0x24, 0x0B, 0xD1, 0xA1, 0xE2, 0xEF, 0x34, 0x69, 0x25, 0x6D,
0xC0, 0x74, 0x67, 0x25, 0x98, 0x7D, 0xC4, 0xF8, 0x52, 0xAB, 0x9B, 0x4B,
0x3A, 0x12, 0x1D, 0xE1, 0xE3, 0xFA, 0xD6, 0xCF, 0x9A, 0xE6, 0x9C, 0x23,
0x4E, 0x39, 0xC4, 0x84, 0x16, 0x88, 0x3D, 0x42, 0x4E, 0xD8, 0x2F, 0xCC,
0xD2, 0x91, 0x67, 0x9D, 0xB6, 0x71, 0x2A, 0x02, 0x65, 0x5F, 0xBB, 0x75,
0x0E, 0x8C, 0xBB, 0x87, 0x97, 0x97, 0xC6, 0xF8, 0xB2, 0x98, 0xE2, 0x2F,
0x68, 0x26, 0x4A, 0x53, 0xEC, 0x79, 0x3A, 0x8A, 0x5F, 0xCC, 0xCF, 0xF0,
0x16, 0x47, 0xB2, 0xD0, 0x43, 0xD6, 0x36, 0x6C, 0xC8, 0xE7, 0x2F, 0xFE,
0xA7, 0x35, 0x39, 0x69, 0xFB, 0x1D, 0x78, 0x45, 0x9D, 0x89, 0x00, 0xC8,
0x41, 0xCF, 0x34, 0x1F, 0xA3, 0xF3, 0xF1, 0xFB, 0x28, 0x14, 0xFB, 0xD8,
0x48, 0x6F, 0xAC, 0xE3, 0xFC, 0x33, 0xD1, 0xDB, 0xAE, 0xEF, 0x27, 0x9E,
0x57, 0x56, 0x29, 0xA2, 0x1A, 0x3A, 0xE5, 0x9A, 0xFE, 0xA4, 0x49, 0xC8,
0x7F, 0xB7, 0x4E, 0xD0, 0x1F, 0x04, 0x6E, 0x58, 0x16, 0xB7, 0xEB, 0x9D,
0xF8, 0x92, 0x3C, 0xC2, 0xB0, 0x21, 0x7C, 0x4E, 0x31, 0x02, 0x03, 0x01,
0x00, 0x01, 0xA3, 0x53, 0x30, 0x51, 0x30, 0x1D, 0x06, 0x03, 0x55, 0x1D,
0x0E, 0x04, 0x16, 0x04, 0x14, 0x67, 0x59, 0x9C, 0xD7, 0x16, 0x3F, 0xE6,
0x98, 0x47, 0x4F, 0xAE, 0x62, 0x4F, 0xAE, 0x27, 0x3A, 0xE8, 0xF6, 0x40,
0xAE, 0x30, 0x1F, 0x06, 0x03, 0x55, 0x1D, 0x23, 0x04, 0x18, 0x30, 0x16,
0x80, 0x14, 0x67, 0x59, 0x9C, 0xD7, 0x16, 0x3F, 0xE6, 0x98, 0x47, 0x4F,
0xAE, 0x62, 0x4F, 0xAE, 0x27, 0x3A, 0xE8, 0xF6, 0x40, 0xAE, 0x30, 0x0F,
0x06, 0x03, 0x55, 0x1D, 0x13, 0x01, 0x01, 0xFF, 0x04, 0x05, 0x30, 0x03,
0x01, 0x01, 0xFF, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7,
0x0D, 0x01, 0x01, 0x0B, 0x05, 0x00, 0x03, 0x82, 0x01, 0x01, 0x00, 0x77,
0x70, 0xC5, 0x15, 0xFE, 0xF8, 0x2D, 0xCB, 0x5C, 0x18, 0x36, 0x87, 0xC9,
0x82, 0xFD, 0x6D, 0x3C, 0x78, 0xD8, 0xCF, 0xEB, 0x71, 0xFD, 0xEB, 0xD7,
0x05, 0x9A, 0xAE, 0xBE, 0xE1, 0x55, 0xCF, 0xE9, 0x04, 0xE3, 0xF1, 0xAE,
0x30, 0xDE, 0x19, 0xC3, 0x5E, 0x25, 0xDE, 0xB7, 0x39, 0x21, 0x57, 0x82,
0xD5, 0x98, 0xD6, 0x19, 0x49, 0x9D, 0x9F, 0xDE, 0x07, 0x9D, 0xEE, 0xB1,
0x24, 0xBD, 0x3E, 0xFD, 0xBA, 0x27, 0xA2, 0x9D, 0x0C, 0x08, 0x77, 0xA7,
0xB1, 0xFA, 0x6E, 0x36, 0xAA, 0xAE, 0x1F, 0xFA, 0xF6, 0xAE, 0x0A, 0x72,
0x48, 0x5C, 0x89, 0xD6, 0x4F, 0x10, 0x80, 0x3A, 0x2A, 0xA8, 0x6C, 0x00,
0x06, 0x41, 0x0B, 0xA6, 0xAA, 0x20, 0xE5, 0xEB, 0x38, 0xD4, 0xF7, 0x67,
0xCC, 0x40, 0x05, 0x61, 0xF9, 0x89, 0x8A, 0xF0, 0xCB, 0x03, 0xD9, 0x19,
0x8D, 0x63, 0x53, 0xB7, 0x2C, 0x53, 0x13, 0xA5, 0x3C, 0x5B, 0x5D, 0xDA,
0x20, 0x96, 0xDD, 0x7F, 0xF8, 0x63, 0x5A, 0x47, 0x59, 0x10, 0x48, 0xA7,
0x35, 0x84, 0xF2, 0x61, 0x4C, 0x3E, 0xAC, 0xE6, 0x06, 0x90, 0x96, 0x07,
0xA3, 0x7B, 0x2D, 0x36, 0xEF, 0x5D, 0xD0, 0x5C, 0x0A, 0x1C, 0x4D, 0xA2,
0x81, 0x18, 0xE3, 0x22, 0xFB, 0xBF, 0x9B, 0x12, 0x68, 0xAD, 0x6A, 0xCD,
0xF2, 0x72, 0xD3, 0xBA, 0x24, 0x63, 0xCC, 0x45, 0x47, 0xDE, 0x83, 0xD6,
0x8A, 0x94, 0xD2, 0xC1, 0xDC, 0xAB, 0xFD, 0x4E, 0xF0, 0x11, 0x21, 0xB9,
0x0F, 0xF3, 0xEE, 0x87, 0xF9, 0x03, 0x1A, 0xB4, 0x75, 0x21, 0x81, 0xDA,
0x2E, 0x1D, 0x82, 0x63, 0x26, 0x34, 0x56, 0x91, 0x2D, 0xDC, 0xFD, 0x0A,
0xF2, 0x3F, 0xBA, 0x44, 0xCD, 0x81, 0x53, 0x1F, 0x8B, 0xD3, 0x38, 0x22,
0x02, 0x05, 0x85, 0x35, 0x41, 0x50, 0xE8, 0x48, 0x6E, 0xE3, 0x7D, 0xA9,
0xFE, 0x5C, 0x39,
};
static int test_DoUserAuthRequestRsaCert(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
const UserAuthRsaTestVector* tv;
int tc = (int)(sizeof(userAuthRsaTestVectors)
/ sizeof(userAuthRsaTestVectors[0]));
int i;
int ret;
int failures = 0;
if ((userAuthRsaSigBlob[RSA_SIG_BLOB_SIG] & 0x80) == 0) {
fprintf(stderr, "\tuserAuthRsaSigBlob needs its high bit set\n");
return 1;
}
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return 1;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return 1;
}
for (i = 0, tv = userAuthRsaTestVectors; i < tc; i++, tv++) {
byte sigBlob[sizeof(userAuthRsaSigBlob)];
byte digest[sizeof(userAuthRsaDigest)];
WS_UserAuthData_PublicKey pk;
/* Vectors that patch the raw public key blob don't apply here; the
* cert path takes its key from a fixed certificate. */
if (tv->pubPatchSz > 0)
continue;
WMEMCPY(sigBlob, userAuthRsaSigBlob, sizeof(sigBlob));
WMEMCPY(digest, userAuthRsaDigest, sizeof(digest));
if (tv->patchSz > 0)
WMEMCPY(sigBlob + tv->patchIdx, tv->patch, tv->patchSz);
if (tv->flipIdx > 0)
sigBlob[tv->flipIdx] ^= 0x01;
WMEMSET(&pk, 0, sizeof(pk));
pk.publicKeyType = (const byte*)"x509v3-ssh-rsa";
pk.publicKeyTypeSz = 14;
pk.publicKey = userAuthRsaCertDer;
pk.publicKeySz = (word32)sizeof(userAuthRsaCertDer);
pk.hasSignature = 1;
pk.signature = sigBlob;
pk.signatureSz = (word32)sizeof(sigBlob);
ret = wolfSSH_TestDoUserAuthRequestRsaCert(ssh, &pk, WC_HASH_TYPE_SHA,
digest, (word32)sizeof(digest));
if (ret != tv->expected) {
fprintf(stderr, "\t[%d] \"%s\" FAIL: got %d, expected %d\n",
i, tv->name, ret, tv->expected);
failures++;
}
}
/* A hash wc_EncodeSignature() cannot encode is a crypto failure, not a
* bad signature. */
{
byte sigBlob[sizeof(userAuthRsaSigBlob)];
byte digest[sizeof(userAuthRsaDigest)];
WS_UserAuthData_PublicKey pk;
WMEMCPY(sigBlob, userAuthRsaSigBlob, sizeof(sigBlob));
WMEMCPY(digest, userAuthRsaDigest, sizeof(digest));
WMEMSET(&pk, 0, sizeof(pk));
pk.publicKeyType = (const byte*)"x509v3-ssh-rsa";
pk.publicKeyTypeSz = 14;
pk.publicKey = userAuthRsaCertDer;
pk.publicKeySz = (word32)sizeof(userAuthRsaCertDer);
pk.hasSignature = 1;
pk.signature = sigBlob;
pk.signatureSz = (word32)sizeof(sigBlob);
ret = wolfSSH_TestDoUserAuthRequestRsaCert(ssh, &pk,
WC_HASH_TYPE_NONE, digest, (word32)sizeof(digest));
if (ret != WS_CRYPTO_FAILED) {
fprintf(stderr, "\t\"unencodable hash\" FAIL: got %d, "
"expected %d\n", ret, WS_CRYPTO_FAILED);
failures++;
}
}
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return failures;
}
#endif /* WOLFSSH_CERTS */
#endif /* !WOLFSSH_NO_RSA && !WOLFSSH_NO_SSH_RSA_SHA1 */
#ifdef WOLFSSH_SFTP
/* IORecv mock that reports no data is available yet. ReceiveData maps this to
* WS_WANT_READ, letting the receive loop reach its body-read state without a
* live socket. Both the server and client halves below use it. */
static WS_MAYBE_UNUSED int RecvAlwaysWantRead(WOLFSSH* ssh, void* data,
word32 sz, void* ctx)
{
WOLFSSH_UNUSED(ssh);
WOLFSSH_UNUSED(data);
WOLFSSH_UNUSED(sz);
WOLFSSH_UNUSED(ctx);
return WS_CBIO_ERR_WANT_READ;
}
#ifndef NO_WOLFSSH_SERVER
/* Property test for the server-side received-packet size bound applied in
* wolfSSH_SFTP_read(). A non-positive size or one above the largest legal
* inbound SFTP message must be rejected before any buffer is allocated;
* in-range sizes are accepted. */
static int test_SftpRecvSizeBound(void)
{
int testVals[7];
int expectOk;
int ret;
int i;
int maxWriteBody;
testVals[0] = -1; /* underflow / error sentinel */
testVals[1] = 0; /* empty body */
testVals[2] = 1; /* smallest accepted body */
testVals[3] = WOLFSSH_MAX_SFTP_PACKET; /* upper bound, accepted */
testVals[4] = WOLFSSH_MAX_SFTP_PACKET + 1; /* just over the bound */
testVals[5] = 0x40000000; /* the ~1 GB attack value */
testVals[6] = 0x7FFFFFFF; /* INT32_MAX */
for (i = 0; i < (int)(sizeof(testVals) / sizeof(testVals[0])); i++) {
ret = wolfSSH_TestSftpRecvSizeCheck(testVals[i]);
expectOk = (testVals[i] > 0 &&
testVals[i] <= WOLFSSH_MAX_SFTP_PACKET);
if (expectOk) {
if (ret != WS_SUCCESS)
return -900 - i;
}
else {
if (ret == WS_SUCCESS)
return -920 - i;
}
}
/* The bound value must be large enough to admit a real maximum-size WRITE,
* otherwise legitimate large writes would be silently rejected. A WRITE
* body is a handle string (length prefix + up to WOLFSSH_MAX_HANDLE), an
* 8-byte file offset, then a data string (length prefix + up to
* WOLFSSH_MAX_SFTP_RW). Guards against a future shrink of the bound (e.g.
* to WOLFSSH_MAX_SFTP_RECV alone). */
maxWriteBody = UINT32_SZ + WOLFSSH_MAX_HANDLE /* handle string */
+ (2 * UINT32_SZ) /* 64-bit offset */
+ UINT32_SZ + WOLFSSH_MAX_SFTP_RW; /* data string */
if (wolfSSH_TestSftpRecvSizeCheck(maxWriteBody) != WS_SUCCESS)
return -930;
return 0;
}
/* Drives a single crafted SFTP request header through wolfSSH_SFTP_read() on a
* fresh server session. The on-wire length field is set to len and the message
* type to WRITE; only the 9-byte header is staged in the channel input buffer,
* never a body. ioRecv, when non-NULL, stands in for the socket if the loop is
* admitted and reaches its body-read state. On success fills *outRet with the
* wolfSSH_SFTP_read() return and *outErr with ssh->error, and returns 0; on a
* setup failure returns a negative sentinel. DiscardIoSend absorbs the
* window-adjust emitted after the header is consumed, and acceptState is
* advanced so that adjust is allowed on the bare session. */
static int SftpRecvDriveHeader(word32 len, WS_CallbackIORecv ioRecv,
int* outRet, int* outErr)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
byte header[WOLFSSH_SFTP_HEADER];
*outRet = WS_SUCCESS;
*outErr = WS_SUCCESS;
header[0] = (byte)((len >> 24) & 0xFF);
header[1] = (byte)((len >> 16) & 0xFF);
header[2] = (byte)((len >> 8) & 0xFF);
header[3] = (byte)( len & 0xFF);
header[LENGTH_SZ] = WOLFSSH_FTP_WRITE; /* message type */
header[LENGTH_SZ + MSG_ID_SZ + 0] = 0x00; /* request id = 1 */
header[LENGTH_SZ + MSG_ID_SZ + 1] = 0x00;
header[LENGTH_SZ + MSG_ID_SZ + 2] = 0x00;
header[LENGTH_SZ + MSG_ID_SZ + 3] = 0x01;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1000;
wolfSSH_SetIOSend(ctx, DiscardIoSend);
if (ioRecv != NULL)
wolfSSH_SetIORecv(ctx, ioRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1001; goto done; }
/* Allow MSGID_CHANNEL_WINDOW_ADJUST on this bare session. */
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch == NULL) { result = -1002; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1003;
goto done;
}
if (wolfSSH_TestChannelPutData(ssh->channelList, header,
(word32)sizeof(header)) != WS_SUCCESS) {
result = -1004;
goto done;
}
*outRet = wolfSSH_SFTP_read(ssh);
*outErr = wolfSSH_get_error(ssh);
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* End-to-end check that the receive loop itself rejects an invalid declared
* inbound length, not just the SFTP_CheckRecvSz helper in isolation. Drives two
* crafted headers whose decoded body length the bound must refuse: one well
* past WOLFSSH_MAX_SFTP_PACKET and one of zero. Each must return WS_FATAL_ERROR
* with ssh->error == WS_BUFFER_E and allocate no body buffer. The zero case
* also guards against ssh->error being left at 0, which a caller could misread
* as a clean channel close. */
static int test_SftpRecvSizeBoundIntegration(void)
{
word32 lens[2];
int rc;
int ret;
int err;
int i;
/* On-wire length field counts the type byte, request id, and body. */
lens[0] = (word32)WOLFSSH_MAX_SFTP_PACKET + 100 + MSG_ID_SZ + UINT32_SZ;
lens[1] = (word32)(MSG_ID_SZ + UINT32_SZ); /* decoded body length 0 */
for (i = 0; i < (int)(sizeof(lens) / sizeof(lens[0])); i++) {
rc = SftpRecvDriveHeader(lens[i], NULL, &ret, &err);
if (rc != 0)
return rc;
if (ret != WS_FATAL_ERROR)
return -945 - (i * 10);
if (err != WS_BUFFER_E)
return -946 - (i * 10);
}
return 0;
}
/* End-to-end check that a legitimate maximum-size WRITE is NOT rejected by the
* server bound. The decoded body length equals the largest real WRITE body
* (handle + 8-byte offset + max data). The bound must admit it: the loop
* allocates the body buffer and then asks for the body that has not arrived, so
* the call returns WS_FATAL_ERROR with ssh->error == WS_WANT_READ (a benign
* retry) rather than WS_BUFFER_E (a bound rejection). RecvAlwaysWantRead stands
* in for a non-blocking socket with no data yet. */
static int test_SftpRecvSizeBoundAccept(void)
{
word32 len;
int rc;
int ret;
int err;
/* Largest legitimate WRITE body, matching test_SftpRecvSizeBound, plus the
* type byte and request id the on-wire length field carries. */
len = (word32)(UINT32_SZ + WOLFSSH_MAX_HANDLE
+ (2 * UINT32_SZ)
+ UINT32_SZ + WOLFSSH_MAX_SFTP_RW)
+ MSG_ID_SZ + UINT32_SZ;
rc = SftpRecvDriveHeader(len, RecvAlwaysWantRead, &ret, &err);
if (rc != 0)
return rc;
if (ret != WS_FATAL_ERROR)
return -955;
/* WS_WANT_READ: body accepted, loop waiting; WS_BUFFER_E would mean a
* legitimate max WRITE was rejected. */
if (err != WS_WANT_READ)
return -956;
return 0;
}
static byte s_sftpSent[512];
static word32 s_sftpSentSz = 0;
static int SftpCaptureIoSend(WOLFSSH* ssh, void* buf, word32 sz, void* ctx)
{
WOLFSSH_UNUSED(ssh);
WOLFSSH_UNUSED(ctx);
if (s_sftpSentSz + sz > (word32)sizeof(s_sftpSent))
return WS_CBIO_ERR_GENERAL;
WMEMCPY(s_sftpSent + s_sftpSentSz, buf, sz);
s_sftpSentSz += sz;
return (int)sz;
}
/* An SSH_FXP_EXTENDED request the server does not implement is answered
* with SSH_FX_OP_UNSUPPORTED (draft-ietf-secsh-filexfer-02 Section 8),
* not the generic SSH_FX_FAILURE. */
static int test_SftpExtendedUnsupported(void)
{
static const char extName[] = "unknown@example.com";
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
int result = 0;
word32 extSz = (word32)(sizeof(extName) - 1);
word32 sz = 0;
word32 i;
byte pkt[WOLFSSH_SFTP_HEADER + UINT32_SZ + sizeof(extName)];
/* STATUS header for request id 7, as it appears on the wire */
static const byte status[] = { WOLFSSH_FTP_STATUS, 0, 0, 0, 7 };
PutU32BE(pkt, MSG_ID_SZ + UINT32_SZ + UINT32_SZ + extSz);
pkt[LENGTH_SZ] = WOLFSSH_FTP_EXTENDED;
PutU32BE(pkt + LENGTH_SZ + MSG_ID_SZ, 7);
sz = WOLFSSH_SFTP_HEADER;
PutU32BE(pkt + sz, extSz);
sz += UINT32_SZ;
WMEMCPY(pkt + sz, extName, extSz);
sz += extSz;
s_sftpSentSz = 0;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -960;
wolfSSH_SetIOSend(ctx, SftpCaptureIoSend);
wolfSSH_SetIORecv(ctx, RecvAlwaysWantRead);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -961; goto done; }
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch == NULL) { result = -962; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -963;
goto done;
}
ch->openConfirmed = 1;
ch->peerWindowSz = 1024;
ch->peerMaxPacketSz = 1024;
if (wolfSSH_TestChannelPutData(ch, pkt, sz) != WS_SUCCESS) {
result = -964;
goto done;
}
if (wolfSSH_SFTP_read(ssh) != WS_SUCCESS) {
result = -965;
goto done;
}
/* no keys yet, so the reply crosses the transport in the clear */
for (i = 0; i + sizeof(status) + UINT32_SZ <= s_sftpSentSz; i++) {
if (WMEMCMP(s_sftpSent + i, status, sizeof(status)) == 0)
break;
}
if (i + sizeof(status) + UINT32_SZ > s_sftpSentSz) {
result = -966;
goto done;
}
i += (word32)sizeof(status);
sz = ((word32)s_sftpSent[i] << 24) | ((word32)s_sftpSent[i + 1] << 16)
| ((word32)s_sftpSent[i + 2] << 8) | (word32)s_sftpSent[i + 3];
if (sz != WOLFSSH_FTP_UNSUPPORTED)
result = -967;
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* NO_WOLFSSH_SERVER */
#ifndef NO_WOLFSSH_CLIENT
/* Builds an SFTP VERSION message in the outSz byte buffer "out", with the
* declared length "len", message type "type", "version", and extSz bytes of
* extension data. Returns the size written, or 0 if it does not fit. */
static word32 SftpBuildVersion(byte* out, word32 outSz, word32 len, byte type,
word32 version, word32 extSz)
{
word32 i;
if (WOLFSSH_SFTP_HEADER + extSz > outSz) {
return 0;
}
PutU32BE(out, len);
out[LENGTH_SZ] = type;
PutU32BE(out + LENGTH_SZ + MSG_ID_SZ, version);
for (i = 0; i < extSz; i++) {
out[WOLFSSH_SFTP_HEADER + i] = (byte)i;
}
return WOLFSSH_SFTP_HEADER + extSz;
}
/* Creates a client session sitting past channel setup and already waiting on
* the VERSION reply, so a connect call runs only the receive half of the
* negotiation. The caller frees ctx and ssh on every path. */
static int SftpClientNewSession(WOLFSSH_CTX** ctxOut, WOLFSSH** sshOut)
{
WOLFSSH_CTX* ctx;
WOLFSSH* ssh;
WOLFSSH_CHANNEL* ch;
*ctxOut = NULL;
*sshOut = NULL;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -1010;
wolfSSH_SetIOSend(ctx, DiscardIoSend);
wolfSSH_SetIORecv(ctx, RecvAlwaysWantRead);
*ctxOut = ctx;
ssh = wolfSSH_new(ctx);
if (ssh == NULL)
return -1011;
*sshOut = ssh;
ssh->connectState = CONNECT_SERVER_CHANNEL_REQUEST_DONE;
ssh->sftpState = SFTP_RECV;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 1024, 1024);
if (ch == NULL)
return -1012;
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
return -1013;
}
return 0;
}
/* Drives wolfSSH_SFTP_connect() over a VERSION message delivered in two pieces,
* split after "split" bytes, with RecvAlwaysWantRead standing in for a
* non-blocking socket. Returns 0, or a negative sentinel on a setup failure. */
static int SftpClientDriveVersion(word32 extSz, word32 split,
int* firstRet, int* firstErr, int* secondRet, int* endState)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
byte msg[WOLFSSH_SFTP_HEADER + 16];
word32 msgSz;
int result;
*firstRet = WS_SUCCESS;
*firstErr = WS_SUCCESS;
*secondRet = WS_SUCCESS;
*endState = 0;
msgSz = SftpBuildVersion(msg, (word32)sizeof(msg),
MSG_ID_SZ + UINT32_SZ + extSz, WOLFSSH_FTP_VERSION,
(word32)WOLFSSH_SFTP_VERSION, extSz);
if (msgSz == 0)
return -1017;
result = SftpClientNewSession(&ctx, &ssh);
if (result == 0) {
if (wolfSSH_TestChannelPutData(ssh->channelList, msg, split)
!= WS_SUCCESS) {
result = -1014;
}
}
if (result == 0) {
*firstRet = wolfSSH_SFTP_connect(ssh);
*firstErr = wolfSSH_get_error(ssh);
if (wolfSSH_TestChannelPutData(ssh->channelList, msg + split,
msgSz - split) != WS_SUCCESS) {
result = -1015;
}
}
if (result == 0) {
*secondRet = wolfSSH_SFTP_connect(ssh);
*endState = ssh->sftpState;
}
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* Delivers one complete VERSION message in a single read, reporting the connect
* result, whether the buffered init state was released, and the ending state. */
static int SftpClientDriveOnce(word32 len, byte type, word32 version,
int* connectRet, int* stateFreed, int* endState)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
byte msg[WOLFSSH_SFTP_HEADER];
word32 msgSz;
int result;
*connectRet = WS_SUCCESS;
*stateFreed = 0;
*endState = 0;
msgSz = SftpBuildVersion(msg, (word32)sizeof(msg), len, type, version, 0);
if (msgSz == 0)
return -1018;
result = SftpClientNewSession(&ctx, &ssh);
if (result == 0) {
if (wolfSSH_TestChannelPutData(ssh->channelList, msg, msgSz)
!= WS_SUCCESS) {
result = -1016;
}
}
if (result == 0) {
*connectRet = wolfSSH_SFTP_connect(ssh);
*stateFreed = (ssh->recvInitState == NULL);
*endState = ssh->sftpState;
}
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* Regression for the client SFTP negotiation losing bytes on a short read: a
* split VERSION message must report WS_WANT_READ, then complete on the retry.
* The splits cover the SFTP_RECV arm (header) and the SFTP_EXT arm. */
static int test_SftpClientRecvInitSplit(void)
{
int rc;
int firstRet;
int firstErr;
int secondRet;
int endState;
/* split inside the header, no extensions */
rc = SftpClientDriveVersion(0, LENGTH_SZ,
&firstRet, &firstErr, &secondRet, &endState);
if (rc != 0)
return rc;
if (firstRet != WS_FATAL_ERROR)
return -960;
if (firstErr != WS_WANT_READ)
return -961;
if (secondRet != WS_SUCCESS)
return -962;
if (endState != SFTP_DONE)
return -963;
/* split inside the extension data following a complete header */
rc = SftpClientDriveVersion(8, WOLFSSH_SFTP_HEADER + 3,
&firstRet, &firstErr, &secondRet, &endState);
if (rc != 0)
return rc;
if (firstRet != WS_FATAL_ERROR)
return -964;
if (firstErr != WS_WANT_READ)
return -965;
if (secondRet != WS_SUCCESS)
return -966;
if (endState != SFTP_DONE)
return -967;
return 0;
}
/* Covers the VERSION checks on a complete message: each rejection must fail the
* connect and release the buffered init state, while a version above ours must
* still negotiate, keeping the bound a "<" rather than a "<=". */
static int test_SftpClientRecvInitVersion(void)
{
int rc;
int connectRet;
int stateFreed;
int endState;
/* declared size smaller than the type and version fields */
rc = SftpClientDriveOnce(1, WOLFSSH_FTP_VERSION,
(word32)WOLFSSH_SFTP_VERSION, &connectRet, &stateFreed, &endState);
if (rc != 0)
return rc;
if (connectRet != WS_FATAL_ERROR)
return -970;
if (!stateFreed)
return -971;
/* declared size past the largest inbound message accepted */
rc = SftpClientDriveOnce((word32)WOLFSSH_MAX_SFTP_RECV + 1,
WOLFSSH_FTP_VERSION, (word32)WOLFSSH_SFTP_VERSION,
&connectRet, &stateFreed, &endState);
if (rc != 0)
return rc;
if (connectRet != WS_FATAL_ERROR)
return -979;
if (!stateFreed)
return -980;
/* INIT echoed back where a VERSION reply is expected */
rc = SftpClientDriveOnce(MSG_ID_SZ + UINT32_SZ, WOLFSSH_FTP_INIT,
(word32)WOLFSSH_SFTP_VERSION, &connectRet, &stateFreed, &endState);
if (rc != 0)
return rc;
if (connectRet != WS_FATAL_ERROR)
return -972;
if (!stateFreed)
return -973;
/* server reporting a version wolfSSH cannot talk to */
rc = SftpClientDriveOnce(MSG_ID_SZ + UINT32_SZ, WOLFSSH_FTP_VERSION,
(word32)WOLFSSH_SFTP_VERSION - 1, &connectRet, &stateFreed,
&endState);
if (rc != 0)
return rc;
if (connectRet != WS_FATAL_ERROR)
return -974;
if (!stateFreed)
return -975;
/* server above our version: continue on with ours */
rc = SftpClientDriveOnce(MSG_ID_SZ + UINT32_SZ, WOLFSSH_FTP_VERSION,
(word32)WOLFSSH_SFTP_VERSION + 1, &connectRet, &stateFreed,
&endState);
if (rc != 0)
return rc;
if (connectRet != WS_SUCCESS)
return -976;
if (!stateFreed)
return -977;
if (endState != SFTP_DONE)
return -978;
return 0;
}
#ifdef WOLFSSH_TEST_SFTP_PUT
/* Builds an SFTP reply in "out": the 9 byte header carrying the request id
* where a VERSION message carries the version, then payloadSz trailing bytes
* for the caller to fill. Returns the size written, or 0 if it does not fit. */
static word32 SftpBuildReply(byte* out, word32 outSz, byte type, word32 reqId,
word32 payloadSz)
{
return SftpBuildVersion(out, outSz, MSG_ID_SZ + UINT32_SZ + payloadSz,
type, reqId, payloadSz);
}
/* This bare session sends unencrypted SSH CHANNEL_DATA packets. Count
* CLOSE requests carrying the one-byte handle returned by the fixture. */
static int SftpPutCountClose(WOLFSSH* ssh, void* buf, word32 sz, void* ctx)
{
const byte* packet = (const byte*)buf;
int* count = (int*)ctx;
word32 msgOffset = LENGTH_SZ + PAD_LENGTH_SZ;
word32 dataOffset = msgOffset + MSG_ID_SZ + UINT32_SZ * 2;
word32 handleOffset = dataOffset + WOLFSSH_SFTP_HEADER + UINT32_SZ;
WOLFSSH_UNUSED(ssh);
if (sz > handleOffset && packet[msgOffset] == MSGID_CHANNEL_DATA &&
packet[dataOffset + LENGTH_SZ] == WOLFSSH_FTP_CLOSE &&
packet[handleOffset - UINT32_SZ] == 0 &&
packet[handleOffset - 3] == 0 && packet[handleOffset - 2] == 0 &&
packet[handleOffset - 1] == 1 && packet[handleOffset] == 'h') {
(*count)++;
}
return (int)sz;
}
/* Drives wolfSSH_SFTP_Put() over a staged handle reply and a write answered by
* an FXP_STATUS carrying the request id "openId + writeIdOfst". Returns 0, or
* a negative sentinel on a setup failure. */
static int SftpClientDrivePutFail(word32 writeIdOfst, int closeMode,
int* putRet, int* putErr,
int* stateFreed)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
char tmpFile[] = "/tmp/wolfssh_sftp_putXXXXXX";
char remote[] = "put_target";
byte reply[WOLFSSH_SFTP_HEADER + (UINT32_SZ * 3)];
word32 replySz;
word32 openId = 0;
int result;
int fd;
int closeCount = 0;
*putRet = WS_SUCCESS;
*putErr = WS_SUCCESS;
*stateFreed = 0;
fd = mkstemp(tmpFile);
if (fd == -1)
return -990;
if (write(fd, "0123456789", 10) != 10) {
close(fd);
unlink(tmpFile);
return -991;
}
close(fd);
result = SftpClientNewSession(&ctx, &ssh);
if (result == 0) {
wolfSSH_SetIOSend(ctx, SftpPutCountClose);
wolfSSH_SetIOWriteCtx(ssh, &closeCount);
ssh->sftpState = SFTP_DONE;
ssh->channelList->peerWindowSz = 4096;
ssh->channelList->peerMaxPacketSz = 1024;
openId = ssh->reqId;
/* answer the remote open with a one byte handle */
replySz = SftpBuildReply(reply, sizeof(reply), WOLFSSH_FTP_HANDLE,
openId, UINT32_SZ + 1);
if (replySz > 0) {
/* the trailing bytes open with the handle string length */
PutU32BE(reply + WOLFSSH_SFTP_HEADER, 1);
reply[WOLFSSH_SFTP_HEADER + UINT32_SZ] = 'h';
}
if (replySz == 0 || wolfSSH_TestChannelPutData(ssh->channelList,
reply, replySz) != WS_SUCCESS) {
result = -992;
}
}
if (result == 0) {
/* reject the write; the message and language tags are empty */
replySz = SftpBuildReply(reply, sizeof(reply), WOLFSSH_FTP_STATUS,
openId + writeIdOfst, UINT32_SZ * 3);
if (replySz > 0) {
PutU32BE(reply + WOLFSSH_SFTP_HEADER, (word32)WOLFSSH_FTP_FAILURE);
PutU32BE(reply + WOLFSSH_SFTP_HEADER + UINT32_SZ, 0);
PutU32BE(reply + WOLFSSH_SFTP_HEADER + (UINT32_SZ * 2), 0);
}
if (replySz == 0 || wolfSSH_TestChannelPutData(ssh->channelList,
reply, replySz) != WS_SUCCESS) {
result = -993;
}
}
if (result == 0) {
*putRet = wolfSSH_SFTP_Put(ssh, tmpFile, remote, 0, NULL);
/* CLOSE must be sent once, including on a rejected WRITE. */
if (closeCount != 1) {
result = -1150;
}
if (result == 0 && writeIdOfst == 1) {
if (*putRet != WS_FATAL_ERROR || ssh->error != WS_WANT_READ ||
ssh->putState == NULL || ssh->closeState == NULL) {
result = -1151;
}
if (result == 0) {
*putRet = wolfSSH_SFTP_Put(ssh, tmpFile, remote, 0, NULL);
if (*putRet != WS_FATAL_ERROR ||
ssh->error != WS_WANT_READ || closeCount != 1) {
result = -1152;
}
}
replySz = SftpBuildReply(reply, sizeof(reply), WOLFSSH_FTP_STATUS,
openId + 2, UINT32_SZ * 3);
PutU32BE(reply + WOLFSSH_SFTP_HEADER, closeMode & 1 ?
WOLFSSH_FTP_FAILURE : WOLFSSH_FTP_OK);
PutU32BE(reply + WOLFSSH_SFTP_HEADER + UINT32_SZ, 0);
PutU32BE(reply + WOLFSSH_SFTP_HEADER + UINT32_SZ * 2, 0);
if (result == 0 && closeMode >= 2) {
/* Suspend again after receiving only part of the reply. */
if (wolfSSH_TestChannelPutData(ssh->channelList, reply,
WOLFSSH_SFTP_HEADER + UINT32_SZ) != WS_SUCCESS) {
result = -1153;
}
if (result == 0) {
*putRet = wolfSSH_SFTP_Put(ssh, tmpFile, remote, 0, NULL);
if (*putRet != WS_FATAL_ERROR ||
ssh->error != WS_WANT_READ ||
ssh->putState == NULL || ssh->closeState == NULL)
result = -1154;
}
if (result == 0 && wolfSSH_TestChannelPutData(
ssh->channelList,
reply + WOLFSSH_SFTP_HEADER + UINT32_SZ,
replySz - WOLFSSH_SFTP_HEADER - UINT32_SZ)
!= WS_SUCCESS)
result = -1155;
}
else if (result == 0 && wolfSSH_TestChannelPutData(
ssh->channelList, reply, replySz) != WS_SUCCESS) {
result = -1156;
}
if (result == 0) {
*putRet = wolfSSH_SFTP_Put(ssh, tmpFile, remote, 0, NULL);
if (closeCount != 1 || ssh->closeState != NULL)
result = -1157;
}
}
*putErr = wolfSSH_get_error(ssh);
*stateFreed = (ssh->putState == NULL);
}
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
unlink(tmpFile);
return result;
}
/* An upload whose write is rejected must report the failure. A status failure
* surfaces as WS_SFTP_STATUS_NOT_OK; a reply with the wrong request id keeps
* the more specific error the send path recorded. */
static int test_SftpClientPutWriteStatusFail(void)
{
int rc;
int putRet;
int putErr;
int stateFreed;
int closeMode;
/* CLOSE succeeds/fails, with a full or split response. The original
* WRITE error must survive every cleanup and retry. */
for (closeMode = 0; closeMode < 4; closeMode++) {
rc = SftpClientDrivePutFail(1, closeMode, &putRet, &putErr,
&stateFreed);
if (rc != 0) {
printf("SFTP PUT close mode %d: %d\n", closeMode, rc);
return rc;
}
if (putRet != WS_FATAL_ERROR)
return -994;
if (putErr != WS_SFTP_STATUS_NOT_OK)
return -995;
if (!stateFreed)
return -996;
}
/* the reply answers a request id the client never sent */
rc = SftpClientDrivePutFail(2, 0, &putRet, &putErr, &stateFreed);
if (rc != 0)
return rc;
if (putRet != WS_FATAL_ERROR)
return -997;
if (putErr != WS_SFTP_BAD_REQ_ID)
return -998;
if (!stateFreed)
return -999;
return 0;
}
/* Stage a complete STATUS reply on the existing in-memory client channel. */
static int SftpGetStatus(WOLFSSH* ssh, word32 id, word32 status)
{
byte reply[WOLFSSH_SFTP_HEADER + UINT32_SZ * 3];
word32 sz;
sz = SftpBuildReply(reply, sizeof(reply), WOLFSSH_FTP_STATUS, id,
UINT32_SZ * 3);
PutU32BE(reply + WOLFSSH_SFTP_HEADER, status);
PutU32BE(reply + WOLFSSH_SFTP_HEADER + UINT32_SZ, 0);
PutU32BE(reply + WOLFSSH_SFTP_HEADER + UINT32_SZ * 2, 0);
return wolfSSH_TestChannelPutData(ssh->channelList, reply, sz);
}
enum SftpGetCleanupMode {
GET_LOCAL_OPEN_FAIL,
GET_READ_FAIL,
GET_EOF,
GET_CLOSE_FAIL,
GET_READ_CLOSE_FAIL,
GET_REMOTE_OPEN_FAIL
};
/* Exercise GET cleanup using only filesystem paths and peer replies. */
static int SftpGetCleanupCase(int mode)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
char path[] = "/tmp/wolfssh_getXXXXXX";
char badPath[sizeof(path) + 8];
char from[] = "get_source";
char* to;
byte reply[WOLFSSH_SFTP_HEADER + UINT32_SZ * 3];
word32 sz;
word32 id;
int fd;
int ret;
int result = 0;
int expected;
fd = mkstemp(path);
if (fd < 0)
return -1100;
close(fd);
WSNPRINTF(badPath, sizeof(badPath), "%s/child", path);
to = mode == GET_LOCAL_OPEN_FAIL ? badPath : path;
ret = SftpClientNewSession(&ctx, &ssh);
if (ret != 0) {
result = ret;
goto done;
}
ssh->sftpState = SFTP_DONE;
ssh->channelList->peerWindowSz = 65536;
ssh->channelList->peerMaxPacketSz = 32768;
id = ssh->reqId;
sz = SftpBuildReply(reply, sizeof(reply), WOLFSSH_FTP_ATTRS, id,
UINT32_SZ * 2);
PutU32BE(reply + WOLFSSH_SFTP_HEADER, WOLFSSH_FILEATRB_PERM);
PutU32BE(reply + WOLFSSH_SFTP_HEADER + UINT32_SZ,
FILEATRB_PER_FILE | 0600);
if (wolfSSH_TestChannelPutData(ssh->channelList, reply, sz) != 0) {
result = -1101;
goto done;
}
if (mode == GET_REMOTE_OPEN_FAIL) {
if (SftpGetStatus(ssh, id + 1, WOLFSSH_FTP_FAILURE) != 0) {
result = -1117;
goto done;
}
ret = wolfSSH_SFTP_Get(ssh, from, to, 0, NULL);
if (ret == WS_SUCCESS || ssh->getState != NULL ||
ssh->closeState != NULL || ssh->reqId != id + 2) {
result = -1118;
}
goto done;
}
sz = SftpBuildReply(reply, sizeof(reply), WOLFSSH_FTP_HANDLE, id + 1,
UINT32_SZ + 1);
PutU32BE(reply + WOLFSSH_SFTP_HEADER, 1);
reply[WOLFSSH_SFTP_HEADER + UINT32_SZ] = 'h';
if (wolfSSH_TestChannelPutData(ssh->channelList, reply, sz) != 0) {
result = -1102;
goto done;
}
ret = wolfSSH_SFTP_Get(ssh, from, to, 0, NULL);
/* The failure must still close the remote file, so even local-open
* failure waits for a CLOSE reply, rather than freeing GET immediately. */
if (ret != WS_FATAL_ERROR || ssh->error != WS_WANT_READ ||
ssh->getState == NULL) {
result = -1103;
goto done;
}
if (mode != GET_LOCAL_OPEN_FAIL) {
ret = SftpGetStatus(ssh, id + 2,
mode == GET_READ_FAIL || mode == GET_READ_CLOSE_FAIL ?
WOLFSSH_FTP_PERMISSION : WOLFSSH_FTP_EOF);
if (ret != 0) {
result = -1107;
goto done;
}
ret = wolfSSH_SFTP_Get(ssh, from, to, 0, NULL);
if (ret != WS_FATAL_ERROR || ssh->error != WS_WANT_READ ||
ssh->getState == NULL || ssh->closeState == NULL) {
result = -1108;
goto done;
}
}
if (ssh->closeState == NULL ||
ssh->reqId != id + (mode == GET_LOCAL_OPEN_FAIL ? 2 : 3)) {
result = -1109;
goto done;
}
/* Reenter with no reply: the CLOSE must remain pending. */
ret = wolfSSH_SFTP_Get(ssh, from, to, 0, NULL);
if (ret != WS_FATAL_ERROR || ssh->error != WS_WANT_READ ||
ssh->getState == NULL || ssh->closeState == NULL) {
result = -1110;
goto done;
}
sz = SftpBuildReply(reply, sizeof(reply), WOLFSSH_FTP_STATUS,
id + (mode == GET_LOCAL_OPEN_FAIL ? 2 : 3), UINT32_SZ * 3);
PutU32BE(reply + WOLFSSH_SFTP_HEADER,
mode == GET_CLOSE_FAIL || mode == GET_READ_CLOSE_FAIL ?
WOLFSSH_FTP_FAILURE : WOLFSSH_FTP_OK);
PutU32BE(reply + WOLFSSH_SFTP_HEADER + UINT32_SZ, 0);
PutU32BE(reply + WOLFSSH_SFTP_HEADER + UINT32_SZ * 2, 0);
/* Split the CLOSE response across calls as well as delaying it. */
if (wolfSSH_TestChannelPutData(ssh->channelList, reply,
WOLFSSH_SFTP_HEADER + UINT32_SZ) != 0) {
result = -1115;
goto done;
}
ret = wolfSSH_SFTP_Get(ssh, from, to, 0, NULL);
if (ret != WS_FATAL_ERROR || ssh->error != WS_WANT_READ ||
ssh->getState == NULL || ssh->closeState == NULL) {
result = -1116;
goto done;
}
if (wolfSSH_TestChannelPutData(ssh->channelList,
reply + WOLFSSH_SFTP_HEADER + UINT32_SZ,
sz - WOLFSSH_SFTP_HEADER - UINT32_SZ) != 0) {
result = -1111;
goto done;
}
ret = wolfSSH_SFTP_Get(ssh, from, to, 0, NULL);
expected = mode == GET_LOCAL_OPEN_FAIL ? WS_BAD_FILE_E :
mode == GET_EOF ? WS_SUCCESS : WS_FATAL_ERROR;
if (ret != (mode == GET_EOF ? WS_SUCCESS : WS_FATAL_ERROR) ||
(mode != GET_EOF && ssh->error != expected) ||
ssh->getState != NULL || ssh->closeState != NULL) {
result = -1112;
goto done;
}
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
unlink(path);
return result;
}
static int test_SftpGetCleanup(void)
{
int mode;
int ret;
for (mode = GET_LOCAL_OPEN_FAIL; mode <= GET_REMOTE_OPEN_FAIL; mode++) {
ret = SftpGetCleanupCase(mode);
if (ret != 0) {
printf("SFTP GET cleanup mode %d: %d\n", mode, ret);
return ret;
}
}
return 0;
}
/* Stage a HANDLE reply carrying the one byte handle "h". */
static int SftpPutHandle(WOLFSSH* ssh, word32 id)
{
byte reply[WOLFSSH_SFTP_HEADER + UINT32_SZ + 1];
word32 sz;
sz = SftpBuildReply(reply, sizeof(reply), WOLFSSH_FTP_HANDLE, id,
UINT32_SZ + 1);
PutU32BE(reply + WOLFSSH_SFTP_HEADER, 1);
reply[WOLFSSH_SFTP_HEADER + UINT32_SZ] = 'h';
return wolfSSH_TestChannelPutData(ssh->channelList, reply, sz);
}
/* An interrupted GET holds its local file open. Freeing the session must
* close it. */
static int test_SftpGetFreeClosesLocal(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
char path[] = "/tmp/wolfssh_getfreeXXXXXX";
char from[] = "get_source";
byte reply[WOLFSSH_SFTP_HEADER + UINT32_SZ * 2];
word32 sz;
word32 id;
int fd;
int ret;
int result = 0;
fd = mkstemp(path);
if (fd < 0)
return -1250;
close(fd);
ret = SftpClientNewSession(&ctx, &ssh);
if (ret != 0) {
result = ret;
goto done;
}
ssh->sftpState = SFTP_DONE;
ssh->channelList->peerWindowSz = 65536;
ssh->channelList->peerMaxPacketSz = 32768;
id = ssh->reqId;
sz = SftpBuildReply(reply, sizeof(reply), WOLFSSH_FTP_ATTRS, id,
UINT32_SZ * 2);
PutU32BE(reply + WOLFSSH_SFTP_HEADER, WOLFSSH_FILEATRB_PERM);
PutU32BE(reply + WOLFSSH_SFTP_HEADER + UINT32_SZ,
FILEATRB_PER_FILE | 0600);
if (wolfSSH_TestChannelPutData(ssh->channelList, reply, sz) != 0 ||
SftpPutHandle(ssh, id + 1) != 0) {
result = -1251;
goto done;
}
/* GET opens its local file on the lowest free descriptor, found here */
fd = open(path, O_RDONLY);
if (fd < 0) {
result = -1252;
goto done;
}
close(fd);
ret = wolfSSH_SFTP_Get(ssh, from, path, 0, NULL);
if (ret != WS_FATAL_ERROR || ssh->error != WS_WANT_READ ||
ssh->getState == NULL || fcntl(fd, F_GETFD) == -1) {
result = -1253;
goto done;
}
wolfSSH_free(ssh);
ssh = NULL;
if (fcntl(fd, F_GETFD) != -1 || errno != EBADF)
result = -1254;
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
unlink(path);
return result;
}
/* An interrupted PUT holds its local file open. Freeing the session must
* close it. */
static int test_SftpPutFreeClosesLocal(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
char path[] = "/tmp/wolfssh_putfreeXXXXXX";
char to[] = "put_dest";
int fd;
int ret;
int result = 0;
fd = mkstemp(path);
if (fd < 0)
return -1255;
close(fd);
ret = SftpClientNewSession(&ctx, &ssh);
if (ret != 0) {
result = ret;
goto done;
}
ssh->sftpState = SFTP_DONE;
ssh->channelList->peerWindowSz = 65536;
ssh->channelList->peerMaxPacketSz = 32768;
/* PUT opens its local file on the lowest free descriptor, found here */
fd = open(path, O_RDONLY);
if (fd < 0) {
result = -1256;
goto done;
}
close(fd);
/* no HANDLE reply is staged, so the remote open waits for one */
ret = wolfSSH_SFTP_Put(ssh, path, to, 0, NULL);
if (ret != WS_FATAL_ERROR || ssh->error != WS_WANT_READ ||
ssh->putState == NULL || fcntl(fd, F_GETFD) == -1) {
result = -1257;
goto done;
}
wolfSSH_free(ssh);
ssh = NULL;
if (fcntl(fd, F_GETFD) != -1 || errno != EBADF)
result = -1258;
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
unlink(path);
return result;
}
/* STAT must fail on an ATTRS reply whose flags promise more than it holds. */
static int test_SftpStatBadAttrs(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WS_SFTP_FILEATRB atr;
byte reply[WOLFSSH_SFTP_HEADER + UINT32_SZ];
word32 sz;
int ret;
int result = 0;
ret = SftpClientNewSession(&ctx, &ssh);
if (ret != 0) {
result = ret;
goto done;
}
ssh->sftpState = SFTP_DONE;
ssh->channelList->peerWindowSz = 65536;
ssh->channelList->peerMaxPacketSz = 32768;
/* SIZE flagged, but the 64-bit size is missing */
sz = SftpBuildReply(reply, sizeof(reply), WOLFSSH_FTP_ATTRS, ssh->reqId,
UINT32_SZ);
PutU32BE(reply + WOLFSSH_SFTP_HEADER, WOLFSSH_FILEATRB_SIZE);
if (wolfSSH_TestChannelPutData(ssh->channelList, reply, sz) != 0) {
result = -1255;
goto done;
}
WMEMSET(&atr, 0, sizeof(atr));
ret = wolfSSH_SFTP_STAT(ssh, (char*)"f", &atr);
if (ret != WS_FATAL_ERROR || wolfSSH_get_error(ssh) != WS_BUFFER_E ||
ssh->lstatState != NULL)
result = -1256;
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* RMDIR maps a failure status to a WS_* code: WS_PERMISSIONS for a
* permission failure, otherwise WS_SFTP_STATUS_NOT_OK in the error. */
static int SftpRmdirStatusCase(word32 status, int expRet, int expErr)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
int ret;
int result = 0;
ret = SftpClientNewSession(&ctx, &ssh);
if (ret != 0) {
result = ret;
goto done;
}
ssh->sftpState = SFTP_DONE;
ssh->channelList->peerWindowSz = 65536;
ssh->channelList->peerMaxPacketSz = 32768;
if (SftpGetStatus(ssh, ssh->reqId, status) != 0) {
result = -1257;
goto done;
}
ret = wolfSSH_SFTP_RMDIR(ssh, (char*)"d");
if (ret != expRet || wolfSSH_get_error(ssh) != expErr ||
ssh->rmdirState != NULL)
result = -1258;
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
static int test_SftpRmdirStatus(void)
{
int ret;
ret = SftpRmdirStatusCase(WOLFSSH_FTP_OK, WS_SUCCESS, WS_SUCCESS);
if (ret == 0)
ret = SftpRmdirStatusCase(WOLFSSH_FTP_PERMISSION, WS_PERMISSIONS,
WS_PERMISSIONS);
if (ret == 0)
ret = SftpRmdirStatusCase(WOLFSSH_FTP_NOFILE, WS_FATAL_ERROR,
WS_SFTP_STATUS_NOT_OK);
if (ret == 0)
ret = SftpRmdirStatusCase(WOLFSSH_FTP_FAILURE, WS_FATAL_ERROR,
WS_SFTP_STATUS_NOT_OK);
return ret;
}
#ifdef WOLFSSH_TEST_CAPTURING_ALLOCATOR
/* Guard allocator. Each block carries its size in a header; a freed block is
* poisoned and held, so a later write to it is seen by GuardIntact(), and the
* count of live blocks shows a leak. */
#define GUARD_HDR_SZ 16
#define GUARD_POISON 0xDB
typedef struct GuardFreed {
byte* raw;
struct GuardFreed* next;
} GuardFreed;
static GuardFreed* guardFreed = NULL;
static long guardLive = 0;
static void* GuardMalloc(size_t size)
{
byte* raw = (byte*)malloc(size + GUARD_HDR_SZ);
if (raw == NULL)
return NULL;
WMEMCPY(raw, &size, sizeof(size));
guardLive++;
return raw + GUARD_HDR_SZ;
}
static void GuardFree(void* ptr)
{
GuardFreed* node;
byte* raw;
size_t size;
if (ptr == NULL)
return;
raw = (byte*)ptr - GUARD_HDR_SZ;
WMEMCPY(&size, raw, sizeof(size));
WMEMSET(ptr, GUARD_POISON, size);
guardLive--;
node = (GuardFreed*)malloc(sizeof(*node));
if (node == NULL) {
free(raw);
return;
}
node->raw = raw;
node->next = guardFreed;
guardFreed = node;
}
static void* GuardRealloc(void* ptr, size_t size)
{
void* p;
size_t oldSz;
if (ptr == NULL)
return GuardMalloc(size);
p = GuardMalloc(size);
if (p != NULL) {
WMEMCPY(&oldSz, (byte*)ptr - GUARD_HDR_SZ, sizeof(oldSz));
WMEMCPY(p, ptr, oldSz < size ? oldSz : size);
GuardFree(ptr);
}
return p;
}
/* Returns 1 if no freed block was written to. */
static int GuardIntact(void)
{
GuardFreed* f;
size_t size;
size_t i;
for (f = guardFreed; f != NULL; f = f->next) {
WMEMCPY(&size, f->raw, sizeof(size));
for (i = 0; i < size; i++) {
if (f->raw[GUARD_HDR_SZ + i] != GUARD_POISON)
return 0;
}
}
return 1;
}
static void GuardDrain(void)
{
GuardFreed* f = guardFreed;
while (f != NULL) {
GuardFreed* next = f->next;
free(f->raw);
free(f);
f = next;
}
guardFreed = NULL;
}
enum SftpNegFailOp {
NEG_FAIL_STAT,
NEG_FAIL_LS,
NEG_FAIL_CLOSE,
NEG_FAIL_RENAME,
NEG_FAIL_GET,
NEG_FAIL_OP_COUNT
};
/* A request that negotiates SFTP on its own, answered by a bad VERSION, must
* fail without touching its own freed state. */
static int SftpNegFailCase(int op)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WS_SFTP_FILEATRB atr;
WS_SFTPNAME* name;
byte msg[WOLFSSH_SFTP_HEADER];
byte handle[1] = { 'h' };
word32 msgSz;
int ret;
int result;
result = SftpClientNewSession(&ctx, &ssh);
if (result != 0)
goto done;
ssh->channelList->peerWindowSz = 65536;
ssh->channelList->peerMaxPacketSz = 32768;
/* INIT echoed back where a VERSION reply is expected */
msgSz = SftpBuildVersion(msg, (word32)sizeof(msg), MSG_ID_SZ + UINT32_SZ,
WOLFSSH_FTP_INIT, (word32)WOLFSSH_SFTP_VERSION, 0);
if (msgSz == 0 || wolfSSH_TestChannelPutData(ssh->channelList, msg,
msgSz) != WS_SUCCESS) {
result = -1260;
goto done;
}
WMEMSET(&atr, 0, sizeof(atr));
switch (op) {
case NEG_FAIL_STAT:
ret = wolfSSH_SFTP_STAT(ssh, (char*)"f", &atr);
break;
case NEG_FAIL_LS:
name = wolfSSH_SFTP_LS(ssh, (char*)".");
ret = name == NULL ? WS_FATAL_ERROR : WS_SUCCESS;
wolfSSH_SFTPNAME_list_free(name);
break;
case NEG_FAIL_CLOSE:
ret = wolfSSH_SFTP_Close(ssh, handle, sizeof(handle));
break;
case NEG_FAIL_RENAME:
ret = wolfSSH_SFTP_Rename(ssh, "a", "b");
break;
default:
ret = wolfSSH_SFTP_Get(ssh, (char*)"f", (char*)"/nonexistent/f",
0, NULL);
break;
}
if (ret == WS_SUCCESS || ssh->sftpState == SFTP_DONE)
result = -1261;
else if (!GuardIntact())
result = -1262;
else if (ssh->lstatState != NULL || ssh->lsState != NULL ||
ssh->closeState != NULL || ssh->renameState != NULL ||
ssh->getState != NULL || ssh->sendState != NULL ||
ssh->recvInitState != NULL)
result = -1263;
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* Stage a NAME reply carrying one entry, "name", with no attributes. */
static int SftpPutName(WOLFSSH* ssh, word32 id, const char* name)
{
byte reply[WOLFSSH_SFTP_HEADER + UINT32_SZ * 4 + 16];
word32 nameSz = (word32)WSTRLEN(name);
word32 idx = WOLFSSH_SFTP_HEADER;
word32 sz;
sz = SftpBuildReply(reply, sizeof(reply), WOLFSSH_FTP_NAME, id,
UINT32_SZ * 4 + nameSz);
if (sz == 0)
return -1;
PutU32BE(reply + idx, 1);
idx += UINT32_SZ;
PutU32BE(reply + idx, nameSz);
idx += UINT32_SZ;
WMEMCPY(reply + idx, name, nameSz);
idx += nameSz;
PutU32BE(reply + idx, 0);
idx += UINT32_SZ;
PutU32BE(reply + idx, 0);
return wolfSSH_TestChannelPutData(ssh->channelList, reply, sz);
}
/* An interrupted LS holds the entries read so far. Freeing the session must
* free them. */
static int SftpLsFreeCase(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WS_SFTPNAME* name;
word32 id;
int result;
result = SftpClientNewSession(&ctx, &ssh);
if (result != 0)
goto done;
ssh->sftpState = SFTP_DONE;
ssh->channelList->peerWindowSz = 65536;
ssh->channelList->peerMaxPacketSz = 32768;
id = ssh->reqId;
/* REALPATH, OPENDIR and the first READDIR answered; the next READDIR
* waits */
if (SftpPutName(ssh, id, "/d") != 0 || SftpPutHandle(ssh, id + 1) != 0 ||
SftpPutName(ssh, id + 2, "entry") != 0) {
result = -1264;
goto done;
}
name = wolfSSH_SFTP_LS(ssh, (char*)"d");
if (name != NULL || ssh->error != WS_WANT_READ || ssh->lsState == NULL) {
wolfSSH_SFTPNAME_list_free(name);
result = -1265;
}
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
static int test_SftpClientStateTeardown(void)
{
wolfSSL_Malloc_cb prevMf = NULL;
wolfSSL_Free_cb prevFf = NULL;
wolfSSL_Realloc_cb prevRf = NULL;
int op;
int ret = 0;
wolfSSL_GetAllocators(&prevMf, &prevFf, &prevRf);
for (op = 0; op <= NEG_FAIL_OP_COUNT && ret == 0; op++) {
guardLive = 0;
if (wolfSSL_SetAllocators(GuardMalloc, GuardFree,
GuardRealloc) != 0)
return -1266;
ret = op < NEG_FAIL_OP_COUNT ? SftpNegFailCase(op) : SftpLsFreeCase();
wolfSSL_SetAllocators(prevMf, prevFf, prevRf);
if (ret == 0 && !GuardIntact())
ret = -1267;
if (ret == 0 && guardLive != 0)
ret = -1268;
GuardDrain();
if (ret != 0)
printf("SFTP client state teardown case %d: %d\n", op, ret);
}
return ret;
}
#endif /* WOLFSSH_TEST_CAPTURING_ALLOCATOR */
/* Inject a real fread error by replacing the input descriptor with a
* write-only descriptor. No access to the private PUT state is needed. */
typedef struct SftpPutReadIo {
int localFd;
int errorFd;
int fault;
int injected;
int setupError;
int writes;
int closes;
struct stat source;
} SftpPutReadIo;
static int SftpPutReadSend(WOLFSSH* ssh, void* buf, word32 sz, void* ctx)
{
SftpPutReadIo* io = (SftpPutReadIo*)ctx;
const byte* packet = (const byte*)buf;
word32 msgOffset = LENGTH_SZ + PAD_LENGTH_SZ;
word32 dataOffset = msgOffset + MSG_ID_SZ + UINT32_SZ * 2;
byte type;
struct stat st;
WOLFSSH_UNUSED(ssh);
if (sz <= dataOffset + LENGTH_SZ ||
packet[msgOffset] != MSGID_CHANNEL_DATA)
return (int)sz;
type = packet[dataOffset + LENGTH_SZ];
if (type == WOLFSSH_FTP_WRITE)
io->writes++;
if (type == WOLFSSH_FTP_CLOSE)
io->closes++;
if (!io->injected && ((io->fault == 1 && type == WOLFSSH_FTP_OPEN) ||
(io->fault == 2 && type == WOLFSSH_FTP_WRITE))) {
/* The fixture reserved the lowest free fd just before PUT. Verify
* that it really is the source file before replacing it. */
if (fstat(io->localFd, &st) != 0 ||
st.st_dev != io->source.st_dev ||
st.st_ino != io->source.st_ino ||
dup2(io->errorFd, io->localFd) < 0)
io->setupError = 1;
io->injected = 1;
}
return (int)sz;
}
static int SftpPutReadCase(word32 size, int fault, int closeFails)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
SftpPutReadIo io;
char path[] = "/tmp/wolfssh_put_readXXXXXX";
char remote[] = "put_target";
byte data[WOLFSSH_MAX_SFTP_RW];
byte reply[WOLFSSH_SFTP_HEADER + UINT32_SZ * 3];
word32 id;
word32 sz;
word32 left = size;
word32 writes = fault == 1 ? 0 : fault == 2 ? 1 :
(size + WOLFSSH_MAX_SFTP_RW - 1) / WOLFSSH_MAX_SFTP_RW;
word32 n;
int fd;
int ret;
int result = 0;
WMEMSET(&io, 0, sizeof(io));
io.errorFd = -1;
io.localFd = -1;
io.fault = fault;
WMEMSET(data, 'x', sizeof(data));
fd = mkstemp(path);
if (fd < 0)
return -1160;
while (left > 0) {
sz = left > sizeof(data) ? (word32)sizeof(data) : left;
if (write(fd, data, sz) != (ssize_t)sz) {
result = -1161;
break;
}
left -= sz;
}
close(fd);
if (result != 0)
goto done;
result = SftpClientNewSession(&ctx, &ssh);
if (result != 0)
goto done;
ssh->sftpState = SFTP_DONE;
/* The mock peer supplies SFTP replies, but cannot complete a rekey. */
wolfSSH_SetHighwater(ssh, 0);
ssh->channelList->peerWindowSz = WOLFSSH_MAX_SFTP_RW * 4;
ssh->channelList->peerMaxPacketSz = WOLFSSH_MAX_SFTP_RW + 1024;
wolfSSH_SetIOSend(ctx, SftpPutReadSend);
wolfSSH_SetIOWriteCtx(ssh, &io);
id = ssh->reqId;
sz = SftpBuildReply(reply, sizeof(reply), WOLFSSH_FTP_HANDLE, id,
UINT32_SZ + 1);
PutU32BE(reply + WOLFSSH_SFTP_HEADER, 1);
reply[WOLFSSH_SFTP_HEADER + UINT32_SZ] = 'h';
if (wolfSSH_TestChannelPutData(ssh->channelList, reply, sz) != WS_SUCCESS) {
result = -1162;
goto done;
}
for (n = 0; n < writes; n++) {
if (SftpGetStatus(ssh, id + n + 1, WOLFSSH_FTP_OK) != WS_SUCCESS) {
result = -1163;
goto done;
}
}
io.errorFd = open(path, O_WRONLY);
if (io.errorFd < 0 || fstat(io.errorFd, &io.source) != 0) {
result = -1164;
goto done;
}
io.localFd = open(path, O_RDONLY);
if (io.localFd < 0) {
result = -1165;
goto done;
}
close(io.localFd);
ret = wolfSSH_SFTP_Put(ssh, path, remote, 0, NULL);
if (io.setupError || (fault && !io.injected) ||
ret != WS_FATAL_ERROR || ssh->error != WS_WANT_READ ||
io.writes != (int)writes || io.closes != 1 ||
ssh->putState == NULL || ssh->closeState == NULL) {
result = -1166;
goto done;
}
/* The local stream must already be closed before awaiting remote CLOSE. */
if (fcntl(io.localFd, F_GETFD) != -1 || errno != EBADF) {
result = -1167;
goto done;
}
if (SftpGetStatus(ssh, id + writes + 1, closeFails ?
WOLFSSH_FTP_FAILURE : WOLFSSH_FTP_OK) != WS_SUCCESS) {
result = -1168;
goto done;
}
ret = wolfSSH_SFTP_Put(ssh, path, remote, 0, NULL);
if (ret != (fault ? WS_FATAL_ERROR : WS_SUCCESS) ||
(fault && ssh->error != WS_BAD_FILE_E) || io.closes != 1 ||
ssh->putState != NULL || ssh->closeState != NULL) {
result = -1169;
}
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
if (io.errorFd >= 0)
close(io.errorFd);
unlink(path);
return result;
}
static int test_SftpPutReadError(void)
{
const word32 sizes[] = {0, 1, WOLFSSH_MAX_SFTP_RW,
WOLFSSH_MAX_SFTP_RW + 1};
word32 n;
int fault;
int closeFails;
int ret;
for (n = 0; n < sizeof(sizes) / sizeof(sizes[0]); n++) {
ret = SftpPutReadCase(sizes[n], 0, 0);
if (ret != 0) {
printf("SFTP PUT EOF size %u: %d\n", sizes[n], ret);
return ret;
}
}
for (fault = 1; fault <= 2; fault++) {
for (closeFails = 0; closeFails <= 1; closeFails++) {
ret = SftpPutReadCase(WOLFSSH_MAX_SFTP_RW * 2 + 1,
fault, closeFails);
if (ret != 0) {
printf("SFTP PUT read fault %d, close failure %d: %d\n",
fault, closeFails, ret);
return ret;
}
}
}
return 0;
}
enum SftpReplyIdOp {
REPLY_ID_REMOVE,
REPLY_ID_RMDIR,
REPLY_ID_CLOSE,
REPLY_ID_SETSTAT,
REPLY_ID_OPEN,
REPLY_ID_REALPATH,
REPLY_ID_LSTAT,
REPLY_ID_OP_COUNT
};
enum SftpReplyIdMode {
REPLY_ID_MATCH,
REPLY_ID_WRONG_ID,
REPLY_ID_WRONG_TYPE,
REPLY_ID_NO_MEMORY
};
/* reply body size whose buffer allocation REPLY_ID_NO_MEMORY fails */
#define REPLY_ID_FAIL_SZ 37
#ifdef WOLFSSH_TEST_CAPTURING_ALLOCATOR
static void* SftpReplyIdMalloc(size_t size)
{
if (size == REPLY_ID_FAIL_SZ)
return NULL;
return malloc(size);
}
#endif
/* Answer one client request with a reply carrying the request id, a wrong
* id, (REALPATH and OPEN only) the right id on a wrong message type, or
* (LSTAT only) a body that cannot be allocated. A matched reply advances the
* request id once; any other reply fails with a specific error and frees the
* request state. */
static int SftpReplyIdCase(int op, int mode)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WS_SFTP_FILEATRB atr;
WS_SFTPNAME* name = NULL;
byte reply[WOLFSSH_SFTP_HEADER + REPLY_ID_FAIL_SZ];
byte handle[WOLFSSH_MAX_HANDLE];
word32 handleSz = sizeof(handle);
#ifdef WOLFSSH_TEST_CAPTURING_ALLOCATOR
wolfSSL_Malloc_cb prevMf;
wolfSSL_Free_cb prevFf;
wolfSSL_Realloc_cb prevRf;
#endif
word32 sz;
word32 id;
word32 status = WOLFSSH_FTP_OK;
int ret;
int failed;
int stateLeft;
int result = 0;
ret = SftpClientNewSession(&ctx, &ssh);
if (ret != 0) {
result = ret;
goto done;
}
ssh->sftpState = SFTP_DONE;
ssh->channelList->peerWindowSz = 65536;
ssh->channelList->peerMaxPacketSz = 32768;
id = ssh->reqId;
if (op == REPLY_ID_REMOVE) {
/* REMOVE checks the file with an LSTAT first */
sz = SftpBuildReply(reply, sizeof(reply), WOLFSSH_FTP_ATTRS, id,
UINT32_SZ);
PutU32BE(reply + WOLFSSH_SFTP_HEADER, 0);
if (wolfSSH_TestChannelPutData(ssh->channelList, reply, sz) != 0) {
result = -1200;
goto done;
}
id++;
}
if (op == REPLY_ID_OPEN || op == REPLY_ID_REALPATH)
status = WOLFSSH_FTP_FAILURE;
if (mode == REPLY_ID_WRONG_TYPE && op == REPLY_ID_OPEN) {
sz = SftpBuildReply(reply, sizeof(reply), WOLFSSH_FTP_ATTRS, id,
UINT32_SZ);
PutU32BE(reply + WOLFSSH_SFTP_HEADER, 0);
ret = wolfSSH_TestChannelPutData(ssh->channelList, reply, sz);
}
else if (mode == REPLY_ID_WRONG_TYPE) {
sz = SftpBuildReply(reply, sizeof(reply), WOLFSSH_FTP_HANDLE, id,
UINT32_SZ + 1);
PutU32BE(reply + WOLFSSH_SFTP_HEADER, 1);
reply[WOLFSSH_SFTP_HEADER + UINT32_SZ] = 'h';
ret = wolfSSH_TestChannelPutData(ssh->channelList, reply, sz);
}
else if (mode == REPLY_ID_NO_MEMORY) {
WMEMSET(reply, 0, sizeof(reply));
sz = SftpBuildReply(reply, sizeof(reply), WOLFSSH_FTP_ATTRS, id,
REPLY_ID_FAIL_SZ);
ret = wolfSSH_TestChannelPutData(ssh->channelList, reply, sz);
}
else {
ret = SftpGetStatus(ssh, mode == REPLY_ID_WRONG_ID ? id + 1 : id,
status);
}
if (ret != 0) {
result = -1201;
goto done;
}
WMEMSET(&atr, 0, sizeof(atr));
switch (op) {
case REPLY_ID_REMOVE:
ret = wolfSSH_SFTP_Remove(ssh, (char*)"f");
stateLeft = ssh->rmState != NULL;
break;
case REPLY_ID_RMDIR:
ret = wolfSSH_SFTP_RMDIR(ssh, (char*)"d");
stateLeft = ssh->rmdirState != NULL;
break;
case REPLY_ID_CLOSE:
handle[0] = 'h';
ret = wolfSSH_SFTP_Close(ssh, handle, 1);
stateLeft = ssh->closeState != NULL;
break;
case REPLY_ID_SETSTAT:
ret = wolfSSH_SFTP_SetSTAT(ssh, (char*)"f", &atr);
stateLeft = ssh->setatrState != NULL;
break;
case REPLY_ID_OPEN:
ret = wolfSSH_SFTP_Open(ssh, (char*)"f", WOLFSSH_FXF_READ, NULL,
handle, &handleSz);
stateLeft = ssh->openState != NULL ||
ssh->getHandleState != NULL;
break;
case REPLY_ID_LSTAT:
#ifdef WOLFSSH_TEST_CAPTURING_ALLOCATOR
if (mode == REPLY_ID_NO_MEMORY) {
wolfSSL_GetAllocators(&prevMf, &prevFf, &prevRf);
wolfSSL_SetAllocators(SftpReplyIdMalloc, prevFf, prevRf);
}
#endif
ret = wolfSSH_SFTP_LSTAT(ssh, (char*)"f", &atr);
#ifdef WOLFSSH_TEST_CAPTURING_ALLOCATOR
if (mode == REPLY_ID_NO_MEMORY)
wolfSSL_SetAllocators(prevMf, prevFf, prevRf);
#endif
stateLeft = ssh->lstatState != NULL;
break;
default:
name = wolfSSH_SFTP_RealPath(ssh, (char*)"p");
ret = name == NULL ? WS_FATAL_ERROR : WS_SUCCESS;
/* realState 0 is SFTP_REAL_SEND_PACKET, ready for a new call */
stateLeft = ssh->nameState != NULL || ssh->realState != 0;
wolfSSH_SFTPNAME_list_free(name);
break;
}
if (stateLeft) {
result = -1202;
}
else if (mode == REPLY_ID_MATCH) {
failed = status != WOLFSSH_FTP_OK;
if ((failed ? ret == WS_SUCCESS : ret != WS_SUCCESS) ||
wolfSSH_get_error(ssh) == WS_SFTP_BAD_REQ_ID ||
ssh->reqId != id + 1) {
result = -1203;
}
}
else if (ret == WS_SUCCESS || wolfSSH_get_error(ssh) !=
(mode == REPLY_ID_WRONG_ID ? WS_SFTP_BAD_REQ_ID :
mode == REPLY_ID_NO_MEMORY ? WS_MEMORY_E :
WS_SFTP_BAD_REQ_TYPE)) {
result = -1204;
}
else if (ssh->reqId != (mode == REPLY_ID_WRONG_TYPE ? id + 1 : id)) {
result = -1205;
}
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
static int test_SftpReplyId(void)
{
int op;
int mode;
int ret;
for (op = 0; op < REPLY_ID_OP_COUNT; op++) {
for (mode = REPLY_ID_MATCH; mode <= REPLY_ID_NO_MEMORY; mode++) {
if (mode == REPLY_ID_WRONG_TYPE && op != REPLY_ID_REALPATH &&
op != REPLY_ID_OPEN)
continue;
if (mode == REPLY_ID_NO_MEMORY) {
#ifdef WOLFSSH_TEST_CAPTURING_ALLOCATOR
if (op != REPLY_ID_LSTAT)
continue;
#else
continue;
#endif
}
ret = SftpReplyIdCase(op, mode);
if (ret != 0) {
printf("SFTP reply id op %d mode %d: %d\n", op, mode, ret);
return ret;
}
}
}
return 0;
}
#endif /* WOLFSSH_TEST_SFTP_PUT */
/* Builds an SFTP DATA reply in "out": the 9 byte header carrying the request
* id where a VERSION message carries the version, then the data string as the
* trailing bytes. Returns the size written, or 0 if it does not fit. */
static word32 SftpBuildData(byte* out, word32 outSz, word32 reqId,
word32 dataSz)
{
word32 msgSz;
msgSz = SftpBuildVersion(out, outSz,
MSG_ID_SZ + UINT32_SZ + UINT32_SZ + dataSz, WOLFSSH_FTP_DATA,
reqId, UINT32_SZ + dataSz);
if (msgSz > 0) {
/* the trailing bytes open with the data string length */
PutU32BE(out + WOLFSSH_SFTP_HEADER, dataSz);
}
return msgSz;
}
/* Drives wolfSSH_SFTP_SendReadPacket() over a DATA reply delivered in two
* pieces, split after "split" bytes, with RecvAlwaysWantRead standing in for a
* non-blocking socket. Returns 0, or a negative sentinel on a setup failure. */
static int SftpClientDriveReadSplit(word32 dataSz, word32 split,
int* firstRet, int* firstErr, int* stateKept, int* secondRet,
byte* out, word32 outSz)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
byte msg[WOLFSSH_SFTP_HEADER + UINT32_SZ + 32];
byte handle[4];
word32 ofst[2];
word32 msgSz;
int result;
*firstRet = WS_SUCCESS;
*firstErr = WS_SUCCESS;
*stateKept = 0;
*secondRet = WS_SUCCESS;
WMEMSET(handle, 'h', sizeof(handle));
WMEMSET(out, 0, outSz);
ofst[0] = 0;
ofst[1] = 0;
result = SftpClientNewSession(&ctx, &ssh);
if (result == 0) {
msgSz = SftpBuildData(msg, (word32)sizeof(msg), ssh->reqId, dataSz);
if (msgSz == 0 || split >= msgSz) {
result = -1019;
}
}
if (result == 0) {
/* ChannelNew leaves the peer window at zero, which would fail the
* READ request before any reply is read */
ssh->channelList->peerWindowSz = 1024;
ssh->channelList->peerMaxPacketSz = 1024;
if (wolfSSH_TestChannelPutData(ssh->channelList, msg, split)
!= WS_SUCCESS) {
result = -1020;
}
}
if (result == 0) {
*firstRet = wolfSSH_SFTP_SendReadPacket(ssh, handle,
(word32)sizeof(handle), ofst, out, outSz);
*firstErr = wolfSSH_get_error(ssh);
*stateKept = (ssh->sendReadState != NULL);
if (wolfSSH_TestChannelPutData(ssh->channelList, msg + split,
msgSz - split) != WS_SUCCESS) {
result = -1021;
}
}
if (result == 0) {
*secondRet = wolfSSH_SFTP_SendReadPacket(ssh, handle,
(word32)sizeof(handle), ofst, out, outSz);
}
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* Regression for the SFTP DATA reply losing bytes when its four byte string
* length arrives split: the read must report WS_WANT_READ, keep the send read
* state, then complete with the payload intact on the retry. */
static int test_SftpSendReadPacketSplit(void)
{
static const word32 splits[4] = { WOLFSSH_SFTP_HEADER,
WOLFSSH_SFTP_HEADER + 1,
WOLFSSH_SFTP_HEADER + 2,
WOLFSSH_SFTP_HEADER + 3 };
byte out[16];
word32 dataSz = 8;
word32 i;
word32 j;
int rc;
int firstRet;
int firstErr;
int stateKept;
int secondRet;
for (i = 0; i < (word32)(sizeof(splits) / sizeof(splits[0])); i++) {
rc = SftpClientDriveReadSplit(dataSz, splits[i], &firstRet, &firstErr,
&stateKept, &secondRet, out, (word32)sizeof(out));
if (rc != 0)
return rc;
if (firstRet != WS_FATAL_ERROR)
return -981;
if (firstErr != WS_WANT_READ)
return -982;
if (!stateKept)
return -983;
if (secondRet != (int)dataSz)
return -984;
for (j = 0; j < dataSz; j++) {
if (out[j] != (byte)(UINT32_SZ + j))
return -985;
}
}
return 0;
}
/* A DATA reply whose string length exceeds the caller's buffer is rejected
* before the payload is allocated for, reporting WS_RECV_OVERFLOW_E. */
static int test_SftpSendReadPacketOverflow(void)
{
byte out[4];
word32 dataSz = 8;
int rc;
int firstRet;
int firstErr;
int stateKept;
int secondRet;
rc = SftpClientDriveReadSplit(dataSz, WOLFSSH_SFTP_HEADER + UINT32_SZ,
&firstRet, &firstErr, &stateKept, &secondRet, out,
(word32)sizeof(out));
if (rc != 0)
return rc;
if (firstRet != WS_FATAL_ERROR)
return -986;
if (firstErr != WS_RECV_OVERFLOW_E)
return -987;
if (stateKept)
return -988;
return 0;
}
#endif /* NO_WOLFSSH_CLIENT */
#endif /* WOLFSSH_SFTP */
#if defined(WOLFSSH_TEST_INTERNAL) && defined(WOLFSSH_SCP) && \
!defined(WOLFSSH_SCP_USER_CALLBACKS)
/* Exercises ExtractFileName, the SCP source helper that splits the leaf name
* from a request path. A bare name with no path separator must be accepted
* (the whole string is the file name); this is the recursive-source
* regression. */
static int test_ScpExtractFileName(void)
{
char name[64];
int ret;
/* bare name, no separator: whole string is the file name (regression) */
WMEMSET(name, 0, sizeof(name));
ret = wolfSSH_TestScpExtractFileName("scp_rk_src", name, sizeof(name));
if (ret != WS_SUCCESS || WSTRCMP(name, "scp_rk_src") != 0)
return -900;
/* leading "./" prefix */
WMEMSET(name, 0, sizeof(name));
ret = wolfSSH_TestScpExtractFileName("./scp_rk_src", name, sizeof(name));
if (ret != WS_SUCCESS || WSTRCMP(name, "scp_rk_src") != 0)
return -901;
/* relative nested path */
WMEMSET(name, 0, sizeof(name));
ret = wolfSSH_TestScpExtractFileName("a/b/c", name, sizeof(name));
if (ret != WS_SUCCESS || WSTRCMP(name, "c") != 0)
return -902;
/* absolute path */
WMEMSET(name, 0, sizeof(name));
ret = wolfSSH_TestScpExtractFileName("/tmp/x/y", name, sizeof(name));
if (ret != WS_SUCCESS || WSTRCMP(name, "y") != 0)
return -903;
/* empty path is rejected */
ret = wolfSSH_TestScpExtractFileName("", name, sizeof(name));
if (ret != WS_BAD_ARGUMENT)
return -904;
/* NULL arguments are rejected */
ret = wolfSSH_TestScpExtractFileName(NULL, name, sizeof(name));
if (ret != WS_BAD_ARGUMENT)
return -905;
ret = wolfSSH_TestScpExtractFileName("scp_rk_src", NULL, sizeof(name));
if (ret != WS_BAD_ARGUMENT)
return -906;
/* destination too small for name plus null terminator */
ret = wolfSSH_TestScpExtractFileName("scp_rk_src", name, 4);
if (ret != WS_SCP_PATH_LEN_E)
return -907;
/* bare "." and ".." are accepted as-is (separator-less leaf names); the
* recursive walk skips "."/".." directory entries separately */
WMEMSET(name, 0, sizeof(name));
ret = wolfSSH_TestScpExtractFileName(".", name, sizeof(name));
if (ret != WS_SUCCESS || WSTRCMP(name, ".") != 0)
return -908;
WMEMSET(name, 0, sizeof(name));
ret = wolfSSH_TestScpExtractFileName("..", name, sizeof(name));
if (ret != WS_SUCCESS || WSTRCMP(name, "..") != 0)
return -909;
/* trailing separator yields an empty leaf name with success */
WMEMSET(name, 0, sizeof(name));
ret = wolfSSH_TestScpExtractFileName("a/b/", name, sizeof(name));
if (ret != WS_SUCCESS || WSTRCMP(name, "") != 0)
return -910;
/* exact-fit boundary of the (fileLen + 1 > fileNameSz) size check:
* "scp_rk_src" is 10 chars, so 11 just fits and 10 is one too small */
WMEMSET(name, 0, sizeof(name));
ret = wolfSSH_TestScpExtractFileName("scp_rk_src", name, 11);
if (ret != WS_SUCCESS || WSTRCMP(name, "scp_rk_src") != 0)
return -911;
ret = wolfSSH_TestScpExtractFileName("scp_rk_src", name, 10);
if (ret != WS_SCP_PATH_LEN_E)
return -912;
return 0;
}
#endif /* WOLFSSH_TEST_INTERNAL && WOLFSSH_SCP && !WOLFSSH_SCP_USER_CALLBACKS */
#if defined(WOLFSSH_TEST_INTERNAL) && defined(WOLFSSH_SCP) && \
!defined(WOLFSSH_SCP_USER_CALLBACKS) && !defined(NO_FILESYSTEM)
/* ScpPushDir bounds the request path against ctx->dirName before copying it.
* The accept side stops short of WS_SUCCESS because no directory that long
* exists to open, so it asserts the guard did not fire rather than success. */
static int test_ScpPushDir(void)
{
char path[DEFAULT_SCP_FILE_NAME_SZ + 1];
int ret;
/* one byte too long for ctx->dirName: rejected before anything is opened */
WMEMSET(path, 'a', DEFAULT_SCP_FILE_NAME_SZ);
path[DEFAULT_SCP_FILE_NAME_SZ] = '\0';
ret = wolfSSH_TestScpPushDir(path);
if (ret != WS_BUFFER_E)
return -913;
/* exact fit clears the length guard and fails at the open instead */
path[DEFAULT_SCP_FILE_NAME_SZ - 1] = '\0';
ret = wolfSSH_TestScpPushDir(path);
if (ret == WS_BUFFER_E)
return -914;
/* NULL path is rejected */
ret = wolfSSH_TestScpPushDir(NULL);
if (ret != WS_BAD_ARGUMENT)
return -915;
return 0;
}
#endif /* WOLFSSH_TEST_INTERNAL && WOLFSSH_SCP &&
* !WOLFSSH_SCP_USER_CALLBACKS && !NO_FILESYSTEM */
#endif /* WOLFSSH_TEST_INTERNAL */
/* Error Code And Message Test */
static int test_Errors(void)
{
const char* errStr;
const char* unknownStr = wolfSSH_ErrorToName(1);
int result = 0;
#ifdef NO_WOLFSSH_STRINGS
/* Ensure a valid error code's string matches an invalid code's.
* The string is that error strings are not available.
*/
errStr = wolfSSH_ErrorToName(WS_BAD_ARGUMENT);
if (errStr != unknownStr)
result = -104;
#else
int i, j = 0;
/* Values that are not or no longer error codes. */
int missing[] = { -1059 };
int missingSz = (int)sizeof(missing)/sizeof(missing[0]);
/* Check that all errors have a string and it's the same through the two
* APIs. Check that the values that are not errors map to the unknown
* string. */
for (i = WS_ERROR; i >= WS_LAST_E; i--) {
errStr = wolfSSH_ErrorToName(i);
if (j < missingSz && i == missing[j]) {
j++;
if (errStr != unknownStr) {
result = -105;
break;
}
}
else {
if (errStr == unknownStr) {
result = -106;
break;
}
}
}
/* Check if the next possible value has been given a string. */
if (result == 0) {
errStr = wolfSSH_ErrorToName(i);
if (errStr != unknownStr)
return -107;
}
#endif
return result;
}
#if defined(WOLFSSH_SFTP) && defined(WOLFSSH_TEST_INTERNAL)
/* Inject a crafted SFTP NAME header declaring an on-wire payload length of
* 'wireLen' into a channel, drive wolfSSH_SFTP_DoName, and report ssh->error
* via outErr. Only the 9-byte header is needed: the NAME size bound is
* checked before the message body is read. Returns 0 on setup success. */
static int sftpDoNameInjectErr(word32 wireLen, int* outErr)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
byte hdr[LENGTH_SZ + MSG_ID_SZ + UINT32_SZ];
int result = 0;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -560;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return -561;
}
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 128, 128);
if (ch == NULL) {
result = -562;
goto done;
}
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -563;
goto done;
}
/* SFTP header: [uint32 length][byte type][uint32 reqId]. */
hdr[0] = (byte)(wireLen >> 24);
hdr[1] = (byte)(wireLen >> 16);
hdr[2] = (byte)(wireLen >> 8);
hdr[3] = (byte)(wireLen);
hdr[LENGTH_SZ] = WOLFSSH_FTP_NAME;
hdr[LENGTH_SZ + MSG_ID_SZ + 0] = 0;
hdr[LENGTH_SZ + MSG_ID_SZ + 1] = 0;
hdr[LENGTH_SZ + MSG_ID_SZ + 2] = 0;
hdr[LENGTH_SZ + MSG_ID_SZ + 3] = 0;
/* Leave reqId non-matching so an in-bound header exits at the request-id
* check without setting WS_BUFFER_E. */
ssh->reqId = 0xFFFFFFFF;
ssh->error = WS_SUCCESS;
if (wolfSSH_TestChannelPutData(ch, hdr, (word32)sizeof(hdr))
!= WS_SUCCESS) {
result = -564;
goto done;
}
*outErr = wolfSSH_TestSftpDoName(ssh);
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* Verify wolfSSH_SFTP_DoName rejects a NAME message larger than
* WOLFSSH_MAX_SFTP_NAME and accepts one at the limit. SFTP_GetHeader
* returns the wire length minus the type and request-id fields, so the
* reported maxSz is wireLen - (UINT32_SZ + MSG_ID_SZ). */
static int test_SftpDoName_sizeBound(void)
{
word32 overhead = UINT32_SZ + MSG_ID_SZ;
int err = 0;
int result;
/* maxSz = WOLFSSH_MAX_SFTP_NAME + 1 -> over the bound, rejected. */
err = WS_SUCCESS;
result = sftpDoNameInjectErr(WOLFSSH_MAX_SFTP_NAME + overhead + 1, &err);
if (result != 0)
return result;
if (err != WS_BUFFER_E)
return -570;
/* maxSz = WOLFSSH_MAX_SFTP_NAME -> at the bound, not rejected (exits at
* the request-id check instead). */
err = WS_SUCCESS;
result = sftpDoNameInjectErr(WOLFSSH_MAX_SFTP_NAME + overhead, &err);
if (result != 0)
return result;
if (err == WS_BUFFER_E)
return -571;
/* A wire length above INT_MAX is far past WOLFSSH_MAX_SFTP_NAME, so
* SFTP_GetHeader refuses it; this must be reported as a size error, not
* a silent NULL with WS_SUCCESS. */
err = WS_SUCCESS;
result = sftpDoNameInjectErr(0x80000000U + overhead, &err);
if (result != 0)
return result;
if (err != WS_BUFFER_E)
return -572;
return 0;
}
/* Inject an SFTP HANDLE reply declaring 'declHandleLen' with 'payloadSz'
* payload bytes, drive wolfSSH_SFTP_GetHandle, and report result, ssh->error,
* and the resulting handle bytes/length (last two optional). 0 on setup ok. */
static int sftpGetHandleInject(word32 payloadSz, word32 declHandleLen,
int* outRet, int* outErr, byte* outHandle, word32* outHandleSz)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
byte pkt[LENGTH_SZ + MSG_ID_SZ + UINT32_SZ
+ UINT32_SZ + WOLFSSH_MAX_HANDLE];
byte handle[WOLFSSH_MAX_HANDLE];
word32 handleSz = WOLFSSH_MAX_HANDLE;
word32 wireLen;
word32 i;
int result = 0;
if (payloadSz > UINT32_SZ + WOLFSSH_MAX_HANDLE)
return -580;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_CLIENT, NULL);
if (ctx == NULL)
return -581;
ssh = wolfSSH_new(ctx);
if (ssh == NULL) {
wolfSSH_CTX_free(ctx);
return -582;
}
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION,
(word32)sizeof(pkt), (word32)sizeof(pkt));
if (ch == NULL) {
result = -583;
goto done;
}
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -584;
goto done;
}
/* SFTP header: [uint32 length][byte type][uint32 reqId], then payload of
* [uint32 declHandleLen][handle bytes]. length counts type + reqId +
* payload. */
wireLen = MSG_ID_SZ + UINT32_SZ + payloadSz;
pkt[0] = (byte)(wireLen >> 24);
pkt[1] = (byte)(wireLen >> 16);
pkt[2] = (byte)(wireLen >> 8);
pkt[3] = (byte)(wireLen);
pkt[LENGTH_SZ] = WOLFSSH_FTP_HANDLE;
pkt[LENGTH_SZ + MSG_ID_SZ + 0] = 0;
pkt[LENGTH_SZ + MSG_ID_SZ + 1] = 0;
pkt[LENGTH_SZ + MSG_ID_SZ + 2] = 0;
pkt[LENGTH_SZ + MSG_ID_SZ + 3] = 1;
pkt[LENGTH_SZ + MSG_ID_SZ + UINT32_SZ + 0] = (byte)(declHandleLen >> 24);
pkt[LENGTH_SZ + MSG_ID_SZ + UINT32_SZ + 1] = (byte)(declHandleLen >> 16);
pkt[LENGTH_SZ + MSG_ID_SZ + UINT32_SZ + 2] = (byte)(declHandleLen >> 8);
pkt[LENGTH_SZ + MSG_ID_SZ + UINT32_SZ + 3] = (byte)(declHandleLen);
for (i = UINT32_SZ; i < payloadSz; i++) {
pkt[LENGTH_SZ + MSG_ID_SZ + UINT32_SZ + i] = (byte)i;
}
/* Match the request id so the flow reaches the handle-copy path. */
ssh->reqId = 1;
ssh->error = WS_SUCCESS;
if (wolfSSH_TestChannelPutData(ch, pkt,
LENGTH_SZ + MSG_ID_SZ + UINT32_SZ + payloadSz) != WS_SUCCESS) {
result = -585;
goto done;
}
*outRet = wolfSSH_TestSftpGetHandle(ssh, handle, &handleSz);
*outErr = ssh->error;
if (outHandleSz != NULL)
*outHandleSz = handleSz;
if (outHandle != NULL)
WMEMCPY(outHandle, handle, sizeof(handle));
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
/* Verify wolfSSH_SFTP_GetHandle bounds the declared handle length against the
* received payload: a length exceeding the payload is rejected with WS_BUFFER_E
* instead of over-reading the buffer, while an exact-fit handle is accepted. */
static int test_SftpGetHandle_sizeBound(void)
{
byte handle[WOLFSSH_MAX_HANDLE];
word32 handleSz = 0;
word32 j;
int ret = WS_SUCCESS;
int err = WS_SUCCESS;
int result;
/* payload = 4 bytes (length prefix only) but declares a 256-byte handle:
* without the payload bound this over-reads the 4-byte buffer. */
result = sftpGetHandleInject(UINT32_SZ, WOLFSSH_MAX_HANDLE, &ret, &err,
NULL, NULL);
if (result != 0)
return result;
if (ret == WS_SUCCESS)
return -590;
if (err != WS_BUFFER_E)
return -591;
/* payload = 8 bytes (4-byte prefix + 4 handle bytes) but declares a 5-byte
* handle: UINT32_SZ + 5 = 9 > 8, so the off-by-one boundary is rejected. */
ret = WS_SUCCESS;
err = WS_SUCCESS;
result = sftpGetHandleInject(UINT32_SZ + 4, 5, &ret, &err, NULL, NULL);
if (result != 0)
return result;
if (ret == WS_SUCCESS)
return -596;
if (err != WS_BUFFER_E)
return -597;
/* payload = 8 bytes carrying a 4-byte handle: exact fit, accepted. The
* injected handle bytes are (byte)(UINT32_SZ + j) for j in [0, 4). */
ret = WS_FATAL_ERROR;
err = WS_FATAL_ERROR;
result = sftpGetHandleInject(UINT32_SZ + 4, 4, &ret, &err,
handle, &handleSz);
if (result != 0)
return result;
if (ret != WS_SUCCESS)
return -592;
if (err != WS_SUCCESS)
return -593;
if (handleSz != 4)
return -594;
for (j = 0; j < handleSz; j++) {
if (handle[j] != (byte)(UINT32_SZ + j))
return -595;
}
return 0;
}
#endif /* WOLFSSH_SFTP && WOLFSSH_TEST_INTERNAL */
#ifdef WOLFSSH_TEST_PREAD_PWRITE
/* The offset arrives as two 32-bit words, low first, so 4 GiB and up lives
* only in the high word. WOLFSSH_LOCAL_PREAD_PWRITE covers the lseek port. */
static int test_PreadPwriteHighOffset(void)
{
static const char nameTemplate[] = "/wolfssh_pofstXXXXXX";
const char* tmpDir;
char tmpFile[256];
unsigned char buf[8];
unsigned int shortOffset[2];
struct stat st;
int result = 0;
int skipped = 0;
int fd;
int ret;
shortOffset[0] = 0;
shortOffset[1] = 1; /* offset of exactly 4 GiB */
/* Honor TMPDIR for the scratch file, falling back to /tmp. This test can
* leave a 4 GiB sparse file behind. */
tmpDir = getenv("TMPDIR");
if (tmpDir == NULL || tmpDir[0] == '\0') {
tmpDir = "/tmp";
}
/* WSNPRINTF truncates instead of failing, so bound the directory first */
if (WSTRLEN(tmpDir) + sizeof(nameTemplate) > sizeof(tmpFile)) {
tmpDir = "/tmp";
}
WSNPRINTF(tmpFile, sizeof(tmpFile), "%s%s", tmpDir, nameTemplate);
fd = mkstemp(tmpFile);
if (fd == -1)
return -935;
if (write(fd, "0123456789ABCDEF", 16) != 16)
result = -936;
/* A port that drops the high word rereads the file start, not EOF. */
if (result == 0) {
WMEMSET(buf, 0, sizeof(buf));
ret = wPread(fd, buf, (unsigned int)sizeof(buf), shortOffset);
if (ret != 0)
result = -937;
}
/* Extending past 4 GiB needs holes left unallocated, so probe with a
* 1 MiB one. A probe that cannot write at all is a broken environment. */
if (result == 0) {
if (lseek(fd, (off_t)1 << 20, SEEK_SET) == (off_t)-1
|| write(fd, "Z", 1) != 1 || fstat(fd, &st) != 0)
result = -941;
else if ((off_t)st.st_blocks * 512 > (off_t)1 << 19)
skipped = 1;
}
/* Only a size cap may skip this. The high word guard returns -1 without
* touching errno, so a rejected valid offset lands on the failure. */
if (result == 0 && !skipped) {
errno = 0;
ret = wPwrite(fd, (unsigned char*)"Z", 1, shortOffset);
if (ret < 0 && (errno == EFBIG || errno == ENOSPC))
skipped = 1;
else if (ret != 1)
result = -938;
}
if (result == 0 && !skipped) {
if (fstat(fd, &st) != 0)
result = -939;
else if (st.st_size != (((off_t)1 << 32) + 1))
result = -940;
}
close(fd);
(void)remove(tmpFile);
if (skipped)
printf("(large file write unsupported, read half only) ");
return result;
}
#endif /* WOLFSSH_TEST_PREAD_PWRITE */
#ifdef WOLFSSH_TEST_PREAD_PWRITE_CEILING
/* The offset arrives as two 32-bit words, low first. A port that seeks with
* a 32-bit type must reject anything the high word reaches, not wrap to the
* low word and read or write the wrong part of the file. */
static int test_PreadPwriteOffsetCeiling(void)
{
static const char contents[] = "0123456789ABCDEF";
char name[64];
unsigned char buf[8];
unsigned int shortOffset[2];
int result = 0;
WFD fd;
WSNPRINTF(name, sizeof(name), "%s/%s", CONFIG_WOLFSSH_SFTP_DEFAULT_DIR,
"pofst.bin");
fd = WOPEN(NULL, name, WOLFSSH_O_RDWR | WOLFSSH_O_CREAT, 0);
if (fd < 0)
return -942;
shortOffset[0] = 0;
shortOffset[1] = 0;
if (wPwrite(fd, (unsigned char*)contents,
(unsigned int)(sizeof(contents) - 1), shortOffset)
!= (int)(sizeof(contents) - 1)) {
result = -943;
}
/* An in-range offset must land where it points, not at the file start. */
if (result == 0) {
shortOffset[0] = 8;
WMEMSET(buf, 0, sizeof(buf));
if (wPread(fd, buf, (unsigned int)sizeof(buf), shortOffset)
!= (int)sizeof(buf)) {
result = -947;
}
else if (WMEMCMP(buf, contents + 8, sizeof(buf)) != 0) {
result = -948;
}
}
/* Exactly 4 GiB, so the offset lives only in the high word. Dropping it
* rereads the file start instead of failing the request. */
shortOffset[0] = 0;
shortOffset[1] = 1;
if (result == 0) {
WMEMSET(buf, 0, sizeof(buf));
if (wPread(fd, buf, (unsigned int)sizeof(buf), shortOffset) >= 0)
result = -944;
}
if (result == 0) {
if (wPwrite(fd, (unsigned char*)"Z", 1, shortOffset) >= 0)
result = -945;
}
if (WCLOSE(NULL, fd) != 0 && result == 0)
result = -946;
(void)WREMOVE(NULL, name);
return result;
}
#endif /* WOLFSSH_TEST_PREAD_PWRITE_CEILING */
#ifdef WOLFSSH_TEST_RESOLVE_OFFSET
/* The ports pass their own seek-type ceiling, so check the boundary against
* an explicit maxOffset rather than whatever this build resolved to. */
static int test_ResolveOffset(void)
{
unsigned int shortOffset[2];
word64 offset;
/* a low word on its own arrives unchanged */
shortOffset[0] = 0x100;
shortOffset[1] = 0;
offset = 1;
if (wResolveOffset(shortOffset, W64LIT(0x7FFFFFFF), &offset) != 0)
return -949;
if (offset != W64LIT(0x100))
return -950;
/* exactly at the ceiling is accepted */
shortOffset[0] = 0x7FFFFFFF;
if (wResolveOffset(shortOffset, W64LIT(0x7FFFFFFF), &offset) != 0)
return -951;
if (offset != W64LIT(0x7FFFFFFF))
return -952;
/* one past it is not */
shortOffset[0] = 0x80000000;
if (wResolveOffset(shortOffset, W64LIT(0x7FFFFFFF), &offset) == 0)
return -953;
/* the high word must reach the result rather than be dropped */
shortOffset[0] = 0;
shortOffset[1] = 1;
if (wResolveOffset(shortOffset, W64LIT(0x1FFFFFFFF), &offset) != 0)
return -954;
if (offset != W64LIT(0x100000000))
return -955;
/* both words together, still inside a wide ceiling */
shortOffset[0] = 0x10;
if (wResolveOffset(shortOffset, W64LIT(0x1FFFFFFFF), &offset) != 0)
return -956;
if (offset != W64LIT(0x100000010))
return -957;
/* the same offset is refused by a 32-bit ceiling */
if (wResolveOffset(shortOffset, W64LIT(0x7FFFFFFF), &offset) == 0)
return -958;
if (wResolveOffset(NULL, W64LIT(0x7FFFFFFF), &offset) == 0)
return -959;
if (wResolveOffset(shortOffset, W64LIT(0x1FFFFFFFF), NULL) == 0)
return -960;
return 0;
}
#endif /* WOLFSSH_TEST_RESOLVE_OFFSET */
#if defined(WOLFSSH_TEST_INTERNAL) && !defined(NO_WOLFSSH_SERVER)
/* IORecv mock reporting nothing to read yet, so the shutdown drain below
* completes without a live socket. */
static int ShutdownIoRecv(WOLFSSH* ssh, void* data, word32 sz, void* ctx)
{
WOLFSSH_UNUSED(ssh);
WOLFSSH_UNUSED(data);
WOLFSSH_UNUSED(sz);
WOLFSSH_UNUSED(ctx);
return WS_CBIO_ERR_WANT_READ;
}
/* wolfSSH_shutdown() has to reach the session channel when the peer numbered
* it differently than this side did, which is the normal case: each side
* picks its own channel IDs. Looking the channel up by the peer's ID while
* matching against the local ID field found nothing, and the whole teardown
* was skipped. Only the EOF and close sends leave a flag behind to check;
* the exit-status request in between does not. */
static int test_ShutdownPeerChannelId(void)
{
WOLFSSH_CTX* ctx = NULL;
WOLFSSH* ssh = NULL;
WOLFSSH_CHANNEL* ch = NULL;
word32 peerChannel;
int result = 0;
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
return -1080;
wolfSSH_SetIOSend(ctx, DiscardIoSend);
wolfSSH_SetIORecv(ctx, ShutdownIoRecv);
ssh = wolfSSH_new(ctx);
if (ssh == NULL) { result = -1081; goto done; }
/* Let the channel messages past the message filter. */
ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT;
ch = ChannelNew(ssh, ID_CHANTYPE_SESSION, 128, 64);
if (ch == NULL) { result = -1082; goto done; }
if (ChannelAppend(ssh, ch) != WS_SUCCESS) {
ChannelDelete(ch, ssh->ctx->heap);
result = -1083;
goto done;
}
peerChannel = ch->channel + 7;
ch->peerChannel = peerChannel;
ch->openConfirmed = 1;
/* The drain at the end of shutdown only sees a want-read, so the return
* is not the interesting part here; what got sent is. */
(void)wolfSSH_shutdown(ssh);
ch = ChannelFind(ssh, peerChannel, WS_CHANNEL_ID_PEER);
if (ch == NULL) { result = -1084; goto done; }
if (!ch->eofTxd) { result = -1085; goto done; }
if (!ch->closeTxd) { result = -1086; goto done; }
done:
wolfSSH_free(ssh);
wolfSSH_CTX_free(ctx);
return result;
}
#endif /* WOLFSSH_TEST_INTERNAL && !NO_WOLFSSH_SERVER */
#if defined(WOLFSSH_TEST_INTERNAL) && \
!defined(WOLFSSH_NO_MLDSA) && !defined(WOLFSSH_NO_MLDSA44) && \
defined(WOLFSSL_MLDSA_PRIVATE_KEY) && !defined(WOLFSSL_MLDSA_NO_ASN1) && \
!defined(WOLFSSL_MLDSA_NO_MAKE_KEY)
/* Make an ML-DSA-44 DER (private-only when the load can derive) and its
* public key. Caller frees *derOut. */
static int mldsa44_der_and_pub(byte** derOut, word32* derSzOut,
byte* pubOut, word32* pubSzOut)
{
MlDsaKey key;
WC_RNG rng;
byte* der;
int derSz;
#ifdef WOLFSSH_HAVE_MLDSA_DERIVE_PUB
const word32 derBufSz = WC_MLDSA_44_PRV_KEY_DER_SIZE;
#else
const word32 derBufSz = WC_MLDSA_44_BOTH_KEY_DER_SIZE;
#endif
int ret = 0;
if (wc_InitRng(&rng) != 0)
return -1;
WMEMSET(&key, 0, sizeof(key));
if (wc_MlDsaKey_Init(&key, NULL, INVALID_DEVID) != 0) {
wc_FreeRng(&rng);
return -1;
}
if (wc_MlDsaKey_SetParams(&key, WC_ML_DSA_44) != 0
|| wc_MlDsaKey_MakeKey(&key, &rng) != 0
|| wc_MlDsaKey_ExportPubRaw(&key, pubOut, pubSzOut) != 0)
ret = -1;
wc_FreeRng(&rng);
der = NULL;
if (ret == 0) {
der = (byte*)WMALLOC(derBufSz, NULL, 0);
if (der == NULL)
ret = -1;
}
if (ret != 0) {
wc_MlDsaKey_Free(&key);
return ret;
}
#ifdef WOLFSSH_HAVE_MLDSA_DERIVE_PUB
derSz = wc_MlDsaKey_PrivateKeyToDer(&key, der, derBufSz);
#else
derSz = wc_MlDsaKey_KeyToDer(&key, der, derBufSz);
#endif
wc_MlDsaKey_Free(&key);
if (derSz <= 0) {
WMEMSET(der, 0, derBufSz);
WFREE(der, NULL, 0);
return -1;
}
*derOut = der;
*derSzOut = (word32)derSz;
return 0;
}
/* Returns keyId's slot, or NULL when it has none. */
static const WOLFSSH_PVT_KEY* FindMlDsaSlot(WOLFSSH_CTX* ctx, byte keyId)
{
word32 slot;
for (slot = 0; slot < ctx->privateKeyCount; slot++) {
if (ctx->privateKey[slot].publicKeyFmt == keyId)
return &ctx->privateKey[slot];
}
return NULL;
}
#ifdef WOLFSSH_TEST_CAPTURING_ALLOCATOR
/* Nonzero when keyId's slot holds exactly the DER der. */
static int MlDsaKeyHeld(WOLFSSH_CTX* ctx, byte keyId,
const byte* der, word32 derSz)
{
const WOLFSSH_PVT_KEY* pvtKey = FindMlDsaSlot(ctx, keyId);
return pvtKey != NULL && pvtKey->key != NULL && pvtKey->keySz == derSz
&& WMEMCMP(pvtKey->key, der, derSz) == 0;
}
#endif
/* Nonzero when keyId's cached public key is exactly pub. */
static int MlDsaPubCached(WOLFSSH_CTX* ctx, byte keyId,
const byte* pub, word32 pubSz)
{
const WOLFSSH_PVT_KEY* pvtKey = FindMlDsaSlot(ctx, keyId);
return pvtKey != NULL && pvtKey->mldsaPub != NULL
&& pvtKey->mldsaPubSz == pubSz
&& WMEMCMP(pvtKey->mldsaPub, pub, pubSz) == 0;
}
#ifdef WOLFSSH_TEST_CAPTURING_ALLOCATOR
/* Counts allocations of exactly failAllocSz bytes (any size when 0) and
* fails the failAllocNth one (1-based); 0 only counts. */
static size_t failAllocSz = 0;
static int failAllocNth = 0;
static int failAllocHits = 0;
static void* FailSizeMalloc(size_t size)
{
if ((failAllocSz == 0 || size == failAllocSz) &&
++failAllocHits == failAllocNth) {
return NULL;
}
return malloc(size);
}
#endif
/* The ML-DSA slot cache is filled at load, replaced on reload, and left
* as it was when a reload's export fails.
* Return codes -710..-721 */
static int test_MlDsaHostPubKeyCache(void)
{
WOLFSSH_CTX* ctx = NULL;
byte* derA = NULL;
byte* derB = NULL;
word32 derASz = 0, derBSz = 0;
byte pubA[WOLFSSH_MLDSA_MAX_PUB_KEY_SZ];
byte pubB[WOLFSSH_MLDSA_MAX_PUB_KEY_SZ];
word32 pubASz = sizeof(pubA), pubBSz = sizeof(pubB);
int result = 0;
if (mldsa44_der_and_pub(&derA, &derASz, pubA, &pubASz) != 0)
return -710;
if (mldsa44_der_and_pub(&derB, &derBSz, pubB, &pubBSz) != 0)
result = -711;
/* The keys must differ for the reload check to mean anything. */
if (result == 0 && pubASz == pubBSz
&& WMEMCMP(pubA, pubB, pubASz) == 0)
result = -712;
if (result == 0) {
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
result = -713;
}
/* The load caches the public key on the slot. */
if (result == 0 && wolfSSH_CTX_UsePrivateKey_buffer(ctx, derA, derASz,
WOLFSSH_FORMAT_ASN1) != WS_SUCCESS)
result = -714;
if (result == 0 && !MlDsaPubCached(ctx, ID_MLDSA44, pubA, pubASz))
result = -715;
/* A reload replaces the cache. */
if (result == 0 && wolfSSH_CTX_UsePrivateKey_buffer(ctx, derB, derBSz,
WOLFSSH_FORMAT_ASN1) != WS_SUCCESS)
result = -716;
if (result == 0 && !MlDsaPubCached(ctx, ID_MLDSA44, pubB, pubBSz))
result = -717;
#ifdef WOLFSSH_TEST_CAPTURING_ALLOCATOR
/* Fail the export's allocation on a reload of key A; key B stays.
* Same-size allocations in IdentifyAsn1Key() come first; skip them. */
if (result == 0) {
wolfSSL_Malloc_cb prevMf = NULL;
wolfSSL_Free_cb prevFf = NULL;
wolfSSL_Realloc_cb prevRf = NULL;
word32 countBefore = ctx->privateKeyCount;
WS_KeySignature* sig = NULL;
int decodeHits;
int loadRet;
wolfSSL_GetAllocators(&prevMf, &prevFf, &prevRf);
failAllocSz = pubASz;
failAllocNth = 0;
failAllocHits = 0;
if (wolfSSL_SetAllocators(FailSizeMalloc, prevFf, prevRf) != 0) {
result = -718;
}
else {
loadRet = IdentifyAsn1Key(derA, derASz, 1, NULL, &sig);
decodeHits = failAllocHits;
if (sig != NULL) {
wolfSSH_KEY_clean(sig);
WFREE(sig, NULL, DYNTYPE_PRIVKEY);
}
failAllocNth = decodeHits + 1;
failAllocHits = 0;
if (loadRet != ID_MLDSA44) {
result = -719;
}
else {
loadRet = wolfSSH_CTX_UsePrivateKey_buffer(ctx, derA,
derASz, WOLFSSH_FORMAT_ASN1);
if (loadRet != WS_MEMORY_E || failAllocHits != failAllocNth)
result = -720;
else if (ctx->privateKeyCount != countBefore
|| !MlDsaPubCached(ctx, ID_MLDSA44, pubB, pubBSz)
|| !MlDsaKeyHeld(ctx, ID_MLDSA44, derB, derBSz))
result = -721;
}
wolfSSL_SetAllocators(prevMf, prevFf, prevRf);
}
}
#endif
if (ctx != NULL)
wolfSSH_CTX_free(ctx);
WMEMSET(derA, 0, derASz);
WFREE(derA, NULL, 0);
if (derB != NULL) {
WMEMSET(derB, 0, derBSz);
WFREE(derB, NULL, 0);
}
return result;
}
#if defined(WOLFSSH_TEST_CAPTURING_ALLOCATOR) && \
defined(WOLFSSH_HAVE_MLDSA_DERIVE_PUB)
/* An out-of-memory derivation of a private-only key is WS_MEMORY_E, not
* WS_CRYPTO_FAILED. Fails each allocation in turn: only the derivation's
* can yield WS_MEMORY_E after the first (the WS_KeySignature itself).
* Return codes -740..-743 */
static int test_MlDsaDeriveOutOfMemory(void)
{
wolfSSL_Malloc_cb prevMf = NULL;
wolfSSL_Free_cb prevFf = NULL;
wolfSSL_Realloc_cb prevRf = NULL;
byte* der = NULL;
word32 derSz = 0;
byte pub[WOLFSSH_MLDSA_MAX_PUB_KEY_SZ];
word32 pubSz = sizeof(pub);
WS_KeySignature* sig = NULL;
int sawMemory = 0;
int nth;
int ret = 0;
int result = 0;
if (mldsa44_der_and_pub(&der, &derSz, pub, &pubSz) != 0)
return -740;
wolfSSL_GetAllocators(&prevMf, &prevFf, &prevRf);
failAllocSz = 0;
for (nth = 2; result == 0 && nth < 1000; nth++) {
failAllocNth = nth;
failAllocHits = 0;
if (wolfSSL_SetAllocators(FailSizeMalloc, prevFf, prevRf) != 0) {
result = -741;
break;
}
ret = IdentifyAsn1Key(der, derSz, 1, NULL, &sig);
wolfSSL_SetAllocators(prevMf, prevFf, prevRf);
if (ret == WS_MEMORY_E)
sawMemory = 1;
if (ret != ID_MLDSA44 && sig != NULL)
result = -742;
if (sig != NULL) {
wolfSSH_KEY_clean(sig);
WFREE(sig, NULL, DYNTYPE_PRIVKEY);
sig = NULL;
}
if (ret == ID_MLDSA44 && failAllocHits < nth)
break; /* nothing left to fail */
}
if (result == 0 && (ret != ID_MLDSA44 || !sawMemory))
result = -743;
WMEMSET(der, 0, derSz);
WFREE(der, NULL, 0);
return result;
}
#endif
#endif /* ML-DSA-44 public key cache test */
#if defined(WOLFSSH_TEST_INTERNAL) && !defined(WOLFSSH_NO_MLDSA) && \
defined(WOLFSSH_NO_MLDSA87) && !defined(WOLFSSL_NO_ML_DSA_87) && \
defined(WOLFSSL_MLDSA_PRIVATE_KEY) && !defined(WOLFSSL_MLDSA_NO_ASN1) && \
!defined(WOLFSSL_MLDSA_NO_MAKE_KEY)
/* A private key of an ML-DSA level this build disabled is refused, with or
* without the public half in the DER: IdentifyAsn1Key() returns no key,
* wolfSSH_ReadKey_buffer() fails, and the load leaves the CTX unchanged.
* Return codes -730..-739 */
static int test_MlDsaDisabledLevelRefused(void)
{
WOLFSSH_CTX* ctx = NULL;
WS_KeySignature* sig = NULL;
MlDsaKey key;
WC_RNG rng;
byte* der = NULL;
int derSz = 0;
int privOnly;
int result = 0;
if (wc_InitRng(&rng) != 0)
return -730;
WMEMSET(&key, 0, sizeof(key));
if (wc_MlDsaKey_Init(&key, NULL, INVALID_DEVID) != 0) {
wc_FreeRng(&rng);
return -730;
}
if (wc_MlDsaKey_SetParams(&key, WC_ML_DSA_87) != 0
|| wc_MlDsaKey_MakeKey(&key, &rng) != 0)
result = -731;
wc_FreeRng(&rng);
if (result == 0) {
der = (byte*)WMALLOC(WC_MLDSA_87_BOTH_KEY_DER_SIZE, NULL, 0);
if (der == NULL)
result = -732;
}
for (privOnly = 0; result == 0 && privOnly <= 1; privOnly++) {
if (privOnly)
derSz = wc_MlDsaKey_PrivateKeyToDer(&key, der,
WC_MLDSA_87_BOTH_KEY_DER_SIZE);
else
derSz = wc_MlDsaKey_KeyToDer(&key, der,
WC_MLDSA_87_BOTH_KEY_DER_SIZE);
if (derSz <= 0)
result = -733;
/* Every IdentifyAsn1Key() caller, not just the host key load. */
if (result == 0 && IdentifyAsn1Key(der, (word32)derSz, 1, NULL,
&sig) != WS_UNIMPLEMENTED_E)
result = -734;
if (sig != NULL) {
wolfSSH_KEY_clean(sig);
WFREE(sig, NULL, DYNTYPE_PRIVKEY);
sig = NULL;
if (result == 0)
result = -735;
}
if (result == 0) {
byte* out = NULL;
word32 outSz = 0;
const byte* outType = NULL;
word32 outTypeSz = 0;
if (wolfSSH_ReadKey_buffer(der, (word32)derSz,
WOLFSSH_FORMAT_ASN1, &out, &outSz, &outType,
&outTypeSz, NULL) != WS_UNIMPLEMENTED_E)
result = -736;
if (out != NULL) {
WMEMSET(out, 0, outSz);
WFREE(out, NULL, DYNTYPE_PRIVKEY);
if (result == 0)
result = -736;
}
}
if (result == 0) {
ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
if (ctx == NULL)
result = -737;
}
if (result == 0 && wolfSSH_CTX_UsePrivateKey_buffer(ctx, der,
(word32)derSz, WOLFSSH_FORMAT_ASN1) != WS_UNIMPLEMENTED_E)
result = -738;
if (result == 0 && ctx->privateKeyCount != 0)
result = -739;
if (ctx != NULL) {
wolfSSH_CTX_free(ctx);
ctx = NULL;
}
}
wc_MlDsaKey_Free(&key);
if (der != NULL) {
WMEMSET(der, 0, WC_MLDSA_87_BOTH_KEY_DER_SIZE);
WFREE(der, NULL, 0);
}
return result;
}
#endif /* disabled ML-DSA level test */
int wolfSSH_UnitTest(int argc, char** argv)
{
int testResult = 0, unitResult = 0;
(void)argc;
(void)argv;
wolfSSH_Init();
unitResult = test_Errors();
printf("Errors: %s\n", (unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_KDF();
printf("KDF: %s\n", (unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#ifdef WOLFSSH_TEST_INTERNAL
unitResult = test_DoProtoId();
printf("DoProtoId: %s\n", (unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_GetMpint();
printf("GetMpint: %s\n", (unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#if defined(WOLFSSH_TEST_INTERNAL) && !defined(NO_WOLFSSH_SERVER)
unitResult = test_DoPacket_UnimplementedConsumesPayload();
printf("DoPacketUnimplemented: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#if defined(WOLFSSH_TEST_INTERNAL) && \
(!defined(WOLFSSH_NO_HMAC_SHA1) || \
!defined(WOLFSSH_NO_HMAC_SHA1_96) || \
!defined(WOLFSSH_NO_HMAC_SHA2_256) || \
!defined(WOLFSSH_NO_HMAC_SHA2_512))
unitResult = test_DoReceive_VerifyMacFailure();
printf("DoReceiveVerifyMac: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#if defined(WOLFSSH_TEST_INTERNAL) && !defined(WOLFSSH_NO_AES_GCM)
unitResult = test_DoReceive_AeadTagFailure();
printf("DoReceiveAeadTag: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#ifdef WOLFSSH_TEST_INTERNAL
unitResult = test_DoReceive_FirstDecryptFailWipes();
printf("DoReceiveFirstDecryptFailWipes: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#if defined(WOLFSSH_TEST_INTERNAL) && !defined(WOLFSSH_NO_AES_GCM)
unitResult = test_AeadNoncePerPacket();
printf("AeadNoncePerPacket: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#if defined(WOLFSSH_TEST_INTERNAL) && !defined(WOLFSSH_NO_AEAD)
unitResult = test_AeadIncrementExpIv();
printf("AeadIncrementExpIv: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#ifdef WOLFSSH_TEST_INTERNAL
unitResult = test_DoReceive_RejectsShortPadding();
printf("DoReceiveRejectsShortPadding: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_DoReceive_RejectsPaddingUnderflow();
printf("DoReceiveRejectsPaddingUnderflow: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#ifdef WOLFSSH_TEST_INTERNAL
unitResult = test_DoReceive_RejectsMisalignedPacket();
printf("DoReceiveRejectsMisalignedPacket: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_DoReceive_RecvZeroIsClose();
printf("DoReceiveRecvZeroIsClose: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#if defined(WOLFSSH_TEST_INTERNAL) && !defined(WOLFSSH_USER_IO) && \
!defined(WOLFSSH_TEST_BLOCK) && !defined(WOLFSSH_LWIP) && \
(defined(__linux__) || defined(__APPLE__))
unitResult = test_EmbedSend_ConnAbortedIsClose();
printf("EmbedSendConnAbortedIsClose: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#if defined(WOLFSSH_TEST_INTERNAL) && !defined(WOLFSSH_NO_AES_CTR)
unitResult = test_DoReceive_RejectsMisalignedCtr();
printf("DoReceiveRejectsMisalignedCtr: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#if defined(WOLFSSH_TEST_INTERNAL) && !defined(WOLFSSH_NO_AES_CBC) && \
!defined(WOLFSSH_NO_HMAC_SHA2_256)
unitResult = test_DoReceive_CbcRejectDiscards();
printf("DoReceiveCbcRejectDiscards: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#if defined(WOLFSSH_TEST_INTERNAL) && !defined(WOLFSSH_NO_AES_GCM)
unitResult = test_DoReceive_RejectsMisalignedAead();
printf("DoReceiveRejectsMisalignedAead: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#if defined(WOLFSSH_TEST_INTERNAL) && !defined(WOLFSSH_NO_DH_GEX_SHA256)
unitResult = test_DhGexGroupValidate();
printf("DhGexGroupValidate: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_DhGexGroupSelect();
printf("DhGexGroupSelect: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_DhGexRequestFloorClamp();
printf("DhGexRequestFloorClamp: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_DhGexGroupAcceptFloor();
printf("DhGexGroupAcceptFloor: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_DhGexServerRejectsUnsatisfiableWindow();
printf("DhGexServerRejectsUnsatisfiableWindow: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_DhGexGroupSendHashConsistency();
printf("DhGexGroupSendHashConsistency: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_DhGexGroupCacheMissFallback();
printf("DhGexGroupCacheMissFallback: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_DhGexGroup16KeyAgree();
printf("DhGexGroup16KeyAgree: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_DhGexGroupAcceptHonorsGenerator();
printf("DhGexGroupAcceptHonorsGenerator: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_DhGexGroupSendRecache();
printf("DhGexGroupSendRecache: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#ifdef WOLFSSH_TEST_INTERNAL
unitResult = test_DoUserAuthBanner();
printf("DoUserAuthBanner: %s\n", (unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_PrepareUserAuthRequestPassword();
printf("PrepareUserAuthRequestPassword: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#ifdef WOLFSSH_OSSH_CERTS
unitResult = test_KEY_clean_osshCert();
printf("KEY_clean_osshCert: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#ifdef WOLFSSH_CERTS
unitResult = test_ParseLeafCert_certCount();
printf("ParseLeafCert_certCount: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#ifndef NO_SHA256
unitResult = test_GenerateKey_multiBlock();
printf("GenerateKey_multiBlock: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
unitResult = test_DoChannelRequest();
printf("DoChannelRequest: %s\n", (unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_DoChannelSuccess();
printf("DoChannelSuccess: %s\n", (unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#ifdef TEST_TERM_REQUEST_NO_TTY
unitResult = test_SendChannelTerminalRequestNoTty();
printf("SendChannelTerminalRequestNoTty: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
unitResult = test_DoChannelFailure();
printf("DoChannelFailure: %s\n", (unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_DoChannelData_overflow();
printf("DoChannelData_overflow: %s\n", (unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_DoChannelExtendedData_overflow();
printf("DoChannelExtendedData_overflow: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_DoChannelWindowAdjust_overflow();
printf("DoChannelWindowAdjust_overflow: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_GetBoolean();
printf("GetBoolean: %s\n", (unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_GetString_zeroDestSz();
printf("GetString_zeroDestSz: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_DoChannelExtendedData_flow();
printf("DoChannelExtendedData_flow: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_ChannelReadWipesConsumed();
printf("ChannelReadWipesConsumed: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_GrowBufferCompactWipesTail();
printf("GrowBufferCompactWipesTail: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#ifndef NO_WOLFSSH_SERVER
unitResult = test_DoChannelExtendedData_unknown_type();
printf("DoChannelExtendedData_unknown_type: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_DoChannelExtendedData_keying();
printf("DoChannelExtendedData_keying: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_DoChannelExtendedData_newkeys();
printf("DoChannelExtendedData_newkeys: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif /* NO_WOLFSSH_SERVER */
unitResult = test_ChannelExtDataBufferGrowth();
printf("ChannelExtDataBufferGrowth: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#ifndef NO_WOLFSSH_SERVER
unitResult = test_ChannelExtDataCredit();
printf("ChannelExtDataCredit: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_ChannelExtDataCreditHighwater();
printf("ChannelExtDataCreditHighwater: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_ChannelWindowSharedStdoutStderr();
printf("ChannelWindowSharedStdoutStderr: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif /* NO_WOLFSSH_SERVER */
unitResult = test_ChannelSendExt();
printf("ChannelSendExt: %s\n", (unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#ifndef NO_WOLFSSH_SERVER
unitResult = test_ChannelExtDataCreditWantWrite();
printf("ChannelExtDataCreditWantWrite: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif /* NO_WOLFSSH_SERVER */
unitResult = test_ChannelCreditWindowGuards();
printf("ChannelCreditWindowGuards: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_ChannelReadExtBadArgs();
printf("ChannelReadExtBadArgs: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#ifndef NO_WOLFSSH_SERVER
unitResult = test_StreamReadExtDataOtherChannel();
printf("StreamReadExtDataOtherChannel: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_WorkerReportsExtDataChannel();
printf("WorkerReportsExtDataChannel: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_WorkerReportsExtDataChannelKeying();
printf("WorkerReportsExtDataChannelKeying: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#if defined(WOLFSSH_TEST_INTERNAL) && !defined(WOLFSSH_NO_HMAC_SHA2_256)
unitResult = test_HighwaterQuietAfterBadPacket();
printf("HighwaterQuietAfterBadPacket: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
unitResult = test_WorkerFlushesOnIdleReceive();
printf("WorkerFlushesOnIdleReceive: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_WorkerReportsOwedFlush();
printf("WorkerReportsOwedFlush: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_WorkerHardRecvErrorOutranksFlush();
printf("WorkerHardRecvErrorOutranksFlush: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_WorkerHardSendErrorOnIdleReceive();
printf("WorkerHardSendErrorOnIdleReceive: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_WorkerChanRxdSurfacesSendError();
printf("WorkerChanRxdSurfacesSendError: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_BundlePacketFailureDropsPartial();
printf("BundlePacketFailureDropsPartial: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_WorkerExtDataSurfacesSendError();
printf("WorkerExtDataSurfacesSendError: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_WorkerEofSurfacesSendError();
printf("WorkerEofSurfacesSendError: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_WorkerChanRxdSurfacesShortFlush();
printf("WorkerChanRxdSurfacesShortFlush: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_WorkerCleanReceiveReportsShortFlush();
printf("WorkerCleanReceiveReportsShortFlush: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_WorkerKeyingSurfacesSendError();
printf("WorkerKeyingSurfacesSendError: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_WorkerKeyingReportsRekey();
printf("WorkerKeyingReportsRekey: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_WorkerDiscardedFlushKeepsError();
printf("WorkerDiscardedFlushKeepsError: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_WorkerSendOobReadReported();
printf("WorkerSendOobReadReported: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_WorkerNoSendCallbackReported();
printf("WorkerNoSendCallbackReported: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_WorkerBadBufferStateReported();
printf("WorkerBadBufferStateReported: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_StreamReadExtDataHeadChannel();
printf("StreamReadExtDataHeadChannel: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_SendPendingWindowAdjustReportsWantWrite();
printf("SendPendingWindowAdjustReportsWantWrite: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_ChannelReadExtHardFailureReported();
printf("ChannelReadExtHardFailureReported: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_ChannelReadExtClearsStaleWantWrite();
printf("ChannelReadExtClearsStaleWantWrite: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_ChannelEofHalfClose();
printf("ChannelEofHalfClose: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_StreamReadEofOtherChannel();
printf("StreamReadEofOtherChannel: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_DoChannelCloseWantWrite();
printf("DoChannelCloseWantWrite: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_DoChannelCloseFlushesReply();
printf("DoChannelCloseFlushesReply: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_DoChannelCloseHardFlushKeepsClose();
printf("DoChannelCloseHardFlushKeepsClose: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#ifdef WOLFSSH_SFTP
unitResult = test_SftpReadEofNoPoll();
printf("SftpReadEofNoPoll: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
unitResult = test_AcceptSurvivesChannelEof();
printf("AcceptSurvivesChannelEof: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#ifndef NO_WOLFSSH_CLIENT
unitResult = test_ConnectSurvivesChannelEof();
printf("ConnectSurvivesChannelEof: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
unitResult = test_WorkerReportsEofChannelKeying();
printf("WorkerReportsEofChannelKeying: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_StreamReadHeadRemoved();
printf("StreamReadHeadRemoved: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#ifndef NO_WOLFSSH_CLIENT
unitResult = test_StreamReadHeadOpenFailed();
printf("StreamReadHeadOpenFailed: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif /* NO_WOLFSSH_CLIENT */
unitResult = test_ChannelExitKeepsChannel();
printf("ChannelExitKeepsChannel: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif /* NO_WOLFSSH_SERVER */
#ifndef NO_WOLFSSH_CLIENT
unitResult = test_ShutdownReportsWorkerOwedFlush();
printf("ShutdownReportsWorkerOwedFlush: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#ifndef NO_WOLFSSH_CLIENT
unitResult = test_HighwaterRekeyKeepsError();
printf("HighwaterRekeyKeepsError: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_TriggerKeyExchangeKeepsError();
printf("TriggerKeyExchangeKeepsError: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_KexInitSendAwayGatesKeying();
printf("KexInitSendAwayGatesKeying: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#ifndef NO_WOLFSSH_CLIENT
unitResult = test_SendEofApi();
printf("SendEofApi: %s\n", (unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif /* NO_WOLFSSH_CLIENT */
#ifndef NO_WOLFSSH_CLIENT
unitResult = test_SendEofUnconfirmedChannel();
printf("SendEofUnconfirmedChannel: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif /* NO_WOLFSSH_CLIENT */
#ifndef NO_WOLFSSH_SERVER
unitResult = test_DoChannelCloseUnconfirmedChannel();
printf("DoChannelCloseUnconfirmedChannel: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif /* NO_WOLFSSH_SERVER */
#ifndef NO_WOLFSSH_CLIENT
unitResult = test_SendEofAfterDisconnect();
printf("SendEofAfterDisconnect: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif /* NO_WOLFSSH_CLIENT */
#if !defined(NO_WOLFSSH_CLIENT) && defined(HAVE_SOCKETPAIR) && \
defined(WSHUTDOWN)
unitResult = test_DrainPeerHangsUp();
printf("DrainPeerHangsUp: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_DrainRetriesShortSend();
printf("DrainRetriesShortSend: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_DrainPeerAlreadyDisconnected();
printf("DrainPeerAlreadyDisconnected: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_DrainHalfCloseOnly();
printf("DrainHalfCloseOnly: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_DrainFlushesQueuedDisconnect();
printf("DrainFlushesQueuedDisconnect: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_DrainPeerGone();
printf("DrainPeerGone: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_DrainFailedRekey();
printf("DrainFailedRekey: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_DrainDisconnectMidRekey();
printf("DrainDisconnectMidRekey: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_WaitForChannelCloseSessionOver();
printf("WaitForChannelCloseSessionOver: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#if defined(WOLFSSH_TEST_INTERNAL) && \
(defined(WOLFSSH_TERM) || defined(WOLFSSH_SHELL))
unitResult = test_WaitForChannelCloseKeepsExitStatus();
printf("WaitForChannelCloseKeepsExitStatus: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#endif
#ifndef NO_WOLFSSH_CLIENT
unitResult = test_SendChannelEofWantWrite();
printf("SendChannelEofWantWrite: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif /* NO_WOLFSSH_CLIENT */
#ifndef NO_WOLFSSH_CLIENT
unitResult = test_SendChannelEofSendFails();
printf("SendChannelEofSendFails: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif /* NO_WOLFSSH_CLIENT */
#ifndef NO_WOLFSSH_CLIENT
unitResult = test_SendChannelEofConnReset();
printf("SendChannelEofConnReset: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif /* NO_WOLFSSH_CLIENT */
#ifndef NO_WOLFSSH_SERVER
unitResult = test_ChannelEofCallback();
printf("ChannelEofCallback: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_ShutdownOwedWriteAfterEofDisconnect();
printf("ShutdownOwedWriteAfterEofDisconnect: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_ShutdownHardEofDisconnectSurfacesOnRetry();
printf("ShutdownHardEofDisconnectSurfacesOnRetry: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif /* NO_WOLFSSH_SERVER */
#ifndef NO_WOLFSSH_SERVER
unitResult = test_WorkerReportsEofChannelId();
printf("WorkerReportsEofChannelId: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif /* NO_WOLFSSH_SERVER */
#ifndef NO_WOLFSSH_CLIENT
unitResult = test_StreamSendEofRekeying();
printf("StreamSendEofRekeying: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif /* NO_WOLFSSH_CLIENT */
#ifndef NO_WOLFSSH_CLIENT
unitResult = test_ShutdownAbsorbsEof();
printf("ShutdownAbsorbsEof: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif /* NO_WOLFSSH_CLIENT */
#ifndef NO_WOLFSSH_CLIENT
unitResult = test_ChannelExitWantWrite();
printf("ChannelExitWantWrite: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif /* NO_WOLFSSH_CLIENT */
unitResult = test_SendChannelData_eofTxd();
printf("SendChannelData_eofTxd: %s\n", (unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_SendChannelData_zeroPeerMaxPacket();
printf("SendChannelData_zeroPeerMaxPacket: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#ifndef NO_WOLFSSH_SERVER
unitResult = test_stream_read_deferredWindowAdjust();
printf("stream_read_deferredWindowAdjust: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_ChannelIdRead_deferredWindowAdjust();
printf("ChannelIdRead_deferredWindowAdjust: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_ChannelIdPeek();
printf("ChannelIdPeek: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif /* NO_WOLFSSH_SERVER */
unitResult = test_CreateMpint();
printf("CreateMpint: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_BuildNameList_emptySrc();
printf("BuildNameList_emptySrc: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#ifdef WOLFSSH_SFTP
unitResult = test_SftpDoName_sizeBound();
printf("SftpDoName_sizeBound: %s\n", (unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_SftpGetHandle_sizeBound();
printf("SftpGetHandle_sizeBound: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#if !defined(WOLFSSH_NO_RSA)
unitResult = test_RsaVerify_BadDigest();
printf("RsaVerify_BadDigest: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_RsaVerify_BadPadding();
printf("RsaVerify_BadPadding: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_RsaVerify_SigRange();
printf("RsaVerify_SigRange: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#if !defined(WOLFSSH_NO_RSA) && !defined(WOLFSSH_NO_SSH_RSA_SHA1)
unitResult = test_DoUserAuthRequestRsa();
printf("DoUserAuthRequestRsa: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_ParseRSAPubKey();
printf("ParseRSAPubKey: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#ifdef WOLFSSH_CERTS
unitResult = test_DoUserAuthRequestRsaCert();
printf("DoUserAuthRequestRsaCert: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#endif
#if !defined(WOLFSSH_NO_ECDSA_SHA2_NISTP256)
unitResult = test_ParseECCPubKey();
printf("ParseECCPubKey: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#if defined(WOLFSSH_CERTS) && !defined(NO_FILESYSTEM)
unitResult = test_ParseECCPubKeyCert();
/* 1 means the ./keys certs were unreadable or unverifiable here */
printf("ParseECCPubKeyCert: %s\n", (unitResult == 0 ? "SUCCESS" :
unitResult > 0 ? "SKIPPED" : "FAILED"));
testResult = testResult || (unitResult < 0);
unitResult = test_DoUserAuthRequestEccCert();
printf("DoUserAuthRequestEccCert: %s\n", (unitResult == 0 ? "SUCCESS" :
unitResult > 0 ? "SKIPPED" : "FAILED"));
testResult = testResult || (unitResult < 0);
#endif
#endif
#if !defined(WOLFSSH_NO_ED25519) && defined(HAVE_ED25519) && \
defined(HAVE_ED25519_SIGN) && defined(HAVE_ED25519_VERIFY) && \
defined(WOLFSSL_ED25519_STREAMING_VERIFY)
unitResult = test_DoUserAuthRequestEd25519();
printf("DoUserAuthRequestEd25519: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_ParseEd25519PubKey();
printf("ParseEd25519PubKey: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#ifndef WOLFSSH_NO_MLDSA
unitResult = test_DoUserAuthRequestMlDsa();
printf("DoUserAuthRequestMlDsa: %s (result=%d)\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"), unitResult);
testResult = testResult || (unitResult != 0);
#ifndef WOLFSSH_NO_MLDSA44
unitResult = test_ParseMlDsaPubKey();
printf("ParseMlDsaPubKey: %s (result=%d)\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"), unitResult);
testResult = testResult || (unitResult != 0);
#endif
#ifndef WOLFSSH_NO_MLDSA_COMPOSITES
unitResult = test_DoUserAuthRequestMlDsaComposite();
printf("DoUserAuthRequestMlDsaComposite: %s (result=%d)\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"), unitResult);
testResult = testResult || (unitResult != 0);
unitResult = test_SignHMlDsaComposite();
printf("SignHMlDsaComposite: %s (result=%d)\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"), unitResult);
testResult = testResult || (unitResult != 0);
unitResult = test_PrepareUserAuthRequestMlDsaComposite_OpenSshEnvelope();
printf("PrepareUserAuthRequestMlDsaComposite_OpenSshEnvelope: "
"%s (result=%d)\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"), unitResult);
testResult = testResult || (unitResult != 0);
#endif /* WOLFSSH_NO_MLDSA_COMPOSITES */
#ifdef WOLFSSH_KEYGEN
#ifndef WOLFSSH_NO_MLDSA_COMPOSITES
unitResult = test_BuildUserAuthRequestMlDsaComposite();
printf("BuildUserAuthRequestMlDsaComposite: %s (result=%d)\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"), unitResult);
testResult = testResult || (unitResult != 0);
#endif /* WOLFSSH_NO_MLDSA_COMPOSITES */
unitResult = test_PrepareUserAuthRequestMlDsa();
printf("PrepareUserAuthRequestMlDsa: %s (result=%d)\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"), unitResult);
testResult = testResult || (unitResult != 0);
#ifdef WOLFSSH_CERTS
unitResult = test_PrepareUserAuthRequestMlDsaCert();
printf("PrepareUserAuthRequestMlDsaCert: %s (result=%d)\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"), unitResult);
testResult = testResult || (unitResult != 0);
#endif /* WOLFSSH_CERTS */
#endif /* WOLFSSH_KEYGEN */
unitResult = test_BuildUserAuthRequestMlDsa();
printf("BuildUserAuthRequestMlDsa: %s (result=%d)\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"), unitResult);
testResult = testResult || (unitResult != 0);
#endif
unitResult = test_ChannelPutData();
printf("ChannelPutData: %s\n", (unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#if defined(WOLFSSH_TEST_INTERNAL) && defined(WOLFSSH_SCP)
unitResult = test_ScpGetFileMode();
printf("ScpGetFileMode: %s\n", (unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_ScpGetFileSize();
printf("ScpGetFileSize: %s\n", (unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_ScpGetTimestamp();
printf("ScpGetTimestamp: %s\n", (unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_ScpGetFileName();
printf("ScpGetFileName: %s\n", (unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#ifndef NO_WOLFSSH_SERVER
unitResult = test_ScpParseCommand();
printf("ScpParseCommand: %s (result=%d)\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"), unitResult);
testResult = testResult || (unitResult != 0);
#endif
unitResult = test_ScpReceiveMessageAfterWarning();
printf("ScpReceiveMessageAfterWarning: %s (result=%d)\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"), unitResult);
testResult = testResult || (unitResult != 0);
#ifndef NO_WOLFSSH_CLIENT
unitResult = test_ScpMakeCmd();
printf("ScpMakeCmd: %s (result=%d)\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"), unitResult);
testResult = testResult || (unitResult != 0);
#endif
unitResult = test_ScpSinkEmptyFileAfterSource();
printf("ScpSinkEmptyFileAfterSource: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
unitResult = test_MsgHighwater();
printf("MsgHighwater: %s\n", (unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_ByteHighwater();
printf("ByteHighwater: %s\n", (unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_DoUserAuthRequest_serviceName();
printf("DoUserAuthRequest_serviceName: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#ifdef WOLFSSH_KEYBOARD_INTERACTIVE
unitResult = test_DoUserAuthRequest_badServiceClearsKb();
printf("DoUserAuthRequest_badServiceClearsKb: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_DoUserAuthInfoResponse_unsolicited();
printf("DoUserAuthInfoResponse_unsolicited: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
unitResult = test_DoUserAuthRequest_rejectsPasswordChange();
printf("DoUserAuthRequest_rejectsPasswordChange: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_SendUserAuthFailure_emptyMethods();
printf("SendUserAuthFailure_emptyMethods: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_UserAuthRejectedSendsFailure();
printf("UserAuthRejectedSendsFailure: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#ifdef WOLFSSH_ALLOW_NONE_CIPHER
unitResult = test_UserAuthNoneCipherRefusesSecrets();
printf("UserAuthNoneCipherRefusesSecrets: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#ifdef WOLFSSH_KEYBOARD_INTERACTIVE
unitResult = test_UserAuthNoneCipherRekeyMidKb();
printf("UserAuthNoneCipherRekeyMidKb: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#endif
#if !defined(WOLFSSH_NO_ECDSA_SHA2_NISTP256) && \
!defined(WOLFSSH_NO_ECDSA_SHA2_NISTP384)
unitResult = test_EccUserAuthCurveMismatch();
printf("EccUserAuthCurveMismatch: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
unitResult = test_MaxAuthAttempts();
printf("MaxAuthAttempts: %s\n", (unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_IdentifyAsn1Key();
printf("IdentifyAsn1Key: %s\n", (unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#if defined(WOLFSSH_TEST_INTERNAL) && \
!defined(WOLFSSH_NO_MLDSA) && !defined(WOLFSSH_NO_MLDSA44) && \
defined(WOLFSSL_MLDSA_PRIVATE_KEY) && !defined(WOLFSSL_MLDSA_NO_ASN1) && \
!defined(WOLFSSL_MLDSA_NO_MAKE_KEY)
unitResult = test_MlDsaHostPubKeyCache();
printf("MlDsaHostPubKeyCache: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#if defined(WOLFSSH_TEST_CAPTURING_ALLOCATOR) && \
defined(WOLFSSH_HAVE_MLDSA_DERIVE_PUB)
unitResult = test_MlDsaDeriveOutOfMemory();
printf("MlDsaDeriveOutOfMemory: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#endif
#if defined(WOLFSSH_TEST_INTERNAL) && !defined(WOLFSSH_NO_MLDSA) && \
defined(WOLFSSH_NO_MLDSA87) && !defined(WOLFSSL_NO_ML_DSA_87) && \
defined(WOLFSSL_MLDSA_PRIVATE_KEY) && !defined(WOLFSSL_MLDSA_NO_ASN1) && \
!defined(WOLFSSL_MLDSA_NO_MAKE_KEY)
unitResult = test_MlDsaDisabledLevelRefused();
printf("MlDsaDisabledLevelRefused: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
unitResult = test_ReadPublicKeyAsn1();
printf("ReadPublicKeyAsn1: %s\n", (unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#ifdef WOLFSSH_SFTP
#ifndef NO_WOLFSSH_SERVER
unitResult = test_SftpRecvSizeBound();
printf("SftpRecvSizeBound: %s\n", (unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_SftpRecvSizeBoundIntegration();
printf("SftpRecvSizeBoundIntegration: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_SftpRecvSizeBoundAccept();
printf("SftpRecvSizeBoundAccept: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_SftpExtendedUnsupported();
printf("SftpExtendedUnsupported: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif /* NO_WOLFSSH_SERVER */
#ifndef NO_WOLFSSH_CLIENT
unitResult = test_SftpClientRecvInitSplit();
printf("SftpClientRecvInitSplit: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_SftpClientRecvInitVersion();
printf("SftpClientRecvInitVersion: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#ifdef WOLFSSH_TEST_SFTP_PUT
unitResult = test_SftpPutReadError();
printf("SftpPutReadError: %s\n", unitResult == 0 ? "SUCCESS" : "FAILED");
testResult = testResult || unitResult;
unitResult = test_SftpGetCleanup();
printf("SftpGetCleanup: %s\n", unitResult == 0 ? "SUCCESS" : "FAILED");
testResult = testResult || unitResult;
unitResult = test_SftpGetFreeClosesLocal();
printf("SftpGetFreeClosesLocal: %s\n",
unitResult == 0 ? "SUCCESS" : "FAILED");
testResult = testResult || unitResult;
unitResult = test_SftpPutFreeClosesLocal();
printf("SftpPutFreeClosesLocal: %s\n",
unitResult == 0 ? "SUCCESS" : "FAILED");
testResult = testResult || unitResult;
unitResult = test_SftpStatBadAttrs();
printf("SftpStatBadAttrs: %s\n", unitResult == 0 ? "SUCCESS" : "FAILED");
testResult = testResult || unitResult;
unitResult = test_SftpRmdirStatus();
printf("SftpRmdirStatus: %s\n", unitResult == 0 ? "SUCCESS" : "FAILED");
testResult = testResult || unitResult;
#ifdef WOLFSSH_TEST_CAPTURING_ALLOCATOR
unitResult = test_SftpClientStateTeardown();
printf("SftpClientStateTeardown: %s\n",
unitResult == 0 ? "SUCCESS" : "FAILED");
testResult = testResult || unitResult;
#endif
unitResult = test_SftpClientPutWriteStatusFail();
printf("SftpClientPutWriteStatusFail: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_SftpReplyId();
printf("SftpReplyId: %s\n", unitResult == 0 ? "SUCCESS" : "FAILED");
testResult = testResult || unitResult;
#endif
unitResult = test_SftpSendReadPacketSplit();
printf("SftpSendReadPacketSplit: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_SftpSendReadPacketOverflow();
printf("SftpSendReadPacketOverflow: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#endif
#if defined(WOLFSSH_SCP) && !defined(WOLFSSH_SCP_USER_CALLBACKS) && \
!defined(NO_FILESYSTEM) && !defined(WOLFSSL_NUCLEUS) && \
!defined(_WIN32) && !defined(WOLFSSH_ZEPHYR)
unitResult = test_ScpRecvCallback_EndDirDepthGuard();
printf("ScpRecvCallback_EndDirDepthGuard: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_ScpRecvCallback_NewDirEnterFail();
printf("ScpRecvCallback_NewDirEnterFail: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_ScpRecvCallback_SymlinkGuard();
printf("ScpRecvCallback_SymlinkGuard: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_ScpRecvCallback_SessionPath();
printf("ScpRecvCallback_SessionPath: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_ScpRecvCallback_Timestamp();
printf("ScpRecvCallback_Timestamp: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#if defined(HAVE_UTIMENSAT) && defined(WOLFSSH_HAVE_SYMLINK)
unitResult = test_ScpTimestamp_NoFollow();
printf("ScpTimestamp_NoFollow: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#endif
#if defined(WOLFSSH_TEST_INTERNAL) && defined(WOLFSSH_SCP) && \
!defined(WOLFSSH_SCP_USER_CALLBACKS)
unitResult = test_ScpExtractFileName();
printf("ScpExtractFileName: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#if defined(WOLFSSH_TEST_INTERNAL) && defined(WOLFSSH_SCP) && \
!defined(WOLFSSH_SCP_USER_CALLBACKS) && !defined(NO_FILESYSTEM)
unitResult = test_ScpPushDir();
printf("ScpPushDir: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#if defined(WOLFSSH_SCP) && !defined(WOLFSSH_SCP_USER_CALLBACKS) && \
defined(NO_FILESYSTEM)
unitResult = test_ScpSendCallback_ExactFitBuffer();
printf("ScpSendCallback_ExactFitBuffer: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_ScpSendCallback_FileNameAndTimes();
printf("ScpSendCallback_FileNameAndTimes: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_ScpRecvCallback_TwoFiles();
printf("ScpRecvCallback_TwoFiles: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_ScpRecvCallback_Oversize();
printf("ScpRecvCallback_Oversize: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#ifdef WOLFSSH_TEST_CAPTURING_ALLOCATOR
unitResult = test_SshResourceFree_zeroesSecrets();
printf("SshResourceFree_zeroesSecrets: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_ChannelDelete_zeroesCommand();
printf("ChannelDelete_zeroesCommand: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_ChannelName_zeroedOnFree();
printf("ChannelName_zeroedOnFree: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#if defined(WOLFSSH_TEST_INTERNAL) && defined(WOLFSSH_SCP)
unitResult = test_ScpFileBuffer_zeroedOnFree();
printf("ScpFileBuffer_zeroedOnFree: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#ifdef WOLFSSH_TEST_INTERNAL
unitResult = test_DoChannelRequest_zeroesRefusedCommand();
printf("DoChannelRequest_zeroesRefusedCommand: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#endif
#ifndef WOLFSSH_NO_DH
unitResult = test_KeyAgreeDh_client_zeroesEphemeralPrivKey();
printf("KeyAgreeDh_client_zeroesEphemeralPrivKey: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_KeyAgreeDh_server_rejectsBadPeerPublic();
printf("KeyAgreeDh_server_rejectsBadPeerPublic: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_KeyAgreeDh_client_rejectsBadPeerPublic();
printf("KeyAgreeDh_client_rejectsBadPeerPublic: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#if defined(WOLFSSH_SMALL_STACK) && defined(WOLFSSH_TEST_CAPTURING_ALLOCATOR)
unitResult = test_KeyAgreeDh_server_zeroesEphemeralPrivKey();
printf("KeyAgreeDh_server_zeroesEphemeralPrivKey: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
unitResult = test_KeyAgreeDh_server_rejectsOutOfRangePeer();
printf("KeyAgreeDh_server_rejectsOutOfRangePeer: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#ifdef HAVE_FFDHE_2048
unitResult = test_KeyAgreeDh_client_rejectsOutOfRangePeer();
printf("KeyAgreeDh_client_rejectsOutOfRangePeer: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
unitResult = test_KeyAgreeDh_rejectsNegativePeer();
printf("KeyAgreeDh_rejectsNegativePeer: %s (result=%d)\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"), unitResult);
testResult = testResult || unitResult;
#endif /* !WOLFSSH_NO_DH */
#if !defined(WOLFSSH_NO_ECDH) && !defined(WOLFSSH_NO_ECDH_SHA2_NISTP256)
unitResult = test_KeyAgreeEcdh_server_rejectsOffCurvePoint();
printf("KeyAgreeEcdh_server_rejectsOffCurvePoint: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_KeyAgreeEcdh_client_rejectsOffCurvePoint();
printf("KeyAgreeEcdh_client_rejectsOffCurvePoint: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif /* !WOLFSSH_NO_ECDH && !WOLFSSH_NO_ECDH_SHA2_NISTP256 */
#if defined(WOLFSSH_SMALL_STACK) && \
defined(WOLFSSH_TEST_CAPTURING_ALLOCATOR) && \
((!defined(WOLFSSH_NO_ECDH) && \
!defined(WOLFSSH_NO_ECDH_SHA2_NISTP256)) || \
!defined(WOLFSSH_NO_CURVE25519_SHA256))
unitResult = test_KeyAgree_server_allocFailCleanup();
printf("KeyAgree_server_allocFailCleanup: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#if !defined(WOLFSSH_NO_NISTP256_MLKEM768_SHA256) || \
!defined(WOLFSSH_NO_NISTP384_MLKEM1024_SHA384) || \
!defined(WOLFSSH_NO_CURVE25519_MLKEM768_SHA256)
unitResult = test_KeyAgreeEcdhMlKem_client();
printf("KeyAgreeEcdhMlKem_client: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#endif
#ifdef WOLFSSH_TEST_SET_CERTMAN
unitResult = test_SetCertManager();
/* 1 means the argument checks passed but the root-CA half was skipped */
printf("SetCertManager: %s\n", (unitResult == 0 ? "SUCCESS" :
unitResult > 0 ? "SKIPPED (root CA checks)" : "FAILED"));
testResult = testResult || (unitResult < 0);
#endif
#ifdef WOLFSSH_WINDOWS_CERT_STORE
unitResult = test_ParseCertStoreSpec();
printf("ParseCertStoreSpec: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_UsePrivateKeyFromStoreArgs();
printf("UsePrivateKeyFromStoreArgs: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#ifdef WOLFSSH_TEST_CERTMAN_PROMOTE
unitResult = test_CertMan_NoPromoteNonCaIntermediate();
printf("CertMan_NoPromoteNonCaIntermediate: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
unitResult = test_CertMan_PromoteValidCaIntermediate();
printf("CertMan_PromoteValidCaIntermediate: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#ifdef WOLFSSL_CERT_EXT
unitResult = test_CertMan_IssuerWithoutSkid();
printf("CertMan_IssuerWithoutSkid: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#ifdef WOLFSSH_TEST_SET_CERTMAN
unitResult = test_CertMan_TrustedRootNotRetagged();
printf("CertMan_TrustedRootNotRetagged: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#ifdef WOLFSSH_CERTMAN_CHAIN_CA
unitResult = test_CertMan_BadSigChildChainCA();
printf("CertMan_BadSigChildChainCA: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#endif
#if defined(WOLFSSH_TEST_SET_CERTMAN) && defined(WOLFSSL_CERT_EXT) && \
defined(WOLFSSH_CERTMAN_CHAIN_CA) && \
!defined(WOLFSSL_STATIC_MEMORY) && !defined(WOLFSSL_DEBUG_MEMORY)
unitResult = test_CertMan_AllocFailKeepsRoot();
printf("CertMan_AllocFailKeepsRoot: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#ifdef WOLFSSL_CERT_EXT
unitResult = test_CertMan_LeafKeyUsage();
printf("CertMan_LeafKeyUsage: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#if !defined(WOLFSSH_NO_FPKI) && defined(WOLFSSL_SUBJ_DIR_ATTR)
unitResult = test_CertMan_ProfileLeafNoSigner();
printf("CertMan_ProfileLeafNoSigner: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#endif
#endif
#ifdef WOLFSSH_KEYGEN
#ifndef WOLFSSH_NO_RSA
unitResult = test_RsaKeyGen();
printf("RsaKeyGen: %s\n", (unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#ifndef WOLFSSH_NO_ECDSA
unitResult = test_EcdsaKeyGen();
printf("EcdsaKeyGen: %s\n", (unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#if !defined(WOLFSSH_NO_ED25519) && defined(HAVE_ED25519) && \
defined(HAVE_ED25519_MAKE_KEY) && defined(HAVE_ED25519_KEY_EXPORT)
unitResult = test_Ed25519KeyGen();
printf("Ed25519KeyGen: %s\n", (unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#ifndef WOLFSSH_NO_MLDSA
unitResult = test_MlDsaKeyGen();
printf("MlDsaKeyGen: %s\n", (unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#ifndef WOLFSSH_NO_MLDSA_COMPOSITES
unitResult = test_MlDsaCompositeKeyGen();
printf("MlDsaCompositeKeyGen: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#else
unitResult = test_MlDsaCompositesDisabled();
printf("MlDsaCompositesDisabled: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif /* WOLFSSH_NO_MLDSA_COMPOSITES */
#endif
#ifdef WOLFSSH_NO_MLDSA
unitResult = test_MlDsaLevelsDisabled();
printf("MlDsaLevelsDisabled: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#endif /* WOLFSSH_KEYGEN */
unitResult = test_OpenSshPemNegative();
printf("OpenSshPemNegative: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#ifdef WOLFSSH_TEST_PREAD_PWRITE
unitResult = test_PreadPwriteHighOffset();
printf("PreadPwriteHighOffset: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#ifdef WOLFSSH_TEST_PREAD_PWRITE_CEILING
unitResult = test_PreadPwriteOffsetCeiling();
printf("PreadPwriteOffsetCeiling: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#ifdef WOLFSSH_TEST_RESOLVE_OFFSET
unitResult = test_ResolveOffset();
printf("ResolveOffset: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#ifndef WOLFSSH_NO_ECDSA_SHA2_NISTP256
unitResult = test_OpenSshFormatNonCompositeRejected();
printf("OpenSshFormatNonCompositeRejected: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#ifdef WOLFSSH_TEST_INTERNAL
unitResult = test_IdentifyOpenSshKeyUnknownName();
printf("IdentifyOpenSshKeyUnknownName: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#if defined(WOLFSSH_TEST_INTERNAL) && !defined(WOLFSSH_NO_ED25519)
unitResult = test_OpenSshKeyEd25519Parse();
printf("OpenSshKeyEd25519Parse: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
#if defined(WOLFSSH_TEST_INTERNAL) && !defined(NO_WOLFSSH_SERVER)
unitResult = test_ShutdownPeerChannelId();
printf("ShutdownPeerChannelId: %s\n",
(unitResult == 0 ? "SUCCESS" : "FAILED"));
testResult = testResult || unitResult;
#endif
wolfSSH_Cleanup();
return (testResult ? 1 : 0);
}
#ifndef NO_UNITTEST_MAIN_DRIVER
int main(int argc, char** argv)
{
return wolfSSH_UnitTest(argc, argv);
}
#endif