diff --git a/src/internal.c b/src/internal.c index b2153e323..9f877f27f 100644 --- a/src/internal.c +++ b/src/internal.c @@ -1781,6 +1781,7 @@ WOLFSSH* SshInit(WOLFSSH* ssh, WOLFSSH_CTX* ctx) ssh->highwaterMark = ctx->highwaterMark; ssh->msgHighwaterMark = ctx->msgHighwaterMark; ssh->maxAuthAttempts = ctx->maxAuthAttempts; + ssh->appChannels = ctx->appChannels; ssh->highwaterCtx = (void*)ssh; ssh->reqSuccessCtx = (void*)ssh; ssh->fs = NULL; @@ -13080,7 +13081,7 @@ static int DoChannelRequest(WOLFSSH* ssh, word32 typeSz; char type[32]; byte wantReply; - int ret, rej = 0; + int ret, rej = 0, sessionReq = 0; WLOG(WS_LOG_DEBUG, "Entering DoChannelRequest()"); @@ -13130,6 +13131,10 @@ static int DoChannelRequest(WOLFSSH* ssh, if (ssh->ctx->channelReqShellCb) { rej = ssh->ctx->channelReqShellCb(channel, ssh->channelReqCtx); } + else { + rej = ssh->appChannels; + } + sessionReq = 1; ssh->clientState = CLIENT_DONE; } else if (ChannelRequestIs(type, typeSz, "exec")) { @@ -13139,6 +13144,10 @@ static int DoChannelRequest(WOLFSSH* ssh, if (ssh->ctx->channelReqExecCb) { rej = ssh->ctx->channelReqExecCb(channel, ssh->channelReqCtx); } + else { + rej = ssh->appChannels; + } + sessionReq = 1; ssh->clientState = CLIENT_DONE; WLOG(WS_LOG_DEBUG, " command = %s", channel->command); @@ -13150,6 +13159,10 @@ static int DoChannelRequest(WOLFSSH* ssh, if (ssh->ctx->channelReqSubsysCb) { rej = ssh->ctx->channelReqSubsysCb(channel, ssh->channelReqCtx); } + else { + rej = ssh->appChannels; + } + sessionReq = 1; ssh->clientState = CLIENT_DONE; WLOG(WS_LOG_DEBUG, " subsystem = %s", channel->command); @@ -13287,11 +13300,25 @@ static int DoChannelRequest(WOLFSSH* ssh, *idx = len; } + /* Record the answer, not the ask: sessionType and command are set before + * the reject decision and stay set on a refusal, so they cannot say + * whether the session was granted. Set even without a wantReply, which + * changes only whether the peer is told. + * + * Look the channel up again rather than reusing the pointer from + * before the callback. A callback may close its own channel, and + * wolfSSH_ChannelFree() frees it, so the old pointer can be dead. */ + if (sessionReq) { + channel = ChannelFind(ssh, channelId, WS_CHANNEL_ID_SELF); + if (channel != NULL) + channel->sessionGranted = (ret == WS_SUCCESS && !rej); + } + if (wantReply) { int replyRet; if (rej) { - WLOG(WS_LOG_DEBUG, "Callback rejecting channel request."); + WLOG(WS_LOG_DEBUG, "Rejecting channel request."); } replyRet = SendChannelSuccess(ssh, channelId, (ret == WS_SUCCESS && !rej)); diff --git a/src/ssh.c b/src/ssh.c index 83f41d762..f27d1c1b0 100644 --- a/src/ssh.c +++ b/src/ssh.c @@ -624,6 +624,8 @@ const char acceptState[] = "accept state: %s"; int wolfSSH_accept(WOLFSSH* ssh) { + byte stopState; + WLOG(WS_LOG_DEBUG, "Entering wolfSSH_accept()"); if (ssh == NULL) @@ -643,6 +645,15 @@ int wolfSSH_accept(WOLFSSH* ssh) return WS_INVALID_STATE_E; } + /* In application-driven mode the state machine stops as soon as the + * user is authenticated; everything past that is the application's. + * Only stop there if the session has not already gone by: the loop + * below tests the stop state exactly, so a state it has stepped over + * would never terminate it. */ + stopState = (ssh->appChannels + && ssh->acceptState <= ACCEPT_SERVER_USERAUTH_SENT) ? + ACCEPT_SERVER_USERAUTH_SENT : ACCEPT_CLIENT_SESSION_ESTABLISHED; + /* check if data pending to be sent */ if (ssh->outputBuffer.length > 0 && ssh->acceptState < ACCEPT_CLIENT_SESSION_ESTABLISHED) { @@ -654,7 +665,11 @@ int wolfSSH_accept(WOLFSSH* ssh) ssh->acceptState != ACCEPT_SERVER_USERAUTH_ACCEPT_SENT && ssh->acceptState != ACCEPT_SERVER_KEXINIT_SENT && ssh->acceptState != ACCEPT_KEYED && - ssh->acceptState != ACCEPT_SERVER_CHANNEL_ACCEPT_SENT) { + ssh->acceptState != ACCEPT_SERVER_CHANNEL_ACCEPT_SENT && + /* Never step over where this call is meant to stop. The + * loop below tests for that state exactly, and the SCP and + * SFTP re-entry states sort after it. */ + ssh->acceptState != stopState) { WLOG(WS_LOG_DEBUG, "Advancing accept state"); ssh->acceptState++; } @@ -676,7 +691,7 @@ int wolfSSH_accept(WOLFSSH* ssh) } } - while (ssh->acceptState != ACCEPT_CLIENT_SESSION_ESTABLISHED) { + while (ssh->acceptState != stopState) { switch (ssh->acceptState) { case ACCEPT_BEGIN: @@ -766,6 +781,12 @@ int wolfSSH_accept(WOLFSSH* ssh) } ssh->acceptState = ACCEPT_SERVER_USERAUTH_SENT; WLOG(WS_LOG_DEBUG, acceptState, "SERVER_USERAUTH_SENT"); + if (stopState == ACCEPT_SERVER_USERAUTH_SENT) { + /* The application takes it from here. Tested through + * stopState so a callback that changed the flag during + * this call cannot half-apply it. */ + break; + } FALL_THROUGH; case ACCEPT_SERVER_USERAUTH_SENT: @@ -4772,7 +4793,8 @@ WOLFSSH_CHANNEL* wolfSSH_ChannelFwdNewRemote(WOLFSSH* ssh, if (newChannel != NULL) ChannelAppend(ssh, newChannel); - WLOG(WS_LOG_DEBUG, "Leaving wolfSSH_ChannelFwdNewRemote(), newChannel = %p, ret = %d", + WLOG(WS_LOG_DEBUG, + "Leaving wolfSSH_ChannelFwdNewRemote(), newChannel = %p, ret = %d", newChannel, ret); return newChannel; } @@ -5766,6 +5788,32 @@ int wolfSSH_CTX_SetChannelReqSubsysCb(WOLFSSH_CTX* ctx, } +int wolfSSH_CTX_SetAppChannels(WOLFSSH_CTX* ctx, byte enable) +{ + int ret = WS_SSH_CTX_NULL_E; + + if (ctx != NULL) { + ctx->appChannels = (enable != 0); + ret = WS_SUCCESS; + } + + return ret; +} + + +int wolfSSH_SetAppChannels(WOLFSSH* ssh, byte enable) +{ + int ret = WS_SSH_NULL_E; + + if (ssh != NULL) { + ssh->appChannels = (enable != 0); + ret = WS_SUCCESS; + } + + return ret; +} + + int wolfSSH_SetChannelOpenCtx(WOLFSSH* ssh, void* ctx) { int ret = WS_SSH_NULL_E; diff --git a/src/wolfsftp.c b/src/wolfsftp.c index 88cca98f8..14b795415 100644 --- a/src/wolfsftp.c +++ b/src/wolfsftp.c @@ -1383,8 +1383,31 @@ int wolfSSH_SFTP_accept(WOLFSSH* ssh) if (ssh->error == WS_WANT_READ || ssh->error == WS_WANT_WRITE) ssh->error = WS_SUCCESS; + /* The grant is what says this session may be served, so it is asked + * for in every accept state. Below the user-auth stop the legacy + * branch would run the handshake itself, which in this mode returns + * with no channel open at all; at the stop or past it there is no + * accept() left that could have checked anything. */ + if (ssh->appChannels) { + /* Application-driven mode parks accept() here for good, so the + * sftp grant it would have checked is the application's subsystem + * callback: serve only a session channel it granted sftp on. The + * request having named sftp is not enough, so this asks for the + * grant as well -- unlike wolfSSH_accept()'s divert, which reads + * only the type and command. The name matches whole: sftpx is + * some other subsystem. */ + const WOLFSSH_CHANNEL* channel = ssh->channelList; + + if (channel == NULL || !channel->sessionGranted + || channel->sessionType != WOLFSSH_SESSION_SUBSYSTEM + || channel->command == NULL + || WSTRCMP(channel->command, "sftp") != 0) { + WLOG(WS_LOG_SFTP, "No sftp subsystem granted on the session"); + return WS_INVALID_STATE_E; + } + } /* check accept is done, if not call wolfSSH accept */ - if (ssh->acceptState < ACCEPT_CLIENT_SESSION_ESTABLISHED) { + else if (ssh->acceptState < ACCEPT_CLIENT_SESSION_ESTABLISHED) { byte name[] = "sftp"; WLOG(WS_LOG_SFTP, "Trying to do SSH accept first"); diff --git a/tests/regress.c b/tests/regress.c index c8c3016de..4e49468a0 100644 --- a/tests/regress.c +++ b/tests/regress.c @@ -1486,6 +1486,208 @@ static void AssertHandshakeRejectsMutatedReply(const char* keyAlgo, } #ifndef WOLFSSH_NO_RSA_SHA2_256 +/* Counts the shell requests the application-driven server answered. */ +static int appChannelsShellReqCount; + +static int AppChannelsShellCb(WOLFSSH_CHANNEL* channel, void* ctx) +{ + (void)channel; + (void)ctx; + appChannelsShellReqCount++; + return 0; +} + +/* Drive an application-driven server: wolfSSH_accept() is expected to return + * at userauth, so the channel open and the shell request are answered by + * wolfSSH_worker() calls the application makes itself. */ +static void RunAppChannelsHandshake(KexReplyHarness* harness, + KexReplyRunResult* result) +{ + word32 step; + + WMEMSET(result, 0, sizeof(*result)); + result->clientRet = WS_FATAL_ERROR; + result->serverRet = WS_FATAL_ERROR; + + for (step = 0; step < REGRESS_MAX_HANDSHAKE_STEPS; step++) { + if (!result->clientSuccess) { + result->clientRet = wolfSSH_connect(harness->client); + result->clientErr = wolfSSH_get_error(harness->client); + if (result->clientRet == WS_SUCCESS) { + result->clientSuccess = 1; + } + else if (!IsHandshakeRetryable(result->clientErr)) { + result->steps = step + 1; + return; + } + } + + if (!result->serverSuccess) { + result->serverRet = wolfSSH_accept(harness->server); + result->serverErr = wolfSSH_get_error(harness->server); + if (result->serverRet == WS_SUCCESS) { + result->serverSuccess = 1; + } + else if (!IsHandshakeRetryable(result->serverErr)) { + result->steps = step + 1; + return; + } + } + else if (harness->server->clientState < CLIENT_DONE) { + result->serverRet = wolfSSH_worker(harness->server, NULL); + result->serverErr = wolfSSH_get_error(harness->server); + if (result->serverRet < WS_SUCCESS + && result->serverErr != WS_CHAN_RXD + && !IsHandshakeRetryable(result->serverErr)) { + result->steps = step + 1; + return; + } + } + + if (result->clientSuccess && result->serverSuccess + && harness->server->clientState >= CLIENT_DONE) { + result->steps = step + 1; + return; + } + } + + result->steps = REGRESS_MAX_HANDSHAKE_STEPS; +} + +/* With wolfSSH_SetAppChannels() on, accept() stops once the user is + * authenticated and the shell request lands on the callback instead. */ +static void TestAppChannelsAcceptStopsAtUserAuth(void) +{ + KexReplyHarness harness; + KexReplyRunResult result; + + appChannelsShellReqCount = 0; + + InitKexReplyHarness(&harness, "rsa-sha2-256", REGRESS_SERVER_KEY_PATH, + 0, NULL); + AssertIntEQ(wolfSSH_CTX_SetChannelReqShellCb(harness.serverCtx, + AppChannelsShellCb), WS_SUCCESS); + AssertIntEQ(wolfSSH_SetAppChannels(harness.server, 1), WS_SUCCESS); + + RunAppChannelsHandshake(&harness, &result); + + AssertTrue(result.clientSuccess); + AssertTrue(result.serverSuccess); + AssertIntEQ(harness.server->acceptState, ACCEPT_SERVER_USERAUTH_SENT); + AssertIntEQ(harness.server->clientState, CLIENT_DONE); + AssertIntEQ(appChannelsShellReqCount, 1); + AssertIntEQ(harness.client->connectState, + CONNECT_SERVER_CHANNEL_REQUEST_DONE); + AssertFalse(harness.clientIo.sawDisconnect); + AssertFalse(harness.serverIo.sawDisconnect); + + FreeKexReplyHarness(&harness); +} + +/* Same mode, no callback registered: nothing can start the shell once + * accept() has returned, so the request is refused. The default mode + * accepts it, which AssertHandshakeSucceeds() covers. */ +static void TestAppChannelsNoShellCbRejects(void) +{ + KexReplyHarness harness; + KexReplyRunResult result; + + InitKexReplyHarness(&harness, "rsa-sha2-256", REGRESS_SERVER_KEY_PATH, + 0, NULL); + AssertIntEQ(wolfSSH_SetAppChannels(harness.server, 1), WS_SUCCESS); + + RunAppChannelsHandshake(&harness, &result); + + /* RunAppChannelsHandshake() also leaves clientSuccess clear when it + * runs out of steps with neither side erroring, so pin the refusal + * itself: the client stopped early, and for the right reason. */ + AssertFalse(result.clientSuccess); + AssertTrue(result.steps < REGRESS_MAX_HANDSHAKE_STEPS); + AssertIntEQ(result.clientErr, WS_CHANOPEN_FAILED); + AssertTrue(harness.client->connectState < + CONNECT_SERVER_CHANNEL_REQUEST_DONE); + AssertIntEQ(harness.server->acceptState, ACCEPT_SERVER_USERAUTH_SENT); + + FreeKexReplyHarness(&harness); +} + +/* The flag is documented as a context setting first, so pin the setter + * returns and the inheritance wolfSSH_new() does. */ +static void TestAppChannelsCtxInherits(void) +{ + WOLFSSH_CTX* ctx; + WOLFSSH* ssh; + + AssertIntEQ(wolfSSH_CTX_SetAppChannels(NULL, 1), WS_SSH_CTX_NULL_E); + AssertIntEQ(wolfSSH_SetAppChannels(NULL, 1), WS_SSH_NULL_E); + + ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL); + AssertNotNull(ctx); + + ssh = wolfSSH_new(ctx); + AssertNotNull(ssh); + AssertIntEQ(ssh->appChannels, 0); + wolfSSH_free(ssh); + + AssertIntEQ(wolfSSH_CTX_SetAppChannels(ctx, 1), WS_SUCCESS); + + ssh = wolfSSH_new(ctx); + AssertNotNull(ssh); + AssertIntEQ(ssh->appChannels, 1); + AssertIntEQ(wolfSSH_SetAppChannels(ssh, 0), WS_SUCCESS); + AssertIntEQ(ssh->appChannels, 0); + wolfSSH_free(ssh); + + wolfSSH_CTX_free(ctx); +} + +/* Turning the mode on after accept() established the session must not leave + * the accept loop hunting for a state it has already stepped past. The flag + * still reaches DoChannelRequest() from there, which is what ssh.h promises, + * so pin both halves: accept() stays put, the requests that follow flip. */ +static void TestAppChannelsLateEnableReturns(void) +{ + KexReplyHarness harness; + KexReplyRunResult result; + /* SSH_MSG_CHANNEL_REQUEST body: channel 0, "shell", wantReply. */ + static byte payShell[] = { + 0x00,0x00,0x00,0x00, /* channelId = 0 */ + 0x00,0x00,0x00,0x05, /* typeSz = 5 */ + 0x73,0x68,0x65,0x6C,0x6C, /* "shell" */ + 0x01 /* wantReply = 1 */ + }; + word32 idx; + + InitKexReplyHarness(&harness, "rsa-sha2-256", REGRESS_SERVER_KEY_PATH, + 0, NULL); + + RunKexReplyHandshake(&harness, &result); + + AssertTrue(result.serverSuccess); + AssertIntEQ(harness.server->acceptState, + ACCEPT_CLIENT_SESSION_ESTABLISHED); + + /* Default mode, no callback registered: the request is granted. */ + idx = 0; + AssertIntEQ(wolfSSH_TestDoChannelRequest(harness.server, payShell, + (word32)sizeof(payShell), &idx), WS_SUCCESS); + AssertIntEQ(wolfSSH_worker(harness.client, NULL), WS_SUCCESS); + + AssertIntEQ(wolfSSH_SetAppChannels(harness.server, 1), WS_SUCCESS); + AssertIntEQ(wolfSSH_accept(harness.server), WS_SUCCESS); + AssertIntEQ(harness.server->acceptState, + ACCEPT_CLIENT_SESSION_ESTABLISHED); + + /* Same request, same session, mode now on: refused instead. */ + idx = 0; + AssertIntEQ(wolfSSH_TestDoChannelRequest(harness.server, payShell, + (word32)sizeof(payShell), &idx), WS_SUCCESS); + AssertTrue(wolfSSH_worker(harness.client, NULL) < WS_SUCCESS); + AssertIntEQ(wolfSSH_get_error(harness.client), WS_CHANOPEN_FAILED); + + FreeKexReplyHarness(&harness); +} + static void TestKexDhReplyRejectsRsaSha2_256SigNameDowngrade(void) { AssertHandshakeSucceeds("rsa-sha2-256", REGRESS_SERVER_KEY_PATH); @@ -3410,7 +3612,8 @@ static void TestChannelCloseCallbackReturnIgnored(void) } /* Builds a plaintext SSH_MSG_CHANNEL_REQUEST whose type-specific tail is a - * single string, which is the shape of both "exec" and "subsystem". */ + * single string, which is the shape of both "exec" and "subsystem". A NULL + * "arg" leaves the tail off, which is the shape of "shell". */ static word32 BuildChannelStringRequestPacket(word32 recipientChannelId, const char* type, byte wantReply, const char* arg, byte* out, word32 outSz) @@ -3421,7 +3624,9 @@ static word32 BuildChannelStringRequestPacket(word32 recipientChannelId, idx = AppendUint32(payload, sizeof(payload), idx, recipientChannelId); idx = AppendString(payload, sizeof(payload), idx, type); idx = AppendByte(payload, sizeof(payload), idx, wantReply); - idx = AppendString(payload, sizeof(payload), idx, arg); + if (arg != NULL) { + idx = AppendString(payload, sizeof(payload), idx, arg); + } return WrapPacket(MSGID_CHANNEL_REQUEST, payload, idx, out, outSz); } @@ -3530,6 +3735,362 @@ static void TestChannelReqSubsysCallbackRuns(void) WOLFSSH_SESSION_SUBSYSTEM), MSGID_CHANNEL_FAILURE); } +/* A request callback owns its channel and may close it. The grant is + * recorded after the callback returns, so it has to find the channel + * again: wolfSSH_ChannelFree() frees it, and writing through the old + * pointer would touch freed memory. */ +static int freeChannelCbCalls; + +static int FreeingSessionReqCb(WOLFSSH_CHANNEL* channel, void* ctx) +{ + (void)ctx; + freeChannelCbCalls++; + AssertIntEQ(wolfSSH_ChannelFree(channel), WS_SUCCESS); + return 0; +} + +static void TestSessionReqCallbackMayFreeChannel(void) +{ + ChannelOpenHarness harness; + WOLFSSH_CHANNEL* channel; + byte in[128]; + word32 inSz; + + freeChannelCbCalls = 0; + + InitChannelOpenHarness(&harness, NULL, 0); + AssertIntEQ(wolfSSH_CTX_SetChannelReqShellCb(harness.ctx, + FreeingSessionReqCb), WS_SUCCESS); + + channel = SeedUnconfirmedChannel(&harness); + AssertIntEQ(ChannelUpdatePeer(channel, 5, 1024, 1024), WS_SUCCESS); + channel->openConfirmed = 1; + + inSz = BuildChannelStringRequestPacket(channel->channel, "shell", 1, + NULL, in, sizeof(in)); + RepointHarnessInput(&harness, in, inSz); + AssertIntEQ(DoReceive(harness.ssh), WS_FATAL_ERROR); + + AssertIntEQ(freeChannelCbCalls, 1); + /* The channel the grant would have been recorded on is gone, so the + * reply cannot be sent either and the session says why. */ + AssertIntEQ(harness.ssh->channelListSz, 0); + AssertNull(harness.ssh->channelList); + AssertIntEQ(wolfSSH_get_error(harness.ssh), WS_INVALID_CHANID); + AssertIntEQ(harness.io.outSz, 0); + + FreeChannelOpenHarness(&harness); +} + +/* accept() re-entered while it is already parked, with a reply still + * queued, has to flush and stay put. Stepping the state on from here + * would put the stop behind it, and the loop tests for that state + * exactly, so the session would run on to established instead. */ +static void TestAppChannelsAcceptKeepsStopWithPendingOutput(void) +{ + ChannelOpenHarness harness; + WOLFSSH_CHANNEL* channel; + + InitChannelOpenHarness(&harness, NULL, 0); + AssertIntEQ(wolfSSH_SetAppChannels(harness.ssh, 1), WS_SUCCESS); + + channel = SeedUnconfirmedChannel(&harness); + AssertIntEQ(ChannelUpdatePeer(channel, 5, 1024, 1024), WS_SUCCESS); + channel->openConfirmed = 1; + + /* A blocked send leaves the channel data queued. Nothing here drives + * a channel request, so clientState stays short of CLIENT_DONE and a + * state stepped past the stop fails the accept below rather than + * spinning in it. */ + harness.io.blockNext = 1; + AssertIntEQ(wolfSSH_stream_send(harness.ssh, (byte*)"x", 1), 1); + AssertTrue(harness.ssh->outputBuffer.length > 0); + AssertTrue(harness.ssh->clientState < CLIENT_DONE); + + AssertIntEQ(harness.ssh->acceptState, ACCEPT_SERVER_USERAUTH_SENT); + AssertIntEQ(wolfSSH_accept(harness.ssh), WS_SUCCESS); + AssertIntEQ(harness.ssh->acceptState, ACCEPT_SERVER_USERAUTH_SENT); + AssertIntEQ(harness.ssh->outputBuffer.length, 0); + + FreeChannelOpenHarness(&harness); +} + +#ifdef WOLFSSH_SFTP +/* SSH_MSG_CHANNEL_DATA carrying an SFTP INIT, version 3. */ +static word32 BuildSftpInitDataPacket(word32 recipientChannelId, byte* out, + word32 outSz) +{ + static const byte init[] = { + 0x00,0x00,0x00,0x05, /* length */ + WOLFSSH_FTP_INIT, + 0x00,0x00,0x00,0x03 /* version = 3 */ + }; + byte payload[32]; + word32 idx = 0; + + idx = AppendUint32(payload, sizeof(payload), idx, recipientChannelId); + idx = AppendUint32(payload, sizeof(payload), idx, (word32)sizeof(init)); + idx = AppendData(payload, sizeof(payload), idx, init, sizeof(init)); + + return WrapPacket(MSGID_CHANNEL_DATA, payload, idx, out, outSz); +} + +/* An application-driven server with a confirmed session channel, its request + * callback for type registered to grant, and one request of that type driven + * through it. Returns the channel; the harness input is left empty. */ +static WOLFSSH_CHANNEL* SeedAppChannelsSession(ChannelOpenHarness* harness, + const char* type, const char* arg) +{ + WOLFSSH_CHANNEL* channel; + byte in[128]; + word32 inSz; + + sessionReqCbCalls = 0; + sessionReqCbReturn = 0; + + InitChannelOpenHarness(harness, NULL, 0); + AssertIntEQ(wolfSSH_SetAppChannels(harness->ssh, 1), WS_SUCCESS); + if (WSTRCMP(type, "shell") == 0) { + AssertIntEQ(wolfSSH_CTX_SetChannelReqShellCb(harness->ctx, + RecordingSessionReqCb), WS_SUCCESS); + } + else { + AssertIntEQ(wolfSSH_CTX_SetChannelReqSubsysCb(harness->ctx, + RecordingSessionReqCb), WS_SUCCESS); + } + + channel = SeedUnconfirmedChannel(harness); + AssertIntEQ(ChannelUpdatePeer(channel, 5, 1024, 1024), WS_SUCCESS); + channel->openConfirmed = 1; + + inSz = BuildChannelStringRequestPacket(channel->channel, type, 1, arg, + in, sizeof(in)); + RepointHarnessInput(harness, in, inSz); + AssertIntEQ(DoReceive(harness->ssh), WS_SUCCESS); + AssertIntEQ(sessionReqCbCalls, 1); + AssertIntEQ(ParseMsgId(harness->io.out, harness->io.outSz), + MSGID_CHANNEL_SUCCESS); + RepointHarnessInput(harness, NULL, 0); + + return channel; +} + +/* wolfSSH_SFTP_accept() in application-driven mode. accept() parks short of + * the session, so the sftp grant it would have checked is the application's + * subsystem callback: with no session channel there is nothing to serve. */ +static void TestSftpAcceptAppChannelsNeedsSession(void) +{ + ChannelOpenHarness harness; + + InitChannelOpenHarness(&harness, NULL, 0); + AssertIntEQ(wolfSSH_SetAppChannels(harness.ssh, 1), WS_SUCCESS); + + AssertIntEQ(wolfSSH_SFTP_accept(harness.ssh), WS_INVALID_STATE_E); + AssertIntEQ(harness.io.outSz, 0); + AssertIntEQ(harness.ssh->error, WS_SUCCESS); + AssertIntEQ(harness.ssh->acceptState, ACCEPT_SERVER_USERAUTH_SENT); + + FreeChannelOpenHarness(&harness); +} + +/* Called ahead of accept(), which is how a server that set the flag on the + * context reaches this entry point. The refusal has to come from the gate: + * running the handshake instead returns with no channel open in this mode, + * and the SFTP exchange then fails on the missing channel. */ +static void TestSftpAcceptAppChannelsRefusesPreAccept(void) +{ + ChannelOpenHarness harness; + + InitChannelOpenHarness(&harness, NULL, 0); + AssertIntEQ(wolfSSH_SetAppChannels(harness.ssh, 1), WS_SUCCESS); + harness.ssh->acceptState = ACCEPT_BEGIN; + + AssertIntEQ(wolfSSH_SFTP_accept(harness.ssh), WS_INVALID_STATE_E); + /* Nothing sent, so no handshake was started ... */ + AssertIntEQ(harness.io.outSz, 0); + AssertIntEQ(harness.ssh->acceptState, ACCEPT_BEGIN); + /* ... and the subsystem name the legacy branch sets was not set. */ + AssertNull(harness.ssh->channelName); + AssertIntEQ(harness.ssh->error, WS_SUCCESS); + + FreeChannelOpenHarness(&harness); +} + +/* A granted shell is not an sftp grant: the INIT the peer pushes on that + * channel stays unread. */ +static void TestSftpAcceptAppChannelsRefusesShell(void) +{ + ChannelOpenHarness harness; + WOLFSSH_CHANNEL* channel; + byte in[64]; + word32 inSz; + + channel = SeedAppChannelsSession(&harness, "shell", NULL); + inSz = BuildSftpInitDataPacket(channel->channel, in, sizeof(in)); + RepointHarnessInput(&harness, in, inSz); + + AssertIntEQ(wolfSSH_SFTP_accept(harness.ssh), WS_INVALID_STATE_E); + AssertIntEQ(harness.io.outSz, 0); + AssertIntEQ(harness.io.inOff, 0); + AssertIntEQ(harness.ssh->error, WS_SUCCESS); + + FreeChannelOpenHarness(&harness); +} + +/* A name that only starts with sftp is not an sftp grant. */ +static void TestSftpAcceptAppChannelsRefusesPrefixName(void) +{ + ChannelOpenHarness harness; + WOLFSSH_CHANNEL* channel; + byte in[64]; + word32 inSz; + + channel = SeedAppChannelsSession(&harness, "subsystem", "sftpx"); + inSz = BuildSftpInitDataPacket(channel->channel, in, sizeof(in)); + RepointHarnessInput(&harness, in, inSz); + + AssertIntEQ(wolfSSH_SFTP_accept(harness.ssh), WS_INVALID_STATE_E); + AssertIntEQ(harness.io.outSz, 0); + AssertIntEQ(harness.io.inOff, 0); + AssertIntEQ(harness.ssh->error, WS_SUCCESS); + + FreeChannelOpenHarness(&harness); +} + +/* The grant the mode relies on: the subsystem callback took sftp, so the + * INIT is answered with a VERSION and accept() stays parked. */ +static void TestSftpAcceptAppChannelsServesGrantedSftp(void) +{ + ChannelOpenHarness harness; + WOLFSSH_CHANNEL* channel; + byte in[64]; + word32 inSz; + /* Offset of the SFTP type byte in the packet the server sends: the + * SSH packet header, then the CHANNEL_DATA payload of recipient + * channel and data-string length, then the SFTP length field. */ + const word32 sftpIdx = LENGTH_SZ + PAD_LENGTH_SZ + MSG_ID_SZ + + UINT32_SZ + UINT32_SZ + UINT32_SZ; + + channel = SeedAppChannelsSession(&harness, "subsystem", "sftp"); + inSz = BuildSftpInitDataPacket(channel->channel, in, sizeof(in)); + RepointHarnessInput(&harness, in, inSz); + + AssertIntEQ(wolfSSH_SFTP_accept(harness.ssh), WS_SFTP_COMPLETE); + AssertIntEQ(ParseMsgId(harness.io.out, harness.io.outSz), + MSGID_CHANNEL_DATA); + AssertTrue(harness.io.outSz > sftpIdx); + AssertIntEQ(harness.io.out[sftpIdx], WOLFSSH_FTP_VERSION); + AssertIntEQ(harness.ssh->acceptState, ACCEPT_SERVER_USERAUTH_SENT); + + FreeChannelOpenHarness(&harness); +} + + +/* An established session is gated too. A server that turns the mode on + * late is past everything accept() would have checked, so the grant is + * the only thing left saying what the channel is: a granted shell is not + * an sftp grant, whatever state accept() finished in. */ +static void TestSftpAcceptAppChannelsRefusesEstablishedShell(void) +{ + ChannelOpenHarness harness; + WOLFSSH_CHANNEL* channel; + byte in[64]; + word32 inSz; + + channel = SeedAppChannelsSession(&harness, "shell", NULL); + harness.ssh->acceptState = ACCEPT_CLIENT_SESSION_ESTABLISHED; + inSz = BuildSftpInitDataPacket(channel->channel, in, sizeof(in)); + RepointHarnessInput(&harness, in, inSz); + + AssertIntEQ(wolfSSH_SFTP_accept(harness.ssh), WS_INVALID_STATE_E); + AssertIntEQ(harness.io.outSz, 0); + AssertIntEQ(harness.io.inOff, 0); + AssertIntEQ(harness.ssh->error, WS_SUCCESS); + + FreeChannelOpenHarness(&harness); +} + +/* The other half of that: asking in every state must not refuse a session + * the callback did grant sftp on, wherever accept() left off. */ +static void TestSftpAcceptAppChannelsServesEstablishedSftp(void) +{ + ChannelOpenHarness harness; + WOLFSSH_CHANNEL* channel; + byte in[64]; + word32 inSz; + + channel = SeedAppChannelsSession(&harness, "subsystem", "sftp"); + harness.ssh->acceptState = ACCEPT_CLIENT_SESSION_ESTABLISHED; + inSz = BuildSftpInitDataPacket(channel->channel, in, sizeof(in)); + RepointHarnessInput(&harness, in, inSz); + + AssertIntEQ(wolfSSH_SFTP_accept(harness.ssh), WS_SFTP_COMPLETE); + AssertIntEQ(ParseMsgId(harness.io.out, harness.io.outSz), + MSGID_CHANNEL_DATA); + + FreeChannelOpenHarness(&harness); +} + +/* A refused "subsystem sftp" still leaves sessionType/command set on the + * channel, so check wolfSSH_SFTP_accept() looks at the grant, not the + * leftovers. rejectVia 0 registers no callback at all (app channels alone + * refuse); 1 registers one that rejects. */ +static void CheckSftpAcceptRefusesUngranted(int rejectVia) +{ + ChannelOpenHarness harness; + WOLFSSH_CHANNEL* channel; + byte in[128]; + word32 inSz; + + sessionReqCbCalls = 0; + sessionReqCbReturn = (rejectVia == 0) ? 0 : 1; + + InitChannelOpenHarness(&harness, NULL, 0); + AssertIntEQ(wolfSSH_SetAppChannels(harness.ssh, 1), WS_SUCCESS); + if (rejectVia != 0) { + AssertIntEQ(wolfSSH_CTX_SetChannelReqSubsysCb(harness.ctx, + RecordingSessionReqCb), WS_SUCCESS); + } + + channel = SeedUnconfirmedChannel(&harness); + AssertIntEQ(ChannelUpdatePeer(channel, 5, 1024, 1024), WS_SUCCESS); + channel->openConfirmed = 1; + + inSz = BuildChannelStringRequestPacket(channel->channel, "subsystem", 1, + "sftp", in, sizeof(in)); + RepointHarnessInput(&harness, in, inSz); + AssertIntEQ(DoReceive(harness.ssh), WS_SUCCESS); + /* With a callback registered, it did the refusing, not app channels + * standing in for a missing one. */ + AssertIntEQ(sessionReqCbCalls, (rejectVia == 0) ? 0 : 1); + /* Either way the peer is told the subsystem was refused. */ + AssertIntEQ(ParseMsgId(harness.io.out, harness.io.outSz), + MSGID_CHANNEL_FAILURE); + + inSz = BuildSftpInitDataPacket(channel->channel, in, sizeof(in)); + RepointHarnessInput(&harness, in, inSz); + + AssertIntEQ(wolfSSH_SFTP_accept(harness.ssh), WS_INVALID_STATE_E); + AssertIntEQ(harness.io.outSz, 0); + + FreeChannelOpenHarness(&harness); +} + + +static void TestSftpAcceptAppChannelsRefusesNoCb(void) +{ + CheckSftpAcceptRefusesUngranted(0); +} + + +static void TestSftpAcceptAppChannelsRefusesRejectedCb(void) +{ + CheckSftpAcceptRefusesUngranted(1); +} + + +#endif /* WOLFSSH_SFTP */ + /* A username change after the first userauth request must end the session. */ static void TestUsernameChangeDisconnects(void) { @@ -13575,6 +14136,19 @@ int main(int argc, char** argv) TestChannelCloseCallbackReturnIgnored(); TestChannelReqExecCallbackRuns(); TestChannelReqSubsysCallbackRuns(); + TestSessionReqCallbackMayFreeChannel(); + TestAppChannelsAcceptKeepsStopWithPendingOutput(); +#ifdef WOLFSSH_SFTP + TestSftpAcceptAppChannelsNeedsSession(); + TestSftpAcceptAppChannelsRefusesPreAccept(); + TestSftpAcceptAppChannelsRefusesShell(); + TestSftpAcceptAppChannelsRefusesPrefixName(); + TestSftpAcceptAppChannelsServesGrantedSftp(); + TestSftpAcceptAppChannelsRefusesEstablishedShell(); + TestSftpAcceptAppChannelsServesEstablishedSftp(); + TestSftpAcceptAppChannelsRefusesNoCb(); + TestSftpAcceptAppChannelsRefusesRejectedCb(); +#endif TestSecondSessionChannelRejected(); TestUsernameChangeDisconnects(); TestSameUserRetryAllowed(); @@ -13780,6 +14354,10 @@ int main(int argc, char** argv) #ifdef KEXDH_REPLY_REGRESS_KEX_ALGO #ifndef WOLFSSH_NO_RSA_SHA2_256 + TestAppChannelsCtxInherits(); + TestAppChannelsAcceptStopsAtUserAuth(); + TestAppChannelsNoShellCbRejects(); + TestAppChannelsLateEnableReturns(); TestKexDhReplyRejectsRsaSha2_256SigNameDowngrade(); #endif #ifndef WOLFSSH_NO_RSA_SHA2_512 diff --git a/tests/unit.c b/tests/unit.c index f67c84084..3e67cbe3b 100644 --- a/tests/unit.c +++ b/tests/unit.c @@ -9295,6 +9295,68 @@ static int test_DoChannelRequest(void) } #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. */ + { + 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" */ + }; + 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); diff --git a/wolfssh/internal.h b/wolfssh/internal.h index be5905afd..20d63e5a5 100644 --- a/wolfssh/internal.h +++ b/wolfssh/internal.h @@ -898,6 +898,7 @@ struct WOLFSSH_CTX { word32 maxAuthAttempts; /* server cap on failed userauth */ byte side; /* client or server */ byte showBanner; + byte appChannels; /* app drives channels, see ssh.h */ #ifdef WOLFSSH_AGENT byte agentEnabled; #endif /* WOLFSSH_AGENT */ @@ -1167,6 +1168,7 @@ struct WOLFSSH { byte serverState; byte processReplyState; byte isKeying; + byte appChannels; /* app drives channels, see ssh.h */ byte authId; /* if using public key or password */ byte supportedAuth[4]; /* supported auth IDs public key , password */ @@ -1411,6 +1413,11 @@ struct WOLFSSH_CHANNEL { byte openConfirmed : 1; byte ptyReq : 1; /* flag for if interactive pty request was received */ byte fwdSetupTxd : 1; /* a LOCAL_SETUP succeeded, a cleanup is owed */ + byte sessionGranted : 1; /* a shell, exec or subsystem request was + * answered CHANNEL_SUCCESS. sessionType and + * command are recorded before that answer is + * decided and stay set on a refusal, so they + * do not say whether anything was granted. */ word32 channel; word32 windowSz; word32 maxPacketSz; diff --git a/wolfssh/ssh.h b/wolfssh/ssh.h index f768fe9e7..815a1a486 100644 --- a/wolfssh/ssh.h +++ b/wolfssh/ssh.h @@ -461,6 +461,32 @@ WOLFSSH_API int wolfSSH_CTX_SetChannelReqSubsysCb(WOLFSSH_CTX* ctx, WOLFSSH_API int wolfSSH_SetChannelReqCtx(WOLFSSH* ssh, void* ctx); WOLFSSH_API void* wolfSSH_GetChannelReqCtx(WOLFSSH* ssh); +/* Application-driven channel handling, server side, off by default. + * + * Off, wolfSSH_accept() runs the session state machine through to an + * established session with the first channel open, as it always has, and a + * shell, exec, or subsystem request with no callback registered for it is + * accepted. + * + * On, wolfSSH_accept() returns WS_SUCCESS as soon as the user has + * authenticated, and the application owns every channel from there, driving + * the session with wolfSSH_worker() and the callbacks above. A shell, exec, + * or subsystem request with no callback registered is then rejected: with + * accept() already returned, nothing is left to service it. + * + * Set it on the context before wolfSSH_new(), or on a session before the + * first wolfSSH_accept() call. Turning it on later still applies to the + * channel requests that follow, but it cannot move where accept() returns + * on a session that has already gone past the user-auth stop. + * + * accept() never reaches the built-in SCP entry point in this mode, so + * WS_SCP_INIT is off the table. wolfSSH_SFTP_accept() still serves, but only + * a session channel the subsystem callback granted sftp on; called ahead of + * that it returns WS_INVALID_STATE_E without recording an error. A pending + * want-read or want-write is still cleared, as on any other call. */ +WOLFSSH_API int wolfSSH_CTX_SetAppChannels(WOLFSSH_CTX* ctx, byte enable); +WOLFSSH_API int wolfSSH_SetAppChannels(WOLFSSH* ssh, byte enable); + typedef int (*WS_CallbackChannelEof)(WOLFSSH_CHANNEL* channel, void* ctx); WOLFSSH_API int wolfSSH_CTX_SetChannelEofCb(WOLFSSH_CTX* ctx, WS_CallbackChannelEof cb);