From c81fcbca39f8f154f2d0a94b391203cc8aa52093 Mon Sep 17 00:00:00 2001 From: Jacob Barthelmeh Date: Tue, 24 May 2022 17:05:53 -0600 Subject: [PATCH 01/48] initial autotools sshd addition --- .gitignore | 3 +++ Makefile.am | 1 + apps/include.am | 13 +++++++++++++ apps/wolfsshd.c | 47 +++++++++++++++++++++++++++++++++++++++++++++++ configure.ac | 9 +++++++++ 5 files changed, 73 insertions(+) create mode 100644 apps/include.am create mode 100644 apps/wolfsshd.c diff --git a/.gitignore b/.gitignore index cad67e11..6a688fca 100644 --- a/.gitignore +++ b/.gitignore @@ -54,6 +54,9 @@ examples/portfwd/portfwd examples/sftpclient/wolfsftp examples/scpclient/wolfscp +# applications +apps/wolfsshd + # test output tests/*.test *.trs diff --git a/Makefile.am b/Makefile.am index 51838c46..f03df800 100644 --- a/Makefile.am +++ b/Makefile.am @@ -33,6 +33,7 @@ EXTRA_DIST+= LICENSING README.md ChangeLog.md include src/include.am include wolfssh/include.am +include apps/include.am include examples/include.am include tests/include.am include keys/include.am diff --git a/apps/include.am b/apps/include.am new file mode 100644 index 00000000..437139c1 --- /dev/null +++ b/apps/include.am @@ -0,0 +1,13 @@ +# vim:ft=automake +# All paths should be given relative to the root + +if BUILD_SSHD +bin_PROGRAMS += apps/wolfsshd +noinst_HEADERS += examples/client/client.h +apps_wolfsshd_SOURCES = apps/wolfsshd.c +apps_wolfsshd_LDADD = src/libwolfssh.la +apps_wolfsshd_DEPENDENCIES = src/libwolfssh.la +endif + +DISTCLEANFILES+= apps/.libs/wolfsshd + diff --git a/apps/wolfsshd.c b/apps/wolfsshd.c new file mode 100644 index 00000000..c97ed940 --- /dev/null +++ b/apps/wolfsshd.c @@ -0,0 +1,47 @@ +/* wolfsshd.c + * + * Copyright (C) 2014-2021 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 . + */ + +#ifdef HAVE_CONFIG_H + #include +#endif + +#ifdef WOLFSSH_SSHD + +#include +#include +#include +#include +#include + +#ifdef NO_INLINE + #include +#else + #define WOLFSSH_MISC_INCLUDED + #include "src/misc.c" +#endif + +int main(int argc, char** argv) +{ + (void)argc; + (void)argv; + printf("wolfSSH SSHD application\n"); + return 0; +} +#endif /* WOLFSSH_SSHD */ diff --git a/configure.ac b/configure.ac index 88ecbe93..071585d9 100644 --- a/configure.ac +++ b/configure.ac @@ -171,6 +171,11 @@ AC_ARG_ENABLE([sftp], [AS_HELP_STRING([--enable-sftp],[Enable SFTP support (default: disabled)])], [ENABLED_SFTP=$enableval],[ENABLED_SFTP=no]) +# SSHD +AC_ARG_ENABLE([sshd], + [AS_HELP_STRING([--enable-sshd],[Enable SSHD support (default: disabled)])], + [ENABLED_SSHD=$enableval],[ENABLED_SSHD=no]) + # TCP/IP Forwarding AC_ARG_ENABLE([fwd], [AS_HELP_STRING([--enable-fwd],[Enable TCP/IP Forwarding support (default: disabled)])], @@ -230,6 +235,8 @@ AS_IF([test "x$ENABLED_SHELL" = "xyes"], AS_IF([test "x$ENABLED_AGENT" = "xyes"],[AM_CPPFLAGS="$AM_CPPFLAGS -DWOLFSSH_AGENT"]) AS_IF([test "x$ENABLED_SMALLSTACK" = "xyes"], [AM_CPPFLAGS="$AM_CPPFLAGS -DWOLFSSH_SMALL_STACK"]) +AS_IF([test "x$ENABLED_SSHD" = "xyes"], + [AM_CPPFLAGS="$AM_CPPFLAGS -DWOLFSSH_SSHD"]) # Set the automake conditionals. AM_CONDITIONAL([BUILD_EXAMPLE_SERVERS],[test "x$ENABLED_EXAMPLES" = "xyes"]) @@ -242,6 +249,7 @@ AM_CONDITIONAL([BUILD_FWD],[test "x$ENABLED_FWD" = "xyes"]) AM_CONDITIONAL([BUILD_TERM],[test "x$ENABLED_TERM" = "xyes"]) AM_CONDITIONAL([BUILD_SHELL],[test "x$ENABLED_SHELL" = "xyes"]) AM_CONDITIONAL([BUILD_AGENT],[test "x$ENABLED_AGENT" = "xyes"]) +AM_CONDITIONAL([BUILD_SSHD],[test "x$ENABLED_SSHD" = "xyes"]) AX_HARDEN_CC_COMPILER_FLAGS @@ -282,6 +290,7 @@ AS_ECHO([" * psuedo-terminal: $ENABLED_PTERM"]) AS_ECHO([" * echoserver shell support: $ENABLED_SHELL"]) AS_ECHO([" * scp: $ENABLED_SCP"]) AS_ECHO([" * sftp: $ENABLED_SFTP"]) +AS_ECHO([" * sshd: $ENABLED_SSHD"]) AS_ECHO([" * agent: $ENABLED_AGENT"]) AS_ECHO([" * TCP/IP Forwarding: $ENABLED_FWD"]) AS_ECHO([" * Examples: $ENABLED_EXAMPLES"]) From 27cf3d31b96a0df354ce05b62559df77f5f690f9 Mon Sep 17 00:00:00 2001 From: Jacob Barthelmeh Date: Wed, 25 May 2022 16:59:42 -0600 Subject: [PATCH 02/48] add initial reading of sshd_config file --- apps/include.am | 5 +- apps/wolfconfig.c | 126 +++++++++++++++++++++++++++++++++++++++++++++ apps/wolfsshd.c | 73 +++++++++++++++++++++++++- apps/wolfsshd.h | 31 +++++++++++ configure.ac | 4 +- wolfssh/internal.h | 3 +- 6 files changed, 235 insertions(+), 7 deletions(-) create mode 100644 apps/wolfconfig.c create mode 100644 apps/wolfsshd.h diff --git a/apps/include.am b/apps/include.am index 437139c1..eddc4c60 100644 --- a/apps/include.am +++ b/apps/include.am @@ -3,8 +3,9 @@ if BUILD_SSHD bin_PROGRAMS += apps/wolfsshd -noinst_HEADERS += examples/client/client.h -apps_wolfsshd_SOURCES = apps/wolfsshd.c +noinst_HEADERS += apps/wolfsshd.h +apps_wolfsshd_SOURCES = apps/wolfsshd.c \ + apps/wolfconfig.c apps_wolfsshd_LDADD = src/libwolfssh.la apps_wolfsshd_DEPENDENCIES = src/libwolfssh.la endif diff --git a/apps/wolfconfig.c b/apps/wolfconfig.c new file mode 100644 index 00000000..25c92117 --- /dev/null +++ b/apps/wolfconfig.c @@ -0,0 +1,126 @@ +/* wolfconfig.c + * + * Copyright (C) 2014-2021 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 . + */ + +#ifdef HAVE_CONFIG_H + #include +#endif + +#ifdef WOLFSSH_SSHD +/* functions for parsing out options from a config file and for handling loading + * key/certs using the env. filesystem */ + +#include +#include +#include +#include +#include + +#ifdef NO_INLINE + #include +#else + #define WOLFSSH_MISC_INCLUDED + #include "src/misc.c" +#endif + +#include "wolfsshd.h" + +struct WOLFSSHD_CONFIG { + void* heap; + char* banner; + char* chrootDir; + char* ciphers; + char* hostKey; + char* hostKeyAlgos; + char* kekAlgos; + char* listenAddress; + char* authKeysFile; + word32 port; + byte passwordAuth:1; + byte pubKeyAuth:1; + byte permitRootLogin:1; + byte permitEmptyPasswords:1; + byte usePrivilegeSeparation:1; +}; + +WOLFSSHD_CONFIG* wolfSSH_NewConfig(void* heap) +{ + WOLFSSHD_CONFIG* ret; + + ret = (WOLFSSHD_CONFIG*)WMALLOC(sizeof(WOLFSSHD_CONFIG), heap, + DYNTYPE_SSHD); + if (ret == NULL) { + printf("issue mallocing config structure for sshd\n"); + } + else { + WMEMSET(ret, 0, sizeof(WOLFSSHD_CONFIG)); + } + return ret; + +} + +void wolfSSH_FreeConfig(WOLFSSHD_CONFIG* conf) +{ + void* heap; + + if (conf != NULL) { + heap = conf->heap; + + WFREE(conf, heap, DYNTYPE_SSHD); + } +} + +#define MAX_LINE_SIZE 160 +int wolfSSH_LoadSSHD(WOLFSSHD_CONFIG* conf, const char* filename) +{ + XFILE f; + int ret = WS_SUCCESS; + char buf[MAX_LINE_SIZE]; + const char* current; + + if (conf == NULL || filename == NULL) + return BAD_FUNC_ARG; + + f = XFOPEN(filename, "rb"); + while ((current = XFGETS(buf, MAX_LINE_SIZE, f)) != NULL) { + int currentSz = (int)XSTRLEN(current); + + /* remove leading spaces */ + while (currentSz > 0 && current[0] == ' ') { + currentSz = currentSz - 1; + current = current + 1; + } + + if (currentSz <= 1) { + continue; /* empty line */ + } + + if (current[0] == '#') { + printf("read commented out line\n%s\n", current); + continue; /* commented out line */ + } + + printf("read config : %s\n", current); + } + XFCLOSE(f); + + return ret; +} + +#endif /* WOLFSSH_SSHD */ diff --git a/apps/wolfsshd.c b/apps/wolfsshd.c index c97ed940..5d0a5e4d 100644 --- a/apps/wolfsshd.c +++ b/apps/wolfsshd.c @@ -26,10 +26,15 @@ #include #include +#include #include #include #include +#include "wolfsshd.h" + +#include + #ifdef NO_INLINE #include #else @@ -37,11 +42,75 @@ #include "src/misc.c" #endif +/* catch interrupts and close down gracefully */ +static volatile byte quit = 0; + +static void ShowUsage(void) +{ + printf("wolfsshd %s\n", LIBWOLFSSH_VERSION_STRING); + printf(" -? display this help and exit\n"); + printf(" -f Configuration file to use, default is /usr/locacl/etc/ssh/sshd_config\n"); +} + +static void interruptCatch(int in) +{ + (void)in; + printf("Closing down wolfSSHD\n"); + quit = 1; +} + +int myoptind = 0; +char* myoptarg = NULL; + int main(int argc, char** argv) { - (void)argc; - (void)argv; + int ret = WS_SUCCESS; + int ch; + WOLFSSHD_CONFIG* conf = NULL; + + const char* configFile = "/usr/local/etc/ssh/sshd_config"; + + signal(SIGINT, interruptCatch); + while ((ch = mygetopt(argc, argv, "?f:")) != -1) { + switch (ch) { + case 'f': + configFile = myoptarg; + break; + + case '?': + ShowUsage(); + return WS_SUCCESS; + + default: + ShowUsage(); + return WS_SUCCESS; + } + } + + if (ret == WS_SUCCESS) { + wolfSSH_Init(); + } + + if (ret == WS_SUCCESS) { + conf = wolfSSH_NewConfig(NULL); + if (conf == NULL) { + ret = WS_MEMORY_E; + } + } + + if (wolfSSH_LoadSSHD(conf, configFile) != WS_SUCCESS) { + printf("Error reading in configure file %s\n", configFile); + } + printf("wolfSSH SSHD application\n"); + + /* wait for incoming connections and fork them off */ + do { + + } while (ret == WS_SUCCESS && quit == 0); + + wolfSSH_FreeConfig(conf); + wolfSSH_Cleanup(); return 0; } #endif /* WOLFSSH_SSHD */ diff --git a/apps/wolfsshd.h b/apps/wolfsshd.h new file mode 100644 index 00000000..0a6797a1 --- /dev/null +++ b/apps/wolfsshd.h @@ -0,0 +1,31 @@ +/* wolfsshd.h + * + * Copyright (C) 2014-2021 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 . + */ + +#ifndef WOLFSSHD_H +#define WOLFSSHD_H + +typedef struct WOLFSSHD_CONFIG WOLFSSHD_CONFIG; + +WOLFSSHD_CONFIG* wolfSSH_NewConfig(void* heap); +void wolfSSH_FreeConfig(WOLFSSHD_CONFIG* conf); +int wolfSSH_LoadSSHD(WOLFSSHD_CONFIG* con, const char* filename); + +#endif /* WOLFSSHD_H */ + diff --git a/configure.ac b/configure.ac index 071585d9..7552a26a 100644 --- a/configure.ac +++ b/configure.ac @@ -113,8 +113,8 @@ AC_ARG_WITH(wolfssl, if test -d "${withval}/lib" && test -d "${withval}/include"; then wcpath=${withval} - LDFLAGS="$LDFLAGS -L${wcpath}/lib" - CPPFLAGS="$CPPFLAGS -I${wcpath}/include" + LDFLAGS="-L${wcpath}/lib $LDFLAGS" + CPPFLAGS="-I${wcpath}/include $CPPFLAGS" else AC_MSG_ERROR([wolfSSL path error (${withval}): missing lib and include]) fi diff --git a/wolfssh/internal.h b/wolfssh/internal.h index 838072ab..dfb29a15 100644 --- a/wolfssh/internal.h +++ b/wolfssh/internal.h @@ -978,7 +978,8 @@ enum WS_DynamicTypes { DYNTYPE_AGENT_BUFFER, DYNTYPE_FILE, DYNTYPE_TEMP, - DYNTYPE_PATH + DYNTYPE_PATH, + DYNTYPE_SSHD }; From 757f3c6b2cb5b4daf1339b3ecea6f88d0d75921e Mon Sep 17 00:00:00 2001 From: Jacob Barthelmeh Date: Mon, 13 Jun 2022 13:31:33 -0600 Subject: [PATCH 03/48] expanding config parsing --- apps/wolfconfig.c | 107 +++++++++++++++++- apps/wolfsshd.c | 280 +++++++++++++++++++++++++++++++++++++++++++--- apps/wolfsshd.h | 9 +- 3 files changed, 373 insertions(+), 23 deletions(-) diff --git a/apps/wolfconfig.c b/apps/wolfconfig.c index 25c92117..8c59fd29 100644 --- a/apps/wolfconfig.c +++ b/apps/wolfconfig.c @@ -51,7 +51,7 @@ struct WOLFSSHD_CONFIG { char* kekAlgos; char* listenAddress; char* authKeysFile; - word32 port; + word16 port; byte passwordAuth:1; byte pubKeyAuth:1; byte permitRootLogin:1; @@ -59,7 +59,45 @@ struct WOLFSSHD_CONFIG { byte usePrivilegeSeparation:1; }; -WOLFSSHD_CONFIG* wolfSSH_NewConfig(void* heap) +/* returns WS_SUCCESS on success */ +static int wolfSSHD_CreateString(char** out, const char* in, int inSz, + void* heap) +{ + int ret = WS_SUCCESS; + int idx = 0; + + /* remove white spaces */ + while (idx < inSz && in[idx] == ' ') idx++; + + if (idx == inSz) { + ret = WS_BAD_ARGUMENT; + } + + /* malloc new string and set it */ + if (ret == WS_SUCCESS) { + *out = (char*)WMALLOC((inSz - idx) + 1, heap, DYNTYPE_SSHD); + if (*out == NULL) { + ret = WS_MEMORY_E; + } + else { + XMEMCPY(*out, in + idx, inSz - idx); + *(*out + (inSz - idx)) = '\0'; + } + } + + return ret; +} + +static void wolfSSHD_FreeString(char** in, void* heap) +{ + if (*in != NULL) { + WFREE(*in, heap, DYNTYPE_SSHD); + *in = NULL; + } + (void)heap; +} + +WOLFSSHD_CONFIG* wolfSSHD_NewConfig(void* heap) { WOLFSSHD_CONFIG* ret; @@ -70,24 +108,66 @@ WOLFSSHD_CONFIG* wolfSSH_NewConfig(void* heap) } else { WMEMSET(ret, 0, sizeof(WOLFSSHD_CONFIG)); + + /* default values */ + ret->port = 22; } return ret; } -void wolfSSH_FreeConfig(WOLFSSHD_CONFIG* conf) +void wolfSSHD_FreeConfig(WOLFSSHD_CONFIG* conf) { void* heap; if (conf != NULL) { heap = conf->heap; + wolfSSHD_FreeString(&conf->authKeysFile, heap); + WFREE(conf, heap, DYNTYPE_SSHD); } } #define MAX_LINE_SIZE 160 -int wolfSSH_LoadSSHD(WOLFSSHD_CONFIG* conf, const char* filename) + +/* returns WS_SUCCESS on success + * Fails if any option is found that is unknown/unsupported + */ +static int wolfSSHD_ParseConfigLine(WOLFSSHD_CONFIG* conf, const char* l, + int lSz) +{ + int ret = WS_BAD_ARGUMENT; + int sz; + + /* supported config options */ + const char authKeyFile[] = "AuthorizedKeysFile"; + + sz = (int)XSTRLEN(authKeyFile); + if (lSz > sz && XSTRNCMP(l, authKeyFile, sz) == 0) { + ret = wolfSSHD_CreateString(&conf->authKeysFile, l + sz, lSz - sz, + conf->heap); + } + + if (XSTRNCMP(l, "UsePrivilegeSeparation", 18) == 0) { + ret = WS_SUCCESS; + } + + if (XSTRNCMP(l, "Subsystem", 9) == 0) { + + ret = WS_SUCCESS; + } + + if (ret == WS_BAD_ARGUMENT) { + printf("unknown / unsuported config line\n"); + } + + (void)conf;(void)lSz; + return ret; +} + + +int wolfSSHD_LoadSSHD(WOLFSSHD_CONFIG* conf, const char* filename) { XFILE f; int ret = WS_SUCCESS; @@ -116,11 +196,28 @@ int wolfSSH_LoadSSHD(WOLFSSHD_CONFIG* conf, const char* filename) continue; /* commented out line */ } - printf("read config : %s\n", current); + ret = wolfSSHD_ParseConfigLine(conf, current, currentSz); + if (ret != WS_SUCCESS) { + printf("Unable to parse config line : %s\n", current); + break; + } } XFCLOSE(f); return ret; } +char* wolfSSHD_GetBanner(WOLFSSHD_CONFIG* conf) +{ + if (conf != NULL) + return conf->banner; + return NULL; +} + +word16 wolfSSHD_GetPort(WOLFSSHD_CONFIG* conf) +{ + if (conf != NULL) + return conf->port; + return 0; +} #endif /* WOLFSSH_SSHD */ diff --git a/apps/wolfsshd.c b/apps/wolfsshd.c index 5d0a5e4d..f6c177af 100644 --- a/apps/wolfsshd.c +++ b/apps/wolfsshd.c @@ -26,11 +26,13 @@ #include #include -#include #include #include #include +#define WOLFSSH_TEST_SERVER +#include + #include "wolfsshd.h" #include @@ -44,6 +46,13 @@ /* catch interrupts and close down gracefully */ static volatile byte quit = 0; +static const char defaultBanner[] = "wolfSSHD\n"; + +/* Initial connection information to pass on to threads/forks */ +typedef struct WOLFSSHD_CONNECTION { + WOLFSSH_CTX* ctx; + int fd; +} WOLFSSHD_CONNECTION; static void ShowUsage(void) { @@ -59,18 +68,240 @@ static void interruptCatch(int in) quit = 1; } +static int SetupCTX(WOLFSSHD_CONFIG* conf, WOLFSSH_CTX** ctx) +{ + int ret = WS_SUCCESS; + const char* banner; + + /* create a new WOLFSSH_CTX */ + *ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL); + if (ctx == NULL) { + fprintf(stderr, "Couldn't allocate SSH CTX data.\n"); + ret = WS_MEMORY_E; + } + + /* setup authority callback for checking peer connections */ + if (ret == WS_SUCCESS) { +// WMEMSET(&pwMapList, 0, sizeof(pwMapList)); +// if (serverArgs->user_auth == NULL) +// wolfSSH_SetUserAuth(ctx, wsUserAuth); +// else +// wolfSSH_SetUserAuth(ctx, ((func_args*)args)->user_auth); + } + + /* set banner to display on connection */ + if (ret == WS_SUCCESS) { + banner = wolfSSHD_GetBanner(conf); + if (banner == NULL) { + banner = defaultBanner; + } + wolfSSH_CTX_SetBanner(*ctx, banner); + } + +#ifdef WOLFSSH_AGENT + /* check if using an agent is enabled */ + if (ret == WS_SUCCESS) { + wolfSSH_CTX_set_agent_cb(ctx, wolfSSH_AGENT_DefaultActions, NULL); + } +#endif + +#ifdef WOLFSSH_FWD + /* check if port forwarding is enabled */ + if (ret == WS_SUCCESS) { + wolfSSH_CTX_SetFwdCb(ctx, wolfSSH_FwdDefaultActions, NULL); + } +#endif + + /* Load in host private key */ +// { +// const char* bufName = NULL; +// #ifndef WOLFSSH_SMALL_STACK +// byte buf[EXAMPLE_KEYLOAD_BUFFER_SZ]; +// #endif +// byte* keyLoadBuf; +// word32 bufSz; +// +// #ifdef WOLFSSH_SMALL_STACK +// keyLoadBuf = (byte*)WMALLOC(EXAMPLE_KEYLOAD_BUFFER_SZ, +// NULL, 0); +// if (keyLoadBuf == NULL) { +// WEXIT(EXIT_FAILURE); +// } +// #else +// keyLoadBuf = buf; +// #endif +// bufSz = EXAMPLE_KEYLOAD_BUFFER_SZ; +// +// bufSz = load_key(peerEcc, keyLoadBuf, bufSz); +// if (bufSz == 0) { +// fprintf(stderr, "Couldn't load key file.\n"); +// WEXIT(EXIT_FAILURE); +// } +// if (wolfSSH_CTX_UsePrivateKey_buffer(ctx, keyLoadBuf, bufSz, +// WOLFSSH_FORMAT_ASN1) < 0) { +// fprintf(stderr, "Couldn't use key buffer.\n"); +// WEXIT(EXIT_FAILURE); +// } +// +// } + + /* Load in host public key */ +// { +// if (userPubKey) { +// byte* userBuf = NULL; +// word32 userBufSz = 0; +// +// /* get the files size */ +// load_file(userPubKey, NULL, &userBufSz); +// +// /* create temp buffer and load in file */ +// if (userBufSz == 0) { +// fprintf(stderr, "Couldn't find size of file %s.\n", userPubKey); +// WEXIT(EXIT_FAILURE); +// } +// +// userBuf = (byte*)WMALLOC(userBufSz, NULL, 0); +// if (userBuf == NULL) { +// fprintf(stderr, "WMALLOC failed\n"); +// WEXIT(EXIT_FAILURE); +// } +// load_file(userPubKey, userBuf, &userBufSz); +// LoadPublicKeyBuffer(userBuf, userBufSz, &pwMapList); +// } +// +// bufSz = (word32)WSTRLEN(samplePasswordBuffer); +// WMEMCPY(keyLoadBuf, samplePasswordBuffer, bufSz); +// keyLoadBuf[bufSz] = 0; +// LoadPasswordBuffer(keyLoadBuf, bufSz, &pwMapList); +// +// if (userEcc) { +// #ifndef WOLFSSH_NO_ECC +// bufName = samplePublicKeyEccBuffer; +// #endif +// } +// else { +// #ifndef WOLFSSH_NO_RSA +// bufName = samplePublicKeyRsaBuffer; +// #endif +// } +// if (bufName != NULL) { +// bufSz = (word32)WSTRLEN(bufName); +// WMEMCPY(keyLoadBuf, bufName, bufSz); +// keyLoadBuf[bufSz] = 0; +// LoadPublicKeyBuffer(keyLoadBuf, bufSz, &pwMapList); +// } +// +// bufSz = (word32)WSTRLEN(sampleNoneBuffer); +// WMEMCPY(keyLoadBuf, sampleNoneBuffer, bufSz); +// keyLoadBuf[bufSz] = 0; +// LoadNoneBuffer(keyLoadBuf, bufSz, &pwMapList); +// +// #ifdef WOLFSSH_SMALL_STACK +// WFREE(keyLoadBuf, NULL, 0); +// #endif +// } + + /* Load in authorized keys */ + + + /* Set allowed connection type, i.e. public key / password */ + + return ret; +} + + +#if 0 +int SFTP_Subsystem() +{ + +} + +int SCP_Subsystem() +{ + +} +#endif + +//static int SHELL_Subsystem(WOLFSSHD_CONNECTION* conn, WOLFSSH* ssh) +//{ +// (void)conn; +// (void)ssh; +// return WS_SUCCESS; +//} + + +/* handle wolfSSH accept and directing to correct subsystem */ +static void* wolfSSHD_HandleConnection(void* arg) +{ + WOLFSSHD_CONNECTION* conn; + WOLFSSH* ssh; + + conn = (WOLFSSHD_CONNECTION*)arg; + ssh = wolfSSH_new(conn->ctx); + wolfSSH_set_fd(ssh, conn->fd); + return NULL; +} + + +/* returns WS_SUCCESS on success */ +static int wolfSSHD_NewConnection(WOLFSSHD_CONNECTION* conn) +{ + int pd; + int ret = WS_SUCCESS; + + pd = fork(); + if (pd < 0) { + printf("issue spawning new process\n"); + ret = -1; + } + + if (pd == 0) { + /* child process */ + (void)wolfSSHD_HandleConnection((void*)&conn); + } + else { + printf("spawned new process %d\n", pd); + } + + return ret; +} + + int myoptind = 0; char* myoptarg = NULL; int main(int argc, char** argv) { - int ret = WS_SUCCESS; + int ret = WS_SUCCESS; + word16 port = 0; + WS_SOCKET_T listenFd = 0; int ch; WOLFSSHD_CONFIG* conf = NULL; + WOLFSSH_CTX* ctx = NULL; const char* configFile = "/usr/local/etc/ssh/sshd_config"; signal(SIGINT, interruptCatch); + + #ifdef DEBUG_WOLFSSH + wolfSSH_Debugging_ON(); + #endif + #ifdef DEBUG_WOLFSSL + wolfSSL_Debugging_ON(); + #endif + + if (ret == WS_SUCCESS) { + wolfSSH_Init(); + } + + if (ret == WS_SUCCESS) { + conf = wolfSSHD_NewConfig(NULL); + if (conf == NULL) { + ret = WS_MEMORY_E; + } + } + + while ((ch = mygetopt(argc, argv, "?f:")) != -1) { switch (ch) { case 'f': @@ -88,28 +319,47 @@ int main(int argc, char** argv) } if (ret == WS_SUCCESS) { - wolfSSH_Init(); + ret = wolfSSHD_LoadSSHD(conf, configFile); + if (ret != WS_SUCCESS) + printf("Error reading in configure file %s\n", configFile); } - if (ret == WS_SUCCESS) { - conf = wolfSSH_NewConfig(NULL); - if (conf == NULL) { - ret = WS_MEMORY_E; - } - } - - if (wolfSSH_LoadSSHD(conf, configFile) != WS_SUCCESS) { - printf("Error reading in configure file %s\n", configFile); + /* port was not overridden with argument, read from config file */ + if (port == 0) { + port = wolfSSHD_GetPort(conf); } printf("wolfSSH SSHD application\n"); + if (ret == WS_SUCCESS) { + ret = SetupCTX(conf, &ctx); + } + + tcp_listen(&listenFd, &port, 1); + /* wait for incoming connections and fork them off */ - do { + while (ret == WS_SUCCESS && quit == 0) { + WOLFSSHD_CONNECTION conn; + #ifdef WOLFSSL_NUCLEUS + struct addr_struct clientAddr; + #else + SOCKADDR_IN_T clientAddr; + socklen_t clientAddrSz = sizeof(clientAddr); + #endif - } while (ret == WS_SUCCESS && quit == 0); + /* wait for a connection */ + conn.ctx = ctx; + #ifdef WOLFSSL_NUCLEUS + conn.fd = NU_Accept(listenFd, &clientAddr, 0); + #else + conn.fd = accept(listenFd, (struct sockaddr*)&clientAddr, + &clientAddrSz); + #endif - wolfSSH_FreeConfig(conf); + ret = wolfSSHD_NewConnection(&conn); + } + + wolfSSHD_FreeConfig(conf); wolfSSH_Cleanup(); return 0; } diff --git a/apps/wolfsshd.h b/apps/wolfsshd.h index 0a6797a1..3494c3f7 100644 --- a/apps/wolfsshd.h +++ b/apps/wolfsshd.h @@ -23,9 +23,12 @@ typedef struct WOLFSSHD_CONFIG WOLFSSHD_CONFIG; -WOLFSSHD_CONFIG* wolfSSH_NewConfig(void* heap); -void wolfSSH_FreeConfig(WOLFSSHD_CONFIG* conf); -int wolfSSH_LoadSSHD(WOLFSSHD_CONFIG* con, const char* filename); +WOLFSSHD_CONFIG* wolfSSHD_NewConfig(void* heap); +void wolfSSHD_FreeConfig(WOLFSSHD_CONFIG* conf); +int wolfSSHD_LoadSSHD(WOLFSSHD_CONFIG* conf, const char* filename); + +char* wolfSSHD_GetBanner(WOLFSSHD_CONFIG* conf); +word16 wolfSSHD_GetPort(WOLFSSHD_CONFIG* conf); #endif /* WOLFSSHD_H */ From 5410cf569052ed6ac8f08005110d03644dce32f0 Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Mon, 13 Jun 2022 15:04:51 -0700 Subject: [PATCH 04/48] add tcp select and port arg --- apps/wolfconfig.c | 27 ++++++++ apps/wolfsshd.c | 154 +++++++++++++++++++++++++++++++++++++++------- 2 files changed, 158 insertions(+), 23 deletions(-) diff --git a/apps/wolfconfig.c b/apps/wolfconfig.c index 8c59fd29..a7f17559 100644 --- a/apps/wolfconfig.c +++ b/apps/wolfconfig.c @@ -158,6 +158,28 @@ static int wolfSSHD_ParseConfigLine(WOLFSSHD_CONFIG* conf, const char* l, ret = WS_SUCCESS; } + if (XSTRNCMP(l, "ChallengeResponseAuthentication", 31) == 0) { + ret = WS_SUCCESS; + } + + if (XSTRNCMP(l, "UsePAM", 6) == 0) { + ret = WS_SUCCESS; + } + + if (XSTRNCMP(l, "X11Forwarding", 13) == 0) { + ret = WS_SUCCESS; + } + + if (XSTRNCMP(l, "PrintMotd", 9) == 0) { + ret = WS_SUCCESS; + } + + if (XSTRNCMP(l, "AcceptEnv", 9) == 0) { + ret = WS_SUCCESS; + } + + + if (ret == WS_BAD_ARGUMENT) { printf("unknown / unsuported config line\n"); } @@ -178,6 +200,11 @@ int wolfSSHD_LoadSSHD(WOLFSSHD_CONFIG* conf, const char* filename) return BAD_FUNC_ARG; f = XFOPEN(filename, "rb"); + if (f == XBADFILE) { + printf("Unable to open SSHD config file %s\n", filename); + return BAD_FUNC_ARG; + } + while ((current = XFGETS(buf, MAX_LINE_SIZE, f)) != NULL) { int currentSz = (int)XSTRLEN(current); diff --git a/apps/wolfsshd.c b/apps/wolfsshd.c index f6c177af..b0417020 100644 --- a/apps/wolfsshd.c +++ b/apps/wolfsshd.c @@ -44,6 +44,10 @@ #include "src/misc.c" #endif +#ifndef WOLFSSHD_TIMEOUT + #define WOLFSSHD_TIMEOUT 1 +#endif + /* catch interrupts and close down gracefully */ static volatile byte quit = 0; static const char defaultBanner[] = "wolfSSHD\n"; @@ -59,6 +63,7 @@ static void ShowUsage(void) printf("wolfsshd %s\n", LIBWOLFSSH_VERSION_STRING); printf(" -? display this help and exit\n"); printf(" -f Configuration file to use, default is /usr/locacl/etc/ssh/sshd_config\n"); + printf(" -p Port number to listen on\n"); } static void interruptCatch(int in) @@ -68,6 +73,38 @@ static void interruptCatch(int in) quit = 1; } +static void wolfSSHDLoggingCb(enum wolfSSH_LogLevel lvl, const char *const str) +{ + fprintf(stderr, "[PID %d]: %s\n", getpid(), str); + (void)lvl; +} + +static int wsUserAuth(byte authType, + WS_UserAuthData* authData, + void* ctx) +{ + if (ctx == NULL) { + fprintf(stderr, "wsUserAuth: ctx not set"); + return WOLFSSH_USERAUTH_FAILURE; + } + + if (authType != WOLFSSH_USERAUTH_PASSWORD && +#ifdef WOLFSSH_ALLOW_USERAUTH_NONE + authType != WOLFSSH_USERAUTH_NONE && +#endif + authType != WOLFSSH_USERAUTH_PUBLICKEY) { + + return WOLFSSH_USERAUTH_FAILURE; + } + + (void)ctx; + (void)authData; + + /* @TODO allows all connections */ + return WOLFSSH_USERAUTH_SUCCESS; +} + + static int SetupCTX(WOLFSSHD_CONFIG* conf, WOLFSSH_CTX** ctx) { int ret = WS_SUCCESS; @@ -76,17 +113,13 @@ static int SetupCTX(WOLFSSHD_CONFIG* conf, WOLFSSH_CTX** ctx) /* create a new WOLFSSH_CTX */ *ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL); if (ctx == NULL) { - fprintf(stderr, "Couldn't allocate SSH CTX data.\n"); + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Couldn't allocate SSH CTX data."); ret = WS_MEMORY_E; } /* setup authority callback for checking peer connections */ if (ret == WS_SUCCESS) { -// WMEMSET(&pwMapList, 0, sizeof(pwMapList)); -// if (serverArgs->user_auth == NULL) -// wolfSSH_SetUserAuth(ctx, wsUserAuth); -// else -// wolfSSH_SetUserAuth(ctx, ((func_args*)args)->user_auth); + wolfSSH_SetUserAuth(*ctx, wsUserAuth); } /* set banner to display on connection */ @@ -233,12 +266,34 @@ int SCP_Subsystem() /* handle wolfSSH accept and directing to correct subsystem */ static void* wolfSSHD_HandleConnection(void* arg) { - WOLFSSHD_CONNECTION* conn; - WOLFSSH* ssh; + int ret = WS_SUCCESS; - conn = (WOLFSSHD_CONNECTION*)arg; - ssh = wolfSSH_new(conn->ctx); - wolfSSH_set_fd(ssh, conn->fd); + WOLFSSHD_CONNECTION* conn = NULL; + WOLFSSH* ssh = NULL; + + if (arg == NULL) { + ret = BAD_FUNC_ARG; + } + + if (ret == WS_SUCCESS) { + conn = (WOLFSSHD_CONNECTION*)arg; + ssh = wolfSSH_new(conn->ctx); + if (ssh == NULL) { + wolfSSH_Log(WS_LOG_ERROR, + "[SSHD] Failed to create new WOLFSSH struct"); + ret = -1; + } + } + + if (ret == WS_SUCCESS) { + wolfSSH_set_fd(ssh, conn->fd); + ret = wolfSSH_accept(ssh); + } + + wolfSSH_free(ssh); + if (conn != NULL) { + WCLOSESOCKET(conn->fd); + } return NULL; } @@ -251,22 +306,59 @@ static int wolfSSHD_NewConnection(WOLFSSHD_CONNECTION* conn) pd = fork(); if (pd < 0) { - printf("issue spawning new process\n"); + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Issue spawning new process"); ret = -1; } if (pd == 0) { /* child process */ - (void)wolfSSHD_HandleConnection((void*)&conn); + (void)wolfSSHD_HandleConnection((void*)conn); } else { - printf("spawned new process %d\n", pd); + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Spawned new process %d\n", pd); } return ret; } +/* return non zero value for a pending connection */ +static int wolfSSHD_PendingConnection(WS_SOCKET_T fd) +{ + int ret; + struct timeval t; + fd_set r, w, e; + WS_SOCKET_T nfds = fd + 1; + + t.tv_usec = 0; + t.tv_sec = WOLFSSHD_TIMEOUT; + + FD_ZERO(&r); + FD_ZERO(&w); + FD_ZERO(&e); + + FD_SET(fd, &r); + ret = select(nfds, &r, &w, &e, &t); + if (ret < 0) { + /* a socket level issue happend */ + printf("Error waiting for connection on socket\n"); + quit = 1; + ret = 0; + } + else if (ret > 0) { + if (FD_ISSET(fd, &r)) { + printf("Connection found\n"); + } + else { + printf("Found write or error data\n"); + ret = 0; /* nothing to read */ + } + } + // printf("Timeout waiting for connection\n"); + return ret; +} + + int myoptind = 0; char* myoptarg = NULL; @@ -283,6 +375,7 @@ int main(int argc, char** argv) signal(SIGINT, interruptCatch); + wolfSSH_SetLoggingCb(wolfSSHDLoggingCb); #ifdef DEBUG_WOLFSSH wolfSSH_Debugging_ON(); #endif @@ -302,12 +395,24 @@ int main(int argc, char** argv) } - while ((ch = mygetopt(argc, argv, "?f:")) != -1) { + while ((ch = mygetopt(argc, argv, "?f:p:")) != -1) { switch (ch) { case 'f': configFile = myoptarg; break; + case 'p': + ret = XATOI(myoptarg); + if (ret < 0) { + printf("Issue parsing port number %s\n", myoptarg); + ret = BAD_FUNC_ARG; + } + else { + port = (word16)ret; + ret = WS_SUCCESS; + } + break; + case '?': ShowUsage(); return WS_SUCCESS; @@ -329,13 +434,14 @@ int main(int argc, char** argv) port = wolfSSHD_GetPort(conf); } - printf("wolfSSH SSHD application\n"); + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Starting wolfSSH SSHD application"); if (ret == WS_SUCCESS) { ret = SetupCTX(conf, &ctx); } tcp_listen(&listenFd, &port, 1); + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Listening on port %d", port); /* wait for incoming connections and fork them off */ while (ret == WS_SUCCESS && quit == 0) { @@ -348,15 +454,17 @@ int main(int argc, char** argv) #endif /* wait for a connection */ - conn.ctx = ctx; - #ifdef WOLFSSL_NUCLEUS - conn.fd = NU_Accept(listenFd, &clientAddr, 0); - #else - conn.fd = accept(listenFd, (struct sockaddr*)&clientAddr, + if (wolfSSHD_PendingConnection(listenFd)) { + conn.ctx = ctx; + #ifdef WOLFSSL_NUCLEUS + conn.fd = NU_Accept(listenFd, &clientAddr, 0); + #else + conn.fd = accept(listenFd, (struct sockaddr*)&clientAddr, &clientAddrSz); - #endif + #endif - ret = wolfSSHD_NewConnection(&conn); + ret = wolfSSHD_NewConnection(&conn); + } } wolfSSHD_FreeConfig(conf); From 65dde05900c12c89f4b1dd699f5d0a73b2840e81 Mon Sep 17 00:00:00 2001 From: Jacob Barthelmeh Date: Tue, 21 Jun 2022 09:05:06 -0600 Subject: [PATCH 05/48] simple ssh connection and start of shell with sshd --- apps/wolfconfig.c | 18 ++- apps/wolfsshd.c | 274 ++++++++++++++++++++++++++++++++++++++-------- apps/wolfsshd.h | 2 + 3 files changed, 250 insertions(+), 44 deletions(-) diff --git a/apps/wolfconfig.c b/apps/wolfconfig.c index a7f17559..91d86241 100644 --- a/apps/wolfconfig.c +++ b/apps/wolfconfig.c @@ -219,7 +219,7 @@ int wolfSSHD_LoadSSHD(WOLFSSHD_CONFIG* conf, const char* filename) } if (current[0] == '#') { - printf("read commented out line\n%s\n", current); + //printf("read commented out line\n%s\n", current); continue; /* commented out line */ } @@ -241,6 +241,22 @@ char* wolfSSHD_GetBanner(WOLFSSHD_CONFIG* conf) return NULL; } +char* wolfSSHD_GetHostPrivateKey(WOLFSSHD_CONFIG* conf) +{ + if (conf != NULL) + return conf->hostKey; + return NULL; +} + +int wolfSSHD_SetHostPrivateKey(WOLFSSHD_CONFIG* conf, const char* hostKeyFile) +{ + if (conf == NULL) + return WS_BAD_ARGUMENT; + + conf->hostKey = (char*)hostKeyFile; + return WS_SUCCESS; +} + word16 wolfSSHD_GetPort(WOLFSSHD_CONFIG* conf) { if (conf != NULL) diff --git a/apps/wolfsshd.c b/apps/wolfsshd.c index b0417020..48d9c554 100644 --- a/apps/wolfsshd.c +++ b/apps/wolfsshd.c @@ -48,6 +48,28 @@ #define WOLFSSHD_TIMEOUT 1 #endif +#ifdef WOLFSSH_SHELL + #ifdef HAVE_PTY_H + #include + #endif + #ifdef HAVE_UTIL_H + #include + #endif + #ifdef HAVE_TERMIOS_H + #include + #endif + #include + #include + #include + + static volatile int ChildRunning = 0; + static void ChildSig(int sig) + { + (void)sig; + ChildRunning = 0; + } +#endif /* WOLFSSH_SHELL */ + /* catch interrupts and close down gracefully */ static volatile byte quit = 0; static const char defaultBanner[] = "wolfSSHD\n"; @@ -83,10 +105,10 @@ static int wsUserAuth(byte authType, WS_UserAuthData* authData, void* ctx) { - if (ctx == NULL) { - fprintf(stderr, "wsUserAuth: ctx not set"); - return WOLFSSH_USERAUTH_FAILURE; - } +// if (ctx == NULL) { +// fprintf(stderr, "wsUserAuth: ctx not set"); +// return WOLFSSH_USERAUTH_FAILURE; +// } if (authType != WOLFSSH_USERAUTH_PASSWORD && #ifdef WOLFSSH_ALLOW_USERAUTH_NONE @@ -100,6 +122,8 @@ static int wsUserAuth(byte authType, (void)ctx; (void)authData; + fprintf(stderr, "returning success always for now"); + /* @TODO allows all connections */ return WOLFSSH_USERAUTH_SUCCESS; } @@ -146,37 +170,40 @@ static int SetupCTX(WOLFSSHD_CONFIG* conf, WOLFSSH_CTX** ctx) #endif /* Load in host private key */ -// { -// const char* bufName = NULL; -// #ifndef WOLFSSH_SMALL_STACK -// byte buf[EXAMPLE_KEYLOAD_BUFFER_SZ]; -// #endif -// byte* keyLoadBuf; -// word32 bufSz; -// -// #ifdef WOLFSSH_SMALL_STACK -// keyLoadBuf = (byte*)WMALLOC(EXAMPLE_KEYLOAD_BUFFER_SZ, -// NULL, 0); -// if (keyLoadBuf == NULL) { -// WEXIT(EXIT_FAILURE); -// } -// #else -// keyLoadBuf = buf; -// #endif -// bufSz = EXAMPLE_KEYLOAD_BUFFER_SZ; -// -// bufSz = load_key(peerEcc, keyLoadBuf, bufSz); -// if (bufSz == 0) { -// fprintf(stderr, "Couldn't load key file.\n"); -// WEXIT(EXIT_FAILURE); -// } -// if (wolfSSH_CTX_UsePrivateKey_buffer(ctx, keyLoadBuf, bufSz, -// WOLFSSH_FORMAT_ASN1) < 0) { -// fprintf(stderr, "Couldn't use key buffer.\n"); -// WEXIT(EXIT_FAILURE); -// } -// -// } + if (ret == WS_SUCCESS) { + char* hostKey = wolfSSHD_GetHostPrivateKey(conf); + + if (hostKey == NULL) { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] No host private key set"); + ret = WS_BAD_ARGUMENT; + } + else { + FILE* f; + + f = fopen(hostKey, "rb"); + if (f == NULL) { + wolfSSH_Log(WS_LOG_ERROR, + "[SSHD] Unable to open host private key"); + ret = WS_BAD_ARGUMENT; + } + else { + byte* data; + int dataSz = 4096; + + data = (byte*)WMALLOC(dataSz, NULL, 0); + + dataSz = (int)fread(data, 1, dataSz, f); + fclose(f); + if (wolfSSH_CTX_UsePrivateKey_buffer(*ctx, data, dataSz, + WOLFSSH_FORMAT_ASN1) < 0) { + wolfSSH_Log(WS_LOG_ERROR, + "[SSHD] Unable parse host private key"); + ret = WS_BAD_ARGUMENT; + } + WFREE(data, NULL, 0); + } + } + } /* Load in host public key */ // { @@ -255,12 +282,148 @@ int SCP_Subsystem() } #endif -//static int SHELL_Subsystem(WOLFSSHD_CONNECTION* conn, WOLFSSH* ssh) -//{ -// (void)conn; -// (void)ssh; -// return WS_SUCCESS; -//} +#ifdef WOLFSSH_SHELL +static int SHELL_Subsystem(WOLFSSHD_CONNECTION* conn, WOLFSSH* ssh) +{ + WS_SOCKET_T sshFd = 0; + int rc; + const char *userName; + struct passwd *p_passwd; + WS_SOCKET_T childFd = 0; + pid_t childPid; +#ifndef EXAMPLE_BUFFER_SZ + #define EXAMPLE_BUFFER_SZ 4096 +#endif + byte shellBuffer[EXAMPLE_BUFFER_SZ]; + byte channelBuffer[EXAMPLE_BUFFER_SZ]; + + userName = wolfSSH_GetUsername(ssh); + p_passwd = getpwnam((const char *)userName); + if (p_passwd == NULL) { + /* Not actually a user on the system. */ + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Invalid user name found"); + return WS_FATAL_ERROR; + } + + ChildRunning = 1; + childPid = forkpty(&childFd, NULL, NULL, NULL); + + if (childPid < 0) { + /* forkpty failed, so return */ + ChildRunning = 0; + return WS_FATAL_ERROR; + } + else if (childPid == 0) { + /* Child process */ + const char *args[] = {"-sh", NULL}; + + signal(SIGINT, SIG_DFL); + + printf("userName is %s\n", userName); + system("env"); + + setenv("HOME", p_passwd->pw_dir, 1); + setenv("LOGNAME", p_passwd->pw_name, 1); + rc = chdir(p_passwd->pw_dir); + if (rc != 0) { + return WS_FATAL_ERROR; + } + + execv("/bin/sh", (char **)args); + } + + struct termios tios; + word32 shellChannelId = 0; + printf("In childPid > 0; getpid=%d\n", (int)getpid()); + signal(SIGCHLD, ChildSig); + + rc = tcgetattr(childFd, &tios); + if (rc != 0) { + return WS_FATAL_ERROR; + } + rc = tcsetattr(childFd, TCSAFLUSH, &tios); + if (rc != 0) { + return WS_FATAL_ERROR; + } + +#ifdef SHELL_DEBUG + termios_show(childFd); +#endif + + while (ChildRunning) { + fd_set readFds; + WS_SOCKET_T maxFd; + int cnt_r; + int cnt_w; + + FD_ZERO(&readFds); + FD_SET(sshFd, &readFds); + maxFd = sshFd; + + FD_SET(childFd, &readFds); + if (childFd > maxFd) + maxFd = childFd; + rc = select((int)maxFd + 1, &readFds, NULL, NULL, NULL); + if (rc == -1) + break; + + if (FD_ISSET(sshFd, &readFds)) { + word32 lastChannel = 0; + + /* The following tries to read from the first channel inside + the stream. If the pending data in the socket is for + another channel, this will return an error with id + WS_CHAN_RXD. That means the agent has pending data in its + channel. The additional channel is only used with the + agent. */ + cnt_r = wolfSSH_worker(ssh, &lastChannel); + if (cnt_r < 0) { + rc = wolfSSH_get_error(ssh); + if (rc == WS_CHAN_RXD) { + if (lastChannel == shellChannelId) { + cnt_r = wolfSSH_ChannelIdRead(ssh, shellChannelId, + channelBuffer, + sizeof channelBuffer); + if (cnt_r <= 0) + break; + cnt_w = (int)write(childFd, + channelBuffer, cnt_r); + if (cnt_w <= 0) + break; + } + } + else if (rc == WS_CHANNEL_CLOSED) { + continue; + } + else if (rc != WS_WANT_READ) { + break; + } + } + } + + if (FD_ISSET(childFd, &readFds)) { + cnt_r = (int)read(childFd, shellBuffer, sizeof shellBuffer); + /* This read will return 0 on EOF */ + if (cnt_r <= 0) { + int err = errno; + if (err != EAGAIN) { + break; + } + } + else { + if (cnt_r > 0) { + cnt_w = wolfSSH_ChannelIdSend(ssh, shellChannelId, + shellBuffer, cnt_r); + if (cnt_w < 0) + break; + } + } + } + } + (void)conn; + return WS_SUCCESS; +} +#endif /* handle wolfSSH accept and directing to correct subsystem */ @@ -288,8 +451,22 @@ static void* wolfSSHD_HandleConnection(void* arg) if (ret == WS_SUCCESS) { wolfSSH_set_fd(ssh, conn->fd); ret = wolfSSH_accept(ssh); + if (ret != WS_SUCCESS) { + wolfSSH_Log(WS_LOG_ERROR, + "[SSHD] Failed to accept WOLFSSH connection"); + } } +#ifdef WOLFSSH_SHELL + printf("ret of accept = %d\n",ret); + if (ret == WS_SUCCESS) { + printf("trying to run shell\n"); + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Entering new shell"); + SHELL_Subsystem(conn, ssh); + } +#endif + + wolfSSH_shutdown(ssh); wolfSSH_free(ssh); if (conn != NULL) { WCLOSESOCKET(conn->fd); @@ -371,7 +548,8 @@ int main(int argc, char** argv) WOLFSSHD_CONFIG* conf = NULL; WOLFSSH_CTX* ctx = NULL; - const char* configFile = "/usr/local/etc/ssh/sshd_config"; + const char* configFile = "/usr/local/etc/ssh/sshd_config"; + const char* hostKeyFile = NULL; signal(SIGINT, interruptCatch); @@ -395,7 +573,7 @@ int main(int argc, char** argv) } - while ((ch = mygetopt(argc, argv, "?f:p:")) != -1) { + while ((ch = mygetopt(argc, argv, "?f:p:h:")) != -1) { switch (ch) { case 'f': configFile = myoptarg; @@ -413,6 +591,10 @@ int main(int argc, char** argv) } break; + case 'h': + hostKeyFile = myoptarg; + break; + case '?': ShowUsage(); return WS_SUCCESS; @@ -434,12 +616,18 @@ int main(int argc, char** argv) port = wolfSSHD_GetPort(conf); } + /* check if host key file was passed in */ + if (hostKeyFile != NULL) { + wolfSSHD_SetHostPrivateKey(conf, hostKeyFile); + } + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Starting wolfSSH SSHD application"); if (ret == WS_SUCCESS) { ret = SetupCTX(conf, &ctx); } + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Starting to listen on port %d", port); tcp_listen(&listenFd, &port, 1); wolfSSH_Log(WS_LOG_INFO, "[SSHD] Listening on port %d", port); diff --git a/apps/wolfsshd.h b/apps/wolfsshd.h index 3494c3f7..aa216a3c 100644 --- a/apps/wolfsshd.h +++ b/apps/wolfsshd.h @@ -28,6 +28,8 @@ void wolfSSHD_FreeConfig(WOLFSSHD_CONFIG* conf); int wolfSSHD_LoadSSHD(WOLFSSHD_CONFIG* conf, const char* filename); char* wolfSSHD_GetBanner(WOLFSSHD_CONFIG* conf); +char* wolfSSHD_GetHostPrivateKey(WOLFSSHD_CONFIG* conf); +int wolfSSHD_SetHostPrivateKey(WOLFSSHD_CONFIG* conf, const char* hostKeyFile); word16 wolfSSHD_GetPort(WOLFSSHD_CONFIG* conf); #endif /* WOLFSSHD_H */ From 475ee1f113ccd9bdd29e5be06785ae7696f781c2 Mon Sep 17 00:00:00 2001 From: Jacob Barthelmeh Date: Wed, 6 Jul 2022 16:22:44 -0600 Subject: [PATCH 06/48] add wolfauth file for peer auth --- apps/include.am | 6 +- apps/wolfauth.c | 256 ++++++++++++++++++++++++++++++++++++++++++++++ apps/wolfconfig.c | 37 ++++++- apps/wolfsshd.c | 145 +++++++++++++++++--------- apps/wolfsshd.h | 4 + 5 files changed, 394 insertions(+), 54 deletions(-) create mode 100644 apps/wolfauth.c diff --git a/apps/include.am b/apps/include.am index eddc4c60..114ba9a0 100644 --- a/apps/include.am +++ b/apps/include.am @@ -3,9 +3,11 @@ if BUILD_SSHD bin_PROGRAMS += apps/wolfsshd -noinst_HEADERS += apps/wolfsshd.h +noinst_HEADERS += apps/wolfsshd.h \ + apps/wolfauth.h apps_wolfsshd_SOURCES = apps/wolfsshd.c \ - apps/wolfconfig.c + apps/wolfconfig.c \ + apps/wolfauth.c apps_wolfsshd_LDADD = src/libwolfssh.la apps_wolfsshd_DEPENDENCIES = src/libwolfssh.la endif diff --git a/apps/wolfauth.c b/apps/wolfauth.c new file mode 100644 index 00000000..fa98f8a4 --- /dev/null +++ b/apps/wolfauth.c @@ -0,0 +1,256 @@ +/* wolfauth.c + * + * Copyright (C) 2014-2021 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 . + */ + +#ifdef HAVE_CONFIG_H + #include +#endif + +#ifdef WOLFSSH_SSHD + +#include +#include +#include +#include +#include + +#ifdef NO_INLINE + #include +#else + #define WOLFSSH_MISC_INCLUDED + #include "src/misc.c" +#endif + +#include "wolfauth.h" + +#include + +#include +#include +#include + +static byte passwdRetry = 3; + +/* Map user names to passwords */ +/* Use arrays for username and p. The password or public key can + * be hashed and the hash stored here. Then I won't need the type. */ +struct USER_NODE { + byte type; + byte username[32]; + word32 usernameSz; + byte fingerprint[WC_SHA256_DIGEST_SIZE]; + struct USER_NODE* next; +}; + + +/* Takes a users input and adds it to the list of accepted users + * 'value' can be a users password / public key / or certificate + * returns an updated list on success (i.e. 'new' -> 'list' -> ...) or NULL + * on failure + */ +USER_NODE* AddNewUser(USER_NODE* list, byte type, const byte* username, + word32 usernameSz, const byte* value, word32 valueSz) +{ + USER_NODE* map; + + map = (USER_NODE*)WMALLOC(sizeof(USER_NODE), NULL, 0); + if (map != NULL) { + map->type = type; + if (usernameSz >= sizeof(map->username)) + usernameSz = sizeof(map->username) - 1; + WMEMCPY(map->username, username, usernameSz + 1); + map->username[usernameSz] = 0; + map->usernameSz = usernameSz; + + if (type != WOLFSSH_USERAUTH_NONE) { + wc_Sha256Hash(value, valueSz, map->fingerprint); + } + + map->next = list; + } + + return map; +} + + +/* returns WS_SUCCESS if user/password found */ +static int CheckPassword(const byte* usr, const byte* pw, int pwSz) +{ + int ret = WS_SUCCESS; + struct passwd* pwInfo; +// struct spwd* spwInfo; + char* encPw; /* encrypted version of password */ + char tmp[256]; + + pwInfo = getpwnam((const char*)usr); + if (pwInfo == NULL) { + /* user name not found on system */ + ret = WS_FATAL_ERROR; + } + + /* check for shadow password record */ +// spwInfo = getspnam(usr); +// if (spwInfo != NULL) { +// pwInfo->pw_passwd = spwInfo->sp_pwdp; +// } +// +{ + int z; + for (z = 0; z < pwSz; z++) + tmp[z] = pw[z]; + tmp[z] = '\0'; +} + + if (ret == WS_SUCCESS) { + encPw = crypt((const char*)tmp, pwInfo->pw_passwd); + if (encPw == NULL) { + /* error encrypting password for comparison */ + ret = WS_FATAL_ERROR; + } + } + +{ + int z; + printf("peer pw : "); + for (z = 0; z < pwSz; z++) + printf("%02X", pw[z]); + printf("\n"); + printf(" pw : "); + for (z = 0; z < pwSz; z++) + printf("%02X", pwInfo->pw_passwd[z]); + printf("\n"); + printf(" enc : "); + for (z = 0; z < pwSz; z++) + printf("%02X", encPw[z]); + printf("\n"); +} + if (ret == WS_SUCCESS) { + if (XSTRCMP(encPw, pwInfo->pw_passwd) == 0) { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] User %s log in successful", usr); + } + else { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] User %s log in fail", usr); + ret = WS_FATAL_ERROR; + } + } + (void)pwSz; + + return ret; +} + + +int DefaultUserAuth(byte authType, WS_UserAuthData* authData, void* ctx) +{ + USER_NODE* map; + byte authHash[WC_SHA256_DIGEST_SIZE]; + int ret; + + if (authType != WOLFSSH_USERAUTH_PASSWORD && +#ifdef WOLFSSH_ALLOW_USERAUTH_NONE + authType != WOLFSSH_USERAUTH_NONE && +#endif + authType != WOLFSSH_USERAUTH_PUBLICKEY) { + + return WOLFSSH_USERAUTH_FAILURE; + } + map = (USER_NODE*)ctx; + + /* check if password on system */ + if (authData->type == WOLFSSH_USERAUTH_PASSWORD) { + if (CheckPassword(authData->username, authData->sf.password.password, + authData->sf.password.passwordSz) == WS_SUCCESS) { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Password and user on system"); + return WOLFSSH_USERAUTH_SUCCESS; + } + } + + if (authType == WOLFSSH_USERAUTH_PASSWORD) { + wc_Sha256Hash(authData->sf.password.password, + authData->sf.password.passwordSz, + authHash); + } + else if (authType == WOLFSSH_USERAUTH_PUBLICKEY) { + wc_Sha256Hash(authData->sf.publicKey.publicKey, + authData->sf.publicKey.publicKeySz, + authHash); + } + + while (map != NULL) { + if (authData->usernameSz == map->usernameSz && + WMEMCMP(authData->username, map->username, map->usernameSz) == 0 && + authData->type == map->type) { + + if (authData->type == WOLFSSH_USERAUTH_PUBLICKEY) { + if (WMEMCMP(map->fingerprint, authHash, + WC_SHA256_DIGEST_SIZE) == 0) { + return WOLFSSH_USERAUTH_SUCCESS; + } + else { + return WOLFSSH_USERAUTH_INVALID_PUBLICKEY; + } + } + else if (authData->type == WOLFSSH_USERAUTH_PASSWORD) { + if (WMEMCMP(map->fingerprint, authHash, + WC_SHA256_DIGEST_SIZE) == 0) { + return WOLFSSH_USERAUTH_SUCCESS; + } + else { + passwdRetry--; + return (passwdRetry > 0) ? + WOLFSSH_USERAUTH_INVALID_PASSWORD : + WOLFSSH_USERAUTH_REJECTED; + } + } +#ifdef WOLFSSH_ALLOW_USERAUTH_NONE + else if (authData->type == WOLFSSH_USERAUTH_NONE) { + return WOLFSSH_USERAUTH_SUCCESS; + } +#endif /* WOLFSSH_ALLOW_USERAUTH_NONE */ + else { + return WOLFSSH_USERAUTH_INVALID_AUTHTYPE; + } + + if (authData->type == map->type) { + if (WMEMCMP(map->fingerprint, authHash, + WC_SHA256_DIGEST_SIZE) == 0) { + return WOLFSSH_USERAUTH_SUCCESS; + } + else { + if (authType == WOLFSSH_USERAUTH_PASSWORD) { + passwdRetry--; + ret = (passwdRetry > 0) ? + WOLFSSH_USERAUTH_INVALID_PASSWORD : + WOLFSSH_USERAUTH_REJECTED; + } + else { + ret = WOLFSSH_USERAUTH_INVALID_PUBLICKEY; + } + return ret; + } + } + else { + return WOLFSSH_USERAUTH_INVALID_AUTHTYPE; + } + } + map = map->next; + } + + return WOLFSSH_USERAUTH_INVALID_USER; +} +#endif /* WOLFSSH_SSHD */ diff --git a/apps/wolfconfig.c b/apps/wolfconfig.c index 91d86241..c745f388 100644 --- a/apps/wolfconfig.c +++ b/apps/wolfconfig.c @@ -52,11 +52,11 @@ struct WOLFSSHD_CONFIG { char* listenAddress; char* authKeysFile; word16 port; + byte usePrivilegeSeparation; byte passwordAuth:1; byte pubKeyAuth:1; byte permitRootLogin:1; byte permitEmptyPasswords:1; - byte usePrivilegeSeparation:1; }; /* returns WS_SUCCESS on success */ @@ -141,7 +141,8 @@ static int wolfSSHD_ParseConfigLine(WOLFSSHD_CONFIG* conf, const char* l, int sz; /* supported config options */ - const char authKeyFile[] = "AuthorizedKeysFile"; + const char authKeyFile[] = "AuthorizedKeysFile"; + const char privilegeSeparation[] = "UsePrivilegeSeparation"; sz = (int)XSTRLEN(authKeyFile); if (lSz > sz && XSTRNCMP(l, authKeyFile, sz) == 0) { @@ -149,8 +150,32 @@ static int wolfSSHD_ParseConfigLine(WOLFSSHD_CONFIG* conf, const char* l, conf->heap); } - if (XSTRNCMP(l, "UsePrivilegeSeparation", 18) == 0) { - ret = WS_SUCCESS; + sz = (int)XSTRLEN(privilegeSeparation); + if (lSz > sz && XSTRNCMP(l, privilegeSeparation, sz) == 0) { + char* privType = NULL; + ret = wolfSSHD_CreateString(&privType, l + sz, lSz - sz, conf->heap); + + /* check if is an allowed option */ + if (XSTRNCMP(privType, "sandbox", 7) == 0) { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Sandbox privilege separation"); + ret = WS_SUCCESS; + } + + if (XSTRNCMP(privType, "yes", 3) == 0) { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Privilege separation enabled"); + ret = WS_SUCCESS; + } + + if (XSTRNCMP(privType, "no", 2) == 0) { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Turning off privilege separation!"); + ret = WS_SUCCESS; + } + + if (ret != WS_SUCCESS) { + wolfSSH_Log(WS_LOG_ERROR, + "[SSHD] Unknown/supported privilege separation!"); + } + wolfSSHD_FreeString(&privType, conf->heap); } if (XSTRNCMP(l, "Subsystem", 9) == 0) { @@ -201,9 +226,11 @@ int wolfSSHD_LoadSSHD(WOLFSSHD_CONFIG* conf, const char* filename) f = XFOPEN(filename, "rb"); if (f == XBADFILE) { - printf("Unable to open SSHD config file %s\n", filename); + wolfSSH_Log(WS_LOG_ERROR, "Unable to open SSHD config file %s\n", + filename); return BAD_FUNC_ARG; } + wolfSSH_Log(WS_LOG_INFO, "[SSHD] parsing config file %s", filename); while ((current = XFGETS(buf, MAX_LINE_SIZE, f)) != NULL) { int currentSz = (int)XSTRLEN(current); diff --git a/apps/wolfsshd.c b/apps/wolfsshd.c index 48d9c554..1e2430c8 100644 --- a/apps/wolfsshd.c +++ b/apps/wolfsshd.c @@ -34,6 +34,7 @@ #include #include "wolfsshd.h" +#include "wolfauth.h" #include @@ -70,6 +71,8 @@ } #endif /* WOLFSSH_SHELL */ +static volatile byte debugMode = 0; /* default to off */ + /* catch interrupts and close down gracefully */ static volatile byte quit = 0; static const char defaultBanner[] = "wolfSSHD\n"; @@ -86,6 +89,7 @@ static void ShowUsage(void) printf(" -? display this help and exit\n"); printf(" -f Configuration file to use, default is /usr/locacl/etc/ssh/sshd_config\n"); printf(" -p Port number to listen on\n"); + printf(" -d Turn on debug mode\n"); } static void interruptCatch(int in) @@ -97,35 +101,10 @@ static void interruptCatch(int in) static void wolfSSHDLoggingCb(enum wolfSSH_LogLevel lvl, const char *const str) { - fprintf(stderr, "[PID %d]: %s\n", getpid(), str); - (void)lvl; -} - -static int wsUserAuth(byte authType, - WS_UserAuthData* authData, - void* ctx) -{ -// if (ctx == NULL) { -// fprintf(stderr, "wsUserAuth: ctx not set"); -// return WOLFSSH_USERAUTH_FAILURE; -// } - - if (authType != WOLFSSH_USERAUTH_PASSWORD && -#ifdef WOLFSSH_ALLOW_USERAUTH_NONE - authType != WOLFSSH_USERAUTH_NONE && -#endif - authType != WOLFSSH_USERAUTH_PUBLICKEY) { - - return WOLFSSH_USERAUTH_FAILURE; + if (debugMode) { + fprintf(stderr, "[PID %d]: %s\n", getpid(), str); } - - (void)ctx; - (void)authData; - - fprintf(stderr, "returning success always for now"); - - /* @TODO allows all connections */ - return WOLFSSH_USERAUTH_SUCCESS; + (void)lvl; } @@ -143,7 +122,7 @@ static int SetupCTX(WOLFSSHD_CONFIG* conf, WOLFSSH_CTX** ctx) /* setup authority callback for checking peer connections */ if (ret == WS_SUCCESS) { - wolfSSH_SetUserAuth(*ctx, wsUserAuth); + wolfSSH_SetUserAuth(*ctx, DefaultUserAuth); } /* set banner to display on connection */ @@ -270,12 +249,67 @@ static int SetupCTX(WOLFSSHD_CONFIG* conf, WOLFSSH_CTX** ctx) } -#if 0 -int SFTP_Subsystem() +#ifdef WOLFSSH_SFTP +/* handle SFTP operations + * returns 0 on success + */ +static int SFTP_Subsystem(WOLFSSH* ssh, WOLFSSHD_CONNECTION* conn) { + byte tmp[1]; + int ret = WS_SUCCESS; + int error = WS_SUCCESS; + WS_SOCKET_T sockfd; + int select_ret = 0; + sockfd = (WS_SOCKET_T)wolfSSH_get_fd(ssh); + do { +// if (threadCtx->nonBlock) { +// if (error == WS_WANT_READ) +// printf("... sftp server would read block\n"); +// else if (error == WS_WANT_WRITE) +// printf("... sftp server would write block\n"); +// } + + if (wolfSSH_stream_peek(ssh, tmp, 1) > 0) { + select_ret = WS_SELECT_RECV_READY; + } + else { + select_ret = tcp_select(sockfd, TEST_SFTP_TIMEOUT); + } + + if (select_ret == WS_SELECT_RECV_READY || + select_ret == WS_SELECT_ERROR_READY || + error == WS_WANT_WRITE) + { + ret = wolfSSH_SFTP_read(ssh); + error = wolfSSH_get_error(ssh); + } + else if (select_ret == WS_SELECT_TIMEOUT) + error = WS_WANT_READ; + else + error = WS_FATAL_ERROR; + + if (error == WS_WANT_READ || error == WS_WANT_WRITE || + error == WS_CHAN_RXD || error == WS_REKEYING || + error == WS_WINDOW_FULL) + ret = error; + + if (ret == WS_FATAL_ERROR && error == 0) { + WOLFSSH_CHANNEL* channel = + wolfSSH_ChannelNext(ssh, NULL); + if (channel && wolfSSH_ChannelGetEof(channel)) { + ret = 0; + break; + } + } + } while (ret != WS_FATAL_ERROR); + + return ret; } +#endif + +#ifdef WOLFSSH_SCP int SCP_Subsystem() { @@ -457,14 +491,25 @@ static void* wolfSSHD_HandleConnection(void* arg) } } -#ifdef WOLFSSH_SHELL - printf("ret of accept = %d\n",ret); - if (ret == WS_SUCCESS) { - printf("trying to run shell\n"); - wolfSSH_Log(WS_LOG_INFO, "[SSHD] Entering new shell"); - SHELL_Subsystem(conn, ssh); + switch (ret) { + case WS_SFTP_COMPLETE: + #ifdef WOLFSSH_SFTP + ret = SFTP_Subsystem(ssh, conn); + #else + err_sys("SFTP not compiled in. Please use --enable-sftp"); + #endif + break; + + case WS_SUCCESS: /* default success case to shell */ + #ifdef WOLFSSH_SHELL + printf("ret of accept = %d\n",ret); + if (ret == WS_SUCCESS) { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Entering new shell"); + SHELL_Subsystem(conn, ssh); + } + #endif + break; } -#endif wolfSSH_shutdown(ssh); wolfSSH_free(ssh); @@ -573,21 +618,23 @@ int main(int argc, char** argv) } - while ((ch = mygetopt(argc, argv, "?f:p:h:")) != -1) { + while ((ch = mygetopt(argc, argv, "?f:p:h:d")) != -1) { switch (ch) { case 'f': configFile = myoptarg; break; case 'p': - ret = XATOI(myoptarg); - if (ret < 0) { - printf("Issue parsing port number %s\n", myoptarg); - ret = BAD_FUNC_ARG; - } - else { - port = (word16)ret; - ret = WS_SUCCESS; + if (ret == WS_SUCCESS) { + ret = XATOI(myoptarg); + if (ret < 0) { + printf("Issue parsing port number %s\n", myoptarg); + ret = BAD_FUNC_ARG; + } + else { + port = (word16)ret; + ret = WS_SUCCESS; + } } break; @@ -595,6 +642,10 @@ int main(int argc, char** argv) hostKeyFile = myoptarg; break; + case 'd': + debugMode = 1; /* turn on debug mode */ + break; + case '?': ShowUsage(); return WS_SUCCESS; diff --git a/apps/wolfsshd.h b/apps/wolfsshd.h index aa216a3c..47650711 100644 --- a/apps/wolfsshd.h +++ b/apps/wolfsshd.h @@ -23,6 +23,10 @@ typedef struct WOLFSSHD_CONFIG WOLFSSHD_CONFIG; +#define WOLFSSHD_PRIV_SEPARAT 0 +#define WOLFSSHD_PRIV_SANDBOX 1 +#define WOLFSSHD_PRIV_OFF 2 + WOLFSSHD_CONFIG* wolfSSHD_NewConfig(void* heap); void wolfSSHD_FreeConfig(WOLFSSHD_CONFIG* conf); int wolfSSHD_LoadSSHD(WOLFSSHD_CONFIG* conf, const char* filename); From 474527b89c09d168d873d247c8d8d2b9f9d4790d Mon Sep 17 00:00:00 2001 From: Jacob Barthelmeh Date: Wed, 6 Jul 2022 16:31:59 -0600 Subject: [PATCH 07/48] add missing wolfauth header file --- apps/wolfauth.h | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 apps/wolfauth.h diff --git a/apps/wolfauth.h b/apps/wolfauth.h new file mode 100644 index 00000000..0347f06f --- /dev/null +++ b/apps/wolfauth.h @@ -0,0 +1,31 @@ +/* wolfauth.h + * + * Copyright (C) 2014-2021 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 . + */ + + + +#ifndef WOLFAUTH_H +#define WOLFAUTH_H + +typedef struct USER_NODE USER_NODE; + +USER_NODE* AddNewUser(USER_NODE* list, byte type, const byte* username, + word32 usernameSz, const byte* value, word32 valueSz); +int DefaultUserAuth(byte authType, WS_UserAuthData* authData, void* ctx); +#endif /* WOLFAUTH_H */ From 787d5be9006dc35d7761c308649e2330d5d8dbc8 Mon Sep 17 00:00:00 2001 From: Hayden Roche Date: Thu, 7 Jul 2022 13:01:43 -0700 Subject: [PATCH 08/48] Add more functionality to wolfsshd, other improvements. - Moved all wolfsshd source code into apps/wolfsshd/. Then future apps, e.g. an ssh-keygen type utility, will get their own subdirectory under apps/. - Rename wolfauth.(c|h) to auth.(c|h), rename wolfconfig.c to config.c. - Add support for checking user public keys against an authorized keys file. Doesn't support parsing options and comments in the key file, yet. Parsing special tokens (e.g. %h) and absolute paths in the AuthorizedKeysFile string are also not supported. - Comment out currently unused USER_NODE code. Could be useful later on if we integrate wolfsshd in an environment where the OS doesn't have its own username service. - Modify configure.ac to bring in libcrypt if wolfsshd is enabled. --- .gitignore | 6 +- Makefile.am | 2 +- apps/include.am | 16 - apps/wolfauth.c | 256 ---------- apps/wolfsshd/auth.c | 587 +++++++++++++++++++++++ apps/{wolfauth.h => wolfsshd/auth.h} | 9 +- apps/{wolfconfig.c => wolfsshd/config.c} | 31 +- apps/wolfsshd/include.am | 14 + apps/{ => wolfsshd}/wolfsshd.c | 36 +- apps/{ => wolfsshd}/wolfsshd.h | 5 + configure.ac | 4 + 11 files changed, 668 insertions(+), 298 deletions(-) delete mode 100644 apps/include.am delete mode 100644 apps/wolfauth.c create mode 100644 apps/wolfsshd/auth.c rename apps/{wolfauth.h => wolfsshd/auth.h} (93%) rename apps/{wolfconfig.c => wolfsshd/config.c} (92%) create mode 100644 apps/wolfsshd/include.am rename apps/{ => wolfsshd}/wolfsshd.c (97%) rename apps/{ => wolfsshd}/wolfsshd.h (90%) diff --git a/.gitignore b/.gitignore index 6a688fca..8db4d74d 100644 --- a/.gitignore +++ b/.gitignore @@ -23,7 +23,9 @@ aclocal.m4 lt*.m4 *.cache -config.* +config.h* +configure~ +config.status configure libtool libtool.m4 @@ -55,7 +57,7 @@ examples/sftpclient/wolfsftp examples/scpclient/wolfscp # applications -apps/wolfsshd +apps/wolfsshd/wolfsshd # test output tests/*.test diff --git a/Makefile.am b/Makefile.am index f03df800..a8759d4f 100644 --- a/Makefile.am +++ b/Makefile.am @@ -33,7 +33,7 @@ EXTRA_DIST+= LICENSING README.md ChangeLog.md include src/include.am include wolfssh/include.am -include apps/include.am +include apps/wolfsshd/include.am include examples/include.am include tests/include.am include keys/include.am diff --git a/apps/include.am b/apps/include.am deleted file mode 100644 index 114ba9a0..00000000 --- a/apps/include.am +++ /dev/null @@ -1,16 +0,0 @@ -# vim:ft=automake -# All paths should be given relative to the root - -if BUILD_SSHD -bin_PROGRAMS += apps/wolfsshd -noinst_HEADERS += apps/wolfsshd.h \ - apps/wolfauth.h -apps_wolfsshd_SOURCES = apps/wolfsshd.c \ - apps/wolfconfig.c \ - apps/wolfauth.c -apps_wolfsshd_LDADD = src/libwolfssh.la -apps_wolfsshd_DEPENDENCIES = src/libwolfssh.la -endif - -DISTCLEANFILES+= apps/.libs/wolfsshd - diff --git a/apps/wolfauth.c b/apps/wolfauth.c deleted file mode 100644 index fa98f8a4..00000000 --- a/apps/wolfauth.c +++ /dev/null @@ -1,256 +0,0 @@ -/* wolfauth.c - * - * Copyright (C) 2014-2021 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 . - */ - -#ifdef HAVE_CONFIG_H - #include -#endif - -#ifdef WOLFSSH_SSHD - -#include -#include -#include -#include -#include - -#ifdef NO_INLINE - #include -#else - #define WOLFSSH_MISC_INCLUDED - #include "src/misc.c" -#endif - -#include "wolfauth.h" - -#include - -#include -#include -#include - -static byte passwdRetry = 3; - -/* Map user names to passwords */ -/* Use arrays for username and p. The password or public key can - * be hashed and the hash stored here. Then I won't need the type. */ -struct USER_NODE { - byte type; - byte username[32]; - word32 usernameSz; - byte fingerprint[WC_SHA256_DIGEST_SIZE]; - struct USER_NODE* next; -}; - - -/* Takes a users input and adds it to the list of accepted users - * 'value' can be a users password / public key / or certificate - * returns an updated list on success (i.e. 'new' -> 'list' -> ...) or NULL - * on failure - */ -USER_NODE* AddNewUser(USER_NODE* list, byte type, const byte* username, - word32 usernameSz, const byte* value, word32 valueSz) -{ - USER_NODE* map; - - map = (USER_NODE*)WMALLOC(sizeof(USER_NODE), NULL, 0); - if (map != NULL) { - map->type = type; - if (usernameSz >= sizeof(map->username)) - usernameSz = sizeof(map->username) - 1; - WMEMCPY(map->username, username, usernameSz + 1); - map->username[usernameSz] = 0; - map->usernameSz = usernameSz; - - if (type != WOLFSSH_USERAUTH_NONE) { - wc_Sha256Hash(value, valueSz, map->fingerprint); - } - - map->next = list; - } - - return map; -} - - -/* returns WS_SUCCESS if user/password found */ -static int CheckPassword(const byte* usr, const byte* pw, int pwSz) -{ - int ret = WS_SUCCESS; - struct passwd* pwInfo; -// struct spwd* spwInfo; - char* encPw; /* encrypted version of password */ - char tmp[256]; - - pwInfo = getpwnam((const char*)usr); - if (pwInfo == NULL) { - /* user name not found on system */ - ret = WS_FATAL_ERROR; - } - - /* check for shadow password record */ -// spwInfo = getspnam(usr); -// if (spwInfo != NULL) { -// pwInfo->pw_passwd = spwInfo->sp_pwdp; -// } -// -{ - int z; - for (z = 0; z < pwSz; z++) - tmp[z] = pw[z]; - tmp[z] = '\0'; -} - - if (ret == WS_SUCCESS) { - encPw = crypt((const char*)tmp, pwInfo->pw_passwd); - if (encPw == NULL) { - /* error encrypting password for comparison */ - ret = WS_FATAL_ERROR; - } - } - -{ - int z; - printf("peer pw : "); - for (z = 0; z < pwSz; z++) - printf("%02X", pw[z]); - printf("\n"); - printf(" pw : "); - for (z = 0; z < pwSz; z++) - printf("%02X", pwInfo->pw_passwd[z]); - printf("\n"); - printf(" enc : "); - for (z = 0; z < pwSz; z++) - printf("%02X", encPw[z]); - printf("\n"); -} - if (ret == WS_SUCCESS) { - if (XSTRCMP(encPw, pwInfo->pw_passwd) == 0) { - wolfSSH_Log(WS_LOG_INFO, "[SSHD] User %s log in successful", usr); - } - else { - wolfSSH_Log(WS_LOG_INFO, "[SSHD] User %s log in fail", usr); - ret = WS_FATAL_ERROR; - } - } - (void)pwSz; - - return ret; -} - - -int DefaultUserAuth(byte authType, WS_UserAuthData* authData, void* ctx) -{ - USER_NODE* map; - byte authHash[WC_SHA256_DIGEST_SIZE]; - int ret; - - if (authType != WOLFSSH_USERAUTH_PASSWORD && -#ifdef WOLFSSH_ALLOW_USERAUTH_NONE - authType != WOLFSSH_USERAUTH_NONE && -#endif - authType != WOLFSSH_USERAUTH_PUBLICKEY) { - - return WOLFSSH_USERAUTH_FAILURE; - } - map = (USER_NODE*)ctx; - - /* check if password on system */ - if (authData->type == WOLFSSH_USERAUTH_PASSWORD) { - if (CheckPassword(authData->username, authData->sf.password.password, - authData->sf.password.passwordSz) == WS_SUCCESS) { - wolfSSH_Log(WS_LOG_INFO, "[SSHD] Password and user on system"); - return WOLFSSH_USERAUTH_SUCCESS; - } - } - - if (authType == WOLFSSH_USERAUTH_PASSWORD) { - wc_Sha256Hash(authData->sf.password.password, - authData->sf.password.passwordSz, - authHash); - } - else if (authType == WOLFSSH_USERAUTH_PUBLICKEY) { - wc_Sha256Hash(authData->sf.publicKey.publicKey, - authData->sf.publicKey.publicKeySz, - authHash); - } - - while (map != NULL) { - if (authData->usernameSz == map->usernameSz && - WMEMCMP(authData->username, map->username, map->usernameSz) == 0 && - authData->type == map->type) { - - if (authData->type == WOLFSSH_USERAUTH_PUBLICKEY) { - if (WMEMCMP(map->fingerprint, authHash, - WC_SHA256_DIGEST_SIZE) == 0) { - return WOLFSSH_USERAUTH_SUCCESS; - } - else { - return WOLFSSH_USERAUTH_INVALID_PUBLICKEY; - } - } - else if (authData->type == WOLFSSH_USERAUTH_PASSWORD) { - if (WMEMCMP(map->fingerprint, authHash, - WC_SHA256_DIGEST_SIZE) == 0) { - return WOLFSSH_USERAUTH_SUCCESS; - } - else { - passwdRetry--; - return (passwdRetry > 0) ? - WOLFSSH_USERAUTH_INVALID_PASSWORD : - WOLFSSH_USERAUTH_REJECTED; - } - } -#ifdef WOLFSSH_ALLOW_USERAUTH_NONE - else if (authData->type == WOLFSSH_USERAUTH_NONE) { - return WOLFSSH_USERAUTH_SUCCESS; - } -#endif /* WOLFSSH_ALLOW_USERAUTH_NONE */ - else { - return WOLFSSH_USERAUTH_INVALID_AUTHTYPE; - } - - if (authData->type == map->type) { - if (WMEMCMP(map->fingerprint, authHash, - WC_SHA256_DIGEST_SIZE) == 0) { - return WOLFSSH_USERAUTH_SUCCESS; - } - else { - if (authType == WOLFSSH_USERAUTH_PASSWORD) { - passwdRetry--; - ret = (passwdRetry > 0) ? - WOLFSSH_USERAUTH_INVALID_PASSWORD : - WOLFSSH_USERAUTH_REJECTED; - } - else { - ret = WOLFSSH_USERAUTH_INVALID_PUBLICKEY; - } - return ret; - } - } - else { - return WOLFSSH_USERAUTH_INVALID_AUTHTYPE; - } - } - map = map->next; - } - - return WOLFSSH_USERAUTH_INVALID_USER; -} -#endif /* WOLFSSH_SSHD */ diff --git a/apps/wolfsshd/auth.c b/apps/wolfsshd/auth.c new file mode 100644 index 00000000..a2d087e1 --- /dev/null +++ b/apps/wolfsshd/auth.c @@ -0,0 +1,587 @@ +/* auth.c + * + * Copyright (C) 2014-2021 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 . + */ + +#ifdef HAVE_CONFIG_H + #include +#endif + +#ifdef WOLFSSH_SSHD + +#include +#include +#include +#include +#include +#include + +#ifdef NO_INLINE + #include +#else + #define WOLFSSH_MISC_INCLUDED + #include "src/misc.c" +#endif + +#include "auth.h" + +#include + +#ifndef _WIN32 +#include +#include +#include +#include +#endif + +#if 0 +static byte passwdRetry = 3; + +/* Map user names to passwords */ +/* Use arrays for username and p. The password or public key can + * be hashed and the hash stored here. Then I won't need the type. */ +struct USER_NODE { + byte type; + byte username[32]; + word32 usernameSz; + byte fingerprint[WC_SHA256_DIGEST_SIZE]; + struct USER_NODE* next; +}; + + +/* Takes a users input and adds it to the list of accepted users + * 'value' can be a users password / public key / or certificate + * returns an updated list on success (i.e. 'new' -> 'list' -> ...) or NULL + * on failure + */ +USER_NODE* AddNewUser(USER_NODE* list, byte type, const byte* username, + word32 usernameSz, const byte* value, word32 valueSz) +{ + USER_NODE* map; + + map = (USER_NODE*)WMALLOC(sizeof(USER_NODE), NULL, 0); + if (map != NULL) { + map->type = type; + if (usernameSz >= sizeof(map->username)) + usernameSz = sizeof(map->username) - 1; + WMEMCPY(map->username, username, usernameSz + 1); + map->username[usernameSz] = 0; + map->usernameSz = usernameSz; + + if (type != WOLFSSH_USERAUTH_NONE) { + wc_Sha256Hash(value, valueSz, map->fingerprint); + } + + map->next = list; + } + + return map; +} + +int DefaultUserAuth(byte authType, WS_UserAuthData* authData, void* ctx) +{ + USER_NODE* map; + byte authHash[WC_SHA256_DIGEST_SIZE]; + int ret; + + if (authType != WOLFSSH_USERAUTH_PASSWORD && +#ifdef WOLFSSH_ALLOW_USERAUTH_NONE + authType != WOLFSSH_USERAUTH_NONE && +#endif + authType != WOLFSSH_USERAUTH_PUBLICKEY) { + + return WOLFSSH_USERAUTH_FAILURE; + } + map = (USER_NODE*)ctx; + + /* check if password on system */ + if (authData->type == WOLFSSH_USERAUTH_PASSWORD) { + if (CheckPassword(authData->username, authData->sf.password.password, + authData->sf.password.passwordSz) == WS_SUCCESS) { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Password and user on system"); + return WOLFSSH_USERAUTH_SUCCESS; + } + } + + if (authType == WOLFSSH_USERAUTH_PASSWORD) { + wc_Sha256Hash(authData->sf.password.password, + authData->sf.password.passwordSz, + authHash); + } + else if (authType == WOLFSSH_USERAUTH_PUBLICKEY) { + wc_Sha256Hash(authData->sf.publicKey.publicKey, + authData->sf.publicKey.publicKeySz, + authHash); + } + + while (map != NULL) { + if (authData->usernameSz == map->usernameSz && + WMEMCMP(authData->username, map->username, map->usernameSz) == 0 && + authData->type == map->type) { + + if (authData->type == WOLFSSH_USERAUTH_PUBLICKEY) { + if (WMEMCMP(map->fingerprint, authHash, + WC_SHA256_DIGEST_SIZE) == 0) { + return WOLFSSH_USERAUTH_SUCCESS; + } + else { + return WOLFSSH_USERAUTH_INVALID_PUBLICKEY; + } + } + else if (authData->type == WOLFSSH_USERAUTH_PASSWORD) { + if (WMEMCMP(map->fingerprint, authHash, + WC_SHA256_DIGEST_SIZE) == 0) { + return WOLFSSH_USERAUTH_SUCCESS; + } + else { + passwdRetry--; + return (passwdRetry > 0) ? + WOLFSSH_USERAUTH_INVALID_PASSWORD : + WOLFSSH_USERAUTH_REJECTED; + } + } +#ifdef WOLFSSH_ALLOW_USERAUTH_NONE + else if (authData->type == WOLFSSH_USERAUTH_NONE) { + return WOLFSSH_USERAUTH_SUCCESS; + } +#endif /* WOLFSSH_ALLOW_USERAUTH_NONE */ + else { + return WOLFSSH_USERAUTH_INVALID_AUTHTYPE; + } + + if (authData->type == map->type) { + if (WMEMCMP(map->fingerprint, authHash, + WC_SHA256_DIGEST_SIZE) == 0) { + return WOLFSSH_USERAUTH_SUCCESS; + } + else { + if (authType == WOLFSSH_USERAUTH_PASSWORD) { + passwdRetry--; + ret = (passwdRetry > 0) ? + WOLFSSH_USERAUTH_INVALID_PASSWORD : + WOLFSSH_USERAUTH_REJECTED; + } + else { + ret = WOLFSSH_USERAUTH_INVALID_PUBLICKEY; + } + return ret; + } + } + else { + return WOLFSSH_USERAUTH_INVALID_AUTHTYPE; + } + } + map = map->next; + } + + return WOLFSSH_USERAUTH_INVALID_USER; +} +#endif + +static int CheckAuthKeysLine(char* line, word32 lineSz, const byte* key, + word32 keySz) +{ + int ret = WS_SUCCESS; + char* type; + char* keyCandBase64; /* cand == candidate */ + word32 keyCandBase64Sz; + byte* keyCand = NULL; + word32 keyCandSz; + char* last; + enum { + NUM_ALLOWED_TYPES = 5 + }; + static const char* allowedTypes[NUM_ALLOWED_TYPES] = { + "ssh-rsa", + "ssh-ed25519", + "ecdsa-sha2-nistp256", + "ecdsa-sha2-nistp384", + "ecdsa-sha2-nistp521" + }; + int typeOk = 0; + int i; + + if (line == NULL || lineSz == 0 || key == NULL || keySz == 0) { + ret = WS_BAD_ARGUMENT; + } + + if (ret == WS_SUCCESS) { + if ((type = WSTRTOK(line, " ", &last)) == NULL) { + ret = WS_FATAL_ERROR; + } + else if ((keyCandBase64 = WSTRTOK(NULL, " ", &last)) == NULL) { + ret = WS_FATAL_ERROR; + } + } + if (ret == WS_SUCCESS) { + for (i = 0; i < NUM_ALLOWED_TYPES; ++i) { + if (WSTRCMP(type, allowedTypes[i]) == 0) { + typeOk = 1; + break; + } + } + if (!typeOk) { + ret = WS_FATAL_ERROR; + } + } + if (ret == WS_SUCCESS) { + keyCandBase64Sz = XSTRLEN(keyCandBase64); + keyCandSz = (keyCandBase64Sz * 3 + 3) / 4; + keyCand = (byte*)WMALLOC(keyCandSz, NULL, DYNTYPE_BUFFER); + if (keyCand == NULL) { + ret = WS_MEMORY_E; + } + else { + if (Base64_Decode((byte*)keyCandBase64, keyCandBase64Sz, keyCand, + &keyCandSz) != 0) { + ret = WS_FATAL_ERROR; + } + } + } + if (ret == WS_SUCCESS && keyCandSz == keySz && + WMEMCMP(key, keyCand, keySz) == 0) { + ret = 1; + } + + if (keyCand != NULL) { + WFREE(keyCand, NULL, DYNTYPE_BUFFER); + } + + return ret; +} + +/* returns WS_SUCCESS if user/password found */ +static int CheckPassword(const byte* usr, const byte* pw, int pwSz) +{ + int ret = WS_SUCCESS; + struct passwd* pwInfo; +// struct spwd* spwInfo; + char* encPw; /* encrypted version of password */ + char tmp[256]; + + pwInfo = getpwnam((const char*)usr); + if (pwInfo == NULL) { + /* user name not found on system */ + ret = WS_FATAL_ERROR; + } + + /* check for shadow password record */ +// spwInfo = getspnam(usr); +// if (spwInfo != NULL) { +// pwInfo->pw_passwd = spwInfo->sp_pwdp; +// } +// +{ + int z; + for (z = 0; z < pwSz; z++) + tmp[z] = pw[z]; + tmp[z] = '\0'; +} + + if (ret == WS_SUCCESS) { + encPw = crypt((const char*)tmp, pwInfo->pw_passwd); + if (encPw == NULL) { + /* error encrypting password for comparison */ + ret = WS_FATAL_ERROR; + } + } + +{ + int z; + printf("peer pw : "); + for (z = 0; z < pwSz; z++) + printf("%02X", pw[z]); + printf("\n"); + printf(" pw : "); + for (z = 0; z < pwSz; z++) + printf("%02X", pwInfo->pw_passwd[z]); + printf("\n"); + printf(" enc : "); + for (z = 0; z < pwSz; z++) + printf("%02X", encPw[z]); + printf("\n"); +} + if (ret == WS_SUCCESS) { + if (XSTRCMP(encPw, pwInfo->pw_passwd) == 0) { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] User %s log in successful", usr); + } + else { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] User %s log in fail", usr); + ret = WS_FATAL_ERROR; + } + } + (void)pwSz; + + return ret; +} + +enum { + USER_LOOKUP_ERROR = -1, + USER_LOOKUP_FAILURE = 0, + USER_LOOKUP_SUCCESS = 1 +}; + +#ifndef _WIN32 +static int CheckUserUnix(const char* name) { + int ret = USER_LOOKUP_FAILURE; + struct passwd* pwInfo; + + errno = 0; + pwInfo = getpwnam(name); + if (pwInfo == NULL) { + if (errno != 0) { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Error calling getpwnam for user " + "%s.", name); + ret = USER_LOOKUP_ERROR; + } + } + else { + ret = USER_LOOKUP_SUCCESS; + } + + return ret; +} + +static const char authKeysDefault[] = ".ssh/authorized_keys"; +static char authKeysPattern[32] = {0}; + +void SetAuthKeysPattern(const char* pattern) +{ + if (pattern != NULL) { + WMEMSET(authKeysPattern, 0, sizeof(authKeysPattern)); + WSTRNCPY(authKeysPattern, pattern, sizeof(authKeysPattern)); + } +} + +static int ResolveAuthKeysPath(const char* homeDir, char* resolved) +{ + int ret = WS_SUCCESS; + char* idx; + int homeDirSz; + const char* suffix = authKeysDefault; + + if (homeDir == NULL || resolved == NULL) { + ret = WS_BAD_ARGUMENT; + } + + if (ret == WS_SUCCESS) { + if (*authKeysPattern != 0) { + /* TODO: token substitutions (e.g. %h) */ + if (*authKeysPattern == '/') { + /* TODO: handle absolute path case */ + ret = WS_FATAL_ERROR; + } + else { + suffix = authKeysPattern; + } + } + } + if (ret == WS_SUCCESS) { + idx = resolved; + homeDirSz = XSTRLEN(homeDir); + XMEMCPY(idx, homeDir, homeDirSz); + idx += homeDirSz; + *(idx++) = '/'; + /* Intentionally copying the null term from suffix. */ + XMEMCPY(idx, suffix, WSTRLEN(suffix)); + } + + return ret; +} + +static int CheckPublicKeyUnix(const byte* name, const byte* key, word32 keySz) +{ + int ret = WS_SUCCESS; + struct passwd* pwInfo; + char* authKeysFile = NULL; + XFILE f; + enum { + /* TODO: Probably needs to be even bigger for larger key sizes. */ + MAX_LINE_SZ = 500, + MAX_PATH_SZ = 80 + }; + char* lineBuf = NULL; + char* current; + word32 currentSz; + int foundKey = 0; + int rc; + char authKeysPath[MAX_PATH_SZ]; + + errno = 0; + pwInfo = getpwnam((const char*)name); + if (pwInfo == NULL) { + if (errno != 0) { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Error calling getpwnam for user " + "%s.", name); + ret = WS_ERROR; + } + } + if (ret == WS_SUCCESS) { + WMEMSET(authKeysPath, 0, sizeof(authKeysPath)); + ret = ResolveAuthKeysPath(pwInfo->pw_dir, authKeysPath); + } + if (ret == WS_SUCCESS) { + f = XFOPEN(authKeysPath, "rb"); + if (f == XBADFILE) { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Unable to open %s", + authKeysPath); + ret = WS_BAD_FILE_E; + } + } + if (ret == WS_SUCCESS) { + lineBuf = (char*)WMALLOC(MAX_LINE_SZ, NULL, DYNTYPE_BUFFER); + if (lineBuf == NULL) { + ret = WS_MEMORY_E; + } + } + while (ret == WS_SUCCESS && + (current = XFGETS(lineBuf, MAX_LINE_SZ, f)) != NULL) { + currentSz = XSTRLEN(current); + + /* remove leading spaces */ + while (currentSz > 0 && current[0] == ' ') { + currentSz = currentSz - 1; + current = current + 1; + } + + if (currentSz <= 1) { + continue; /* empty line */ + } + + if (current[0] == '#') { + continue; /* commented out line */ + } + + rc = CheckAuthKeysLine(current, currentSz, key, keySz); + if (rc == 1) { + foundKey = 1; + break; + } + else if (rc < 0) { + ret = rc; + break; + } + } + XFCLOSE(f); + + if (ret == WS_SUCCESS && !foundKey) { + ret = WS_ERROR; + } + + if (lineBuf != NULL) { + WFREE(lineBuf, NULL, DYNTYPE_BUFFER); + } + if (authKeysFile != NULL) { + WFREE(authKeysFile, NULL, DYNTYPE_STRING); + } + + return ret; +} +#endif /* !_WIN32*/ + +static int CheckUser(const char* name) +{ + int ret = USER_LOOKUP_FAILURE; + +#ifdef _WIN32 + /* TODO: Implement for Windows. */ +#else + ret = CheckUserUnix(name); +#endif + + if (ret == USER_LOOKUP_FAILURE) { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] User %s doesn't exist.", name); + } + else if (ret == USER_LOOKUP_ERROR) { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Error looking up user %s.", name); + } + else { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] User ok."); + } + + return ret; +} + +static int CheckPublicKey(const byte* name, const byte* key, word32 keySz) +{ + int ret = 0; + +#ifdef _WIN32 + /* TODO: Implement for Windows. */ +#else + ret = CheckPublicKeyUnix(name, key, keySz); +#endif + + return ret; +} + +int DefaultUserAuth(byte authType, WS_UserAuthData* authData, void* ctx) +{ + int ret = WOLFSSH_USERAUTH_FAILURE; + + (void)ctx; + /* TODO: Auth will need some info from the config. For example, the auth + * keys file path or the allowed users, if not all users are allowed. Could + * pass the config in the ctx pointer... + */ + + if (authType != WOLFSSH_USERAUTH_PASSWORD && +#ifdef WOLFSSH_ALLOW_USERAUTH_NONE + authType != WOLFSSH_USERAUTH_NONE && +#endif + authType != WOLFSSH_USERAUTH_PUBLICKEY) { + + ret = WOLFSSH_USERAUTH_INVALID_AUTHTYPE; + } + + /* Check user exists. */ + if (ret == WOLFSSH_USERAUTH_SUCCESS) { + /* TODO: Is authData and its members guaranteed to be non-NULL? */ + if (CheckUser((const char*)authData->username) <= 0) { + ret = WOLFSSH_USERAUTH_INVALID_USER; + } + } + + /* Check if password is valid for this user. */ + if (authData->type == WOLFSSH_USERAUTH_PASSWORD) { + if (CheckPassword(authData->username, authData->sf.password.password, + authData->sf.password.passwordSz) == WS_SUCCESS) { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Password ok."); + ret = WOLFSSH_USERAUTH_SUCCESS; + } + else { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Password incorrect."); + ret = WOLFSSH_USERAUTH_INVALID_PASSWORD; + } + } + /* Check if public key is in this user's authorized_keys file. */ + else if (authData->type == WOLFSSH_USERAUTH_PUBLICKEY) { + if (CheckPublicKey(authData->username, authData->sf.publicKey.publicKey, + authData->sf.publicKey.publicKeySz) == WS_SUCCESS) { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Public key ok."); + ret = WOLFSSH_USERAUTH_SUCCESS; + } + else { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Public key not authorized."); + ret = WOLFSSH_USERAUTH_INVALID_PUBLICKEY; + } + } + + return ret; +} +#endif /* WOLFSSH_SSHD */ diff --git a/apps/wolfauth.h b/apps/wolfsshd/auth.h similarity index 93% rename from apps/wolfauth.h rename to apps/wolfsshd/auth.h index 0347f06f..c501d185 100644 --- a/apps/wolfauth.h +++ b/apps/wolfsshd/auth.h @@ -1,4 +1,4 @@ -/* wolfauth.h +/* auth.h * * Copyright (C) 2014-2021 wolfSSL Inc. * @@ -18,14 +18,17 @@ * along with wolfSSH. If not, see . */ - - #ifndef WOLFAUTH_H #define WOLFAUTH_H +#if 0 typedef struct USER_NODE USER_NODE; USER_NODE* AddNewUser(USER_NODE* list, byte type, const byte* username, word32 usernameSz, const byte* value, word32 valueSz); +#endif + +void SetAuthKeysPattern(const char* pattern); int DefaultUserAuth(byte authType, WS_UserAuthData* authData, void* ctx); + #endif /* WOLFAUTH_H */ diff --git a/apps/wolfconfig.c b/apps/wolfsshd/config.c similarity index 92% rename from apps/wolfconfig.c rename to apps/wolfsshd/config.c index c745f388..7f19e4f3 100644 --- a/apps/wolfconfig.c +++ b/apps/wolfsshd/config.c @@ -1,4 +1,4 @@ -/* wolfconfig.c +/* config.c * * Copyright (C) 2014-2021 wolfSSL Inc. * @@ -110,7 +110,7 @@ WOLFSSHD_CONFIG* wolfSSHD_NewConfig(void* heap) WMEMSET(ret, 0, sizeof(WOLFSSHD_CONFIG)); /* default values */ - ret->port = 22; + ret->port = 9387; } return ret; @@ -139,6 +139,7 @@ static int wolfSSHD_ParseConfigLine(WOLFSSHD_CONFIG* conf, const char* l, { int ret = WS_BAD_ARGUMENT; int sz; + char* tmp; /* supported config options */ const char authKeyFile[] = "AuthorizedKeysFile"; @@ -146,8 +147,10 @@ static int wolfSSHD_ParseConfigLine(WOLFSSHD_CONFIG* conf, const char* l, sz = (int)XSTRLEN(authKeyFile); if (lSz > sz && XSTRNCMP(l, authKeyFile, sz) == 0) { - ret = wolfSSHD_CreateString(&conf->authKeysFile, l + sz, lSz - sz, - conf->heap); + ret = wolfSSHD_CreateString(&tmp, l + sz, lSz - sz, conf->heap); + if (ret == WS_SUCCESS) { + wolfSSHD_SetAuthKeysFile(conf, tmp); + } } sz = (int)XSTRLEN(privilegeSeparation); @@ -258,9 +261,29 @@ int wolfSSHD_LoadSSHD(WOLFSSHD_CONFIG* conf, const char* filename) } XFCLOSE(f); + SetAuthKeysPattern(conf->authKeysFile); + return ret; } +char* wolfSSHD_GetAuthKeysFile(WOLFSSHD_CONFIG* conf) +{ + if (conf != NULL) + return conf->authKeysFile; + return NULL; +} + +int wolfSSHD_SetAuthKeysFile(WOLFSSHD_CONFIG* conf, const char* file) +{ + if (conf == NULL) { + return WS_BAD_ARGUMENT; + } + + conf->authKeysFile = (char*)file; + + return WS_SUCCESS; +} + char* wolfSSHD_GetBanner(WOLFSSHD_CONFIG* conf) { if (conf != NULL) diff --git a/apps/wolfsshd/include.am b/apps/wolfsshd/include.am new file mode 100644 index 00000000..1059f7df --- /dev/null +++ b/apps/wolfsshd/include.am @@ -0,0 +1,14 @@ +if BUILD_SSHD + +bin_PROGRAMS += apps/wolfsshd/wolfsshd +noinst_HEADERS += apps/wolfsshd/wolfsshd.h \ + apps/wolfsshd/auth.h +apps_wolfsshd_wolfsshd_SOURCES = apps/wolfsshd/wolfsshd.c \ + apps/wolfsshd/config.c \ + apps/wolfsshd/auth.c +apps_wolfsshd_wolfsshd_LDADD = src/libwolfssh.la +apps_wolfsshd_wolfsshd_DEPENDENCIES = src/libwolfssh.la + +DISTCLEANFILES+= apps/wolfsshd/.libs/wolfsshd + +endif BUILD_SSHD diff --git a/apps/wolfsshd.c b/apps/wolfsshd/wolfsshd.c similarity index 97% rename from apps/wolfsshd.c rename to apps/wolfsshd/wolfsshd.c index 1e2430c8..0c984d20 100644 --- a/apps/wolfsshd.c +++ b/apps/wolfsshd/wolfsshd.c @@ -29,12 +29,13 @@ #include #include #include +#include #define WOLFSSH_TEST_SERVER #include #include "wolfsshd.h" -#include "wolfauth.h" +#include "auth.h" #include @@ -87,7 +88,7 @@ static void ShowUsage(void) { printf("wolfsshd %s\n", LIBWOLFSSH_VERSION_STRING); printf(" -? display this help and exit\n"); - printf(" -f Configuration file to use, default is /usr/locacl/etc/ssh/sshd_config\n"); + printf(" -f Configuration file to use, default is /usr/local/etc/ssh/sshd_config\n"); printf(" -p Port number to listen on\n"); printf(" -d Turn on debug mode\n"); } @@ -107,7 +108,6 @@ static void wolfSSHDLoggingCb(enum wolfSSH_LogLevel lvl, const char *const str) (void)lvl; } - static int SetupCTX(WOLFSSHD_CONFIG* conf, WOLFSSH_CTX** ctx) { int ret = WS_SUCCESS; @@ -148,8 +148,11 @@ static int SetupCTX(WOLFSSHD_CONFIG* conf, WOLFSSH_CTX** ctx) } #endif + /* TODO: Currently expects a private key in DER format. Add logic to handle + * PEM, too. wc_PemToDer. */ /* Load in host private key */ if (ret == WS_SUCCESS) { + char* hostKey = wolfSSHD_GetHostPrivateKey(conf); if (hostKey == NULL) { @@ -159,7 +162,7 @@ static int SetupCTX(WOLFSSHD_CONFIG* conf, WOLFSSH_CTX** ctx) else { FILE* f; - f = fopen(hostKey, "rb"); + f = XFOPEN(hostKey, "rb"); if (f == NULL) { wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Unable to open host private key"); @@ -171,8 +174,9 @@ static int SetupCTX(WOLFSSHD_CONFIG* conf, WOLFSSH_CTX** ctx) data = (byte*)WMALLOC(dataSz, NULL, 0); - dataSz = (int)fread(data, 1, dataSz, f); - fclose(f); + dataSz = (int)XFREAD(data, 1, dataSz, f); + XFCLOSE(f); + if (wolfSSH_CTX_UsePrivateKey_buffer(*ctx, data, dataSz, WOLFSSH_FORMAT_ASN1) < 0) { wolfSSH_Log(WS_LOG_ERROR, @@ -240,9 +244,6 @@ static int SetupCTX(WOLFSSHD_CONFIG* conf, WOLFSSH_CTX** ctx) // #endif // } - /* Load in authorized keys */ - - /* Set allowed connection type, i.e. public key / password */ return ret; @@ -599,12 +600,12 @@ int main(int argc, char** argv) signal(SIGINT, interruptCatch); wolfSSH_SetLoggingCb(wolfSSHDLoggingCb); - #ifdef DEBUG_WOLFSSH - wolfSSH_Debugging_ON(); - #endif - #ifdef DEBUG_WOLFSSL - wolfSSL_Debugging_ON(); - #endif +#ifdef DEBUG_WOLFSSH + wolfSSH_Debugging_ON(); +#endif +#ifdef DEBUG_WOLFSSL + wolfSSL_Debugging_ON(); +#endif if (ret == WS_SUCCESS) { wolfSSH_Init(); @@ -617,7 +618,6 @@ int main(int argc, char** argv) } } - while ((ch = mygetopt(argc, argv, "?f:p:h:d")) != -1) { switch (ch) { case 'f': @@ -677,6 +677,9 @@ int main(int argc, char** argv) if (ret == WS_SUCCESS) { ret = SetupCTX(conf, &ctx); } + else { + /* TODO: handle error. */ + } wolfSSH_Log(WS_LOG_INFO, "[SSHD] Starting to listen on port %d", port); tcp_listen(&listenFd, &port, 1); @@ -708,6 +711,7 @@ int main(int argc, char** argv) wolfSSHD_FreeConfig(conf); wolfSSH_Cleanup(); + return 0; } #endif /* WOLFSSH_SSHD */ diff --git a/apps/wolfsshd.h b/apps/wolfsshd/wolfsshd.h similarity index 90% rename from apps/wolfsshd.h rename to apps/wolfsshd/wolfsshd.h index 47650711..34269f5c 100644 --- a/apps/wolfsshd.h +++ b/apps/wolfsshd/wolfsshd.h @@ -21,6 +21,8 @@ #ifndef WOLFSSHD_H #define WOLFSSHD_H +#include "auth.h" + typedef struct WOLFSSHD_CONFIG WOLFSSHD_CONFIG; #define WOLFSSHD_PRIV_SEPARAT 0 @@ -35,6 +37,9 @@ char* wolfSSHD_GetBanner(WOLFSSHD_CONFIG* conf); char* wolfSSHD_GetHostPrivateKey(WOLFSSHD_CONFIG* conf); int wolfSSHD_SetHostPrivateKey(WOLFSSHD_CONFIG* conf, const char* hostKeyFile); word16 wolfSSHD_GetPort(WOLFSSHD_CONFIG* conf); +char* wolfSSHD_GetAuthKeysFile(WOLFSSHD_CONFIG* conf); +int wolfSSHD_SetAuthKeysFile(WOLFSSHD_CONFIG* conf, const char* file); + #endif /* WOLFSSHD_H */ diff --git a/configure.ac b/configure.ac index 7552a26a..427d880f 100644 --- a/configure.ac +++ b/configure.ac @@ -238,6 +238,10 @@ AS_IF([test "x$ENABLED_SMALLSTACK" = "xyes"], AS_IF([test "x$ENABLED_SSHD" = "xyes"], [AM_CPPFLAGS="$AM_CPPFLAGS -DWOLFSSH_SSHD"]) +if test "$ENABLED_SSHD" = "yes"; then + AC_CHECK_LIB([crypt], [crypt], [], [AC_MSG_ERROR([libcrypt is required for sshd])]) +fi + # Set the automake conditionals. AM_CONDITIONAL([BUILD_EXAMPLE_SERVERS],[test "x$ENABLED_EXAMPLES" = "xyes"]) AM_CONDITIONAL([BUILD_EXAMPLE_CLIENTS],[test "x$ENABLED_EXAMPLES" = "xyes"]) From 76a17c97656db2bf28ccf1ccca65fc7d4f712eec Mon Sep 17 00:00:00 2001 From: Hayden Roche Date: Fri, 15 Jul 2022 11:39:41 -0700 Subject: [PATCH 09/48] sshd improvements, get password auth working --- apps/wolfsshd/auth.c | 351 +++++++++++++++++++++++++++++-------------- 1 file changed, 240 insertions(+), 111 deletions(-) diff --git a/apps/wolfsshd/auth.c b/apps/wolfsshd/auth.c index a2d087e1..3af6c7dd 100644 --- a/apps/wolfsshd/auth.c +++ b/apps/wolfsshd/auth.c @@ -45,6 +45,7 @@ #ifndef _WIN32 #include #include +#include #include #include #endif @@ -193,10 +194,15 @@ int DefaultUserAuth(byte authType, WS_UserAuthData* authData, void* ctx) } #endif +enum { + WSSHD_AUTH_FAILURE = 0, + WSSHD_AUTH_SUCCESS = 1 +}; + static int CheckAuthKeysLine(char* line, word32 lineSz, const byte* key, word32 keySz) { - int ret = WS_SUCCESS; + int ret = WSSHD_AUTH_SUCCESS; char* type; char* keyCandBase64; /* cand == candidate */ word32 keyCandBase64Sz; @@ -220,7 +226,7 @@ static int CheckAuthKeysLine(char* line, word32 lineSz, const byte* key, ret = WS_BAD_ARGUMENT; } - if (ret == WS_SUCCESS) { + if (ret == WSSHD_AUTH_SUCCESS) { if ((type = WSTRTOK(line, " ", &last)) == NULL) { ret = WS_FATAL_ERROR; } @@ -228,7 +234,7 @@ static int CheckAuthKeysLine(char* line, word32 lineSz, const byte* key, ret = WS_FATAL_ERROR; } } - if (ret == WS_SUCCESS) { + if (ret == WSSHD_AUTH_SUCCESS) { for (i = 0; i < NUM_ALLOWED_TYPES; ++i) { if (WSTRCMP(type, allowedTypes[i]) == 0) { typeOk = 1; @@ -239,7 +245,7 @@ static int CheckAuthKeysLine(char* line, word32 lineSz, const byte* key, ret = WS_FATAL_ERROR; } } - if (ret == WS_SUCCESS) { + if (ret == WSSHD_AUTH_SUCCESS) { keyCandBase64Sz = XSTRLEN(keyCandBase64); keyCandSz = (keyCandBase64Sz * 3 + 3) / 4; keyCand = (byte*)WMALLOC(keyCandSz, NULL, DYNTYPE_BUFFER); @@ -253,9 +259,10 @@ static int CheckAuthKeysLine(char* line, word32 lineSz, const byte* key, } } } - if (ret == WS_SUCCESS && keyCandSz == keySz && - WMEMCMP(key, keyCand, keySz) == 0) { - ret = 1; + if (ret == WSSHD_AUTH_SUCCESS) { + if (keyCandSz != keySz || WMEMCMP(key, keyCand, keySz) != 0) { + ret = WSSHD_AUTH_FAILURE; + } } if (keyCand != NULL) { @@ -265,14 +272,117 @@ static int CheckAuthKeysLine(char* line, word32 lineSz, const byte* key, return ret; } -/* returns WS_SUCCESS if user/password found */ -static int CheckPassword(const byte* usr, const byte* pw, int pwSz) +#ifndef _WIN32 +static int ExtractSalt(char* hash, char** salt, int saltSz) { int ret = WS_SUCCESS; + int idx = 0; + char* p; + + if (hash == NULL || salt == NULL || *salt == NULL || saltSz <= 0) { + ret = WS_SUCCESS; + } + + if (ret == 0) { + if (hash[idx] != '$') { + ret = WS_FATAL_ERROR; + } + else { + ++idx; + if (idx >= saltSz) { + ret = WS_BUFFER_E; + } + } + } + if (ret == 0) { + p = strstr(hash + idx, "$"); + if (p == NULL) { + ret = -1; + } + else { + idx += (p - hash); + if (idx >= saltSz) { + ret = WS_BUFFER_E; + } + } + } + if (ret == 0) { + p = strstr(p + 1, "$"); + if (p == NULL) { + ret = WS_FATAL_ERROR; + } + else { + idx += (p - (hash + idx) + 1); + if (idx >= saltSz) { + ret = WS_BUFFER_E; + } + } + } + if (ret == 0) { + memcpy(*salt, hash, idx); + (*salt)[idx] = 0; + } + + return ret; +} + +static int CheckPasswordHashUnix(const char* input, char* stored) +{ + int ret = WSSHD_AUTH_SUCCESS; + int rc; + char salt[32]; + char* p = salt; + char* hashedInput; + + if (input == NULL || stored == NULL) { + ret = WS_BAD_ARGUMENT; + } + + if (ret == WSSHD_AUTH_SUCCESS) { + rc = ExtractSalt(stored, &p, sizeof(salt)); + if (rc != WS_SUCCESS) { + ret = rc; + } + } + if (ret == WSSHD_AUTH_SUCCESS) { + hashedInput = crypt(input, salt); + if (hashedInput == NULL) { + ret = WS_FATAL_ERROR; + } + else { + if (WMEMCMP(hashedInput, stored, WSTRLEN(stored)) != 0) { + ret = WSSHD_AUTH_FAILURE; + } + } + } + + return ret; +} + +static int CheckPasswordUnix(const byte* usr, const byte* pw, int pwSz) +{ + int ret = WS_SUCCESS; + char* pwStr = NULL; struct passwd* pwInfo; -// struct spwd* spwInfo; - char* encPw; /* encrypted version of password */ - char tmp[256]; + struct spwd* shadowInfo; + /* The hash of the user's password stored on the system. */ + char* storedHash; + char* storedHashCpy = NULL; + + if (usr == NULL || pw == NULL || pwSz < 0) { + ret = WS_BAD_ARGUMENT; + } + + if (ret == WS_SUCCESS) { + pwStr = (char*)WMALLOC(pwSz + 1, NULL, DYNTYPE_STRING); + if (pwStr == NULL) { + ret = WS_MEMORY_E; + } + else { + XMEMCPY(pwStr, pw, pwSz); + pwStr[pwSz] = 0; + } + } pwInfo = getpwnam((const char*)usr); if (pwInfo == NULL) { @@ -280,65 +390,45 @@ static int CheckPassword(const byte* usr, const byte* pw, int pwSz) ret = WS_FATAL_ERROR; } - /* check for shadow password record */ -// spwInfo = getspnam(usr); -// if (spwInfo != NULL) { -// pwInfo->pw_passwd = spwInfo->sp_pwdp; -// } -// -{ - int z; - for (z = 0; z < pwSz; z++) - tmp[z] = pw[z]; - tmp[z] = '\0'; -} - if (ret == WS_SUCCESS) { - encPw = crypt((const char*)tmp, pwInfo->pw_passwd); - if (encPw == NULL) { - /* error encrypting password for comparison */ - ret = WS_FATAL_ERROR; - } - } - -{ - int z; - printf("peer pw : "); - for (z = 0; z < pwSz; z++) - printf("%02X", pw[z]); - printf("\n"); - printf(" pw : "); - for (z = 0; z < pwSz; z++) - printf("%02X", pwInfo->pw_passwd[z]); - printf("\n"); - printf(" enc : "); - for (z = 0; z < pwSz; z++) - printf("%02X", encPw[z]); - printf("\n"); -} - if (ret == WS_SUCCESS) { - if (XSTRCMP(encPw, pwInfo->pw_passwd) == 0) { - wolfSSH_Log(WS_LOG_INFO, "[SSHD] User %s log in successful", usr); + if (pwInfo->pw_passwd[0] == 'x') { + shadowInfo = getspnam((const char*)usr); + if (shadowInfo == NULL) { + ret = WS_FATAL_ERROR; + } + else { + storedHash = shadowInfo->sp_pwdp; + } } else { - wolfSSH_Log(WS_LOG_INFO, "[SSHD] User %s log in fail", usr); - ret = WS_FATAL_ERROR; + storedHash = pwInfo->pw_passwd; } } - (void)pwSz; + if (ret == WS_SUCCESS) { + storedHashCpy = WSTRDUP(storedHash, NULL, DYNTYPE_STRING); + if (storedHash == NULL) { + ret = WS_MEMORY_E; + } + } + + if (ret == WS_SUCCESS) { + ret = CheckPasswordHashUnix(pwStr, storedHashCpy); + } + + if (pwStr != NULL) { + WFREE(pwStr, NULL, DYNTYPE_STRING); + } + if (storedHashCpy != NULL) { + WFREE(storedHashCpy, NULL, DYNTYPE_STRING); + } return ret; } - -enum { - USER_LOOKUP_ERROR = -1, - USER_LOOKUP_FAILURE = 0, - USER_LOOKUP_SUCCESS = 1 -}; +#endif /* !_WIN32 */ #ifndef _WIN32 static int CheckUserUnix(const char* name) { - int ret = USER_LOOKUP_FAILURE; + int ret = WSSHD_AUTH_FAILURE; struct passwd* pwInfo; errno = 0; @@ -347,11 +437,11 @@ static int CheckUserUnix(const char* name) { if (errno != 0) { wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Error calling getpwnam for user " "%s.", name); - ret = USER_LOOKUP_ERROR; + ret = WS_FATAL_ERROR; } } else { - ret = USER_LOOKUP_SUCCESS; + ret = WSSHD_AUTH_SUCCESS; } return ret; @@ -406,7 +496,8 @@ static int ResolveAuthKeysPath(const char* homeDir, char* resolved) static int CheckPublicKeyUnix(const byte* name, const byte* key, word32 keySz) { - int ret = WS_SUCCESS; + int ret = WSSHD_AUTH_SUCCESS; + int rc; struct passwd* pwInfo; char* authKeysFile = NULL; XFILE f; @@ -419,7 +510,6 @@ static int CheckPublicKeyUnix(const byte* name, const byte* key, word32 keySz) char* current; word32 currentSz; int foundKey = 0; - int rc; char authKeysPath[MAX_PATH_SZ]; errno = 0; @@ -428,14 +518,19 @@ static int CheckPublicKeyUnix(const byte* name, const byte* key, word32 keySz) if (errno != 0) { wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Error calling getpwnam for user " "%s.", name); - ret = WS_ERROR; + ret = WS_FATAL_ERROR; } } - if (ret == WS_SUCCESS) { + if (ret == WSSHD_AUTH_SUCCESS) { WMEMSET(authKeysPath, 0, sizeof(authKeysPath)); - ret = ResolveAuthKeysPath(pwInfo->pw_dir, authKeysPath); + rc = ResolveAuthKeysPath(pwInfo->pw_dir, authKeysPath); + if (rc != WS_SUCCESS) { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Failed to resolve authorized keys" + " file path."); + ret = rc; + } } - if (ret == WS_SUCCESS) { + if (ret == WSSHD_AUTH_SUCCESS) { f = XFOPEN(authKeysPath, "rb"); if (f == XBADFILE) { wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Unable to open %s", @@ -443,13 +538,13 @@ static int CheckPublicKeyUnix(const byte* name, const byte* key, word32 keySz) ret = WS_BAD_FILE_E; } } - if (ret == WS_SUCCESS) { + if (ret == WSSHD_AUTH_SUCCESS) { lineBuf = (char*)WMALLOC(MAX_LINE_SZ, NULL, DYNTYPE_BUFFER); if (lineBuf == NULL) { ret = WS_MEMORY_E; } } - while (ret == WS_SUCCESS && + while (ret == WSSHD_AUTH_SUCCESS && (current = XFGETS(lineBuf, MAX_LINE_SZ, f)) != NULL) { currentSz = XSTRLEN(current); @@ -468,7 +563,7 @@ static int CheckPublicKeyUnix(const byte* name, const byte* key, word32 keySz) } rc = CheckAuthKeysLine(current, currentSz, key, keySz); - if (rc == 1) { + if (rc == WSSHD_AUTH_SUCCESS) { foundKey = 1; break; } @@ -479,8 +574,8 @@ static int CheckPublicKeyUnix(const byte* name, const byte* key, word32 keySz) } XFCLOSE(f); - if (ret == WS_SUCCESS && !foundKey) { - ret = WS_ERROR; + if (ret == WSSHD_AUTH_SUCCESS && !foundKey) { + ret = WSSHD_AUTH_FAILURE; } if (lineBuf != NULL) { @@ -494,9 +589,13 @@ static int CheckPublicKeyUnix(const byte* name, const byte* key, word32 keySz) } #endif /* !_WIN32*/ +/* + * Returns WSSHD_AUTH_SUCCESS if user found, WSSHD_AUTH_FAILURE if user not + * found, and negative values if an error occurs during checking. + */ static int CheckUser(const char* name) { - int ret = USER_LOOKUP_FAILURE; + int ret = WSSHD_AUTH_FAILURE; #ifdef _WIN32 /* TODO: Implement for Windows. */ @@ -504,19 +603,26 @@ static int CheckUser(const char* name) ret = CheckUserUnix(name); #endif - if (ret == USER_LOOKUP_FAILURE) { - wolfSSH_Log(WS_LOG_INFO, "[SSHD] User %s doesn't exist.", name); - } - else if (ret == USER_LOOKUP_ERROR) { - wolfSSH_Log(WS_LOG_INFO, "[SSHD] Error looking up user %s.", name); - } - else { - wolfSSH_Log(WS_LOG_INFO, "[SSHD] User ok."); - } - return ret; } +/* + * Returns WSSHD_AUTH_SUCCESS if user found, WSSHD_AUTH_FAILURE if user not + * found, and negative values if an error occurs during checking. + */ +static int CheckPassword(const byte* usr, const byte* pw, int pwSz) +{ +#ifdef _WIN32 + /* TODO: Add CheckPasswordWin. */ +#else + return CheckPasswordUnix(usr, pw, pwSz); +#endif +} + +/* + * Returns WSSHD_AUTH_SUCCESS if public key ok, WSSHD_AUTH_FAILURE if key not + * ok, and negative values if an error occurs during checking. + */ static int CheckPublicKey(const byte* name, const byte* key, word32 keySz) { int ret = 0; @@ -532,7 +638,8 @@ static int CheckPublicKey(const byte* name, const byte* key, word32 keySz) int DefaultUserAuth(byte authType, WS_UserAuthData* authData, void* ctx) { - int ret = WOLFSSH_USERAUTH_FAILURE; + int ret = WOLFSSH_USERAUTH_SUCCESS; + int rc; (void)ctx; /* TODO: Auth will need some info from the config. For example, the auth @@ -550,35 +657,57 @@ int DefaultUserAuth(byte authType, WS_UserAuthData* authData, void* ctx) } /* Check user exists. */ - if (ret == WOLFSSH_USERAUTH_SUCCESS) { - /* TODO: Is authData and its members guaranteed to be non-NULL? */ - if (CheckUser((const char*)authData->username) <= 0) { - ret = WOLFSSH_USERAUTH_INVALID_USER; - } + /* TODO: Is authData and its members guaranteed to be non-NULL? */ + rc = CheckUser((const char*)authData->username); + if (rc == WSSHD_AUTH_SUCCESS) { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] User ok."); + } + else if (ret == WSSHD_AUTH_FAILURE) { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] User %s doesn't exist.", + authData->username); + ret = WOLFSSH_USERAUTH_INVALID_USER; + } + else { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Error looking up user %s.", + authData->username); + ret = WOLFSSH_USERAUTH_FAILURE; } - /* Check if password is valid for this user. */ - if (authData->type == WOLFSSH_USERAUTH_PASSWORD) { - if (CheckPassword(authData->username, authData->sf.password.password, - authData->sf.password.passwordSz) == WS_SUCCESS) { - wolfSSH_Log(WS_LOG_INFO, "[SSHD] Password ok."); - ret = WOLFSSH_USERAUTH_SUCCESS; + if (ret == WOLFSSH_USERAUTH_SUCCESS) { + /* Check if password is valid for this user. */ + if (authData->type == WOLFSSH_USERAUTH_PASSWORD) { + rc = CheckPassword(authData->username, + authData->sf.password.password, + authData->sf.password.passwordSz); + if (rc == WSSHD_AUTH_SUCCESS) { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Password ok."); + } + else if (rc == WSSHD_AUTH_FAILURE) { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Password incorrect."); + ret = WOLFSSH_USERAUTH_INVALID_PASSWORD; + } + else { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Error checking password."); + ret = WOLFSSH_USERAUTH_FAILURE; + } } - else { - wolfSSH_Log(WS_LOG_INFO, "[SSHD] Password incorrect."); - ret = WOLFSSH_USERAUTH_INVALID_PASSWORD; - } - } - /* Check if public key is in this user's authorized_keys file. */ - else if (authData->type == WOLFSSH_USERAUTH_PUBLICKEY) { - if (CheckPublicKey(authData->username, authData->sf.publicKey.publicKey, - authData->sf.publicKey.publicKeySz) == WS_SUCCESS) { - wolfSSH_Log(WS_LOG_INFO, "[SSHD] Public key ok."); - ret = WOLFSSH_USERAUTH_SUCCESS; - } - else { - wolfSSH_Log(WS_LOG_INFO, "[SSHD] Public key not authorized."); - ret = WOLFSSH_USERAUTH_INVALID_PUBLICKEY; + /* Check if public key is in this user's authorized_keys file. */ + else if (authData->type == WOLFSSH_USERAUTH_PUBLICKEY) { + rc = CheckPublicKey(authData->username, + authData->sf.publicKey.publicKey, + authData->sf.publicKey.publicKeySz); + if (rc == WSSHD_AUTH_SUCCESS) { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Public key ok."); + ret = WOLFSSH_USERAUTH_SUCCESS; + } + else if (rc == WSSHD_AUTH_FAILURE) { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Public key not authorized."); + ret = WOLFSSH_USERAUTH_INVALID_PUBLICKEY; + } + else { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Error checking public key."); + ret = WOLFSSH_USERAUTH_FAILURE; + } } } From 2982ae88ee0805e87698807bb691a4ac7af5bfd8 Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Fri, 15 Jul 2022 13:30:58 -0700 Subject: [PATCH 10/48] define for crypt use, set fd for shell, tie in sftp --- apps/wolfsshd/auth.c | 5 +++-- apps/wolfsshd/wolfsshd.c | 34 ++++++++++++++++++++++------------ 2 files changed, 25 insertions(+), 14 deletions(-) diff --git a/apps/wolfsshd/auth.c b/apps/wolfsshd/auth.c index 3af6c7dd..5e7d8cde 100644 --- a/apps/wolfsshd/auth.c +++ b/apps/wolfsshd/auth.c @@ -24,6 +24,9 @@ #ifdef WOLFSSH_SSHD +#define _XOPEN_SOURCE +#include + #include #include #include @@ -40,8 +43,6 @@ #include "auth.h" -#include - #ifndef _WIN32 #include #include diff --git a/apps/wolfsshd/wolfsshd.c b/apps/wolfsshd/wolfsshd.c index 0c984d20..d13e8cee 100644 --- a/apps/wolfsshd/wolfsshd.c +++ b/apps/wolfsshd/wolfsshd.c @@ -91,6 +91,7 @@ static void ShowUsage(void) printf(" -f Configuration file to use, default is /usr/local/etc/ssh/sshd_config\n"); printf(" -p Port number to listen on\n"); printf(" -d Turn on debug mode\n"); + printf(" -h host private key file to use\n"); } static void interruptCatch(int in) @@ -251,6 +252,8 @@ static int SetupCTX(WOLFSSHD_CONFIG* conf, WOLFSSH_CTX** ctx) #ifdef WOLFSSH_SFTP +#define TEST_SFTP_TIMEOUT 1 + /* handle SFTP operations * returns 0 on success */ @@ -305,6 +308,7 @@ static int SFTP_Subsystem(WOLFSSH* ssh, WOLFSSHD_CONNECTION* conn) } } while (ret != WS_FATAL_ERROR); + (void)conn; return ret; } #endif @@ -354,8 +358,9 @@ static int SHELL_Subsystem(WOLFSSHD_CONNECTION* conn, WOLFSSH* ssh) signal(SIGINT, SIG_DFL); - printf("userName is %s\n", userName); - system("env"); + if (system("env") != 0) { + printf("0 return value from system call\n"); + } setenv("HOME", p_passwd->pw_dir, 1); setenv("LOGNAME", p_passwd->pw_name, 1); @@ -366,10 +371,10 @@ static int SHELL_Subsystem(WOLFSSHD_CONNECTION* conn, WOLFSSH* ssh) execv("/bin/sh", (char **)args); } + sshFd = wolfSSH_get_fd(ssh); struct termios tios; word32 shellChannelId = 0; - printf("In childPid > 0; getpid=%d\n", (int)getpid()); signal(SIGCHLD, ChildSig); rc = tcgetattr(childFd, &tios); @@ -381,15 +386,13 @@ static int SHELL_Subsystem(WOLFSSHD_CONNECTION* conn, WOLFSSH* ssh) return WS_FATAL_ERROR; } -#ifdef SHELL_DEBUG - termios_show(childFd); -#endif - while (ChildRunning) { + byte tmp[2]; fd_set readFds; WS_SOCKET_T maxFd; int cnt_r; int cnt_w; + int pending = 0; FD_ZERO(&readFds); FD_SET(sshFd, &readFds); @@ -398,11 +401,17 @@ static int SHELL_Subsystem(WOLFSSHD_CONNECTION* conn, WOLFSSH* ssh) FD_SET(childFd, &readFds); if (childFd > maxFd) maxFd = childFd; - rc = select((int)maxFd + 1, &readFds, NULL, NULL, NULL); - if (rc == -1) - break; - if (FD_ISSET(sshFd, &readFds)) { + if (wolfSSH_stream_peek(ssh, tmp, 1) <= 0) { + rc = select((int)maxFd + 1, &readFds, NULL, NULL, NULL); + if (rc == -1) + break; + } + else { + pending = 1; /* found some pending SSH data */ + } + + if (pending || FD_ISSET(sshFd, &readFds)) { word32 lastChannel = 0; /* The following tries to read from the first channel inside @@ -455,6 +464,7 @@ static int SHELL_Subsystem(WOLFSSHD_CONNECTION* conn, WOLFSSH* ssh) } } } + (void)conn; return WS_SUCCESS; } @@ -486,7 +496,7 @@ static void* wolfSSHD_HandleConnection(void* arg) if (ret == WS_SUCCESS) { wolfSSH_set_fd(ssh, conn->fd); ret = wolfSSH_accept(ssh); - if (ret != WS_SUCCESS) { + if (ret != WS_SUCCESS && ret != WS_SFTP_COMPLETE) { wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Failed to accept WOLFSSH connection"); } From e493d3aeb2c1300be6d0b16d564a916a1d4e3603 Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Fri, 15 Jul 2022 13:51:54 -0700 Subject: [PATCH 11/48] assume sshd builds use shell, better support for routing session types after SSH accept --- apps/wolfsshd/wolfsshd.c | 56 ++++++++++++++++++++++++++++------------ configure.ac | 2 ++ 2 files changed, 42 insertions(+), 16 deletions(-) diff --git a/apps/wolfsshd/wolfsshd.c b/apps/wolfsshd/wolfsshd.c index d13e8cee..97c108e8 100644 --- a/apps/wolfsshd/wolfsshd.c +++ b/apps/wolfsshd/wolfsshd.c @@ -502,24 +502,48 @@ static void* wolfSSHD_HandleConnection(void* arg) } } - switch (ret) { - case WS_SFTP_COMPLETE: - #ifdef WOLFSSH_SFTP - ret = SFTP_Subsystem(ssh, conn); - #else - err_sys("SFTP not compiled in. Please use --enable-sftp"); - #endif - break; + if (ret == WS_SUCCESS || ret == WS_SFTP_COMPLETE) { + switch (wolfSSH_GetSessionType(ssh)) { + case WOLFSSH_SESSION_SHELL: + #ifdef WOLFSSH_SHELL + if (ret == WS_SUCCESS) { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Entering new shell"); + SHELL_Subsystem(conn, ssh); + } + #else + wolfSSH_Log(WS_LOG_ERROR, + "[SSHD] Shell support is disabled"); + ret = WS_NOT_COMPILED; + #endif + break; - case WS_SUCCESS: /* default success case to shell */ - #ifdef WOLFSSH_SHELL - printf("ret of accept = %d\n",ret); - if (ret == WS_SUCCESS) { - wolfSSH_Log(WS_LOG_INFO, "[SSHD] Entering new shell"); - SHELL_Subsystem(conn, ssh); + case WOLFSSH_SESSION_SUBSYSTEM: + /* test for known subsystems */ + switch (ret) { + case WS_SFTP_COMPLETE: + #ifdef WOLFSSH_SFTP + ret = SFTP_Subsystem(ssh, conn); + #else + err_sys("SFTP not compiled in. Please use --enable-sftp"); + #endif + break; + + default: + wolfSSH_Log(WS_LOG_ERROR, + "[SSHD] Unknown or build not supporting subsystem" + " found [%s]", wolfSSH_GetSessionCommand(ssh)); + ret = WS_NOT_COMPILED; + } + break; + + case WOLFSSH_SESSION_UNKNOWN: + case WOLFSSH_SESSION_EXEC: + case WOLFSSH_SESSION_TERMINAL: + default: + wolfSSH_Log(WS_LOG_ERROR, + "[SSHD] Unknown or build not supporting session type found"); + ret = WS_NOT_COMPILED; } - #endif - break; } wolfSSH_shutdown(ssh); diff --git a/configure.ac b/configure.ac index 427d880f..9522eb1f 100644 --- a/configure.ac +++ b/configure.ac @@ -216,6 +216,8 @@ AS_IF([test "x$ENABLED_DISTRO" = "xyes"], [ENABLED_ALL=yes; enable_shared=yes; enable_static=yes]) AS_IF([test "x$ENABLED_ALL" = "xyes"], [ENABLED_KEYGEN=yes; ENABLED_SCP=yes; ENABLED_SFTP=yes; ENABLED_FWD=yes; ENABLED_SHELL=yes; ENABLED_AGENT=yes]) +AS_IF([test "x$ENABLED_SSHD" = "xyes"], + [ENABLED_SHELL=yes;]) # Set the defined flags for the code. AS_IF([test "x$ENABLED_INLINE" = "xno"], From 7b8ce149d76be94caa66cd394f8985aa7ade9e0e Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Fri, 15 Jul 2022 16:05:54 -0700 Subject: [PATCH 12/48] add look for libpam and adjust for QNX build --- apps/wolfsshd/auth.c | 32 +++++++++++++++++++++++++++----- apps/wolfsshd/config.c | 19 +++++++++++++++++-- apps/wolfsshd/wolfsshd.c | 12 +++++------- configure.ac | 30 +++++++++++++++++++++++++++++- examples/echoserver/echoserver.c | 6 ++++++ 5 files changed, 84 insertions(+), 15 deletions(-) diff --git a/apps/wolfsshd/auth.c b/apps/wolfsshd/auth.c index 5e7d8cde..e830e208 100644 --- a/apps/wolfsshd/auth.c +++ b/apps/wolfsshd/auth.c @@ -24,7 +24,9 @@ #ifdef WOLFSSH_SSHD -#define _XOPEN_SOURCE +#ifdef __linux__ + #define _XOPEN_SOURCE +#endif #include #include @@ -47,7 +49,6 @@ #include #include #include -#include #include #endif @@ -274,6 +275,17 @@ static int CheckAuthKeysLine(char* line, word32 lineSz, const byte* key, } #ifndef _WIN32 + +#ifdef WOLFSSH_USE_PAM +static int CheckPasswordPAM(const byte* usr, const byte* pw, int pwSz) +{ + (void)usr; + (void)pw; + (void)pwSz; + return 0; +} +#else + static int ExtractSalt(char* hash, char** salt, int saltSz) { int ret = WS_SUCCESS; @@ -327,6 +339,7 @@ static int ExtractSalt(char* hash, char** salt, int saltSz) return ret; } +#ifdef WOLFSSH_HAVE_LIBCRYPT static int CheckPasswordHashUnix(const char* input, char* stored) { int ret = WSSHD_AUTH_SUCCESS; @@ -359,6 +372,7 @@ static int CheckPasswordHashUnix(const char* input, char* stored) return ret; } +#endif /* WOLFSSH_HAVE_LIBCRYPT */ static int CheckPasswordUnix(const byte* usr, const byte* pw, int pwSz) { @@ -384,7 +398,7 @@ static int CheckPasswordUnix(const byte* usr, const byte* pw, int pwSz) pwStr[pwSz] = 0; } } - + pwInfo = getpwnam((const char*)usr); if (pwInfo == NULL) { /* user name not found on system */ @@ -413,7 +427,12 @@ static int CheckPasswordUnix(const byte* usr, const byte* pw, int pwSz) } if (ret == WS_SUCCESS) { + #ifdef WOLFSSH_HAVE_LIBCRYPT ret = CheckPasswordHashUnix(pwStr, storedHashCpy); + #else + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] No compiled in password check"); + ret = WS_NOT_COMPILED; + #endif } if (pwStr != NULL) { @@ -425,6 +444,7 @@ static int CheckPasswordUnix(const byte* usr, const byte* pw, int pwSz) return ret; } +#endif /* WOLFSSH_USE_PAM */ #endif /* !_WIN32 */ #ifndef _WIN32 @@ -455,7 +475,7 @@ void SetAuthKeysPattern(const char* pattern) { if (pattern != NULL) { WMEMSET(authKeysPattern, 0, sizeof(authKeysPattern)); - WSTRNCPY(authKeysPattern, pattern, sizeof(authKeysPattern)); + WSTRNCPY(authKeysPattern, pattern, sizeof(authKeysPattern) - 1); } } @@ -501,7 +521,7 @@ static int CheckPublicKeyUnix(const byte* name, const byte* key, word32 keySz) int rc; struct passwd* pwInfo; char* authKeysFile = NULL; - XFILE f; + XFILE f = NULL; enum { /* TODO: Probably needs to be even bigger for larger key sizes. */ MAX_LINE_SZ = 500, @@ -615,6 +635,8 @@ static int CheckPassword(const byte* usr, const byte* pw, int pwSz) { #ifdef _WIN32 /* TODO: Add CheckPasswordWin. */ +#elif defined(WOLFSSH_USE_PAM) + return CheckPasswordPAM(usr, pw, pwSz); #else return CheckPasswordUnix(usr, pw, pwSz); #endif diff --git a/apps/wolfsshd/config.c b/apps/wolfsshd/config.c index 7f19e4f3..5bf61571 100644 --- a/apps/wolfsshd/config.c +++ b/apps/wolfsshd/config.c @@ -157,7 +157,7 @@ static int wolfSSHD_ParseConfigLine(WOLFSSHD_CONFIG* conf, const char* l, if (lSz > sz && XSTRNCMP(l, privilegeSeparation, sz) == 0) { char* privType = NULL; ret = wolfSSHD_CreateString(&privType, l + sz, lSz - sz, conf->heap); - + /* check if is an allowed option */ if (XSTRNCMP(privType, "sandbox", 7) == 0) { wolfSSH_Log(WS_LOG_INFO, "[SSHD] Sandbox privilege separation"); @@ -182,27 +182,42 @@ static int wolfSSHD_ParseConfigLine(WOLFSSHD_CONFIG* conf, const char* l, } if (XSTRNCMP(l, "Subsystem", 9) == 0) { - + //@TODO ret = WS_SUCCESS; } if (XSTRNCMP(l, "ChallengeResponseAuthentication", 31) == 0) { + //@TODO ret = WS_SUCCESS; } if (XSTRNCMP(l, "UsePAM", 6) == 0) { + //@TODO ret = WS_SUCCESS; } if (XSTRNCMP(l, "X11Forwarding", 13) == 0) { + //@TODO ret = WS_SUCCESS; } if (XSTRNCMP(l, "PrintMotd", 9) == 0) { + //@TODO ret = WS_SUCCESS; } if (XSTRNCMP(l, "AcceptEnv", 9) == 0) { + //@TODO + ret = WS_SUCCESS; + } + + if (XSTRNCMP(l, "Protocol", 8) == 0) { + //@TODO + ret = WS_SUCCESS; + } + + if (XSTRNCMP(l, "LoginGraceTime", 14) == 0) { + //@TODO ret = WS_SUCCESS; } diff --git a/apps/wolfsshd/wolfsshd.c b/apps/wolfsshd/wolfsshd.c index 97c108e8..0fcc64c5 100644 --- a/apps/wolfsshd/wolfsshd.c +++ b/apps/wolfsshd/wolfsshd.c @@ -62,7 +62,12 @@ #endif #include #include +#if defined(__QNX__) || defined(__QNXNTO__) + #include + #include +#else #include +#endif static volatile int ChildRunning = 0; static void ChildSig(int sig) @@ -314,13 +319,6 @@ static int SFTP_Subsystem(WOLFSSH* ssh, WOLFSSHD_CONNECTION* conn) #endif -#ifdef WOLFSSH_SCP -int SCP_Subsystem() -{ - -} -#endif - #ifdef WOLFSSH_SHELL static int SHELL_Subsystem(WOLFSSHD_CONNECTION* conn, WOLFSSH* ssh) { diff --git a/configure.ac b/configure.ac index 9522eb1f..a159a908 100644 --- a/configure.ac +++ b/configure.ac @@ -201,6 +201,12 @@ AC_ARG_ENABLE([smallstack], [AS_HELP_STRING([--enable-smallstack],[Enable small stack (default: disabled)])], [ENABLED_SMALLSTACK=$enableval],[ENABLED_SMALLSTACK=no]) +# use PAM lib +AC_ARG_WITH([pam], + [AS_HELP_STRING([--with-pam=PATH],[PATH to directory with the PAM library])], + [PAM_LIB=$withval], + [PAM_LIB=""]) + # Enable All AC_ARG_ENABLE([all], [AS_HELP_STRING([--enable-all],[Enable all wolfSSH features (default: disabled)])], @@ -241,9 +247,31 @@ AS_IF([test "x$ENABLED_SSHD" = "xyes"], [AM_CPPFLAGS="$AM_CPPFLAGS -DWOLFSSH_SSHD"]) if test "$ENABLED_SSHD" = "yes"; then - AC_CHECK_LIB([crypt], [crypt], [], [AC_MSG_ERROR([libcrypt is required for sshd])]) + if test -n "$PAM_LIB" + then + AC_MSG_CHECKING([for directory $PAM_LIB]) + if ! test -d "$PAM_LIB" + then + AC_MSG_ERROR([PAM lib dir $PAM_LIB not found.]) + fi + AC_MSG_RESULT([yes]) + AM_LDFLAGS="-L$PAM_LIB $AM_LDFLAGS" + + LIBS="$LIBS -lpam" + AM_CPPFLAGS="$AM_CPPFLAGS -DWOLFSSH_USE_PAM" + #TODO check on link to lib + #AC_CHECK_LIB([pam], [pam], + # [AM_CPPFLAGS="$AM_CPPFLAGS -DWOLFSSH_USE_PAM"; LIBS="$LIBS -lpam"], + # [AC_MSG_ERROR(libpam not found)]) + else + AC_CHECK_LIB([crypt], [crypt], + [AM_CPPFLAGS="$AM_CPPFLAGS -DWOLFSSH_HAVE_LIBCRYPT"; + LIBS="$LIBS -lcrypt"], + [AC_MSG_ERROR(libcrypt not found)]) + fi fi + # Set the automake conditionals. AM_CONDITIONAL([BUILD_EXAMPLE_SERVERS],[test "x$ENABLED_EXAMPLES" = "xyes"]) AM_CONDITIONAL([BUILD_EXAMPLE_CLIENTS],[test "x$ENABLED_EXAMPLES" = "xyes"]) diff --git a/examples/echoserver/echoserver.c b/examples/echoserver/echoserver.c index 196f3140..6c4d3e36 100644 --- a/examples/echoserver/echoserver.c +++ b/examples/echoserver/echoserver.c @@ -69,6 +69,12 @@ #endif #include #include +#if defined(__QNX__) || defined(__QNXNTO__) + #include + #include +#else + #include +#endif #endif /* WOLFSSH_SHELL */ #ifdef WOLFSSH_AGENT From 11c1a3998daf5bd37f1df509653b9dd539a41a70 Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Wed, 20 Jul 2022 10:55:42 -0700 Subject: [PATCH 13/48] use function callbacks for auth --- apps/wolfsshd/auth.c | 201 ++++++++++++++++++++++++++++----------- apps/wolfsshd/auth.h | 25 +++++ apps/wolfsshd/wolfsshd.c | 58 +++++++---- 3 files changed, 206 insertions(+), 78 deletions(-) diff --git a/apps/wolfsshd/auth.c b/apps/wolfsshd/auth.c index e830e208..c7c1941f 100644 --- a/apps/wolfsshd/auth.c +++ b/apps/wolfsshd/auth.c @@ -52,6 +52,14 @@ #include #endif +struct WOLFSSHD_AUTH { + CallbackCheckUser CheckUserCb; + CallbackCheckPassword CheckPasswordCb; + CallbackCheckPublicKey CheckPublicKeyCb; + void* heap; +}; + + #if 0 static byte passwdRetry = 3; @@ -248,7 +256,7 @@ static int CheckAuthKeysLine(char* line, word32 lineSz, const byte* key, } } if (ret == WSSHD_AUTH_SUCCESS) { - keyCandBase64Sz = XSTRLEN(keyCandBase64); + keyCandBase64Sz = (word32)XSTRLEN(keyCandBase64); keyCandSz = (keyCandBase64Sz * 3 + 3) / 4; keyCand = (byte*)WMALLOC(keyCandSz, NULL, DYNTYPE_BUFFER); if (keyCand == NULL) { @@ -452,6 +460,7 @@ static int CheckUserUnix(const char* name) { int ret = WSSHD_AUTH_FAILURE; struct passwd* pwInfo; + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Unix check user"); errno = 0; pwInfo = getpwnam(name); if (pwInfo == NULL) { @@ -504,7 +513,7 @@ static int ResolveAuthKeysPath(const char* homeDir, char* resolved) } if (ret == WS_SUCCESS) { idx = resolved; - homeDirSz = XSTRLEN(homeDir); + homeDirSz = (int)XSTRLEN(homeDir); XMEMCPY(idx, homeDir, homeDirSz); idx += homeDirSz; *(idx++) = '/'; @@ -532,7 +541,7 @@ static int CheckPublicKeyUnix(const byte* name, const byte* key, word32 keySz) word32 currentSz; int foundKey = 0; char authKeysPath[MAX_PATH_SZ]; - + errno = 0; pwInfo = getpwnam((const char*)name); if (pwInfo == NULL) { @@ -567,7 +576,7 @@ static int CheckPublicKeyUnix(const byte* name, const byte* key, word32 keySz) } while (ret == WSSHD_AUTH_SUCCESS && (current = XFGETS(lineBuf, MAX_LINE_SZ, f)) != NULL) { - currentSz = XSTRLEN(current); + currentSz = (word32)XSTRLEN(current); /* remove leading spaces */ while (currentSz > 0 && current[0] == ' ') { @@ -610,61 +619,30 @@ static int CheckPublicKeyUnix(const byte* name, const byte* key, word32 keySz) } #endif /* !_WIN32*/ -/* - * Returns WSSHD_AUTH_SUCCESS if user found, WSSHD_AUTH_FAILURE if user not - * found, and negative values if an error occurs during checking. - */ -static int CheckUser(const char* name) -{ - int ret = WSSHD_AUTH_FAILURE; - -#ifdef _WIN32 - /* TODO: Implement for Windows. */ -#else - ret = CheckUserUnix(name); -#endif - - return ret; -} - -/* - * Returns WSSHD_AUTH_SUCCESS if user found, WSSHD_AUTH_FAILURE if user not - * found, and negative values if an error occurs during checking. - */ -static int CheckPassword(const byte* usr, const byte* pw, int pwSz) -{ -#ifdef _WIN32 - /* TODO: Add CheckPasswordWin. */ -#elif defined(WOLFSSH_USE_PAM) - return CheckPasswordPAM(usr, pw, pwSz); -#else - return CheckPasswordUnix(usr, pw, pwSz); -#endif -} - -/* - * Returns WSSHD_AUTH_SUCCESS if public key ok, WSSHD_AUTH_FAILURE if key not - * ok, and negative values if an error occurs during checking. - */ -static int CheckPublicKey(const byte* name, const byte* key, word32 keySz) -{ - int ret = 0; - -#ifdef _WIN32 - /* TODO: Implement for Windows. */ -#else - ret = CheckPublicKeyUnix(name, key, keySz); -#endif - - return ret; -} int DefaultUserAuth(byte authType, WS_UserAuthData* authData, void* ctx) { int ret = WOLFSSH_USERAUTH_SUCCESS; int rc; + WOLFSSHD_AUTH* auth; + + if (ctx == NULL) { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] No auth callbacks passed in"); + return WOLFSSH_USERAUTH_FAILURE; + } + else { + auth = (WOLFSSHD_AUTH*)ctx; + if (auth->CheckUserCb == NULL) { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] No way to check the user is set"); + return WOLFSSH_USERAUTH_FAILURE; + } + } + + if (authData == NULL) { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] No authData passed in"); + return WOLFSSH_USERAUTH_FAILURE; + } - (void)ctx; /* TODO: Auth will need some info from the config. For example, the auth * keys file path or the allowed users, if not all users are allowed. Could * pass the config in the ctx pointer... @@ -680,8 +658,8 @@ int DefaultUserAuth(byte authType, WS_UserAuthData* authData, void* ctx) } /* Check user exists. */ - /* TODO: Is authData and its members guaranteed to be non-NULL? */ - rc = CheckUser((const char*)authData->username); + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Checking user name %s", authData->username); + rc = auth->CheckUserCb((const char*)authData->username); if (rc == WSSHD_AUTH_SUCCESS) { wolfSSH_Log(WS_LOG_INFO, "[SSHD] User ok."); } @@ -699,7 +677,7 @@ int DefaultUserAuth(byte authType, WS_UserAuthData* authData, void* ctx) if (ret == WOLFSSH_USERAUTH_SUCCESS) { /* Check if password is valid for this user. */ if (authData->type == WOLFSSH_USERAUTH_PASSWORD) { - rc = CheckPassword(authData->username, + rc = auth->CheckPasswordCb(authData->username, authData->sf.password.password, authData->sf.password.passwordSz); if (rc == WSSHD_AUTH_SUCCESS) { @@ -716,7 +694,7 @@ int DefaultUserAuth(byte authType, WS_UserAuthData* authData, void* ctx) } /* Check if public key is in this user's authorized_keys file. */ else if (authData->type == WOLFSSH_USERAUTH_PUBLICKEY) { - rc = CheckPublicKey(authData->username, + rc = auth->CheckPublicKeyCb(authData->username, authData->sf.publicKey.publicKey, authData->sf.publicKey.publicKeySz); if (rc == WSSHD_AUTH_SUCCESS) { @@ -736,4 +714,113 @@ int DefaultUserAuth(byte authType, WS_UserAuthData* authData, void* ctx) return ret; } + + +static int SetDefaultUserCheck(WOLFSSHD_AUTH* auth) +{ + int ret = WS_NOT_COMPILED; + +#ifdef _WIN32 + /* TODO: Implement for Windows. */ +#else + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Setting default Unix user name check"); + auth->CheckUserCb = CheckUserUnix; + ret = WS_SUCCESS; +#endif + + return ret; +} + + +static int SetDefaultPasswordCheck(WOLFSSHD_AUTH* auth) +{ + int ret = WS_NOT_COMPILED; + +#ifdef _WIN32 + /* TODO: Add CheckPasswordWin. */ +#elif defined(WOLFSSH_USE_PAM) + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Setting PAM password check"); + auth->CheckPasswordCb = CheckPasswordPAM; + ret = WS_SUCCESS; +#else + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Setting Unix password check"); + auth->CheckPasswordCb = CheckPasswordUnix; + ret = WS_SUCCESS; +#endif + return ret; +} + + +static int SetDefaultPublicKeyCheck(WOLFSSHD_AUTH* auth) +{ + int ret = WS_NOT_COMPILED; + +#ifdef _WIN32 + /* TODO: Implement for Windows. */ +#else + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Setting Unix public key check"); + auth->CheckPublicKeyCb = CheckPublicKeyUnix; + ret = WS_SUCCESS; +#endif + return ret; +} + + +/* Sets the default functions to be used for authentication of peer. + * Later the default functions could be overriden if needed. + * returns a newly created WOLFSSHD_AUTH struct success */ +WOLFSSHD_AUTH * wolfSSHD_CreateUserAuth(void* heap) +{ + WOLFSSHD_AUTH* auth; + + auth = (WOLFSSHD_AUTH*)WMALLOC(sizeof(WOLFSSHD_AUTH), heap, DYNTYPE_SSHD); + if (auth != NULL) { + int ret; + + auth->heap = heap; + + /* set the default user checking based on build */ + ret = SetDefaultUserCheck(auth); + if (ret != WS_SUCCESS) { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Error setting default user check."); + } + + /* set the default password checking based on build */ + if (ret == WS_SUCCESS) { + ret = SetDefaultPasswordCheck(auth); + if (ret != WS_SUCCESS) { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Error setting default " + "password check."); + } + } + + /* set the default public key checking based on build */ + if (ret == WS_SUCCESS) { + ret = SetDefaultPublicKeyCheck(auth); + if (ret != WS_SUCCESS) { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Error setting default " + "public key check."); + } + } + + /* error case in setting one of the default callbacks */ + if (ret != WS_SUCCESS) { + (void)wolfSSHD_FreeUserAuth(auth); + auth = NULL; + } + } + + + return auth; +} + + +/* returns WS_SUCCESS on success */ +int wolfSSHD_FreeUserAuth(WOLFSSHD_AUTH* auth) +{ + if (auth != NULL) { + WFREE(auth, auth->heap, DYNTYPE_SSHD); + } + return WS_SUCCESS; +} #endif /* WOLFSSH_SSHD */ diff --git a/apps/wolfsshd/auth.h b/apps/wolfsshd/auth.h index c501d185..90347eb4 100644 --- a/apps/wolfsshd/auth.h +++ b/apps/wolfsshd/auth.h @@ -31,4 +31,29 @@ USER_NODE* AddNewUser(USER_NODE* list, byte type, const byte* username, void SetAuthKeysPattern(const char* pattern); int DefaultUserAuth(byte authType, WS_UserAuthData* authData, void* ctx); +typedef struct WOLFSSHD_AUTH WOLFSSHD_AUTH; + +/* + * Returns WSSHD_AUTH_SUCCESS if user found, WSSHD_AUTH_FAILURE if user not + * found, and negative values if an error occurs during checking. + */ +typedef int (*CallbackCheckUser)(const char* usr); + + +/* + * Returns WSSHD_AUTH_SUCCESS if user found, WSSHD_AUTH_FAILURE if user not + * found, and negative values if an error occurs during checking. + */ +typedef int (*CallbackCheckPassword)(const byte* usr, const byte* psw, + int pswSz); + +/* + * Returns WSSHD_AUTH_SUCCESS if public key ok, WSSHD_AUTH_FAILURE if key not + * ok, and negative values if an error occurs during checking. + */ +typedef int (*CallbackCheckPublicKey)(const byte* usr, const byte* key, + word32 keySz); + +WOLFSSHD_AUTH * wolfSSHD_CreateUserAuth(void* heap); +int wolfSSHD_FreeUserAuth(WOLFSSHD_AUTH* auth); #endif /* WOLFAUTH_H */ diff --git a/apps/wolfsshd/wolfsshd.c b/apps/wolfsshd/wolfsshd.c index 0fcc64c5..53c2d96f 100644 --- a/apps/wolfsshd/wolfsshd.c +++ b/apps/wolfsshd/wolfsshd.c @@ -85,8 +85,9 @@ static const char defaultBanner[] = "wolfSSHD\n"; /* Initial connection information to pass on to threads/forks */ typedef struct WOLFSSHD_CONNECTION { - WOLFSSH_CTX* ctx; - int fd; + WOLFSSH_CTX* ctx; + WOLFSSHD_AUTH* auth; + int fd; } WOLFSSHD_CONNECTION; static void ShowUsage(void) @@ -493,6 +494,7 @@ static void* wolfSSHD_HandleConnection(void* arg) if (ret == WS_SUCCESS) { wolfSSH_set_fd(ssh, conn->fd); + wolfSSH_SetUserAuthCtx(ssh, conn->auth); ret = wolfSSH_accept(ssh); if (ret != WS_SUCCESS && ret != WS_SFTP_COMPLETE) { wolfSSH_Log(WS_LOG_ERROR, @@ -624,6 +626,7 @@ int main(int argc, char** argv) WS_SOCKET_T listenFd = 0; int ch; WOLFSSHD_CONFIG* conf = NULL; + WOLFSSHD_AUTH* auth = NULL; WOLFSSH_CTX* ctx = NULL; const char* configFile = "/usr/local/etc/ssh/sshd_config"; @@ -713,35 +716,48 @@ int main(int argc, char** argv) /* TODO: handle error. */ } - wolfSSH_Log(WS_LOG_INFO, "[SSHD] Starting to listen on port %d", port); - tcp_listen(&listenFd, &port, 1); - wolfSSH_Log(WS_LOG_INFO, "[SSHD] Listening on port %d", port); + if (ret == WS_SUCCESS) { + auth = wolfSSHD_CreateUserAuth(NULL); + if (auth == NULL) { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Issue creating auth struct"); + ret = WS_MEMORY_E; + } + printf("created auth %p\n", auth); + } - /* wait for incoming connections and fork them off */ - while (ret == WS_SUCCESS && quit == 0) { - WOLFSSHD_CONNECTION conn; - #ifdef WOLFSSL_NUCLEUS - struct addr_struct clientAddr; - #else - SOCKADDR_IN_T clientAddr; - socklen_t clientAddrSz = sizeof(clientAddr); - #endif + if (ret == WS_SUCCESS) { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Starting to listen on port %d", port); + tcp_listen(&listenFd, &port, 1); + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Listening on port %d", port); - /* wait for a connection */ - if (wolfSSHD_PendingConnection(listenFd)) { - conn.ctx = ctx; + /* wait for incoming connections and fork them off */ + while (ret == WS_SUCCESS && quit == 0) { + WOLFSSHD_CONNECTION conn; #ifdef WOLFSSL_NUCLEUS - conn.fd = NU_Accept(listenFd, &clientAddr, 0); + struct addr_struct clientAddr; #else - conn.fd = accept(listenFd, (struct sockaddr*)&clientAddr, - &clientAddrSz); + SOCKADDR_IN_T clientAddr; + socklen_t clientAddrSz = sizeof(clientAddr); #endif + conn.auth = auth; - ret = wolfSSHD_NewConnection(&conn); + /* wait for a connection */ + if (wolfSSHD_PendingConnection(listenFd)) { + conn.ctx = ctx; + #ifdef WOLFSSL_NUCLEUS + conn.fd = NU_Accept(listenFd, &clientAddr, 0); + #else + conn.fd = accept(listenFd, (struct sockaddr*)&clientAddr, + &clientAddrSz); + #endif + + ret = wolfSSHD_NewConnection(&conn); + } } } wolfSSHD_FreeConfig(conf); + wolfSSHD_FreeUserAuth(auth); wolfSSH_Cleanup(); return 0; From 311738d0578e6d3fba45a3c57efa17d63fa54378 Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Thu, 21 Jul 2022 14:43:43 -0700 Subject: [PATCH 14/48] add link to liblogin with QNX for crypt --- apps/wolfsshd/auth.c | 15 ++++++++++++--- apps/wolfsshd/wolfsshd.c | 1 - configure.ac | 18 ++++++++++++++---- 3 files changed, 26 insertions(+), 8 deletions(-) diff --git a/apps/wolfsshd/auth.c b/apps/wolfsshd/auth.c index c7c1941f..1fff14a2 100644 --- a/apps/wolfsshd/auth.c +++ b/apps/wolfsshd/auth.c @@ -294,6 +294,7 @@ static int CheckPasswordPAM(const byte* usr, const byte* pw, int pwSz) } #else +#if defined(WOLFSSH_HAVE_LIBCRYPT) || defined(WOLFSSH_HAVE_LIBLOGIN) static int ExtractSalt(char* hash, char** salt, int saltSz) { int ret = WS_SUCCESS; @@ -347,7 +348,6 @@ static int ExtractSalt(char* hash, char** salt, int saltSz) return ret; } -#ifdef WOLFSSH_HAVE_LIBCRYPT static int CheckPasswordHashUnix(const char* input, char* stored) { int ret = WSSHD_AUTH_SUCCESS; @@ -380,7 +380,7 @@ static int CheckPasswordHashUnix(const char* input, char* stored) return ret; } -#endif /* WOLFSSH_HAVE_LIBCRYPT */ +#endif /* WOLFSSH_HAVE_LIBCRYPT || WOLFSSH_HAVE_LIBLOGIN */ static int CheckPasswordUnix(const byte* usr, const byte* pw, int pwSz) { @@ -415,8 +415,17 @@ static int CheckPasswordUnix(const byte* usr, const byte* pw, int pwSz) if (ret == WS_SUCCESS) { if (pwInfo->pw_passwd[0] == 'x') { + #ifdef WOLFSSH_HAVE_LIBCRYPT shadowInfo = getspnam((const char*)usr); + #else + shadowInfo = getspnam((char*)usr); + #endif if (shadowInfo == NULL) { + wolfSSH_Log(WS_LOG_ERROR, + "[SSHD] Error getting user password info"); + wolfSSH_Log(WS_LOG_ERROR, + "[SSHD] Possibly permisions level error?" + " i.e SSHD not ran as sudo"); ret = WS_FATAL_ERROR; } else { @@ -435,7 +444,7 @@ static int CheckPasswordUnix(const byte* usr, const byte* pw, int pwSz) } if (ret == WS_SUCCESS) { - #ifdef WOLFSSH_HAVE_LIBCRYPT + #if defined(WOLFSSH_HAVE_LIBCRYPT) || defined(WOLFSSH_HAVE_LIBLOGIN) ret = CheckPasswordHashUnix(pwStr, storedHashCpy); #else wolfSSH_Log(WS_LOG_ERROR, "[SSHD] No compiled in password check"); diff --git a/apps/wolfsshd/wolfsshd.c b/apps/wolfsshd/wolfsshd.c index 53c2d96f..1cfe8b0e 100644 --- a/apps/wolfsshd/wolfsshd.c +++ b/apps/wolfsshd/wolfsshd.c @@ -722,7 +722,6 @@ int main(int argc, char** argv) wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Issue creating auth struct"); ret = WS_MEMORY_E; } - printf("created auth %p\n", auth); } if (ret == WS_SUCCESS) { diff --git a/configure.ac b/configure.ac index a159a908..dacdadb0 100644 --- a/configure.ac +++ b/configure.ac @@ -264,10 +264,20 @@ if test "$ENABLED_SSHD" = "yes"; then # [AM_CPPFLAGS="$AM_CPPFLAGS -DWOLFSSH_USE_PAM"; LIBS="$LIBS -lpam"], # [AC_MSG_ERROR(libpam not found)]) else - AC_CHECK_LIB([crypt], [crypt], - [AM_CPPFLAGS="$AM_CPPFLAGS -DWOLFSSH_HAVE_LIBCRYPT"; - LIBS="$LIBS -lcrypt"], - [AC_MSG_ERROR(libcrypt not found)]) + case $host in + *qnx*) + # QNX uses liblogin for crypt operation + AC_CHECK_LIB([login], [login], + [AM_CPPFLAGS="$AM_CPPFLAGS -DWOLFSSH_HAVE_LIBLOGIN"; + LIBS="$LIBS -llogin"], + [AC_MSG_ERROR(liblogin not found)]) + ;; + *) + AC_CHECK_LIB([crypt], [crypt], + [AM_CPPFLAGS="$AM_CPPFLAGS -DWOLFSSH_HAVE_LIBCRYPT"; + LIBS="$LIBS -lcrypt"], + [AC_MSG_ERROR(libcrypt not found)]) + esac fi fi From f8439af47ede480d7a91ed1a2b3e7192cd056bb1 Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Thu, 21 Jul 2022 16:23:01 -0700 Subject: [PATCH 15/48] add support to handle PermitEmptyPasswords config --- apps/wolfsshd/auth.c | 178 +++++++++++++++++++++++---------------- apps/wolfsshd/auth.h | 8 +- apps/wolfsshd/config.c | 39 ++++++++- apps/wolfsshd/wolfsshd.c | 2 +- apps/wolfsshd/wolfsshd.h | 8 +- 5 files changed, 153 insertions(+), 82 deletions(-) diff --git a/apps/wolfsshd/auth.c b/apps/wolfsshd/auth.c index 1fff14a2..16030585 100644 --- a/apps/wolfsshd/auth.c +++ b/apps/wolfsshd/auth.c @@ -43,7 +43,7 @@ #include "src/misc.c" #endif -#include "auth.h" +#include "wolfsshd.h" #ifndef _WIN32 #include @@ -56,6 +56,7 @@ struct WOLFSSHD_AUTH { CallbackCheckUser CheckUserCb; CallbackCheckPassword CheckPasswordCb; CallbackCheckPublicKey CheckPublicKeyCb; + WOLFSSHD_CONFIG* conf; void* heap; }; @@ -294,7 +295,7 @@ static int CheckPasswordPAM(const byte* usr, const byte* pw, int pwSz) } #else -#if defined(WOLFSSH_HAVE_LIBCRYPT) || defined(WOLFSSH_HAVE_LIBLOGIN) +#if defined(WOLFSSH_HAVE_LIBCRYPT) static int ExtractSalt(char* hash, char** salt, int saltSz) { int ret = WS_SUCCESS; @@ -347,13 +348,12 @@ static int ExtractSalt(char* hash, char** salt, int saltSz) return ret; } +#endif /* WOLFSSH_HAVE_LIBCRYPT */ +#if defined(WOLFSSH_HAVE_LIBCRYPT) || defined(WOLFSSH_HAVE_LIBLOGIN) static int CheckPasswordHashUnix(const char* input, char* stored) { int ret = WSSHD_AUTH_SUCCESS; - int rc; - char salt[32]; - char* p = salt; char* hashedInput; if (input == NULL || stored == NULL) { @@ -361,13 +361,7 @@ static int CheckPasswordHashUnix(const char* input, char* stored) } if (ret == WSSHD_AUTH_SUCCESS) { - rc = ExtractSalt(stored, &p, sizeof(salt)); - if (rc != WS_SUCCESS) { - ret = rc; - } - } - if (ret == WSSHD_AUTH_SUCCESS) { - hashedInput = crypt(input, salt); + hashedInput = crypt(input, stored); if (hashedInput == NULL) { ret = WS_FATAL_ERROR; } @@ -382,7 +376,7 @@ static int CheckPasswordHashUnix(const char* input, char* stored) } #endif /* WOLFSSH_HAVE_LIBCRYPT || WOLFSSH_HAVE_LIBLOGIN */ -static int CheckPasswordUnix(const byte* usr, const byte* pw, int pwSz) +static int CheckPasswordUnix(const char* usr, const byte* pw, word32 pwSz) { int ret = WS_SUCCESS; char* pwStr = NULL; @@ -392,7 +386,7 @@ static int CheckPasswordUnix(const byte* usr, const byte* pw, int pwSz) char* storedHash; char* storedHashCpy = NULL; - if (usr == NULL || pw == NULL || pwSz < 0) { + if (usr == NULL || pw == NULL) { ret = WS_BAD_ARGUMENT; } @@ -533,7 +527,7 @@ static int ResolveAuthKeysPath(const char* homeDir, char* resolved) return ret; } -static int CheckPublicKeyUnix(const byte* name, const byte* key, word32 keySz) +static int CheckPublicKeyUnix(const char* name, const byte* key, word32 keySz) { int ret = WSSHD_AUTH_SUCCESS; int rc; @@ -629,10 +623,89 @@ static int CheckPublicKeyUnix(const byte* name, const byte* key, word32 keySz) #endif /* !_WIN32*/ +static int DoCheckUser(const char* usr, WOLFSSHD_AUTH* auth) +{ + int ret = WOLFSSH_USERAUTH_FAILURE; + int rc; + + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Checking user name %s", usr); + rc = auth->CheckUserCb(usr); + if (rc == WSSHD_AUTH_SUCCESS) { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] User ok."); + ret = WOLFSSH_USERAUTH_SUCCESS; + } + else if (ret == WSSHD_AUTH_FAILURE) { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] User %s doesn't exist.", usr); + ret = WOLFSSH_USERAUTH_INVALID_USER; + } + else { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Error looking up user %s.", usr); + ret = WOLFSSH_USERAUTH_FAILURE; + } + return ret; +} + + +/* @TODO this will take in a pipe or equivilant to talk to a privliged thread + * rathar than having WOLFSSHD_AUTH directly with privilige seperation */ +static int RequestAuthentication(const char* usr, int type, const byte* data, + int dataSz, WOLFSSHD_AUTH* auth) +{ + int ret; + + ret = DoCheckUser(usr, auth); + if (ret == WOLFSSH_USERAUTH_SUCCESS && type == WOLFSSH_USERAUTH_PASSWORD) { + int rc; + + /* Check if password is valid for this user. */ + /* first handle empty password cases */ + if (dataSz == 0 && wolfSSHD_ConfigOptionEnabled(auth->conf, + WOLFSSHD_EMPTY_PASSWORD) != 1) { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Empty passwords not allowed!"); + ret = WOLFSSH_USERAUTH_FAILURE; + } + else { + rc = auth->CheckPasswordCb(usr, data, dataSz); + if (rc == WSSHD_AUTH_SUCCESS) { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Password ok."); + } + else if (rc == WSSHD_AUTH_FAILURE) { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Password incorrect."); + ret = WOLFSSH_USERAUTH_INVALID_PASSWORD; + } + else { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Error checking password."); + ret = WOLFSSH_USERAUTH_FAILURE; + } + } + } + + + if (ret == WOLFSSH_USERAUTH_SUCCESS && type == WOLFSSH_USERAUTH_PUBLICKEY) { + int rc; + + rc = auth->CheckPublicKeyCb(usr, data, dataSz); + if (rc == WSSHD_AUTH_SUCCESS) { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Public key ok."); + ret = WOLFSSH_USERAUTH_SUCCESS; + } + else if (rc == WSSHD_AUTH_FAILURE) { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Public key not authorized."); + ret = WOLFSSH_USERAUTH_INVALID_PUBLICKEY; + } + else { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Error checking public key."); + ret = WOLFSSH_USERAUTH_FAILURE; + } + } + + return ret; +} + + int DefaultUserAuth(byte authType, WS_UserAuthData* authData, void* ctx) { int ret = WOLFSSH_USERAUTH_SUCCESS; - int rc; WOLFSSHD_AUTH* auth; if (ctx == NULL) { @@ -652,11 +725,6 @@ int DefaultUserAuth(byte authType, WS_UserAuthData* authData, void* ctx) return WOLFSSH_USERAUTH_FAILURE; } - /* TODO: Auth will need some info from the config. For example, the auth - * keys file path or the allowed users, if not all users are allowed. Could - * pass the config in the ctx pointer... - */ - if (authType != WOLFSSH_USERAUTH_PASSWORD && #ifdef WOLFSSH_ALLOW_USERAUTH_NONE authType != WOLFSSH_USERAUTH_NONE && @@ -666,59 +734,22 @@ int DefaultUserAuth(byte authType, WS_UserAuthData* authData, void* ctx) ret = WOLFSSH_USERAUTH_INVALID_AUTHTYPE; } - /* Check user exists. */ - wolfSSH_Log(WS_LOG_INFO, "[SSHD] Checking user name %s", authData->username); - rc = auth->CheckUserCb((const char*)authData->username); - if (rc == WSSHD_AUTH_SUCCESS) { - wolfSSH_Log(WS_LOG_INFO, "[SSHD] User ok."); - } - else if (ret == WSSHD_AUTH_FAILURE) { - wolfSSH_Log(WS_LOG_INFO, "[SSHD] User %s doesn't exist.", - authData->username); - ret = WOLFSSH_USERAUTH_INVALID_USER; - } - else { - wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Error looking up user %s.", - authData->username); - ret = WOLFSSH_USERAUTH_FAILURE; + /* call to possibly privilaged authentecator for password check */ + if (ret == WOLFSSH_USERAUTH_SUCCESS && + authData->type == WOLFSSH_USERAUTH_PASSWORD) { + ret = RequestAuthentication((const char*)authData->username, + authData->type, + authData->sf.password.password, + authData->sf.password.passwordSz, auth); } - if (ret == WOLFSSH_USERAUTH_SUCCESS) { - /* Check if password is valid for this user. */ - if (authData->type == WOLFSSH_USERAUTH_PASSWORD) { - rc = auth->CheckPasswordCb(authData->username, - authData->sf.password.password, - authData->sf.password.passwordSz); - if (rc == WSSHD_AUTH_SUCCESS) { - wolfSSH_Log(WS_LOG_INFO, "[SSHD] Password ok."); - } - else if (rc == WSSHD_AUTH_FAILURE) { - wolfSSH_Log(WS_LOG_INFO, "[SSHD] Password incorrect."); - ret = WOLFSSH_USERAUTH_INVALID_PASSWORD; - } - else { - wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Error checking password."); - ret = WOLFSSH_USERAUTH_FAILURE; - } - } - /* Check if public key is in this user's authorized_keys file. */ - else if (authData->type == WOLFSSH_USERAUTH_PUBLICKEY) { - rc = auth->CheckPublicKeyCb(authData->username, - authData->sf.publicKey.publicKey, - authData->sf.publicKey.publicKeySz); - if (rc == WSSHD_AUTH_SUCCESS) { - wolfSSH_Log(WS_LOG_INFO, "[SSHD] Public key ok."); - ret = WOLFSSH_USERAUTH_SUCCESS; - } - else if (rc == WSSHD_AUTH_FAILURE) { - wolfSSH_Log(WS_LOG_INFO, "[SSHD] Public key not authorized."); - ret = WOLFSSH_USERAUTH_INVALID_PUBLICKEY; - } - else { - wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Error checking public key."); - ret = WOLFSSH_USERAUTH_FAILURE; - } - } + /* call to possibly privilaged authentecator for public key check */ + if (ret == WOLFSSH_USERAUTH_SUCCESS && + authData->type == WOLFSSH_USERAUTH_PUBLICKEY) { + ret = RequestAuthentication((const char*)authData->username, + authData->type, + authData->sf.publicKey.publicKey, + authData->sf.publicKey.publicKeySz, auth); } return ret; @@ -778,7 +809,7 @@ static int SetDefaultPublicKeyCheck(WOLFSSHD_AUTH* auth) /* Sets the default functions to be used for authentication of peer. * Later the default functions could be overriden if needed. * returns a newly created WOLFSSHD_AUTH struct success */ -WOLFSSHD_AUTH * wolfSSHD_CreateUserAuth(void* heap) +WOLFSSHD_AUTH * wolfSSHD_CreateUserAuth(void* heap, WOLFSSHD_CONFIG* conf) { WOLFSSHD_AUTH* auth; @@ -787,6 +818,7 @@ WOLFSSHD_AUTH * wolfSSHD_CreateUserAuth(void* heap) int ret; auth->heap = heap; + auth->conf = conf; /* set the default user checking based on build */ ret = SetDefaultUserCheck(auth); diff --git a/apps/wolfsshd/auth.h b/apps/wolfsshd/auth.h index 90347eb4..f99109e9 100644 --- a/apps/wolfsshd/auth.h +++ b/apps/wolfsshd/auth.h @@ -44,16 +44,16 @@ typedef int (*CallbackCheckUser)(const char* usr); * Returns WSSHD_AUTH_SUCCESS if user found, WSSHD_AUTH_FAILURE if user not * found, and negative values if an error occurs during checking. */ -typedef int (*CallbackCheckPassword)(const byte* usr, const byte* psw, - int pswSz); +typedef int (*CallbackCheckPassword)(const char* usr, const byte* psw, + word32 pswSz); /* * Returns WSSHD_AUTH_SUCCESS if public key ok, WSSHD_AUTH_FAILURE if key not * ok, and negative values if an error occurs during checking. */ -typedef int (*CallbackCheckPublicKey)(const byte* usr, const byte* key, +typedef int (*CallbackCheckPublicKey)(const char* usr, const byte* key, word32 keySz); -WOLFSSHD_AUTH * wolfSSHD_CreateUserAuth(void* heap); +WOLFSSHD_AUTH * wolfSSHD_CreateUserAuth(void* heap, WOLFSSHD_CONFIG* conf); int wolfSSHD_FreeUserAuth(WOLFSSHD_AUTH* auth); #endif /* WOLFAUTH_H */ diff --git a/apps/wolfsshd/config.c b/apps/wolfsshd/config.c index 5bf61571..52c86a37 100644 --- a/apps/wolfsshd/config.c +++ b/apps/wolfsshd/config.c @@ -142,8 +142,9 @@ static int wolfSSHD_ParseConfigLine(WOLFSSHD_CONFIG* conf, const char* l, char* tmp; /* supported config options */ - const char authKeyFile[] = "AuthorizedKeysFile"; - const char privilegeSeparation[] = "UsePrivilegeSeparation"; + const char authKeyFile[] = "AuthorizedKeysFile"; + const char privilegeSeparation[] = "UsePrivilegeSeparation"; + const char permitEmptyPasswords[] = "PermitEmptyPasswords"; sz = (int)XSTRLEN(authKeyFile); if (lSz > sz && XSTRNCMP(l, authKeyFile, sz) == 0) { @@ -222,12 +223,29 @@ static int wolfSSHD_ParseConfigLine(WOLFSSHD_CONFIG* conf, const char* l, } + sz = (int)XSTRLEN(permitEmptyPasswords); + if (lSz > sz && XSTRNCMP(l, permitEmptyPasswords, sz) == 0) { + char* emptyPasswd = NULL; + ret = wolfSSHD_CreateString(&emptyPasswd, l + sz, lSz - sz, conf->heap); + + if (XSTRNCMP(emptyPasswd, "yes", 3) == 0) { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Empty password enabled"); + conf->permitEmptyPasswords = 1; + ret = WS_SUCCESS; + } + + /* default is no */ + if (XSTRNCMP(emptyPasswd, "no", 2) == 0) { + ret = WS_SUCCESS; + } + wolfSSHD_FreeString(&emptyPasswd, conf->heap); + } if (ret == WS_BAD_ARGUMENT) { printf("unknown / unsuported config line\n"); } - (void)conf;(void)lSz; + (void)lSz; return ret; } @@ -328,4 +346,19 @@ word16 wolfSSHD_GetPort(WOLFSSHD_CONFIG* conf) return conf->port; return 0; } + + +/* test if the 'opt' options is enabled or not in 'conf' for the flags set + * return 1 if enabled and 0 if not */ +int wolfSSHD_ConfigOptionEnabled(WOLFSSHD_CONFIG* conf, word32 opt) +{ + int ret = 0; + + switch (opt) { + case WOLFSSHD_EMPTY_PASSWORD: + ret = conf->permitEmptyPasswords; + break; + } + return ret; +} #endif /* WOLFSSH_SSHD */ diff --git a/apps/wolfsshd/wolfsshd.c b/apps/wolfsshd/wolfsshd.c index 1cfe8b0e..11091867 100644 --- a/apps/wolfsshd/wolfsshd.c +++ b/apps/wolfsshd/wolfsshd.c @@ -717,7 +717,7 @@ int main(int argc, char** argv) } if (ret == WS_SUCCESS) { - auth = wolfSSHD_CreateUserAuth(NULL); + auth = wolfSSHD_CreateUserAuth(NULL, conf); if (auth == NULL) { wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Issue creating auth struct"); ret = WS_MEMORY_E; diff --git a/apps/wolfsshd/wolfsshd.h b/apps/wolfsshd/wolfsshd.h index 34269f5c..126ce281 100644 --- a/apps/wolfsshd/wolfsshd.h +++ b/apps/wolfsshd/wolfsshd.h @@ -21,9 +21,10 @@ #ifndef WOLFSSHD_H #define WOLFSSHD_H +typedef struct WOLFSSHD_CONFIG WOLFSSHD_CONFIG; + #include "auth.h" -typedef struct WOLFSSHD_CONFIG WOLFSSHD_CONFIG; #define WOLFSSHD_PRIV_SEPARAT 0 #define WOLFSSHD_PRIV_SANDBOX 1 @@ -41,5 +42,10 @@ char* wolfSSHD_GetAuthKeysFile(WOLFSSHD_CONFIG* conf); int wolfSSHD_SetAuthKeysFile(WOLFSSHD_CONFIG* conf, const char* file); +/* on/off flag options to check */ +#define WOLFSSHD_EMPTY_PASSWORD 1 + +int wolfSSHD_ConfigOptionEnabled(WOLFSSHD_CONFIG* conf, word32 opt); + #endif /* WOLFSSHD_H */ From d16f642734fb492601d2223b0bfca982b0acd6fb Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Thu, 21 Jul 2022 16:26:26 -0700 Subject: [PATCH 16/48] pass full string in as salt --- apps/wolfsshd/auth.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/wolfsshd/auth.c b/apps/wolfsshd/auth.c index 16030585..c216206c 100644 --- a/apps/wolfsshd/auth.c +++ b/apps/wolfsshd/auth.c @@ -295,7 +295,7 @@ static int CheckPasswordPAM(const byte* usr, const byte* pw, int pwSz) } #else -#if defined(WOLFSSH_HAVE_LIBCRYPT) +#if 0 static int ExtractSalt(char* hash, char** salt, int saltSz) { int ret = WS_SUCCESS; @@ -348,7 +348,7 @@ static int ExtractSalt(char* hash, char** salt, int saltSz) return ret; } -#endif /* WOLFSSH_HAVE_LIBCRYPT */ +#endif #if defined(WOLFSSH_HAVE_LIBCRYPT) || defined(WOLFSSH_HAVE_LIBLOGIN) static int CheckPasswordHashUnix(const char* input, char* stored) From 85109e66cff17a3d7ef9ccb6d5615c2126424b5f Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Mon, 25 Jul 2022 09:26:05 -0700 Subject: [PATCH 17/48] raise and lower permissions levels --- apps/wolfsshd/auth.c | 83 ++++++++++++++++++++++++++++++++++++++++ apps/wolfsshd/auth.h | 2 + apps/wolfsshd/wolfsshd.c | 36 ++++++++++++++++- 3 files changed, 120 insertions(+), 1 deletion(-) diff --git a/apps/wolfsshd/auth.c b/apps/wolfsshd/auth.c index c216206c..96f90295 100644 --- a/apps/wolfsshd/auth.c +++ b/apps/wolfsshd/auth.c @@ -26,6 +26,7 @@ #ifdef __linux__ #define _XOPEN_SOURCE + #define _GNU_SOURCE #endif #include @@ -57,6 +58,8 @@ struct WOLFSSHD_AUTH { CallbackCheckPassword CheckPasswordCb; CallbackCheckPublicKey CheckPublicKeyCb; WOLFSSHD_CONFIG* conf; + int gid; + int uid; void* heap; }; @@ -653,7 +656,17 @@ static int RequestAuthentication(const char* usr, int type, const byte* data, { int ret; + if (auth == NULL) + return WOLFSSH_USERAUTH_FAILURE; + ret = DoCheckUser(usr, auth); + + /* temporarily elevate permissions */ + if (wolfSSHD_RaisePermissions(auth) != 0) { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Failure to raise permissions for auth"); + ret = WOLFSSH_USERAUTH_FAILURE; + } + if (ret == WOLFSSH_USERAUTH_SUCCESS && type == WOLFSSH_USERAUTH_PASSWORD) { int rc; @@ -699,6 +712,11 @@ static int RequestAuthentication(const char* usr, int type, const byte* data, } } + + if (wolfSSHD_ReducePermissions(auth) != 0) { + /* stop everything if not able to reduce permissions level */ + exit(1); + } return ret; } @@ -816,6 +834,8 @@ WOLFSSHD_AUTH * wolfSSHD_CreateUserAuth(void* heap, WOLFSSHD_CONFIG* conf) auth = (WOLFSSHD_AUTH*)WMALLOC(sizeof(WOLFSSHD_AUTH), heap, DYNTYPE_SSHD); if (auth != NULL) { int ret; + struct passwd* pwInfo; + const char* usr = "sshd"; auth->heap = heap; auth->conf = conf; @@ -844,6 +864,20 @@ WOLFSSHD_AUTH * wolfSSHD_CreateUserAuth(void* heap, WOLFSSHD_CONFIG* conf) } } + if (ret == WS_SUCCESS) { + pwInfo = getpwnam(usr); + if (pwInfo == NULL) { + /* user name not found on system */ + wolfSSH_Log(WS_LOG_INFO, "[SSHD] No sshd user found to use"); + ret = WS_FATAL_ERROR; + } + } + + if (ret == WS_SUCCESS) { + auth->gid = pwInfo->pw_gid; + auth->uid = pwInfo->pw_uid; + } + /* error case in setting one of the default callbacks */ if (ret != WS_SUCCESS) { (void)wolfSSHD_FreeUserAuth(auth); @@ -864,4 +898,53 @@ int wolfSSHD_FreeUserAuth(WOLFSSHD_AUTH* auth) } return WS_SUCCESS; } + + +/* return 0 on success */ +int wolfSSHD_RaisePermissions(WOLFSSHD_AUTH* auth) +{ + int ret = 0; + + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Attempting to raise permissions level"); + if (auth) { + if (setegid(0) != 0) { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Error rasing gid"); + ret = WS_FATAL_ERROR; + } + + if (seteuid(0) != 0) { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Error rasing uid"); + ret = WS_FATAL_ERROR; + } + } + else { + ret = WS_BAD_ARGUMENT; + } + + return ret; +} + + +/* return 0 on success */ +int wolfSSHD_ReducePermissions(WOLFSSHD_AUTH* auth) +{ + int ret = 0; + + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Lowering permissions level"); + if (auth) { + if (setegid(auth->gid) != 0) { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Error setting sshd gid"); + ret = WS_FATAL_ERROR; + } + + if (seteuid(auth->uid) != 0) { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Error setting sshd uid"); + ret = WS_FATAL_ERROR; + } + } + else { + ret = WS_BAD_ARGUMENT; + } + return ret; +} #endif /* WOLFSSH_SSHD */ diff --git a/apps/wolfsshd/auth.h b/apps/wolfsshd/auth.h index f99109e9..8e96c65e 100644 --- a/apps/wolfsshd/auth.h +++ b/apps/wolfsshd/auth.h @@ -56,4 +56,6 @@ typedef int (*CallbackCheckPublicKey)(const char* usr, const byte* key, WOLFSSHD_AUTH * wolfSSHD_CreateUserAuth(void* heap, WOLFSSHD_CONFIG* conf); int wolfSSHD_FreeUserAuth(WOLFSSHD_AUTH* auth); +int wolfSSHD_ReducePermissions(WOLFSSHD_AUTH* auth); +int wolfSSHD_RaisePermissions(WOLFSSHD_AUTH* auth); #endif /* WOLFAUTH_H */ diff --git a/apps/wolfsshd/wolfsshd.c b/apps/wolfsshd/wolfsshd.c index 11091867..8973d42e 100644 --- a/apps/wolfsshd/wolfsshd.c +++ b/apps/wolfsshd/wolfsshd.c @@ -336,13 +336,30 @@ static int SHELL_Subsystem(WOLFSSHD_CONNECTION* conn, WOLFSSH* ssh) byte channelBuffer[EXAMPLE_BUFFER_SZ]; userName = wolfSSH_GetUsername(ssh); + + /* temporarily elevate permissions to get users information */ + if (wolfSSHD_RaisePermissions(conn->auth) != 0) { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Failure to raise permissions for auth"); + return WS_FATAL_ERROR; + } + p_passwd = getpwnam((const char *)userName); if (p_passwd == NULL) { /* Not actually a user on the system. */ wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Invalid user name found"); + if (wolfSSHD_ReducePermissions(conn->auth) != 0) { + /* stop everything if not able to reduce permissions level */ + exit(1); + } + return WS_FATAL_ERROR; } + if (wolfSSHD_ReducePermissions(conn->auth) != 0) { + /* stop everything if not able to reduce permissions level */ + exit(1); + } + ChildRunning = 1; childPid = forkpty(&childFd, NULL, NULL, NULL); @@ -354,15 +371,24 @@ static int SHELL_Subsystem(WOLFSSHD_CONNECTION* conn, WOLFSSH* ssh) else if (childPid == 0) { /* Child process */ const char *args[] = {"-sh", NULL}; + char cmd[80]; signal(SIGINT, SIG_DFL); + setgid(p_passwd->pw_gid); + setuid(p_passwd->pw_uid); if (system("env") != 0) { printf("0 return value from system call\n"); } setenv("HOME", p_passwd->pw_dir, 1); setenv("LOGNAME", p_passwd->pw_name, 1); + + /* @TODO this needs reworked, can just exit into root */ + WMEMSET(cmd, 0, sizeof(cmd)); + XSNPRINTF(cmd, sizeof(cmd), "su %s", userName); + printf("executing command [%s]\n", cmd); + system(cmd); rc = chdir(p_passwd->pw_dir); if (rc != 0) { return WS_FATAL_ERROR; @@ -609,7 +635,7 @@ static int wolfSSHD_PendingConnection(WS_SOCKET_T fd) else { printf("Found write or error data\n"); ret = 0; /* nothing to read */ - } + } } // printf("Timeout waiting for connection\n"); return ret; @@ -724,6 +750,14 @@ int main(int argc, char** argv) } } + /* seperate privlage permisions */ + if (ret == WS_SUCCESS) { + if (wolfSSHD_ReducePermissions(auth) != 0) { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Error lowering permissions level"); + ret = WS_FATAL_ERROR; + } + } + if (ret == WS_SUCCESS) { wolfSSH_Log(WS_LOG_INFO, "[SSHD] Starting to listen on port %d", port); tcp_listen(&listenFd, &port, 1); From 374f675553e335802b93f58eb46835ce0fa33a76 Mon Sep 17 00:00:00 2001 From: Hayden Roche Date: Tue, 26 Jul 2022 09:27:01 -0700 Subject: [PATCH 18/48] Add support for PEM host keys. --- apps/wolfsshd/auth.c | 4 +++- apps/wolfsshd/wolfsshd.c | 25 ++++++++++++++++++++++--- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/apps/wolfsshd/auth.c b/apps/wolfsshd/auth.c index 96f90295..3174d1dc 100644 --- a/apps/wolfsshd/auth.c +++ b/apps/wolfsshd/auth.c @@ -608,7 +608,9 @@ static int CheckPublicKeyUnix(const char* name, const byte* key, word32 keySz) break; } } - XFCLOSE(f); + if (f != XBADFILE) { + XFCLOSE(f); + } if (ret == WSSHD_AUTH_SUCCESS && !foundKey) { ret = WSSHD_AUTH_FAILURE; diff --git a/apps/wolfsshd/wolfsshd.c b/apps/wolfsshd/wolfsshd.c index 8973d42e..49c4370d 100644 --- a/apps/wolfsshd/wolfsshd.c +++ b/apps/wolfsshd/wolfsshd.c @@ -30,6 +30,7 @@ #include #include #include +#include #define WOLFSSH_TEST_SERVER #include @@ -119,6 +120,9 @@ static int SetupCTX(WOLFSSHD_CONFIG* conf, WOLFSSH_CTX** ctx) { int ret = WS_SUCCESS; const char* banner; + DerBuffer* der = NULL; + byte* privBuf; + word32 privBufSz; /* create a new WOLFSSH_CTX */ *ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL); @@ -184,13 +188,28 @@ static int SetupCTX(WOLFSSHD_CONFIG* conf, WOLFSSH_CTX** ctx) dataSz = (int)XFREAD(data, 1, dataSz, f); XFCLOSE(f); - if (wolfSSH_CTX_UsePrivateKey_buffer(*ctx, data, dataSz, - WOLFSSH_FORMAT_ASN1) < 0) { + if (wc_PemToDer(data, dataSz, PRIVATEKEY_TYPE, &der, NULL, + NULL, NULL) != 0) { + wolfSSH_Log(WS_LOG_DEBUG, "[SSHD] Failed to convert host " + "private key from PEM. Assuming key in DER " + "format."); + privBuf = data; + privBufSz = dataSz; + } + else { + privBuf = der->buffer; + privBufSz = der->length; + } + + if (wolfSSH_CTX_UsePrivateKey_buffer(*ctx, privBuf, privBufSz, + WOLFSSH_FORMAT_ASN1) < 0) { wolfSSH_Log(WS_LOG_ERROR, - "[SSHD] Unable parse host private key"); + "[SSHD] Failed to use host private key."); ret = WS_BAD_ARGUMENT; } + WFREE(data, NULL, 0); + wc_FreeDer(&der); } } } From 8d1d2fb63322a73b7397411e39249eaf9d7293dd Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Tue, 26 Jul 2022 10:56:30 -0700 Subject: [PATCH 19/48] add support for grace login timer --- apps/wolfsshd/auth.c | 13 +++++- apps/wolfsshd/auth.h | 1 + apps/wolfsshd/config.c | 86 +++++++++++++++++++++++++++++++++++++--- apps/wolfsshd/wolfsshd.c | 70 +++++++++++++++++++++++++++++--- apps/wolfsshd/wolfsshd.h | 3 +- 5 files changed, 160 insertions(+), 13 deletions(-) diff --git a/apps/wolfsshd/auth.c b/apps/wolfsshd/auth.c index 3174d1dc..5e3520e5 100644 --- a/apps/wolfsshd/auth.c +++ b/apps/wolfsshd/auth.c @@ -674,7 +674,7 @@ static int RequestAuthentication(const char* usr, int type, const byte* data, /* Check if password is valid for this user. */ /* first handle empty password cases */ - if (dataSz == 0 && wolfSSHD_ConfigOptionEnabled(auth->conf, + if (dataSz == 0 && wolfSSHD_ConfigGetOption(auth->conf, WOLFSSHD_EMPTY_PASSWORD) != 1) { wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Empty passwords not allowed!"); ret = WOLFSSH_USERAUTH_FAILURE; @@ -949,4 +949,15 @@ int wolfSSHD_ReducePermissions(WOLFSSHD_AUTH* auth) } return ret; } + + +long wolfSSHD_GetGraceTime(WOLFSSHD_AUTH* auth) +{ + long ret = 0; + + if (auth != NULL) { + ret = wolfSSHD_ConfigGetOption(auth->conf, WOLFSSHD_GRACE_LOGIN_TIME); + } + return ret; +} #endif /* WOLFSSH_SSHD */ diff --git a/apps/wolfsshd/auth.h b/apps/wolfsshd/auth.h index 8e96c65e..e1468ef3 100644 --- a/apps/wolfsshd/auth.h +++ b/apps/wolfsshd/auth.h @@ -58,4 +58,5 @@ WOLFSSHD_AUTH * wolfSSHD_CreateUserAuth(void* heap, WOLFSSHD_CONFIG* conf); int wolfSSHD_FreeUserAuth(WOLFSSHD_AUTH* auth); int wolfSSHD_ReducePermissions(WOLFSSHD_AUTH* auth); int wolfSSHD_RaisePermissions(WOLFSSHD_AUTH* auth); +long wolfSSHD_GetGraceTime(WOLFSSHD_AUTH* auth); #endif /* WOLFAUTH_H */ diff --git a/apps/wolfsshd/config.c b/apps/wolfsshd/config.c index 52c86a37..e840fab3 100644 --- a/apps/wolfsshd/config.c +++ b/apps/wolfsshd/config.c @@ -51,6 +51,7 @@ struct WOLFSSHD_CONFIG { char* kekAlgos; char* listenAddress; char* authKeysFile; + long loginTimer; word16 port; byte usePrivilegeSeparation; byte passwordAuth:1; @@ -59,6 +60,64 @@ struct WOLFSSHD_CONFIG { byte permitEmptyPasswords:1; }; + +/* convert a string into seconds, handles if 'm' for minutes follows the string + * number, i.e. 2m + * Returns the value on success and negative value on failure */ +static long wolfSSHD_GetConfigInt(const char* in, int inSz, int isTime, + void* heap) +{ + long ret = 0; + int mult = 1; /* multiplier */ + int idx = 0; + int sz = 0; + + /* remove leading white spaces */ + while (idx < inSz && in[idx] == ' ') idx++; + + if (idx == inSz) { + ret = WS_BAD_ARGUMENT; + } + + /* remove trailing white spaces */ + if (ret == 0) { + for (sz = 1; sz + idx < inSz; sz++) { + if (in[sz + idx] == ' ') break; + if (in[sz + idx] == '\n') break; + } + } + + /* check for multipliers */ + if (isTime && ret == 0) { + if (in[sz - 1 + idx] == 'm') { + sz--; + mult = 60; + } + if (in[sz - 1 + idx] == 'h') { + sz--; + mult = 60*60; + } + } + + if (ret == 0) { + char* num = (char*)WMALLOC(sz + 1, heap, DYNTYPE_SSHD); + if (num == NULL) { + ret = WS_MEMORY_E; + } + else { + WMEMCPY(num, in + idx, sz); + num[sz] = '\0'; + ret = atol(num); + if (ret > 0) { + ret = ret * mult; + } + WFREE(num, heap, DYNTYPE_SSHD); + } + } + + return ret; +} + /* returns WS_SUCCESS on success */ static int wolfSSHD_CreateString(char** out, const char* in, int inSz, void* heap) @@ -66,7 +125,7 @@ static int wolfSSHD_CreateString(char** out, const char* in, int inSz, int ret = WS_SUCCESS; int idx = 0; - /* remove white spaces */ + /* remove leading white spaces */ while (idx < inSz && in[idx] == ' ') idx++; if (idx == inSz) { @@ -144,6 +203,7 @@ static int wolfSSHD_ParseConfigLine(WOLFSSHD_CONFIG* conf, const char* l, /* supported config options */ const char authKeyFile[] = "AuthorizedKeysFile"; const char privilegeSeparation[] = "UsePrivilegeSeparation"; + const char loginGraceTime[] = "LoginGraceTime"; const char permitEmptyPasswords[] = "PermitEmptyPasswords"; sz = (int)XSTRLEN(authKeyFile); @@ -217,9 +277,20 @@ static int wolfSSHD_ParseConfigLine(WOLFSSHD_CONFIG* conf, const char* l, ret = WS_SUCCESS; } - if (XSTRNCMP(l, "LoginGraceTime", 14) == 0) { - //@TODO - ret = WS_SUCCESS; + sz = (int)XSTRLEN(loginGraceTime); + if (lSz > sz && XSTRNCMP(l, loginGraceTime, sz) == 0) { + long num; + + num = wolfSSHD_GetConfigInt(l + sz, lSz - sz, 1, conf->heap); + if (num < 0) { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Issue getting login grace time"); + } + else { + ret = WS_SUCCESS; + conf->loginTimer = num; + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Setting login grace time to %ld", + num); + } } @@ -350,14 +421,17 @@ word16 wolfSSHD_GetPort(WOLFSSHD_CONFIG* conf) /* test if the 'opt' options is enabled or not in 'conf' for the flags set * return 1 if enabled and 0 if not */ -int wolfSSHD_ConfigOptionEnabled(WOLFSSHD_CONFIG* conf, word32 opt) +long wolfSSHD_ConfigGetOption(WOLFSSHD_CONFIG* conf, word32 opt) { - int ret = 0; + long ret = 0; switch (opt) { case WOLFSSHD_EMPTY_PASSWORD: ret = conf->permitEmptyPasswords; break; + case WOLFSSHD_GRACE_LOGIN_TIME: + ret = conf->loginTimer; + break; } return ret; } diff --git a/apps/wolfsshd/wolfsshd.c b/apps/wolfsshd/wolfsshd.c index 49c4370d..133dbe3d 100644 --- a/apps/wolfsshd/wolfsshd.c +++ b/apps/wolfsshd/wolfsshd.c @@ -374,17 +374,19 @@ static int SHELL_Subsystem(WOLFSSHD_CONNECTION* conn, WOLFSSH* ssh) return WS_FATAL_ERROR; } - if (wolfSSHD_ReducePermissions(conn->auth) != 0) { - /* stop everything if not able to reduce permissions level */ - exit(1); - } - ChildRunning = 1; childPid = forkpty(&childFd, NULL, NULL, NULL); + if (wolfSSHD_ReducePermissions(conn->auth) != 0) { + /* stop everything if not able to reduce permissions level */ + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Issue reducing permissions level," + " exiting now"); + exit(1); + } if (childPid < 0) { /* forkpty failed, so return */ ChildRunning = 0; + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Issue creating new forkpty"); return WS_FATAL_ERROR; } else if (childPid == 0) { @@ -514,6 +516,13 @@ static int SHELL_Subsystem(WOLFSSHD_CONNECTION* conn, WOLFSSH* ssh) } #endif +static __thread int timeOut = 0; +static void alarmCatch(int signum) +{ + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Failed login within grace period"); + timeOut = 1; + (void)signum; +} /* handle wolfSSH accept and directing to correct subsystem */ static void* wolfSSHD_HandleConnection(void* arg) @@ -538,9 +547,40 @@ static void* wolfSSHD_HandleConnection(void* arg) } if (ret == WS_SUCCESS) { + int error; + int select_ret = 0; + long graceTime; + wolfSSH_set_fd(ssh, conn->fd); wolfSSH_SetUserAuthCtx(ssh, conn->auth); + + /* set alarm for login grace time */ + graceTime = wolfSSHD_GetGraceTime(conn->auth); + if (graceTime > 0) { + signal(SIGALRM, alarmCatch); + alarm(graceTime); + } + ret = wolfSSH_accept(ssh); + error = wolfSSH_get_error(ssh); + while (timeOut == 0 && (ret != WS_SUCCESS + && ret != WS_SCP_COMPLETE && ret != WS_SFTP_COMPLETE) + && (error == WS_WANT_READ || error == WS_WANT_WRITE)) { + + select_ret = tcp_select(conn->fd, 1); + if (select_ret == WS_SELECT_RECV_READY || + select_ret == WS_SELECT_ERROR_READY || + error == WS_WANT_WRITE) + { + ret = wolfSSH_accept(ssh); + error = wolfSSH_get_error(ssh); + } + else if (select_ret == WS_SELECT_TIMEOUT) + error = WS_WANT_READ; + else + error = WS_FATAL_ERROR; + } + if (ret != WS_SUCCESS && ret != WS_SFTP_COMPLETE) { wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Failed to accept WOLFSSH connection"); @@ -591,6 +631,7 @@ static void* wolfSSHD_HandleConnection(void* arg) } } + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Attempting to close down connection"); wolfSSH_shutdown(ssh); wolfSSH_free(ssh); if (conn != NULL) { @@ -803,6 +844,25 @@ int main(int argc, char** argv) &clientAddrSz); #endif + { + #ifdef USE_WINDOWS_API + unsigned long blocking = 1; + int ret = ioctlsocket(conn.fd, FIONBIO, &blocking); + if (ret == SOCKET_ERROR) + err_sys("ioctlsocket failed"); + #elif defined(WOLFSSL_MDK_ARM) || defined(WOLFSSL_KEIL_TCP_NET) \ + || defined (WOLFSSL_TIRTOS)|| defined(WOLFSSL_VXWORKS) || \ + defined(WOLFSSL_NUCLEUS) + /* non blocking not supported, for now */ + #else + int flags = fcntl(conn.fd, F_GETFL, 0); + if (flags < 0) + err_sys("fcntl get failed"); + flags = fcntl(conn.fd, F_SETFL, flags | O_NONBLOCK); + if (flags < 0) + err_sys("fcntl set failed"); + #endif + } ret = wolfSSHD_NewConnection(&conn); } } diff --git a/apps/wolfsshd/wolfsshd.h b/apps/wolfsshd/wolfsshd.h index 126ce281..6644b420 100644 --- a/apps/wolfsshd/wolfsshd.h +++ b/apps/wolfsshd/wolfsshd.h @@ -44,8 +44,9 @@ int wolfSSHD_SetAuthKeysFile(WOLFSSHD_CONFIG* conf, const char* file); /* on/off flag options to check */ #define WOLFSSHD_EMPTY_PASSWORD 1 +#define WOLFSSHD_GRACE_LOGIN_TIME 2 -int wolfSSHD_ConfigOptionEnabled(WOLFSSHD_CONFIG* conf, word32 opt); +long wolfSSHD_ConfigGetOption(WOLFSSHD_CONFIG* conf, word32 opt); #endif /* WOLFSSHD_H */ From 477fb6c5c8498a5877aa76c8db73c784d6c2b98d Mon Sep 17 00:00:00 2001 From: Hayden Roche Date: Tue, 26 Jul 2022 14:07:25 -0700 Subject: [PATCH 20/48] Add HostKey support and other config file code improvements. - hostKeyFile and authKeysFile members of the config are now dynamically allocated strings owned by the config. - Break out sshd_config option handling into more modular functions. --- apps/wolfsshd/config.c | 354 +++++++++++++++++++++++++++------------ apps/wolfsshd/wolfsshd.c | 2 - 2 files changed, 243 insertions(+), 113 deletions(-) diff --git a/apps/wolfsshd/config.c b/apps/wolfsshd/config.c index e840fab3..6fc69d0e 100644 --- a/apps/wolfsshd/config.c +++ b/apps/wolfsshd/config.c @@ -46,7 +46,7 @@ struct WOLFSSHD_CONFIG { char* banner; char* chrootDir; char* ciphers; - char* hostKey; + char* hostKeyFile; char* hostKeyAlgos; char* kekAlgos; char* listenAddress; @@ -182,7 +182,12 @@ void wolfSSHD_FreeConfig(WOLFSSHD_CONFIG* conf) if (conf != NULL) { heap = conf->heap; - wolfSSHD_FreeString(&conf->authKeysFile, heap); + if (conf->authKeysFile != NULL) { + wolfSSHD_FreeString(&conf->authKeysFile, heap); + } + if (conf->hostKeyFile != NULL) { + wolfSSHD_FreeString(&conf->hostKeyFile, heap); + } WFREE(conf, heap, DYNTYPE_SSHD); } @@ -190,133 +195,222 @@ void wolfSSHD_FreeConfig(WOLFSSHD_CONFIG* conf) #define MAX_LINE_SIZE 160 -/* returns WS_SUCCESS on success - * Fails if any option is found that is unknown/unsupported - */ -static int wolfSSHD_ParseConfigLine(WOLFSSHD_CONFIG* conf, const char* l, - int lSz) +typedef struct { + int tag; + const char* name; +} CONFIG_OPTION; + +enum { + OPT_AUTH_KEYS_FILE = 0, + OPT_PRIV_SEP = 1, + OPT_PERMIT_EMPTY_PW = 2, + OPT_SUBSYSTEM = 3, + OPT_CHALLENGE_RESPONSE_AUTH = 4, + OPT_USE_PAM = 5, + OPT_X11_FORWARDING = 6, + OPT_PRINT_MOTD = 7, + OPT_ACCEPT_ENV = 8, + OPT_PROTOCOL = 9, + OPT_LOGIN_GRACE_TIME = 10, + OPT_HOST_KEY = 11 +}; +enum { + NUM_OPTIONS = 12 +}; + +static const CONFIG_OPTION options[NUM_OPTIONS] = { + {OPT_AUTH_KEYS_FILE, "AuthorizedKeysFile"}, + {OPT_PRIV_SEP, "UsePrivilegeSeparation"}, + {OPT_PERMIT_EMPTY_PW, "PermitEmptyPasswords"}, + {OPT_SUBSYSTEM, "Subsystem"}, + {OPT_CHALLENGE_RESPONSE_AUTH, "ChallengeResponseAuthentication"}, + {OPT_USE_PAM, "UsePAM"}, + {OPT_X11_FORWARDING, "X11Forwarding"}, + {OPT_PRINT_MOTD, "PrintMotd"}, + {OPT_ACCEPT_ENV, "AcceptEnv"}, + {OPT_PROTOCOL, "Protocol"}, + {OPT_LOGIN_GRACE_TIME, "LoginGraceTime"}, + {OPT_HOST_KEY, "HostKey"} +}; + +static int wolfSSHD_HandlePrivSep(WOLFSSHD_CONFIG* conf, const char* value) { - int ret = WS_BAD_ARGUMENT; - int sz; - char* tmp; + int ret = WS_SUCCESS; - /* supported config options */ - const char authKeyFile[] = "AuthorizedKeysFile"; - const char privilegeSeparation[] = "UsePrivilegeSeparation"; - const char loginGraceTime[] = "LoginGraceTime"; - const char permitEmptyPasswords[] = "PermitEmptyPasswords"; - - sz = (int)XSTRLEN(authKeyFile); - if (lSz > sz && XSTRNCMP(l, authKeyFile, sz) == 0) { - ret = wolfSSHD_CreateString(&tmp, l + sz, lSz - sz, conf->heap); - if (ret == WS_SUCCESS) { - wolfSSHD_SetAuthKeysFile(conf, tmp); - } + if (conf == NULL || value == NULL) { + ret = WS_BAD_ARGUMENT; } - sz = (int)XSTRLEN(privilegeSeparation); - if (lSz > sz && XSTRNCMP(l, privilegeSeparation, sz) == 0) { - char* privType = NULL; - ret = wolfSSHD_CreateString(&privType, l + sz, lSz - sz, conf->heap); - - /* check if is an allowed option */ - if (XSTRNCMP(privType, "sandbox", 7) == 0) { + if (ret == WS_SUCCESS) { + if (WSTRCMP(value, "sandbox") == 0) { wolfSSH_Log(WS_LOG_INFO, "[SSHD] Sandbox privilege separation"); - ret = WS_SUCCESS; } - if (XSTRNCMP(privType, "yes", 3) == 0) { + if (WSTRCMP(value, "yes") == 0) { wolfSSH_Log(WS_LOG_INFO, "[SSHD] Privilege separation enabled"); - ret = WS_SUCCESS; } - if (XSTRNCMP(privType, "no", 2) == 0) { - wolfSSH_Log(WS_LOG_INFO, "[SSHD] Turning off privilege separation!"); - ret = WS_SUCCESS; + if (WSTRCMP(value, "no") == 0) { + wolfSSH_Log(WS_LOG_INFO, + "[SSHD] Turning off privilege separation!"); } if (ret != WS_SUCCESS) { wolfSSH_Log(WS_LOG_ERROR, - "[SSHD] Unknown/supported privilege separation!"); + "[SSHD] Unknown/supported privilege separation!"); + ret = WS_BAD_ARGUMENT; } - wolfSSHD_FreeString(&privType, conf->heap); } - if (XSTRNCMP(l, "Subsystem", 9) == 0) { - //@TODO - ret = WS_SUCCESS; + return ret; +} + +static int wolfSSHD_HandleLoginGraceTime(WOLFSSHD_CONFIG* conf, + const char* value) +{ + int ret = WS_SUCCESS; + long num; + + if (conf == NULL || value == NULL) { + ret = WS_BAD_ARGUMENT; } - if (XSTRNCMP(l, "ChallengeResponseAuthentication", 31) == 0) { - //@TODO - ret = WS_SUCCESS; - } - - if (XSTRNCMP(l, "UsePAM", 6) == 0) { - //@TODO - ret = WS_SUCCESS; - } - - if (XSTRNCMP(l, "X11Forwarding", 13) == 0) { - //@TODO - ret = WS_SUCCESS; - } - - if (XSTRNCMP(l, "PrintMotd", 9) == 0) { - //@TODO - ret = WS_SUCCESS; - } - - if (XSTRNCMP(l, "AcceptEnv", 9) == 0) { - //@TODO - ret = WS_SUCCESS; - } - - if (XSTRNCMP(l, "Protocol", 8) == 0) { - //@TODO - ret = WS_SUCCESS; - } - - sz = (int)XSTRLEN(loginGraceTime); - if (lSz > sz && XSTRNCMP(l, loginGraceTime, sz) == 0) { - long num; - - num = wolfSSHD_GetConfigInt(l + sz, lSz - sz, 1, conf->heap); + if (ret == WS_SUCCESS) { + num = wolfSSHD_GetConfigInt(value, XSTRLEN(value), 1, conf->heap); if (num < 0) { - wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Issue getting login grace time"); + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Issue getting login grace " + "time"); + ret = num; } else { - ret = WS_SUCCESS; conf->loginTimer = num; - wolfSSH_Log(WS_LOG_INFO, "[SSHD] Setting login grace time to %ld", - num); + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Setting login grace time to " + "%ld", num); } } + return ret; +} - sz = (int)XSTRLEN(permitEmptyPasswords); - if (lSz > sz && XSTRNCMP(l, permitEmptyPasswords, sz) == 0) { - char* emptyPasswd = NULL; - ret = wolfSSHD_CreateString(&emptyPasswd, l + sz, lSz - sz, conf->heap); +/* TODO: Can value be const? */ +static int wolfSSHD_HandleConfigOption(WOLFSSHD_CONFIG* conf, int opt, + const char* value) +{ + int ret = WS_BAD_ARGUMENT; - if (XSTRNCMP(emptyPasswd, "yes", 3) == 0) { - wolfSSH_Log(WS_LOG_INFO, "[SSHD] Empty password enabled"); - conf->permitEmptyPasswords = 1; + switch (opt) { + case OPT_AUTH_KEYS_FILE: + ret = wolfSSHD_SetAuthKeysFile(conf, value); + break; + case OPT_PRIV_SEP: + ret = wolfSSHD_HandlePrivSep(conf, value); + break; + case OPT_SUBSYSTEM: + /* TODO */ ret = WS_SUCCESS; - } - - /* default is no */ - if (XSTRNCMP(emptyPasswd, "no", 2) == 0) { + break; + case OPT_CHALLENGE_RESPONSE_AUTH: + /* TODO */ ret = WS_SUCCESS; + break; + case OPT_USE_PAM: + /* TODO */ + ret = WS_SUCCESS; + break; + case OPT_X11_FORWARDING: + /* TODO */ + ret = WS_SUCCESS; + break; + case OPT_PRINT_MOTD: + /* TODO */ + ret = WS_SUCCESS; + break; + case OPT_ACCEPT_ENV: + /* TODO */ + ret = WS_SUCCESS; + break; + case OPT_PROTOCOL: + /* TODO */ + ret = WS_SUCCESS; + break; + case OPT_LOGIN_GRACE_TIME: + ret = wolfSSHD_HandleLoginGraceTime(conf, value); + break; + case OPT_HOST_KEY: + ret = wolfSSHD_SetHostPrivateKey(conf, value); + break; + default: + break; + } + + return ret; +} + +static int CountWhitespace(const char* in, int inSz, byte inv) +{ + int i = 0; + + if (in != NULL) { + for (; i < inSz; ++i) { + if (inv) { + if (isspace(in[i])) { + break; + } + } + else { + if (!isspace(in[i])) { + break; + } + } } - wolfSSHD_FreeString(&emptyPasswd, conf->heap); } - if (ret == WS_BAD_ARGUMENT) { - printf("unknown / unsuported config line\n"); + return i; +} + +/* returns WS_SUCCESS on success + * Fails if any option is found that is unknown/unsupported + */ +static int wolfSSHD_ParseConfigLine(WOLFSSHD_CONFIG* conf, const char* l, + int lSz) +{ + int ret = WS_BAD_ARGUMENT; + int sz; + char tmp[MAX_FILENAME_SZ]; + int idx; + const CONFIG_OPTION* found = NULL; + + for (idx = 0; idx < NUM_OPTIONS; ++idx) { + sz = (int)WSTRLEN(options[idx].name); + if (lSz >= sz && WSTRNCMP(l, options[idx].name, sz) == 0) { + found = &options[idx]; + break; + } + } + + if (found != NULL) { + /* + * Count leading and trailing whitespace. Use that information to cut + * out just the string itself when creating tmp. + */ + idx = sz; + idx += CountWhitespace(l + idx, lSz - sz, 0); + sz = CountWhitespace(l + idx, lSz - sz, 1); + if (sz >= MAX_FILENAME_SZ) { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Filename too long."); + ret = WS_FATAL_ERROR; + } + else { + WMEMCPY(tmp, l + idx, sz); + tmp[sz] = 0; + ret = wolfSSHD_HandleConfigOption(conf, found->tag, tmp); + } + } + else { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Error parsing config line."); + ret = WS_FATAL_ERROR; } - (void)lSz; return ret; } @@ -372,43 +466,81 @@ int wolfSSHD_LoadSSHD(WOLFSSHD_CONFIG* conf, const char* filename) char* wolfSSHD_GetAuthKeysFile(WOLFSSHD_CONFIG* conf) { - if (conf != NULL) - return conf->authKeysFile; - return NULL; + char* ret = NULL; + + if (conf != NULL) { + ret = conf->authKeysFile; + } + + return ret; } int wolfSSHD_SetAuthKeysFile(WOLFSSHD_CONFIG* conf, const char* file) { + int ret = WS_SUCCESS; + if (conf == NULL) { - return WS_BAD_ARGUMENT; + ret = WS_BAD_ARGUMENT; } - conf->authKeysFile = (char*)file; + if (ret == WS_SUCCESS) { + if (conf->authKeysFile != NULL) { + wolfSSHD_FreeString(&conf->authKeysFile, conf->heap); + conf->authKeysFile = NULL; + } - return WS_SUCCESS; + if (file != NULL) { + ret = wolfSSHD_CreateString(&conf->authKeysFile, file, + WSTRLEN(file), conf->heap); + } + } + + return ret; } char* wolfSSHD_GetBanner(WOLFSSHD_CONFIG* conf) { - if (conf != NULL) - return conf->banner; - return NULL; + char* ret = NULL; + + if (conf != NULL) { + ret = conf->banner; + } + + return ret; } char* wolfSSHD_GetHostPrivateKey(WOLFSSHD_CONFIG* conf) { - if (conf != NULL) - return conf->hostKey; - return NULL; + char* ret = NULL; + + if (conf != NULL) { + ret = conf->hostKeyFile; + } + + return ret; } -int wolfSSHD_SetHostPrivateKey(WOLFSSHD_CONFIG* conf, const char* hostKeyFile) +int wolfSSHD_SetHostPrivateKey(WOLFSSHD_CONFIG* conf, const char* file) { - if (conf == NULL) - return WS_BAD_ARGUMENT; + int ret = WS_SUCCESS; - conf->hostKey = (char*)hostKeyFile; - return WS_SUCCESS; + if (conf == NULL) { + ret = WS_BAD_ARGUMENT; + } + + if (ret == WS_SUCCESS) { + if (conf->hostKeyFile != NULL) { + wolfSSHD_FreeString(&conf->hostKeyFile, conf->heap); + conf->hostKeyFile = NULL; + } + + if (file != NULL) { + ret = wolfSSHD_CreateString(&conf->hostKeyFile, file, + WSTRLEN(file), conf->heap); + } + } + + return ret; } word16 wolfSSHD_GetPort(WOLFSSHD_CONFIG* conf) diff --git a/apps/wolfsshd/wolfsshd.c b/apps/wolfsshd/wolfsshd.c index 133dbe3d..9ea1637a 100644 --- a/apps/wolfsshd/wolfsshd.c +++ b/apps/wolfsshd/wolfsshd.c @@ -159,8 +159,6 @@ static int SetupCTX(WOLFSSHD_CONFIG* conf, WOLFSSH_CTX** ctx) } #endif - /* TODO: Currently expects a private key in DER format. Add logic to handle - * PEM, too. wc_PemToDer. */ /* Load in host private key */ if (ret == WS_SUCCESS) { From 48b627d70d28f32c9d0c063c35b4fb756e0176b9 Mon Sep 17 00:00:00 2001 From: Hayden Roche Date: Wed, 27 Jul 2022 15:10:38 -0700 Subject: [PATCH 21/48] Refactor various wolfSSHD code. - Move function declarations for WOLFSSHD_CONFIG from wolfsshd.h to a new header, configuration.h. Change config.c to configuration.c. (using "configuration" so as not to collide with autotools' config.h) - Make the WOLFSSL_CONFIG* member of WOLFSSHD_AUTH const. At least at the moment, it shouldn't be necessary for this member to be writable. - Replace wolfSSHD_ConfigGetOption with functions to get specific members from the config. - Namespace all config functions with wolfSSHD_Config* and all auth functions with wolfSSHD_Auth. - Add const to function parameters, where possible. - Remove wolfSSHD_ prefix from static functions. Just use PascalCase. These don't need namespacing since they aren't visible outside their translation unit. - Modify GetConfigInt to expect leading and trailing whitespace to have already been removed. It will have been removed in the context this function is used in configuration.c. --- apps/wolfsshd/auth.c | 31 ++-- apps/wolfsshd/auth.h | 10 +- apps/wolfsshd/{config.c => configuration.c} | 150 ++++++++++-------- apps/wolfsshd/{wolfsshd.h => configuration.h} | 27 ++-- apps/wolfsshd/include.am | 4 +- apps/wolfsshd/wolfsshd.c | 40 ++--- 6 files changed, 133 insertions(+), 129 deletions(-) rename apps/wolfsshd/{config.c => configuration.c} (79%) rename apps/wolfsshd/{wolfsshd.h => configuration.h} (59%) diff --git a/apps/wolfsshd/auth.c b/apps/wolfsshd/auth.c index 5e3520e5..918b983c 100644 --- a/apps/wolfsshd/auth.c +++ b/apps/wolfsshd/auth.c @@ -44,7 +44,7 @@ #include "src/misc.c" #endif -#include "wolfsshd.h" +#include "configuration.h" #ifndef _WIN32 #include @@ -57,7 +57,7 @@ struct WOLFSSHD_AUTH { CallbackCheckUser CheckUserCb; CallbackCheckPassword CheckPasswordCb; CallbackCheckPublicKey CheckPublicKeyCb; - WOLFSSHD_CONFIG* conf; + const WOLFSSHD_CONFIG* conf; int gid; int uid; void* heap; @@ -664,7 +664,7 @@ static int RequestAuthentication(const char* usr, int type, const byte* data, ret = DoCheckUser(usr, auth); /* temporarily elevate permissions */ - if (wolfSSHD_RaisePermissions(auth) != 0) { + if (wolfSSHD_AuthRaisePermissions(auth) != 0) { wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Failure to raise permissions for auth"); ret = WOLFSSH_USERAUTH_FAILURE; } @@ -674,8 +674,7 @@ static int RequestAuthentication(const char* usr, int type, const byte* data, /* Check if password is valid for this user. */ /* first handle empty password cases */ - if (dataSz == 0 && wolfSSHD_ConfigGetOption(auth->conf, - WOLFSSHD_EMPTY_PASSWORD) != 1) { + if (dataSz == 0 && wolfSSHD_ConfigGetPermitEmptyPw(auth->conf) != 1) { wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Empty passwords not allowed!"); ret = WOLFSSH_USERAUTH_FAILURE; } @@ -715,7 +714,7 @@ static int RequestAuthentication(const char* usr, int type, const byte* data, } - if (wolfSSHD_ReducePermissions(auth) != 0) { + if (wolfSSHD_AuthReducePermissions(auth) != 0) { /* stop everything if not able to reduce permissions level */ exit(1); } @@ -829,7 +828,7 @@ static int SetDefaultPublicKeyCheck(WOLFSSHD_AUTH* auth) /* Sets the default functions to be used for authentication of peer. * Later the default functions could be overriden if needed. * returns a newly created WOLFSSHD_AUTH struct success */ -WOLFSSHD_AUTH * wolfSSHD_CreateUserAuth(void* heap, WOLFSSHD_CONFIG* conf) +WOLFSSHD_AUTH* wolfSSHD_AuthCreateUser(void* heap, const WOLFSSHD_CONFIG* conf) { WOLFSSHD_AUTH* auth; @@ -882,7 +881,7 @@ WOLFSSHD_AUTH * wolfSSHD_CreateUserAuth(void* heap, WOLFSSHD_CONFIG* conf) /* error case in setting one of the default callbacks */ if (ret != WS_SUCCESS) { - (void)wolfSSHD_FreeUserAuth(auth); + (void)wolfSSHD_AuthFreeUser(auth); auth = NULL; } } @@ -893,7 +892,7 @@ WOLFSSHD_AUTH * wolfSSHD_CreateUserAuth(void* heap, WOLFSSHD_CONFIG* conf) /* returns WS_SUCCESS on success */ -int wolfSSHD_FreeUserAuth(WOLFSSHD_AUTH* auth) +int wolfSSHD_AuthFreeUser(WOLFSSHD_AUTH* auth) { if (auth != NULL) { WFREE(auth, auth->heap, DYNTYPE_SSHD); @@ -903,7 +902,7 @@ int wolfSSHD_FreeUserAuth(WOLFSSHD_AUTH* auth) /* return 0 on success */ -int wolfSSHD_RaisePermissions(WOLFSSHD_AUTH* auth) +int wolfSSHD_AuthRaisePermissions(WOLFSSHD_AUTH* auth) { int ret = 0; @@ -928,7 +927,7 @@ int wolfSSHD_RaisePermissions(WOLFSSHD_AUTH* auth) /* return 0 on success */ -int wolfSSHD_ReducePermissions(WOLFSSHD_AUTH* auth) +int wolfSSHD_AuthReducePermissions(WOLFSSHD_AUTH* auth) { int ret = 0; @@ -950,14 +949,14 @@ int wolfSSHD_ReducePermissions(WOLFSSHD_AUTH* auth) return ret; } - -long wolfSSHD_GetGraceTime(WOLFSSHD_AUTH* auth) +long wolfSSHD_AuthGetGraceTime(const WOLFSSHD_AUTH* auth) { - long ret = 0; + long ret = WS_BAD_ARGUMENT; - if (auth != NULL) { - ret = wolfSSHD_ConfigGetOption(auth->conf, WOLFSSHD_GRACE_LOGIN_TIME); + if (auth != NULL && auth->conf != NULL) { + ret = wolfSSHD_ConfigGetGraceTime(auth->conf); } + return ret; } #endif /* WOLFSSH_SSHD */ diff --git a/apps/wolfsshd/auth.h b/apps/wolfsshd/auth.h index e1468ef3..42dc9af5 100644 --- a/apps/wolfsshd/auth.h +++ b/apps/wolfsshd/auth.h @@ -54,9 +54,9 @@ typedef int (*CallbackCheckPassword)(const char* usr, const byte* psw, typedef int (*CallbackCheckPublicKey)(const char* usr, const byte* key, word32 keySz); -WOLFSSHD_AUTH * wolfSSHD_CreateUserAuth(void* heap, WOLFSSHD_CONFIG* conf); -int wolfSSHD_FreeUserAuth(WOLFSSHD_AUTH* auth); -int wolfSSHD_ReducePermissions(WOLFSSHD_AUTH* auth); -int wolfSSHD_RaisePermissions(WOLFSSHD_AUTH* auth); -long wolfSSHD_GetGraceTime(WOLFSSHD_AUTH* auth); +WOLFSSHD_AUTH* wolfSSHD_AuthCreateUser(void* heap, const WOLFSSHD_CONFIG* conf); +int wolfSSHD_AuthFreeUser(WOLFSSHD_AUTH* auth); +int wolfSSHD_AuthReducePermissions(WOLFSSHD_AUTH* auth); +int wolfSSHD_AuthRaisePermissions(WOLFSSHD_AUTH* auth); +long wolfSSHD_AuthGetGraceTime(const WOLFSSHD_AUTH* auth); #endif /* WOLFAUTH_H */ diff --git a/apps/wolfsshd/config.c b/apps/wolfsshd/configuration.c similarity index 79% rename from apps/wolfsshd/config.c rename to apps/wolfsshd/configuration.c index 6fc69d0e..38f13407 100644 --- a/apps/wolfsshd/config.c +++ b/apps/wolfsshd/configuration.c @@ -1,4 +1,4 @@ -/* config.c +/* configuration.c * * Copyright (C) 2014-2021 wolfSSL Inc. * @@ -39,7 +39,7 @@ #include "src/misc.c" #endif -#include "wolfsshd.h" +#include "configuration.h" struct WOLFSSHD_CONFIG { void* heap; @@ -64,31 +64,15 @@ struct WOLFSSHD_CONFIG { /* convert a string into seconds, handles if 'm' for minutes follows the string * number, i.e. 2m * Returns the value on success and negative value on failure */ -static long wolfSSHD_GetConfigInt(const char* in, int inSz, int isTime, - void* heap) +static long GetConfigInt(const char* in, int inSz, int isTime, void* heap) { long ret = 0; int mult = 1; /* multiplier */ int idx = 0; int sz = 0; - /* remove leading white spaces */ - while (idx < inSz && in[idx] == ' ') idx++; - - if (idx == inSz) { - ret = WS_BAD_ARGUMENT; - } - - /* remove trailing white spaces */ - if (ret == 0) { - for (sz = 1; sz + idx < inSz; sz++) { - if (in[sz + idx] == ' ') break; - if (in[sz + idx] == '\n') break; - } - } - /* check for multipliers */ - if (isTime && ret == 0) { + if (isTime) { if (in[sz - 1 + idx] == 'm') { sz--; mult = 60; @@ -119,8 +103,7 @@ static long wolfSSHD_GetConfigInt(const char* in, int inSz, int isTime, } /* returns WS_SUCCESS on success */ -static int wolfSSHD_CreateString(char** out, const char* in, int inSz, - void* heap) +static int CreateString(char** out, const char* in, int inSz, void* heap) { int ret = WS_SUCCESS; int idx = 0; @@ -147,7 +130,7 @@ static int wolfSSHD_CreateString(char** out, const char* in, int inSz, return ret; } -static void wolfSSHD_FreeString(char** in, void* heap) +static void FreeString(char** in, void* heap) { if (*in != NULL) { WFREE(*in, heap, DYNTYPE_SSHD); @@ -175,19 +158,15 @@ WOLFSSHD_CONFIG* wolfSSHD_NewConfig(void* heap) } -void wolfSSHD_FreeConfig(WOLFSSHD_CONFIG* conf) +void wolfSSHD_ConfigFree(WOLFSSHD_CONFIG* conf) { void* heap; if (conf != NULL) { heap = conf->heap; - if (conf->authKeysFile != NULL) { - wolfSSHD_FreeString(&conf->authKeysFile, heap); - } - if (conf->hostKeyFile != NULL) { - wolfSSHD_FreeString(&conf->hostKeyFile, heap); - } + FreeString(&conf->authKeysFile, heap); + FreeString(&conf->hostKeyFile, heap); WFREE(conf, heap, DYNTYPE_SSHD); } @@ -233,7 +212,7 @@ static const CONFIG_OPTION options[NUM_OPTIONS] = { {OPT_HOST_KEY, "HostKey"} }; -static int wolfSSHD_HandlePrivSep(WOLFSSHD_CONFIG* conf, const char* value) +static int HandlePrivSep(WOLFSSHD_CONFIG* conf, const char* value) { int ret = WS_SUCCESS; @@ -265,8 +244,7 @@ static int wolfSSHD_HandlePrivSep(WOLFSSHD_CONFIG* conf, const char* value) return ret; } -static int wolfSSHD_HandleLoginGraceTime(WOLFSSHD_CONFIG* conf, - const char* value) +static int HandleLoginGraceTime(WOLFSSHD_CONFIG* conf, const char* value) { int ret = WS_SUCCESS; long num; @@ -276,7 +254,7 @@ static int wolfSSHD_HandleLoginGraceTime(WOLFSSHD_CONFIG* conf, } if (ret == WS_SUCCESS) { - num = wolfSSHD_GetConfigInt(value, XSTRLEN(value), 1, conf->heap); + num = GetConfigInt(value, XSTRLEN(value), 1, conf->heap); if (num < 0) { wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Issue getting login grace " "time"); @@ -292,18 +270,42 @@ static int wolfSSHD_HandleLoginGraceTime(WOLFSSHD_CONFIG* conf, return ret; } -/* TODO: Can value be const? */ -static int wolfSSHD_HandleConfigOption(WOLFSSHD_CONFIG* conf, int opt, - const char* value) +static int HandlePermitEmptyPw(WOLFSSHD_CONFIG* conf, const char* value) +{ + int ret = WS_SUCCESS; + + if (conf == NULL || value == NULL) { + ret = WS_BAD_ARGUMENT; + } + + if (ret == WS_SUCCESS) { + if (WSTRCMP(value, "no") == 0) { + conf->permitEmptyPasswords = 0; + } + else if (WSTRCMP(value, "yes") == 0) { + conf->permitEmptyPasswords = 1; + } + else { + ret = WS_BAD_ARGUMENT; + } + } + + return ret; +} + +static int HandleConfigOption(WOLFSSHD_CONFIG* conf, int opt, const char* value) { int ret = WS_BAD_ARGUMENT; switch (opt) { case OPT_AUTH_KEYS_FILE: - ret = wolfSSHD_SetAuthKeysFile(conf, value); + ret = wolfSSHD_ConfigSetAuthKeysFile(conf, value); break; case OPT_PRIV_SEP: - ret = wolfSSHD_HandlePrivSep(conf, value); + ret = HandlePrivSep(conf, value); + break; + case OPT_PERMIT_EMPTY_PW: + ret = HandlePermitEmptyPw(conf, value); break; case OPT_SUBSYSTEM: /* TODO */ @@ -334,10 +336,10 @@ static int wolfSSHD_HandleConfigOption(WOLFSSHD_CONFIG* conf, int opt, ret = WS_SUCCESS; break; case OPT_LOGIN_GRACE_TIME: - ret = wolfSSHD_HandleLoginGraceTime(conf, value); + ret = HandleLoginGraceTime(conf, value); break; case OPT_HOST_KEY: - ret = wolfSSHD_SetHostPrivateKey(conf, value); + ret = wolfSSHD_ConfigSetHostKeyFile(conf, value); break; default: break; @@ -371,8 +373,7 @@ static int CountWhitespace(const char* in, int inSz, byte inv) /* returns WS_SUCCESS on success * Fails if any option is found that is unknown/unsupported */ -static int wolfSSHD_ParseConfigLine(WOLFSSHD_CONFIG* conf, const char* l, - int lSz) +static int ParseConfigLine(WOLFSSHD_CONFIG* conf, const char* l, int lSz) { int ret = WS_BAD_ARGUMENT; int sz; @@ -403,7 +404,7 @@ static int wolfSSHD_ParseConfigLine(WOLFSSHD_CONFIG* conf, const char* l, else { WMEMCPY(tmp, l + idx, sz); tmp[sz] = 0; - ret = wolfSSHD_HandleConfigOption(conf, found->tag, tmp); + ret = HandleConfigOption(conf, found->tag, tmp); } } else { @@ -415,7 +416,7 @@ static int wolfSSHD_ParseConfigLine(WOLFSSHD_CONFIG* conf, const char* l, } -int wolfSSHD_LoadSSHD(WOLFSSHD_CONFIG* conf, const char* filename) +int wolfSSHD_ConfigLoad(WOLFSSHD_CONFIG* conf, const char* filename) { XFILE f; int ret = WS_SUCCESS; @@ -451,7 +452,7 @@ int wolfSSHD_LoadSSHD(WOLFSSHD_CONFIG* conf, const char* filename) continue; /* commented out line */ } - ret = wolfSSHD_ParseConfigLine(conf, current, currentSz); + ret = ParseConfigLine(conf, current, currentSz); if (ret != WS_SUCCESS) { printf("Unable to parse config line : %s\n", current); break; @@ -464,7 +465,7 @@ int wolfSSHD_LoadSSHD(WOLFSSHD_CONFIG* conf, const char* filename) return ret; } -char* wolfSSHD_GetAuthKeysFile(WOLFSSHD_CONFIG* conf) +char* wolfSSHD_ConfigGetAuthKeysFile(const WOLFSSHD_CONFIG* conf) { char* ret = NULL; @@ -475,7 +476,7 @@ char* wolfSSHD_GetAuthKeysFile(WOLFSSHD_CONFIG* conf) return ret; } -int wolfSSHD_SetAuthKeysFile(WOLFSSHD_CONFIG* conf, const char* file) +int wolfSSHD_ConfigSetAuthKeysFile(WOLFSSHD_CONFIG* conf, const char* file) { int ret = WS_SUCCESS; @@ -485,12 +486,12 @@ int wolfSSHD_SetAuthKeysFile(WOLFSSHD_CONFIG* conf, const char* file) if (ret == WS_SUCCESS) { if (conf->authKeysFile != NULL) { - wolfSSHD_FreeString(&conf->authKeysFile, conf->heap); + FreeString(&conf->authKeysFile, conf->heap); conf->authKeysFile = NULL; } if (file != NULL) { - ret = wolfSSHD_CreateString(&conf->authKeysFile, file, + ret = CreateString(&conf->authKeysFile, file, WSTRLEN(file), conf->heap); } } @@ -498,7 +499,7 @@ int wolfSSHD_SetAuthKeysFile(WOLFSSHD_CONFIG* conf, const char* file) return ret; } -char* wolfSSHD_GetBanner(WOLFSSHD_CONFIG* conf) +char* wolfSSHD_ConfigGetBanner(const WOLFSSHD_CONFIG* conf) { char* ret = NULL; @@ -509,7 +510,7 @@ char* wolfSSHD_GetBanner(WOLFSSHD_CONFIG* conf) return ret; } -char* wolfSSHD_GetHostPrivateKey(WOLFSSHD_CONFIG* conf) +char* wolfSSHD_ConfigGetHostKeyFile(const WOLFSSHD_CONFIG* conf) { char* ret = NULL; @@ -520,7 +521,7 @@ char* wolfSSHD_GetHostPrivateKey(WOLFSSHD_CONFIG* conf) return ret; } -int wolfSSHD_SetHostPrivateKey(WOLFSSHD_CONFIG* conf, const char* file) +int wolfSSHD_ConfigSetHostKeyFile(WOLFSSHD_CONFIG* conf, const char* file) { int ret = WS_SUCCESS; @@ -530,12 +531,12 @@ int wolfSSHD_SetHostPrivateKey(WOLFSSHD_CONFIG* conf, const char* file) if (ret == WS_SUCCESS) { if (conf->hostKeyFile != NULL) { - wolfSSHD_FreeString(&conf->hostKeyFile, conf->heap); + FreeString(&conf->hostKeyFile, conf->heap); conf->hostKeyFile = NULL; } if (file != NULL) { - ret = wolfSSHD_CreateString(&conf->hostKeyFile, file, + ret = CreateString(&conf->hostKeyFile, file, WSTRLEN(file), conf->heap); } } @@ -543,28 +544,37 @@ int wolfSSHD_SetHostPrivateKey(WOLFSSHD_CONFIG* conf, const char* file) return ret; } -word16 wolfSSHD_GetPort(WOLFSSHD_CONFIG* conf) +word16 wolfSSHD_ConfigGetPort(const WOLFSSHD_CONFIG* conf) { - if (conf != NULL) - return conf->port; - return 0; + word16 ret = 0; + + if (conf != NULL) { + ret = conf->port; + } + + return ret; +} + +byte wolfSSHD_ConfigGetPermitEmptyPw(const WOLFSSHD_CONFIG* conf) +{ + byte ret = 0; + + if (conf != NULL) { + ret = conf->permitEmptyPasswords; + } + + return ret; } -/* test if the 'opt' options is enabled or not in 'conf' for the flags set - * return 1 if enabled and 0 if not */ -long wolfSSHD_ConfigGetOption(WOLFSSHD_CONFIG* conf, word32 opt) +long wolfSSHD_ConfigGetGraceTime(const WOLFSSHD_CONFIG* conf) { - long ret = 0; + long ret = WS_BAD_ARGUMENT; - switch (opt) { - case WOLFSSHD_EMPTY_PASSWORD: - ret = conf->permitEmptyPasswords; - break; - case WOLFSSHD_GRACE_LOGIN_TIME: - ret = conf->loginTimer; - break; + if (conf != NULL) { + ret = conf->loginTimer; } + return ret; } #endif /* WOLFSSH_SSHD */ diff --git a/apps/wolfsshd/wolfsshd.h b/apps/wolfsshd/configuration.h similarity index 59% rename from apps/wolfsshd/wolfsshd.h rename to apps/wolfsshd/configuration.h index 6644b420..9e0549ae 100644 --- a/apps/wolfsshd/wolfsshd.h +++ b/apps/wolfsshd/configuration.h @@ -1,4 +1,4 @@ -/* wolfsshd.h +/* configuration.h * * Copyright (C) 2014-2021 wolfSSL Inc. * @@ -31,22 +31,17 @@ typedef struct WOLFSSHD_CONFIG WOLFSSHD_CONFIG; #define WOLFSSHD_PRIV_OFF 2 WOLFSSHD_CONFIG* wolfSSHD_NewConfig(void* heap); -void wolfSSHD_FreeConfig(WOLFSSHD_CONFIG* conf); -int wolfSSHD_LoadSSHD(WOLFSSHD_CONFIG* conf, const char* filename); +void wolfSSHD_ConfigFree(WOLFSSHD_CONFIG* conf); +int wolfSSHD_ConfigLoad(WOLFSSHD_CONFIG* conf, const char* filename); -char* wolfSSHD_GetBanner(WOLFSSHD_CONFIG* conf); -char* wolfSSHD_GetHostPrivateKey(WOLFSSHD_CONFIG* conf); -int wolfSSHD_SetHostPrivateKey(WOLFSSHD_CONFIG* conf, const char* hostKeyFile); -word16 wolfSSHD_GetPort(WOLFSSHD_CONFIG* conf); -char* wolfSSHD_GetAuthKeysFile(WOLFSSHD_CONFIG* conf); -int wolfSSHD_SetAuthKeysFile(WOLFSSHD_CONFIG* conf, const char* file); - - -/* on/off flag options to check */ -#define WOLFSSHD_EMPTY_PASSWORD 1 -#define WOLFSSHD_GRACE_LOGIN_TIME 2 - -long wolfSSHD_ConfigGetOption(WOLFSSHD_CONFIG* conf, word32 opt); +char* wolfSSHD_ConfigGetBanner(const WOLFSSHD_CONFIG* conf); +char* wolfSSHD_ConfigGetHostKeyFile(const WOLFSSHD_CONFIG* conf); +int wolfSSHD_ConfigSetHostKeyFile(WOLFSSHD_CONFIG* conf, const char* file); +word16 wolfSSHD_ConfigGetPort(const WOLFSSHD_CONFIG* conf); +char* wolfSSHD_ConfigGetAuthKeysFile(const WOLFSSHD_CONFIG* conf); +int wolfSSHD_ConfigSetAuthKeysFile(WOLFSSHD_CONFIG* conf, const char* file); +byte wolfSSHD_ConfigGetPermitEmptyPw(const WOLFSSHD_CONFIG* conf); +long wolfSSHD_ConfigGetGraceTime(const WOLFSSHD_CONFIG* conf); #endif /* WOLFSSHD_H */ diff --git a/apps/wolfsshd/include.am b/apps/wolfsshd/include.am index 1059f7df..94985981 100644 --- a/apps/wolfsshd/include.am +++ b/apps/wolfsshd/include.am @@ -1,10 +1,10 @@ if BUILD_SSHD bin_PROGRAMS += apps/wolfsshd/wolfsshd -noinst_HEADERS += apps/wolfsshd/wolfsshd.h \ +noinst_HEADERS += apps/wolfsshd/configuration.h \ apps/wolfsshd/auth.h apps_wolfsshd_wolfsshd_SOURCES = apps/wolfsshd/wolfsshd.c \ - apps/wolfsshd/config.c \ + apps/wolfsshd/configuration.c \ apps/wolfsshd/auth.c apps_wolfsshd_wolfsshd_LDADD = src/libwolfssh.la apps_wolfsshd_wolfsshd_DEPENDENCIES = src/libwolfssh.la diff --git a/apps/wolfsshd/wolfsshd.c b/apps/wolfsshd/wolfsshd.c index 9ea1637a..b7f9b0b7 100644 --- a/apps/wolfsshd/wolfsshd.c +++ b/apps/wolfsshd/wolfsshd.c @@ -35,7 +35,7 @@ #define WOLFSSH_TEST_SERVER #include -#include "wolfsshd.h" +#include "configuration.h" #include "auth.h" #include @@ -138,7 +138,7 @@ static int SetupCTX(WOLFSSHD_CONFIG* conf, WOLFSSH_CTX** ctx) /* set banner to display on connection */ if (ret == WS_SUCCESS) { - banner = wolfSSHD_GetBanner(conf); + banner = wolfSSHD_ConfigGetBanner(conf); if (banner == NULL) { banner = defaultBanner; } @@ -162,7 +162,7 @@ static int SetupCTX(WOLFSSHD_CONFIG* conf, WOLFSSH_CTX** ctx) /* Load in host private key */ if (ret == WS_SUCCESS) { - char* hostKey = wolfSSHD_GetHostPrivateKey(conf); + char* hostKey = wolfSSHD_ConfigGetHostKeyFile(conf); if (hostKey == NULL) { wolfSSH_Log(WS_LOG_ERROR, "[SSHD] No host private key set"); @@ -355,7 +355,7 @@ static int SHELL_Subsystem(WOLFSSHD_CONNECTION* conn, WOLFSSH* ssh) userName = wolfSSH_GetUsername(ssh); /* temporarily elevate permissions to get users information */ - if (wolfSSHD_RaisePermissions(conn->auth) != 0) { + if (wolfSSHD_AuthRaisePermissions(conn->auth) != 0) { wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Failure to raise permissions for auth"); return WS_FATAL_ERROR; } @@ -364,7 +364,7 @@ static int SHELL_Subsystem(WOLFSSHD_CONNECTION* conn, WOLFSSH* ssh) if (p_passwd == NULL) { /* Not actually a user on the system. */ wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Invalid user name found"); - if (wolfSSHD_ReducePermissions(conn->auth) != 0) { + if (wolfSSHD_AuthReducePermissions(conn->auth) != 0) { /* stop everything if not able to reduce permissions level */ exit(1); } @@ -374,7 +374,7 @@ static int SHELL_Subsystem(WOLFSSHD_CONNECTION* conn, WOLFSSH* ssh) ChildRunning = 1; childPid = forkpty(&childFd, NULL, NULL, NULL); - if (wolfSSHD_ReducePermissions(conn->auth) != 0) { + if (wolfSSHD_AuthReducePermissions(conn->auth) != 0) { /* stop everything if not able to reduce permissions level */ wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Issue reducing permissions level," " exiting now"); @@ -523,7 +523,7 @@ static void alarmCatch(int signum) } /* handle wolfSSH accept and directing to correct subsystem */ -static void* wolfSSHD_HandleConnection(void* arg) +static void* HandleConnection(void* arg) { int ret = WS_SUCCESS; @@ -553,7 +553,7 @@ static void* wolfSSHD_HandleConnection(void* arg) wolfSSH_SetUserAuthCtx(ssh, conn->auth); /* set alarm for login grace time */ - graceTime = wolfSSHD_GetGraceTime(conn->auth); + graceTime = wolfSSHD_AuthGetGraceTime(conn->auth); if (graceTime > 0) { signal(SIGALRM, alarmCatch); alarm(graceTime); @@ -640,7 +640,7 @@ static void* wolfSSHD_HandleConnection(void* arg) /* returns WS_SUCCESS on success */ -static int wolfSSHD_NewConnection(WOLFSSHD_CONNECTION* conn) +static int NewConnection(WOLFSSHD_CONNECTION* conn) { int pd; int ret = WS_SUCCESS; @@ -653,7 +653,7 @@ static int wolfSSHD_NewConnection(WOLFSSHD_CONNECTION* conn) if (pd == 0) { /* child process */ - (void)wolfSSHD_HandleConnection((void*)conn); + (void)HandleConnection((void*)conn); } else { wolfSSH_Log(WS_LOG_INFO, "[SSHD] Spawned new process %d\n", pd); @@ -664,7 +664,7 @@ static int wolfSSHD_NewConnection(WOLFSSHD_CONNECTION* conn) /* return non zero value for a pending connection */ -static int wolfSSHD_PendingConnection(WS_SOCKET_T fd) +static int PendingConnection(WS_SOCKET_T fd) { int ret; struct timeval t; @@ -776,19 +776,19 @@ int main(int argc, char** argv) } if (ret == WS_SUCCESS) { - ret = wolfSSHD_LoadSSHD(conf, configFile); + ret = wolfSSHD_ConfigLoad(conf, configFile); if (ret != WS_SUCCESS) printf("Error reading in configure file %s\n", configFile); } /* port was not overridden with argument, read from config file */ if (port == 0) { - port = wolfSSHD_GetPort(conf); + port = wolfSSHD_ConfigGetPort(conf); } /* check if host key file was passed in */ if (hostKeyFile != NULL) { - wolfSSHD_SetHostPrivateKey(conf, hostKeyFile); + wolfSSHD_ConfigSetHostKeyFile(conf, hostKeyFile); } wolfSSH_Log(WS_LOG_INFO, "[SSHD] Starting wolfSSH SSHD application"); @@ -801,7 +801,7 @@ int main(int argc, char** argv) } if (ret == WS_SUCCESS) { - auth = wolfSSHD_CreateUserAuth(NULL, conf); + auth = wolfSSHD_AuthCreateUser(NULL, conf); if (auth == NULL) { wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Issue creating auth struct"); ret = WS_MEMORY_E; @@ -810,7 +810,7 @@ int main(int argc, char** argv) /* seperate privlage permisions */ if (ret == WS_SUCCESS) { - if (wolfSSHD_ReducePermissions(auth) != 0) { + if (wolfSSHD_AuthReducePermissions(auth) != 0) { wolfSSH_Log(WS_LOG_INFO, "[SSHD] Error lowering permissions level"); ret = WS_FATAL_ERROR; } @@ -833,7 +833,7 @@ int main(int argc, char** argv) conn.auth = auth; /* wait for a connection */ - if (wolfSSHD_PendingConnection(listenFd)) { + if (PendingConnection(listenFd)) { conn.ctx = ctx; #ifdef WOLFSSL_NUCLEUS conn.fd = NU_Accept(listenFd, &clientAddr, 0); @@ -861,13 +861,13 @@ int main(int argc, char** argv) err_sys("fcntl set failed"); #endif } - ret = wolfSSHD_NewConnection(&conn); + ret = NewConnection(&conn); } } } - wolfSSHD_FreeConfig(conf); - wolfSSHD_FreeUserAuth(auth); + wolfSSHD_ConfigFree(conf); + wolfSSHD_AuthFreeUser(auth); wolfSSH_Cleanup(); return 0; From e255679861960ed2430ce5d9f0b4600e2d8c6d5b Mon Sep 17 00:00:00 2001 From: Hayden Roche Date: Wed, 27 Jul 2022 16:46:15 -0700 Subject: [PATCH 22/48] Add support for PasswordAuthentication config option. --- apps/wolfsshd/auth.c | 14 +++++++---- apps/wolfsshd/configuration.c | 44 ++++++++++++++++++++++++++++++++--- apps/wolfsshd/configuration.h | 1 + apps/wolfsshd/wolfsshd.c | 4 ++-- 4 files changed, 54 insertions(+), 9 deletions(-) diff --git a/apps/wolfsshd/auth.c b/apps/wolfsshd/auth.c index 918b983c..ca6d1248 100644 --- a/apps/wolfsshd/auth.c +++ b/apps/wolfsshd/auth.c @@ -651,8 +651,8 @@ static int DoCheckUser(const char* usr, WOLFSSHD_AUTH* auth) } -/* @TODO this will take in a pipe or equivilant to talk to a privliged thread - * rathar than having WOLFSSHD_AUTH directly with privilige seperation */ +/* @TODO this will take in a pipe or equivalent to talk to a privileged thread + * rathar than having WOLFSSHD_AUTH directly with privilege separation */ static int RequestAuthentication(const char* usr, int type, const byte* data, int dataSz, WOLFSSHD_AUTH* auth) { @@ -672,10 +672,16 @@ static int RequestAuthentication(const char* usr, int type, const byte* data, if (ret == WOLFSSH_USERAUTH_SUCCESS && type == WOLFSSH_USERAUTH_PASSWORD) { int rc; + if (wolfSSHD_ConfigGetPwAuth(auth->conf) != 1) { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Password authentication not " + "allowed by configuration!"); + ret = WOLFSSH_USERAUTH_FAILURE; + } /* Check if password is valid for this user. */ /* first handle empty password cases */ - if (dataSz == 0 && wolfSSHD_ConfigGetPermitEmptyPw(auth->conf) != 1) { - wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Empty passwords not allowed!"); + else if (dataSz == 0 && wolfSSHD_ConfigGetPermitEmptyPw(auth->conf) != 1) { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Empty passwords not allowed by " + "configuration!"); ret = WOLFSSH_USERAUTH_FAILURE; } else { diff --git a/apps/wolfsshd/configuration.c b/apps/wolfsshd/configuration.c index 38f13407..fd8d802e 100644 --- a/apps/wolfsshd/configuration.c +++ b/apps/wolfsshd/configuration.c @@ -153,6 +153,7 @@ WOLFSSHD_CONFIG* wolfSSHD_NewConfig(void* heap) /* default values */ ret->port = 9387; + ret->passwordAuth = 1; } return ret; @@ -191,10 +192,11 @@ enum { OPT_ACCEPT_ENV = 8, OPT_PROTOCOL = 9, OPT_LOGIN_GRACE_TIME = 10, - OPT_HOST_KEY = 11 + OPT_HOST_KEY = 11, + OPT_PASSWORD_AUTH = 12 }; enum { - NUM_OPTIONS = 12 + NUM_OPTIONS = 13 }; static const CONFIG_OPTION options[NUM_OPTIONS] = { @@ -209,7 +211,7 @@ static const CONFIG_OPTION options[NUM_OPTIONS] = { {OPT_ACCEPT_ENV, "AcceptEnv"}, {OPT_PROTOCOL, "Protocol"}, {OPT_LOGIN_GRACE_TIME, "LoginGraceTime"}, - {OPT_HOST_KEY, "HostKey"} + {OPT_PASSWORD_AUTH, "PasswordAuthentication"} }; static int HandlePrivSep(WOLFSSHD_CONFIG* conf, const char* value) @@ -293,6 +295,29 @@ static int HandlePermitEmptyPw(WOLFSSHD_CONFIG* conf, const char* value) return ret; } +static int HandlePwAuth(WOLFSSHD_CONFIG* conf, const char* value) +{ + int ret = WS_SUCCESS; + + if (conf == NULL || value == NULL) { + ret = WS_BAD_ARGUMENT; + } + + if (ret == WS_SUCCESS) { + if (WSTRCMP(value, "no") == 0) { + conf->passwordAuth = 0; + } + else if (WSTRCMP(value, "yes") == 0) { + conf->passwordAuth = 1; + } + else { + ret = WS_BAD_ARGUMENT; + } + } + + return ret; +} + static int HandleConfigOption(WOLFSSHD_CONFIG* conf, int opt, const char* value) { int ret = WS_BAD_ARGUMENT; @@ -341,6 +366,9 @@ static int HandleConfigOption(WOLFSSHD_CONFIG* conf, int opt, const char* value) case OPT_HOST_KEY: ret = wolfSSHD_ConfigSetHostKeyFile(conf, value); break; + case OPT_PASSWORD_AUTH: + ret = HandlePwAuth(conf, value); + break; default: break; } @@ -566,6 +594,16 @@ byte wolfSSHD_ConfigGetPermitEmptyPw(const WOLFSSHD_CONFIG* conf) return ret; } +byte wolfSSHD_ConfigGetPwAuth(const WOLFSSHD_CONFIG* conf) +{ + byte ret = 0; + + if (conf != NULL) { + ret = conf->passwordAuth; + } + + return ret; +} long wolfSSHD_ConfigGetGraceTime(const WOLFSSHD_CONFIG* conf) { diff --git a/apps/wolfsshd/configuration.h b/apps/wolfsshd/configuration.h index 9e0549ae..4389ec18 100644 --- a/apps/wolfsshd/configuration.h +++ b/apps/wolfsshd/configuration.h @@ -42,6 +42,7 @@ char* wolfSSHD_ConfigGetAuthKeysFile(const WOLFSSHD_CONFIG* conf); int wolfSSHD_ConfigSetAuthKeysFile(WOLFSSHD_CONFIG* conf, const char* file); byte wolfSSHD_ConfigGetPermitEmptyPw(const WOLFSSHD_CONFIG* conf); long wolfSSHD_ConfigGetGraceTime(const WOLFSSHD_CONFIG* conf); +byte wolfSSHD_ConfigGetPwAuth(const WOLFSSHD_CONFIG* conf); #endif /* WOLFSSHD_H */ diff --git a/apps/wolfsshd/wolfsshd.c b/apps/wolfsshd/wolfsshd.c index b7f9b0b7..564587f6 100644 --- a/apps/wolfsshd/wolfsshd.c +++ b/apps/wolfsshd/wolfsshd.c @@ -531,7 +531,7 @@ static void* HandleConnection(void* arg) WOLFSSH* ssh = NULL; if (arg == NULL) { - ret = BAD_FUNC_ARG; + ret = WS_BAD_ARGUMENT; } if (ret == WS_SUCCESS) { @@ -748,7 +748,7 @@ int main(int argc, char** argv) ret = XATOI(myoptarg); if (ret < 0) { printf("Issue parsing port number %s\n", myoptarg); - ret = BAD_FUNC_ARG; + ret = WS_BAD_ARGUMENT; } else { port = (word16)ret; From d62c1e007802f44333dbd1f5e01d1dd372ca1115 Mon Sep 17 00:00:00 2001 From: Hayden Roche Date: Wed, 27 Jul 2022 16:47:14 -0700 Subject: [PATCH 23/48] Fix GetConfigInt. --- apps/wolfsshd/configuration.c | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/apps/wolfsshd/configuration.c b/apps/wolfsshd/configuration.c index fd8d802e..094b4a1b 100644 --- a/apps/wolfsshd/configuration.c +++ b/apps/wolfsshd/configuration.c @@ -68,16 +68,15 @@ static long GetConfigInt(const char* in, int inSz, int isTime, void* heap) { long ret = 0; int mult = 1; /* multiplier */ - int idx = 0; - int sz = 0; + int sz = inSz; /* check for multipliers */ if (isTime) { - if (in[sz - 1 + idx] == 'm') { + if (in[sz - 1] == 'm') { sz--; mult = 60; } - if (in[sz - 1 + idx] == 'h') { + if (in[sz - 1] == 'h') { sz--; mult = 60*60; } @@ -89,7 +88,7 @@ static long GetConfigInt(const char* in, int inSz, int isTime, void* heap) ret = WS_MEMORY_E; } else { - WMEMCPY(num, in + idx, sz); + WMEMCPY(num, in, sz); num[sz] = '\0'; ret = atol(num); if (ret > 0) { From cef7e5065ae4348e67a85939505b7f9333225aa1 Mon Sep 17 00:00:00 2001 From: Hayden Roche Date: Wed, 27 Jul 2022 16:48:10 -0700 Subject: [PATCH 24/48] Add support for Port config option and change default port back to 22. --- apps/wolfsshd/configuration.c | 45 +++++++++++++++++++++++++++++++---- apps/wolfsshd/wolfsshd.c | 9 +++++-- 2 files changed, 48 insertions(+), 6 deletions(-) diff --git a/apps/wolfsshd/configuration.c b/apps/wolfsshd/configuration.c index 094b4a1b..3f553270 100644 --- a/apps/wolfsshd/configuration.c +++ b/apps/wolfsshd/configuration.c @@ -151,7 +151,7 @@ WOLFSSHD_CONFIG* wolfSSHD_NewConfig(void* heap) WMEMSET(ret, 0, sizeof(WOLFSSHD_CONFIG)); /* default values */ - ret->port = 9387; + ret->port = 22; ret->passwordAuth = 1; } return ret; @@ -192,10 +192,11 @@ enum { OPT_PROTOCOL = 9, OPT_LOGIN_GRACE_TIME = 10, OPT_HOST_KEY = 11, - OPT_PASSWORD_AUTH = 12 + OPT_PASSWORD_AUTH = 12, + OPT_PORT = 13 }; enum { - NUM_OPTIONS = 13 + NUM_OPTIONS = 14 }; static const CONFIG_OPTION options[NUM_OPTIONS] = { @@ -210,7 +211,9 @@ static const CONFIG_OPTION options[NUM_OPTIONS] = { {OPT_ACCEPT_ENV, "AcceptEnv"}, {OPT_PROTOCOL, "Protocol"}, {OPT_LOGIN_GRACE_TIME, "LoginGraceTime"}, - {OPT_PASSWORD_AUTH, "PasswordAuthentication"} + {OPT_HOST_KEY, "HostKey"}, + {OPT_PASSWORD_AUTH, "PasswordAuthentication"}, + {OPT_PORT, "Port"} }; static int HandlePrivSep(WOLFSSHD_CONFIG* conf, const char* value) @@ -317,6 +320,37 @@ static int HandlePwAuth(WOLFSSHD_CONFIG* conf, const char* value) return ret; } +static int HandlePort(WOLFSSHD_CONFIG* conf, const char* value) +{ + int ret = WS_SUCCESS; + int portInt; + + if (conf == NULL || value == NULL) { + ret = WS_BAD_ARGUMENT; + } + + if (ret == WS_SUCCESS) { + portInt = XATOI(value); + if (portInt < 0) { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Unable to parse port number: %s.", + value); + ret = WS_BAD_ARGUMENT; + } + else { + if (portInt <= (word16)-1) { + conf->port = (word16)portInt; + } + else { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Port number %d too big.", + portInt); + ret = WS_BAD_ARGUMENT; + } + } + } + + return ret; +} + static int HandleConfigOption(WOLFSSHD_CONFIG* conf, int opt, const char* value) { int ret = WS_BAD_ARGUMENT; @@ -363,11 +397,14 @@ static int HandleConfigOption(WOLFSSHD_CONFIG* conf, int opt, const char* value) ret = HandleLoginGraceTime(conf, value); break; case OPT_HOST_KEY: + /* TODO: Add logic to check if file exists? */ ret = wolfSSHD_ConfigSetHostKeyFile(conf, value); break; case OPT_PASSWORD_AUTH: ret = HandlePwAuth(conf, value); break; + case OPT_PORT: + ret = HandlePort(conf, value); default: break; } diff --git a/apps/wolfsshd/wolfsshd.c b/apps/wolfsshd/wolfsshd.c index 564587f6..afd4fece 100644 --- a/apps/wolfsshd/wolfsshd.c +++ b/apps/wolfsshd/wolfsshd.c @@ -751,8 +751,13 @@ int main(int argc, char** argv) ret = WS_BAD_ARGUMENT; } else { - port = (word16)ret; - ret = WS_SUCCESS; + if (ret <= (word16)-1) { + port = (word16)ret; + } + else { + printf("Port number %d too big.\n", ret); + ret = WS_BAD_ARGUMENT; + } } } break; From f7fad8b8d0d94b4639a78d21fb29c50c80108547 Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Thu, 28 Jul 2022 15:34:21 +0100 Subject: [PATCH 25/48] Fix compiling issues --- apps/wolfsshd/wolfsshd.c | 4 ++++ configure.ac | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/apps/wolfsshd/wolfsshd.c b/apps/wolfsshd/wolfsshd.c index afd4fece..3920c536 100644 --- a/apps/wolfsshd/wolfsshd.c +++ b/apps/wolfsshd/wolfsshd.c @@ -147,16 +147,20 @@ static int SetupCTX(WOLFSSHD_CONFIG* conf, WOLFSSH_CTX** ctx) #ifdef WOLFSSH_AGENT /* check if using an agent is enabled */ + /* TODO: doesn't work if (ret == WS_SUCCESS) { wolfSSH_CTX_set_agent_cb(ctx, wolfSSH_AGENT_DefaultActions, NULL); } + */ #endif #ifdef WOLFSSH_FWD /* check if port forwarding is enabled */ + /* TODO: doesn't work if (ret == WS_SUCCESS) { wolfSSH_CTX_SetFwdCb(ctx, wolfSSH_FwdDefaultActions, NULL); } + */ #endif /* Load in host private key */ diff --git a/configure.ac b/configure.ac index dacdadb0..200ba7ff 100644 --- a/configure.ac +++ b/configure.ac @@ -221,7 +221,7 @@ AC_ARG_ENABLE([distro], AS_IF([test "x$ENABLED_DISTRO" = "xyes"], [ENABLED_ALL=yes; enable_shared=yes; enable_static=yes]) AS_IF([test "x$ENABLED_ALL" = "xyes"], - [ENABLED_KEYGEN=yes; ENABLED_SCP=yes; ENABLED_SFTP=yes; ENABLED_FWD=yes; ENABLED_SHELL=yes; ENABLED_AGENT=yes]) + [ENABLED_KEYGEN=yes; ENABLED_SCP=yes; ENABLED_SFTP=yes; ENABLED_FWD=yes; ENABLED_SHELL=yes; ENABLED_AGENT=yes; ENABLED_SSHD=yes]) AS_IF([test "x$ENABLED_SSHD" = "xyes"], [ENABLED_SHELL=yes;]) From 90769af1f83063da9bfb18102d4fc4dcb11dc0cc Mon Sep 17 00:00:00 2001 From: Hayden Roche Date: Thu, 28 Jul 2022 13:10:00 -0700 Subject: [PATCH 26/48] Add a test program, test_configuration.c, for testing sshd config. I wanted to be able to test ParseConfigLine directly, so I added some preprocessor logic to expose this function (i.e. make it non-static) when building test_configuration. I fixed a couple bugs discovered by this new testing. --- apps/wolfsshd/configuration.c | 25 ++-- apps/wolfsshd/configuration.h | 5 +- apps/wolfsshd/include.am | 11 +- apps/wolfsshd/test/test_configuration.c | 149 ++++++++++++++++++++++++ 4 files changed, 179 insertions(+), 11 deletions(-) create mode 100644 apps/wolfsshd/test/test_configuration.c diff --git a/apps/wolfsshd/configuration.c b/apps/wolfsshd/configuration.c index 3f553270..5d9a6770 100644 --- a/apps/wolfsshd/configuration.c +++ b/apps/wolfsshd/configuration.c @@ -26,6 +26,12 @@ /* functions for parsing out options from a config file and for handling loading * key/certs using the env. filesystem */ +#ifdef WOLFSSHD_UNIT_TEST +#define WOLFSSHD_STATIC +#else +#define WOLFSSHD_STATIC static +#endif + #include #include #include @@ -91,7 +97,10 @@ static long GetConfigInt(const char* in, int inSz, int isTime, void* heap) WMEMCPY(num, in, sz); num[sz] = '\0'; ret = atol(num); - if (ret > 0) { + if (ret == 0 && WSTRCMP(in, "0") != 0) { + ret = WS_BAD_ARGUMENT; + } + else if (ret > 0) { ret = ret * mult; } WFREE(num, heap, DYNTYPE_SSHD); @@ -228,17 +237,14 @@ static int HandlePrivSep(WOLFSSHD_CONFIG* conf, const char* value) if (WSTRCMP(value, "sandbox") == 0) { wolfSSH_Log(WS_LOG_INFO, "[SSHD] Sandbox privilege separation"); } - - if (WSTRCMP(value, "yes") == 0) { + else if (WSTRCMP(value, "yes") == 0) { wolfSSH_Log(WS_LOG_INFO, "[SSHD] Privilege separation enabled"); } - - if (WSTRCMP(value, "no") == 0) { + else if (WSTRCMP(value, "no") == 0) { wolfSSH_Log(WS_LOG_INFO, "[SSHD] Turning off privilege separation!"); } - - if (ret != WS_SUCCESS) { + else { wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Unknown/supported privilege separation!"); ret = WS_BAD_ARGUMENT; @@ -331,7 +337,7 @@ static int HandlePort(WOLFSSHD_CONFIG* conf, const char* value) if (ret == WS_SUCCESS) { portInt = XATOI(value); - if (portInt < 0) { + if (portInt <= 0) { wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Unable to parse port number: %s.", value); ret = WS_BAD_ARGUMENT; @@ -437,7 +443,8 @@ static int CountWhitespace(const char* in, int inSz, byte inv) /* returns WS_SUCCESS on success * Fails if any option is found that is unknown/unsupported */ -static int ParseConfigLine(WOLFSSHD_CONFIG* conf, const char* l, int lSz) +WOLFSSHD_STATIC int ParseConfigLine(WOLFSSHD_CONFIG* conf, const char* l, + int lSz) { int ret = WS_BAD_ARGUMENT; int sz; diff --git a/apps/wolfsshd/configuration.h b/apps/wolfsshd/configuration.h index 4389ec18..ad7c70f8 100644 --- a/apps/wolfsshd/configuration.h +++ b/apps/wolfsshd/configuration.h @@ -25,7 +25,6 @@ typedef struct WOLFSSHD_CONFIG WOLFSSHD_CONFIG; #include "auth.h" - #define WOLFSSHD_PRIV_SEPARAT 0 #define WOLFSSHD_PRIV_SANDBOX 1 #define WOLFSSHD_PRIV_OFF 2 @@ -44,5 +43,9 @@ byte wolfSSHD_ConfigGetPermitEmptyPw(const WOLFSSHD_CONFIG* conf); long wolfSSHD_ConfigGetGraceTime(const WOLFSSHD_CONFIG* conf); byte wolfSSHD_ConfigGetPwAuth(const WOLFSSHD_CONFIG* conf); +#ifdef WOLFSSHD_UNIT_TEST +int ParseConfigLine(WOLFSSHD_CONFIG* conf, const char* l, int lSz); +#endif + #endif /* WOLFSSHD_H */ diff --git a/apps/wolfsshd/include.am b/apps/wolfsshd/include.am index 94985981..cc20dee1 100644 --- a/apps/wolfsshd/include.am +++ b/apps/wolfsshd/include.am @@ -9,6 +9,15 @@ apps_wolfsshd_wolfsshd_SOURCES = apps/wolfsshd/wolfsshd.c \ apps_wolfsshd_wolfsshd_LDADD = src/libwolfssh.la apps_wolfsshd_wolfsshd_DEPENDENCIES = src/libwolfssh.la -DISTCLEANFILES+= apps/wolfsshd/.libs/wolfsshd +noinst_PROGRAMS += apps/wolfsshd/test/test_configuration +apps_wolfsshd_test_test_configuration_SOURCES = apps/wolfsshd/test/test_configuration.c \ + apps/wolfsshd/configuration.c \ + apps/wolfsshd/auth.c +apps_wolfsshd_test_test_configuration_LDADD = src/libwolfssh.la +apps_wolfsshd_test_test_configuration_DEPENDENCIES = src/libwolfssh.la +apps_wolfsshd_test_test_configuration_CPPFLAGS = -DWOLFSSH_SSHD -DWOLFSSHD_UNIT_TEST -Iapps/wolfsshd/ + +DISTCLEANFILES+= apps/wolfsshd/.libs/wolfsshd \ + apps/wolfsshd/test/.libs/test_configuration endif BUILD_SSHD diff --git a/apps/wolfsshd/test/test_configuration.c b/apps/wolfsshd/test/test_configuration.c new file mode 100644 index 00000000..91da4076 --- /dev/null +++ b/apps/wolfsshd/test/test_configuration.c @@ -0,0 +1,149 @@ +#include + +#include +#include + +static void Log(const char* fmt, ...) +{ + va_list vlist; + + va_start(vlist, fmt); + vfprintf(stderr, fmt, vlist); + va_end(vlist); +} + +typedef int (*TEST_FUNC)(void); +typedef struct { + const char *name; + TEST_FUNC func; +} TEST_CASE; + +#define TEST_DECL(func) { #func, func } + +#define TEST_CASE_CNT (int)(sizeof(testCases) / sizeof(*testCases)) + +static void TestSetup(const TEST_CASE* tc) +{ + Log("Running %s.\n", tc->name); +} + +static void TestCleanup(void) +{ +} + +static int RunTest(const TEST_CASE* tc) +{ + int ret; + + TestSetup(tc); + + ret = tc->func(); + if (ret != 0) { + Log("%s FAILED.\n", tc->name); + } + else { + Log("%s PASSED.\n", tc->name); + } + + TestCleanup(); + + return ret; +} + +typedef struct { + const char* desc; + const char* line; + int shouldFail; +} CONFIG_LINE_VECTOR; + +static int test_ParseConfigLine(void) +{ + int ret = WS_SUCCESS; + int i; + WOLFSSHD_CONFIG* conf; + + static CONFIG_LINE_VECTOR vectors[] = { + /* Port tests. */ + {"Valid port", "Port 22", 0}, + {"Port too big", "Port 65536", 1}, + {"Negative port", "Port -99", 1}, + {"Port NaN", "Port wolfsshd", 1}, + {"Port no value", "Port \n", 1}, + + /* Whitespace tests. */ + {"Extra leading whitespace", "Port 22", 0}, + {"Extra trailing whitespace", "Port 22 \n", 0}, + + /* Privilege separation tests. */ + {"Privilege separation yes", "UsePrivilegeSeparation yes", 0}, + {"Privilege separation no", "UsePrivilegeSeparation no", 0}, + {"Privilege separation sandbox", "UsePrivilegeSeparation sandbox", 0}, + {"Privilege separation invalid", "UsePrivilegeSeparation wolfsshd", 1}, + + /* Login grace time tests. */ + {"Valid login grace time seconds", "LoginGraceTime 60", 0}, + {"Valid login grace time minutes", "LoginGraceTime 1m", 0}, + {"Valid login grace time hours", "LoginGraceTime 1h", 0}, + {"Invalid login grace time", "LoginGraceTime wolfsshd", 1}, + + /* Permit empty password tests. */ + {"Permit empty password no", "PermitEmptyPasswords no", 0}, + {"Permit empty password yes", "PermitEmptyPasswords yes", 0}, + {"Permit empty password invalid", "PermitEmptyPasswords wolfsshd", 1}, + + /* Password auth tests. */ + {"Password auth no", "PasswordAuthentication no", 0}, + {"Password auth yes", "PasswordAuthentication yes", 0}, + {"Password auth invalid", "PasswordAuthentication wolfsshd", 1}, + }; + const int numVectors = (int)(sizeof(vectors) / sizeof(*vectors)); + + conf = wolfSSHD_NewConfig(NULL); + if (conf == NULL) { + ret = WS_MEMORY_E; + } + + if (ret == WS_SUCCESS) { + for (i = 0; i < numVectors; ++i) { + Log(" Testing scenario: %s.", vectors[i].desc); + + ret = ParseConfigLine(conf, vectors[i].line, + WSTRLEN(vectors[i].line)); + + if ((ret == WS_SUCCESS && !vectors[i].shouldFail) || + (ret != WS_SUCCESS && vectors[i].shouldFail)) { + Log(" PASSED.\n"); + ret = WS_SUCCESS; + } + else { + Log(" FAILED.\n"); + ret = WS_FATAL_ERROR; + break; + } + } + } + + return ret; +} + +const TEST_CASE testCases[] = { + TEST_DECL(test_ParseConfigLine) +}; + +int main(int argc, char** argv) +{ + int i; + int ret = WS_SUCCESS; + + (void)argc; + (void)argv; + + for (i = 0; i < TEST_CASE_CNT; ++i) { + ret = RunTest(&testCases[i]); + if (ret != WS_SUCCESS) { + break; + } + } + + return ret; +} From f0caefcc334e0c788e29cc4621dc93d3b2fa5b37 Mon Sep 17 00:00:00 2001 From: Hayden Roche Date: Thu, 28 Jul 2022 13:21:42 -0700 Subject: [PATCH 27/48] Make HandlePort use GetConfigInt and add 0 port test. --- apps/wolfsshd/configuration.c | 8 ++++---- apps/wolfsshd/test/test_configuration.c | 1 + 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/apps/wolfsshd/configuration.c b/apps/wolfsshd/configuration.c index 5d9a6770..c61830de 100644 --- a/apps/wolfsshd/configuration.c +++ b/apps/wolfsshd/configuration.c @@ -329,16 +329,16 @@ static int HandlePwAuth(WOLFSSHD_CONFIG* conf, const char* value) static int HandlePort(WOLFSSHD_CONFIG* conf, const char* value) { int ret = WS_SUCCESS; - int portInt; + long portInt; if (conf == NULL || value == NULL) { ret = WS_BAD_ARGUMENT; } if (ret == WS_SUCCESS) { - portInt = XATOI(value); + portInt = GetConfigInt(value, WSTRLEN(value), 0, conf->heap); if (portInt <= 0) { - wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Unable to parse port number: %s.", + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Invalid port number: %s.", value); ret = WS_BAD_ARGUMENT; } @@ -347,7 +347,7 @@ static int HandlePort(WOLFSSHD_CONFIG* conf, const char* value) conf->port = (word16)portInt; } else { - wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Port number %d too big.", + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Port number %ld too big.", portInt); ret = WS_BAD_ARGUMENT; } diff --git a/apps/wolfsshd/test/test_configuration.c b/apps/wolfsshd/test/test_configuration.c index 91da4076..34da542a 100644 --- a/apps/wolfsshd/test/test_configuration.c +++ b/apps/wolfsshd/test/test_configuration.c @@ -67,6 +67,7 @@ static int test_ParseConfigLine(void) {"Valid port", "Port 22", 0}, {"Port too big", "Port 65536", 1}, {"Negative port", "Port -99", 1}, + {"Port 0", "Port 0", 1}, {"Port NaN", "Port wolfsshd", 1}, {"Port no value", "Port \n", 1}, From ec873e1088216dcee43cba8372a21dcb08d271b8 Mon Sep 17 00:00:00 2001 From: Hayden Roche Date: Thu, 28 Jul 2022 13:34:14 -0700 Subject: [PATCH 28/48] Rename wolfSSHD_NewConfig to wolfSSHD_ConfigNew, following pattern. --- apps/wolfsshd/configuration.c | 2 +- apps/wolfsshd/configuration.h | 2 +- apps/wolfsshd/test/test_configuration.c | 2 +- apps/wolfsshd/wolfsshd.c | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/apps/wolfsshd/configuration.c b/apps/wolfsshd/configuration.c index c61830de..c4a43b36 100644 --- a/apps/wolfsshd/configuration.c +++ b/apps/wolfsshd/configuration.c @@ -147,7 +147,7 @@ static void FreeString(char** in, void* heap) (void)heap; } -WOLFSSHD_CONFIG* wolfSSHD_NewConfig(void* heap) +WOLFSSHD_CONFIG* wolfSSHD_ConfigNew(void* heap) { WOLFSSHD_CONFIG* ret; diff --git a/apps/wolfsshd/configuration.h b/apps/wolfsshd/configuration.h index ad7c70f8..3535a355 100644 --- a/apps/wolfsshd/configuration.h +++ b/apps/wolfsshd/configuration.h @@ -29,7 +29,7 @@ typedef struct WOLFSSHD_CONFIG WOLFSSHD_CONFIG; #define WOLFSSHD_PRIV_SANDBOX 1 #define WOLFSSHD_PRIV_OFF 2 -WOLFSSHD_CONFIG* wolfSSHD_NewConfig(void* heap); +WOLFSSHD_CONFIG* wolfSSHD_ConfigNew(void* heap); void wolfSSHD_ConfigFree(WOLFSSHD_CONFIG* conf); int wolfSSHD_ConfigLoad(WOLFSSHD_CONFIG* conf, const char* filename); diff --git a/apps/wolfsshd/test/test_configuration.c b/apps/wolfsshd/test/test_configuration.c index 34da542a..c671803c 100644 --- a/apps/wolfsshd/test/test_configuration.c +++ b/apps/wolfsshd/test/test_configuration.c @@ -99,7 +99,7 @@ static int test_ParseConfigLine(void) }; const int numVectors = (int)(sizeof(vectors) / sizeof(*vectors)); - conf = wolfSSHD_NewConfig(NULL); + conf = wolfSSHD_ConfigNew(NULL); if (conf == NULL) { ret = WS_MEMORY_E; } diff --git a/apps/wolfsshd/wolfsshd.c b/apps/wolfsshd/wolfsshd.c index 3920c536..415c5d2c 100644 --- a/apps/wolfsshd/wolfsshd.c +++ b/apps/wolfsshd/wolfsshd.c @@ -735,7 +735,7 @@ int main(int argc, char** argv) } if (ret == WS_SUCCESS) { - conf = wolfSSHD_NewConfig(NULL); + conf = wolfSSHD_ConfigNew(NULL); if (conf == NULL) { ret = WS_MEMORY_E; } From b6924ff604a1edead97386893375a8290708c921 Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Fri, 29 Jul 2022 10:14:34 +0100 Subject: [PATCH 29/48] Fix -p breaking everything Specifying a port set `ret` to the port number instead of `WS_SUCCESS` which meant that everything after parameter passing failed silently. --- apps/wolfsshd/wolfsshd.c | 1 + 1 file changed, 1 insertion(+) diff --git a/apps/wolfsshd/wolfsshd.c b/apps/wolfsshd/wolfsshd.c index 415c5d2c..f0f02b84 100644 --- a/apps/wolfsshd/wolfsshd.c +++ b/apps/wolfsshd/wolfsshd.c @@ -757,6 +757,7 @@ int main(int argc, char** argv) else { if (ret <= (word16)-1) { port = (word16)ret; + ret = WS_SUCCESS; } else { printf("Port number %d too big.\n", ret); From afdc1f4c67f7f568a8e99182ee76f63a0cc04148 Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Fri, 29 Jul 2022 13:33:12 +0100 Subject: [PATCH 30/48] Fix compiler errors for PPC32 --- apps/wolfsshd/wolfsshd.c | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/apps/wolfsshd/wolfsshd.c b/apps/wolfsshd/wolfsshd.c index f0f02b84..d94e61e3 100644 --- a/apps/wolfsshd/wolfsshd.c +++ b/apps/wolfsshd/wolfsshd.c @@ -395,11 +395,18 @@ static int SHELL_Subsystem(WOLFSSHD_CONNECTION* conn, WOLFSSH* ssh) /* Child process */ const char *args[] = {"-sh", NULL}; char cmd[80]; + int ret; signal(SIGINT, SIG_DFL); - setgid(p_passwd->pw_gid); - setuid(p_passwd->pw_uid); + ret = setgid(p_passwd->pw_gid); + if (ret) { + printf("Error executing setgid\n"); + } + ret = setuid(p_passwd->pw_uid); + if (ret) { + printf("Error executing setuid\n"); + } if (system("env") != 0) { printf("0 return value from system call\n"); } From 2e4d69e5ea48535ec6669d644abb36b4fb20452c Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Fri, 29 Jul 2022 13:34:47 +0100 Subject: [PATCH 31/48] Missed one function in PPC32 fix --- apps/wolfsshd/wolfsshd.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/apps/wolfsshd/wolfsshd.c b/apps/wolfsshd/wolfsshd.c index d94e61e3..b2f31387 100644 --- a/apps/wolfsshd/wolfsshd.c +++ b/apps/wolfsshd/wolfsshd.c @@ -418,7 +418,11 @@ static int SHELL_Subsystem(WOLFSSHD_CONNECTION* conn, WOLFSSH* ssh) WMEMSET(cmd, 0, sizeof(cmd)); XSNPRINTF(cmd, sizeof(cmd), "su %s", userName); printf("executing command [%s]\n", cmd); - system(cmd); + errno = 0; + ret = system(cmd); + if (ret && errno) { + printf("error executing command\n"); + } rc = chdir(p_passwd->pw_dir); if (rc != 0) { return WS_FATAL_ERROR; From 0b6d6cc09330190e88b94da7c0c4db665e151dd6 Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Fri, 29 Jul 2022 14:07:58 +0100 Subject: [PATCH 32/48] Make a note about 32bit Linux large file support --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 23f9158e..4f2e46cf 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,9 @@ to help with large file transfers. By default channels are set to handle window size for new channels would be as follows `./configure CPPFLAGS=-DDEFAULT_WINDOW_SZ=16384` +For 32bit Linux platforms you can add support for files > 2GB by compling +with `CFLAGS=-D_FILE_OFFSET_BITS=64`. + examples -------- From 3af82ddb427775bda45e29ee3046259edb34ab72 Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Fri, 29 Jul 2022 09:51:04 -0700 Subject: [PATCH 33/48] login as user with new shell --- apps/wolfsshd/wolfsshd.c | 64 ++++++++++++++++++++-------------------- 1 file changed, 32 insertions(+), 32 deletions(-) diff --git a/apps/wolfsshd/wolfsshd.c b/apps/wolfsshd/wolfsshd.c index b2f31387..7c27c4ee 100644 --- a/apps/wolfsshd/wolfsshd.c +++ b/apps/wolfsshd/wolfsshd.c @@ -342,6 +342,11 @@ static int SFTP_Subsystem(WOLFSSH* ssh, WOLFSSHD_CONNECTION* conn) #ifdef WOLFSSH_SHELL + +#ifndef MAX_COMMAND_SZ + #define MAX_COMMAND_SZ 80 +#endif + static int SHELL_Subsystem(WOLFSSHD_CONNECTION* conn, WOLFSSH* ssh) { WS_SOCKET_T sshFd = 0; @@ -378,13 +383,6 @@ static int SHELL_Subsystem(WOLFSSHD_CONNECTION* conn, WOLFSSH* ssh) ChildRunning = 1; childPid = forkpty(&childFd, NULL, NULL, NULL); - if (wolfSSHD_AuthReducePermissions(conn->auth) != 0) { - /* stop everything if not able to reduce permissions level */ - wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Issue reducing permissions level," - " exiting now"); - exit(1); - } - if (childPid < 0) { /* forkpty failed, so return */ ChildRunning = 0; @@ -393,43 +391,45 @@ static int SHELL_Subsystem(WOLFSSHD_CONNECTION* conn, WOLFSSH* ssh) } else if (childPid == 0) { /* Child process */ - const char *args[] = {"-sh", NULL}; - char cmd[80]; + char cmd[MAX_COMMAND_SZ]; int ret; signal(SIGINT, SIG_DFL); - ret = setgid(p_passwd->pw_gid); - if (ret) { - printf("Error executing setgid\n"); - } - ret = setuid(p_passwd->pw_uid); - if (ret) { - printf("Error executing setuid\n"); - } - if (system("env") != 0) { - printf("0 return value from system call\n"); - } - setenv("HOME", p_passwd->pw_dir, 1); setenv("LOGNAME", p_passwd->pw_name, 1); - - /* @TODO this needs reworked, can just exit into root */ - WMEMSET(cmd, 0, sizeof(cmd)); - XSNPRINTF(cmd, sizeof(cmd), "su %s", userName); - printf("executing command [%s]\n", cmd); - errno = 0; - ret = system(cmd); - if (ret && errno) { - printf("error executing command\n"); - } rc = chdir(p_passwd->pw_dir); if (rc != 0) { return WS_FATAL_ERROR; } - execv("/bin/sh", (char **)args); + /* default to /bin/sh if user shell is not set */ + WMEMSET(cmd, 0, sizeof(cmd)); + if (XSTRLEN(p_passwd->pw_shell) == 0) { + XSNPRINTF(cmd, sizeof(cmd), "sudo runuser -u %s -- %s", userName, + "/bin/sh"); + } + else { + XSNPRINTF(cmd, sizeof(cmd), "sudo runuser -u %s -- %s", userName, + p_passwd->pw_shell); + } + + errno = 0; + ret = system(cmd); + if (ret && errno) { + perror("error executing shell command "); + exit(1); + } + exit(0); /* exit child process and close down SSH connection */ } + + if (wolfSSHD_AuthReducePermissions(conn->auth) != 0) { + /* stop everything if not able to reduce permissions level */ + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Issue reducing permissions level," + " exiting now"); + exit(1); + } + sshFd = wolfSSH_get_fd(ssh); struct termios tios; From cd0213572c90aa08d2b9e8bc70d084e5c0783bf2 Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Fri, 29 Jul 2022 16:06:26 -0700 Subject: [PATCH 34/48] add parsing Protocol from sshd_config --- apps/wolfsshd/configuration.c | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/apps/wolfsshd/configuration.c b/apps/wolfsshd/configuration.c index c4a43b36..3786fc0b 100644 --- a/apps/wolfsshd/configuration.c +++ b/apps/wolfsshd/configuration.c @@ -326,6 +326,35 @@ static int HandlePwAuth(WOLFSSHD_CONFIG* conf, const char* value) return ret; } +#define WOLFSSH_PROTOCOL_VERSION 2 +static int HandleProtocol(WOLFSSHD_CONFIG* conf, const char* value) +{ + int ret = WS_SUCCESS; + long portInt; + + if (conf == NULL || value == NULL) { + ret = WS_BAD_ARGUMENT; + } + + if (ret == WS_SUCCESS) { + portInt = GetConfigInt(value, WSTRLEN(value), 0, conf->heap); + if (portInt <= 0) { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Invalid protocol number: %s.", + value); + ret = WS_BAD_ARGUMENT; + } + else { + if (portInt != WOLFSSH_PROTOCOL_VERSION) { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Protocol number %ld not " + "supported.", portInt); + ret = WS_BAD_ARGUMENT; + } + } + } + + return ret; +} + static int HandlePort(WOLFSSHD_CONFIG* conf, const char* value) { int ret = WS_SUCCESS; @@ -397,7 +426,7 @@ static int HandleConfigOption(WOLFSSHD_CONFIG* conf, int opt, const char* value) break; case OPT_PROTOCOL: /* TODO */ - ret = WS_SUCCESS; + ret = HandleProtocol(conf, value); break; case OPT_LOGIN_GRACE_TIME: ret = HandleLoginGraceTime(conf, value); @@ -525,7 +554,7 @@ int wolfSSHD_ConfigLoad(WOLFSSHD_CONFIG* conf, const char* filename) ret = ParseConfigLine(conf, current, currentSz); if (ret != WS_SUCCESS) { - printf("Unable to parse config line : %s\n", current); + fprintf(stderr, "Unable to parse config line : %s\n", current); break; } } From c978b83c28fd032acd59bc388b652932e5bf9739 Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Fri, 29 Jul 2022 16:32:39 -0700 Subject: [PATCH 35/48] add check for PermitRootLogin config --- apps/wolfsshd/auth.c | 11 +++++++-- apps/wolfsshd/configuration.c | 46 ++++++++++++++++++++++++++++++++--- apps/wolfsshd/configuration.h | 1 + 3 files changed, 53 insertions(+), 5 deletions(-) diff --git a/apps/wolfsshd/auth.c b/apps/wolfsshd/auth.c index ca6d1248..0af37df5 100644 --- a/apps/wolfsshd/auth.c +++ b/apps/wolfsshd/auth.c @@ -661,10 +661,17 @@ static int RequestAuthentication(const char* usr, int type, const byte* data, if (auth == NULL) return WOLFSSH_USERAUTH_FAILURE; - ret = DoCheckUser(usr, auth); + if (wolfSSHD_ConfigGetPermitRoot(auth->conf) == 0) { + if (XSTRCMP(usr, "root") == 0) { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Login as root not permited"); + return WOLFSSH_USERAUTH_FAILURE; + } + } + ret = DoCheckUser(usr, auth); /* temporarily elevate permissions */ - if (wolfSSHD_AuthRaisePermissions(auth) != 0) { + if (ret == WOLFSSH_USERAUTH_SUCCESS && + wolfSSHD_AuthRaisePermissions(auth) != 0) { wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Failure to raise permissions for auth"); ret = WOLFSSH_USERAUTH_FAILURE; } diff --git a/apps/wolfsshd/configuration.c b/apps/wolfsshd/configuration.c index 3786fc0b..82a9a30b 100644 --- a/apps/wolfsshd/configuration.c +++ b/apps/wolfsshd/configuration.c @@ -202,10 +202,11 @@ enum { OPT_LOGIN_GRACE_TIME = 10, OPT_HOST_KEY = 11, OPT_PASSWORD_AUTH = 12, - OPT_PORT = 13 + OPT_PORT = 13, + OPT_PERMIT_ROOT = 14 }; enum { - NUM_OPTIONS = 14 + NUM_OPTIONS = 15 }; static const CONFIG_OPTION options[NUM_OPTIONS] = { @@ -222,7 +223,8 @@ static const CONFIG_OPTION options[NUM_OPTIONS] = { {OPT_LOGIN_GRACE_TIME, "LoginGraceTime"}, {OPT_HOST_KEY, "HostKey"}, {OPT_PASSWORD_AUTH, "PasswordAuthentication"}, - {OPT_PORT, "Port"} + {OPT_PORT, "Port"}, + {OPT_PERMIT_ROOT, "PermitRootLogin"} }; static int HandlePrivSep(WOLFSSHD_CONFIG* conf, const char* value) @@ -303,6 +305,29 @@ static int HandlePermitEmptyPw(WOLFSSHD_CONFIG* conf, const char* value) return ret; } +static int HandlePermitRoot(WOLFSSHD_CONFIG* conf, const char* value) +{ + int ret = WS_SUCCESS; + + if (conf == NULL || value == NULL) { + ret = WS_BAD_ARGUMENT; + } + + if (ret == WS_SUCCESS) { + if (WSTRCMP(value, "no") == 0) { + conf->permitRootLogin = 0; + } + else if (WSTRCMP(value, "yes") == 0) { + conf->permitRootLogin = 1; + } + else { + ret = WS_BAD_ARGUMENT; + } + } + + return ret; +} + static int HandlePwAuth(WOLFSSHD_CONFIG* conf, const char* value) { int ret = WS_SUCCESS; @@ -440,6 +465,10 @@ static int HandleConfigOption(WOLFSSHD_CONFIG* conf, int opt, const char* value) break; case OPT_PORT: ret = HandlePort(conf, value); + break; + case OPT_PERMIT_ROOT: + ret = HandlePermitRoot(conf, value); + break; default: break; } @@ -677,6 +706,17 @@ byte wolfSSHD_ConfigGetPwAuth(const WOLFSSHD_CONFIG* conf) return ret; } +byte wolfSSHD_ConfigGetPermitRoot(const WOLFSSHD_CONFIG* conf) +{ + byte ret = 0; + + if (conf != NULL) { + ret = conf->permitRootLogin; + } + + return ret; +} + long wolfSSHD_ConfigGetGraceTime(const WOLFSSHD_CONFIG* conf) { long ret = WS_BAD_ARGUMENT; diff --git a/apps/wolfsshd/configuration.h b/apps/wolfsshd/configuration.h index 3535a355..222b8125 100644 --- a/apps/wolfsshd/configuration.h +++ b/apps/wolfsshd/configuration.h @@ -40,6 +40,7 @@ word16 wolfSSHD_ConfigGetPort(const WOLFSSHD_CONFIG* conf); char* wolfSSHD_ConfigGetAuthKeysFile(const WOLFSSHD_CONFIG* conf); int wolfSSHD_ConfigSetAuthKeysFile(WOLFSSHD_CONFIG* conf, const char* file); byte wolfSSHD_ConfigGetPermitEmptyPw(const WOLFSSHD_CONFIG* conf); +byte wolfSSHD_ConfigGetPermitRoot(const WOLFSSHD_CONFIG* conf); long wolfSSHD_ConfigGetGraceTime(const WOLFSSHD_CONFIG* conf); byte wolfSSHD_ConfigGetPwAuth(const WOLFSSHD_CONFIG* conf); From 4d90993e165d20d7d4156c9be7254ee84b862867 Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Fri, 29 Jul 2022 23:08:19 -0700 Subject: [PATCH 36/48] stub UseDNS, add checking config UsePrivilegeSeparation, scan-build warning fixes --- apps/wolfsshd/auth.c | 43 ++++++++++++++++++++--------------- apps/wolfsshd/configuration.c | 26 ++++++++++++++++++--- apps/wolfsshd/configuration.h | 2 ++ apps/wolfsshd/wolfsshd.c | 2 ++ 4 files changed, 52 insertions(+), 21 deletions(-) diff --git a/apps/wolfsshd/auth.c b/apps/wolfsshd/auth.c index 0af37df5..e5f799f2 100644 --- a/apps/wolfsshd/auth.c +++ b/apps/wolfsshd/auth.c @@ -289,7 +289,7 @@ static int CheckAuthKeysLine(char* line, word32 lineSz, const byte* key, #ifndef _WIN32 #ifdef WOLFSSH_USE_PAM -static int CheckPasswordPAM(const byte* usr, const byte* pw, int pwSz) +static int CheckPasswordPAM(const char* usr, const byte* pw, word32 pwSz) { (void)usr; (void)pw; @@ -404,10 +404,12 @@ static int CheckPasswordUnix(const char* usr, const byte* pw, word32 pwSz) } } - pwInfo = getpwnam((const char*)usr); - if (pwInfo == NULL) { - /* user name not found on system */ - ret = WS_FATAL_ERROR; + if (ret == WS_SUCCESS) { + pwInfo = getpwnam((const char*)usr); + if (pwInfo == NULL) { + /* user name not found on system */ + ret = WS_FATAL_ERROR; + } } if (ret == WS_SUCCESS) { @@ -554,9 +556,10 @@ static int CheckPublicKeyUnix(const char* name, const byte* key, word32 keySz) if (errno != 0) { wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Error calling getpwnam for user " "%s.", name); - ret = WS_FATAL_ERROR; } + ret = WS_FATAL_ERROR; } + if (ret == WSSHD_AUTH_SUCCESS) { WMEMSET(authKeysPath, 0, sizeof(authKeysPath)); rc = ResolveAuthKeysPath(pwInfo->pw_dir, authKeysPath); @@ -942,22 +945,26 @@ int wolfSSHD_AuthRaisePermissions(WOLFSSHD_AUTH* auth) /* return 0 on success */ int wolfSSHD_AuthReducePermissions(WOLFSSHD_AUTH* auth) { + byte flag = 0; int ret = 0; - wolfSSH_Log(WS_LOG_INFO, "[SSHD] Lowering permissions level"); - if (auth) { - if (setegid(auth->gid) != 0) { - wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Error setting sshd gid"); - ret = WS_FATAL_ERROR; - } + flag = wolfSSHD_ConfigGetPrivilegeSeparation(auth->conf); + if (flag == WOLFSSHD_PRIV_SEPARAT || flag == WOLFSSHD_PRIV_SANDBOX) { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Lowering permissions level"); + if (auth) { + if (setegid(auth->gid) != 0) { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Error setting sshd gid"); + ret = WS_FATAL_ERROR; + } - if (seteuid(auth->uid) != 0) { - wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Error setting sshd uid"); - ret = WS_FATAL_ERROR; + if (seteuid(auth->uid) != 0) { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Error setting sshd uid"); + ret = WS_FATAL_ERROR; + } + } + else { + ret = WS_BAD_ARGUMENT; } - } - else { - ret = WS_BAD_ARGUMENT; } return ret; } diff --git a/apps/wolfsshd/configuration.c b/apps/wolfsshd/configuration.c index 82a9a30b..0c28a37d 100644 --- a/apps/wolfsshd/configuration.c +++ b/apps/wolfsshd/configuration.c @@ -203,10 +203,11 @@ enum { OPT_HOST_KEY = 11, OPT_PASSWORD_AUTH = 12, OPT_PORT = 13, - OPT_PERMIT_ROOT = 14 + OPT_PERMIT_ROOT = 14, + OPT_USE_DNS = 15 }; enum { - NUM_OPTIONS = 15 + NUM_OPTIONS = 16 }; static const CONFIG_OPTION options[NUM_OPTIONS] = { @@ -224,7 +225,8 @@ static const CONFIG_OPTION options[NUM_OPTIONS] = { {OPT_HOST_KEY, "HostKey"}, {OPT_PASSWORD_AUTH, "PasswordAuthentication"}, {OPT_PORT, "Port"}, - {OPT_PERMIT_ROOT, "PermitRootLogin"} + {OPT_PERMIT_ROOT, "PermitRootLogin"}, + {OPT_USE_DNS, "UseDNS"} }; static int HandlePrivSep(WOLFSSHD_CONFIG* conf, const char* value) @@ -238,13 +240,16 @@ static int HandlePrivSep(WOLFSSHD_CONFIG* conf, const char* value) if (ret == WS_SUCCESS) { if (WSTRCMP(value, "sandbox") == 0) { wolfSSH_Log(WS_LOG_INFO, "[SSHD] Sandbox privilege separation"); + conf->usePrivilegeSeparation = WOLFSSHD_PRIV_SANDBOX; } else if (WSTRCMP(value, "yes") == 0) { wolfSSH_Log(WS_LOG_INFO, "[SSHD] Privilege separation enabled"); + conf->usePrivilegeSeparation = WOLFSSHD_PRIV_SEPARAT; } else if (WSTRCMP(value, "no") == 0) { wolfSSH_Log(WS_LOG_INFO, "[SSHD] Turning off privilege separation!"); + conf->usePrivilegeSeparation = WOLFSSHD_PRIV_OFF; } else { wolfSSH_Log(WS_LOG_ERROR, @@ -469,6 +474,10 @@ static int HandleConfigOption(WOLFSSHD_CONFIG* conf, int opt, const char* value) case OPT_PERMIT_ROOT: ret = HandlePermitRoot(conf, value); break; + case OPT_USE_DNS: + /* TODO */ + ret = WS_SUCCESS; + break; default: break; } @@ -695,6 +704,17 @@ byte wolfSSHD_ConfigGetPermitEmptyPw(const WOLFSSHD_CONFIG* conf) return ret; } +byte wolfSSHD_ConfigGetPrivilegeSeparation(const WOLFSSHD_CONFIG* conf) +{ + byte ret = 0; + + if (conf != NULL) { + ret = conf->usePrivilegeSeparation; + } + + return ret; +} + byte wolfSSHD_ConfigGetPwAuth(const WOLFSSHD_CONFIG* conf) { byte ret = 0; diff --git a/apps/wolfsshd/configuration.h b/apps/wolfsshd/configuration.h index 222b8125..952a1f87 100644 --- a/apps/wolfsshd/configuration.h +++ b/apps/wolfsshd/configuration.h @@ -25,6 +25,7 @@ typedef struct WOLFSSHD_CONFIG WOLFSSHD_CONFIG; #include "auth.h" +/* 0 so that privilage seperation is default on after struct memset'd on init */ #define WOLFSSHD_PRIV_SEPARAT 0 #define WOLFSSHD_PRIV_SANDBOX 1 #define WOLFSSHD_PRIV_OFF 2 @@ -41,6 +42,7 @@ char* wolfSSHD_ConfigGetAuthKeysFile(const WOLFSSHD_CONFIG* conf); int wolfSSHD_ConfigSetAuthKeysFile(WOLFSSHD_CONFIG* conf, const char* file); byte wolfSSHD_ConfigGetPermitEmptyPw(const WOLFSSHD_CONFIG* conf); byte wolfSSHD_ConfigGetPermitRoot(const WOLFSSHD_CONFIG* conf); +byte wolfSSHD_ConfigGetPrivilegeSeparation(const WOLFSSHD_CONFIG* conf); long wolfSSHD_ConfigGetGraceTime(const WOLFSSHD_CONFIG* conf); byte wolfSSHD_ConfigGetPwAuth(const WOLFSSHD_CONFIG* conf); diff --git a/apps/wolfsshd/wolfsshd.c b/apps/wolfsshd/wolfsshd.c index 7c27c4ee..ad289589 100644 --- a/apps/wolfsshd/wolfsshd.c +++ b/apps/wolfsshd/wolfsshd.c @@ -650,6 +650,8 @@ static void* HandleConnection(void* arg) if (conn != NULL) { WCLOSESOCKET(conn->fd); } + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Return from closing connection = %d", ret); + return NULL; } From 87a9bd43256429302d596738a05193a05b34a47f Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Sat, 30 Jul 2022 00:46:11 -0700 Subject: [PATCH 37/48] cleanup some debug messages and start to actual daemon --- apps/wolfsshd/configuration.c | 3 +- apps/wolfsshd/wolfsshd.c | 127 ++++++++++++++++++++++++++-------- 2 files changed, 99 insertions(+), 31 deletions(-) diff --git a/apps/wolfsshd/configuration.c b/apps/wolfsshd/configuration.c index 0c28a37d..1c6fa95d 100644 --- a/apps/wolfsshd/configuration.c +++ b/apps/wolfsshd/configuration.c @@ -154,7 +154,7 @@ WOLFSSHD_CONFIG* wolfSSHD_ConfigNew(void* heap) ret = (WOLFSSHD_CONFIG*)WMALLOC(sizeof(WOLFSSHD_CONFIG), heap, DYNTYPE_SSHD); if (ret == NULL) { - printf("issue mallocing config structure for sshd\n"); + fprintf(stderr, "Issue malloc'ing config structure for sshd\n"); } else { WMEMSET(ret, 0, sizeof(WOLFSSHD_CONFIG)); @@ -586,7 +586,6 @@ int wolfSSHD_ConfigLoad(WOLFSSHD_CONFIG* conf, const char* filename) } if (current[0] == '#') { - //printf("read commented out line\n%s\n", current); continue; /* commented out line */ } diff --git a/apps/wolfsshd/wolfsshd.c b/apps/wolfsshd/wolfsshd.c index ad289589..d8a7c497 100644 --- a/apps/wolfsshd/wolfsshd.c +++ b/apps/wolfsshd/wolfsshd.c @@ -63,6 +63,7 @@ #endif #include #include + #include #if defined(__QNX__) || defined(__QNXNTO__) #include #include @@ -76,9 +77,21 @@ (void)sig; ChildRunning = 0; } + + static void ConnClose(int sig) + { + pid_t p; + int ret; + p = wait(&ret); + if (p == 0 || p == -1) + return; /* parent or error state*/ + (void)ret; + (void)sig; + } #endif /* WOLFSSH_SHELL */ static volatile byte debugMode = 0; /* default to off */ +static FILE* logFile = NULL; /* catch interrupts and close down gracefully */ static volatile byte quit = 0; @@ -98,24 +111,38 @@ static void ShowUsage(void) printf(" -f Configuration file to use, default is /usr/local/etc/ssh/sshd_config\n"); printf(" -p Port number to listen on\n"); printf(" -d Turn on debug mode\n"); + printf(" -D Run in foreground (do not detach)\n"); printf(" -h host private key file to use\n"); + printf(" -E append to log file\n"); } static void interruptCatch(int in) { (void)in; - printf("Closing down wolfSSHD\n"); + if (logFile) + fprintf(logFile, "Closing down wolfSSHD\n"); quit = 1; } static void wolfSSHDLoggingCb(enum wolfSSH_LogLevel lvl, const char *const str) { if (debugMode) { - fprintf(stderr, "[PID %d]: %s\n", getpid(), str); + fprintf(logFile, "[PID %d]: %s\n", getpid(), str); } (void)lvl; } + +static void CleanupCTX(WOLFSSHD_CONFIG* conf, WOLFSSH_CTX** ctx) +{ + if (ctx != NULL && *ctx != NULL) { + wolfSSH_CTX_free(*ctx); + *ctx = NULL; + } + (void)conf; +} + + static int SetupCTX(WOLFSSHD_CONFIG* conf, WOLFSSH_CTX** ctx) { int ret = WS_SUCCESS; @@ -294,13 +321,6 @@ static int SFTP_Subsystem(WOLFSSH* ssh, WOLFSSHD_CONNECTION* conn) sockfd = (WS_SOCKET_T)wolfSSH_get_fd(ssh); do { -// if (threadCtx->nonBlock) { -// if (error == WS_WANT_READ) -// printf("... sftp server would read block\n"); -// else if (error == WS_WANT_WRITE) -// printf("... sftp server would write block\n"); -// } - if (wolfSSH_stream_peek(ssh, tmp, 1) > 0) { select_ret = WS_SELECT_RECV_READY; } @@ -394,7 +414,8 @@ static int SHELL_Subsystem(WOLFSSHD_CONNECTION* conn, WOLFSSH* ssh) char cmd[MAX_COMMAND_SZ]; int ret; - signal(SIGINT, SIG_DFL); + signal(SIGINT, SIG_DFL); + signal(SIGCHLD, SIG_DFL); setenv("HOME", p_passwd->pw_dir, 1); setenv("LOGNAME", p_passwd->pw_name, 1); @@ -435,6 +456,7 @@ static int SHELL_Subsystem(WOLFSSHD_CONNECTION* conn, WOLFSSH* ssh) struct termios tios; word32 shellChannelId = 0; signal(SIGCHLD, ChildSig); + signal(SIGINT, SIG_DFL); rc = tcgetattr(childFd, &tios); if (rc != 0) { @@ -668,12 +690,16 @@ static int NewConnection(WOLFSSHD_CONNECTION* conn) ret = -1; } - if (pd == 0) { - /* child process */ - (void)HandleConnection((void*)conn); - } - else { - wolfSSH_Log(WS_LOG_INFO, "[SSHD] Spawned new process %d\n", pd); + if (ret == WS_SUCCESS) { + if (pd == 0) { + /* child process */ + signal(SIGINT, SIG_DFL); + (void)HandleConnection((void*)conn); + exit(0); + } + else { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Spawned new process %d\n", pd); + } } return ret; @@ -696,23 +722,25 @@ static int PendingConnection(WS_SOCKET_T fd) FD_ZERO(&e); FD_SET(fd, &r); + errno = 0; ret = select(nfds, &r, &w, &e, &t); if (ret < 0) { - /* a socket level issue happend */ - printf("Error waiting for connection on socket\n"); - quit = 1; + /* a socket level issue happend, could just be a system call int. */ + if (errno != EINTR) { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] TCP socket error on select()"); + quit = 1; + } ret = 0; } else if (ret > 0) { if (FD_ISSET(fd, &r)) { - printf("Connection found\n"); + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Incoming TCP data found"); } else { - printf("Found write or error data\n"); + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Found TCP write or error data"); ret = 0; /* nothing to read */ } } - // printf("Timeout waiting for connection\n"); return ret; } @@ -729,6 +757,7 @@ int main(int argc, char** argv) WOLFSSHD_CONFIG* conf = NULL; WOLFSSHD_AUTH* auth = NULL; WOLFSSH_CTX* ctx = NULL; + byte isDaemon = 1; const char* configFile = "/usr/local/etc/ssh/sshd_config"; const char* hostKeyFile = NULL; @@ -754,7 +783,7 @@ int main(int argc, char** argv) } } - while ((ch = mygetopt(argc, argv, "?f:p:h:d")) != -1) { + while ((ch = mygetopt(argc, argv, "?f:p:h:dDE:")) != -1) { switch (ch) { case 'f': configFile = myoptarg; @@ -764,7 +793,8 @@ int main(int argc, char** argv) if (ret == WS_SUCCESS) { ret = XATOI(myoptarg); if (ret < 0) { - printf("Issue parsing port number %s\n", myoptarg); + fprintf(stderr, "Issue parsing port number %s\n", + myoptarg); ret = WS_BAD_ARGUMENT; } else { @@ -773,7 +803,7 @@ int main(int argc, char** argv) ret = WS_SUCCESS; } else { - printf("Port number %d too big.\n", ret); + fprintf(stderr, "Port number %d too big.\n", ret); ret = WS_BAD_ARGUMENT; } } @@ -788,6 +818,18 @@ int main(int argc, char** argv) debugMode = 1; /* turn on debug mode */ break; + case 'D': + isDaemon = 0; + break; + + case 'E': + logFile = fopen(myoptarg, "ab"); + if (logFile == NULL) { + fprintf(stderr, "Unable to open log file %s\n", myoptarg); + ret = WS_FATAL_ERROR; + } + break; + case '?': ShowUsage(); return WS_SUCCESS; @@ -801,11 +843,11 @@ int main(int argc, char** argv) if (ret == WS_SUCCESS) { ret = wolfSSHD_ConfigLoad(conf, configFile); if (ret != WS_SUCCESS) - printf("Error reading in configure file %s\n", configFile); + fprintf(stderr, "Error reading in configure file %s\n", configFile); } /* port was not overridden with argument, read from config file */ - if (port == 0) { + if (ret == WS_SUCCESS && port == 0) { port = wolfSSHD_ConfigGetPort(conf); } @@ -814,9 +856,8 @@ int main(int argc, char** argv) wolfSSHD_ConfigSetHostKeyFile(conf, hostKeyFile); } - wolfSSH_Log(WS_LOG_INFO, "[SSHD] Starting wolfSSH SSHD application"); - if (ret == WS_SUCCESS) { + wolfSSH_Log(WS_LOG_INFO, "[SSHD] Starting wolfSSH SSHD application"); ret = SetupCTX(conf, &ctx); } else { @@ -839,6 +880,33 @@ int main(int argc, char** argv) } } + if (logFile == NULL) { + logFile = stderr; + } + + /* run as a daemon */ + if (ret == WS_SUCCESS && isDaemon) { + pid_t p; + + p = fork(); + if (p < 0) { + fprintf(stderr, "Failed to fork process\n"); + ret = WS_FATAL_ERROR; + } + + if (ret == WS_SUCCESS) { + if (p > 0) { + exit(0); /* stop parent process */ + } + + if (setsid() < 0) { + fprintf(stderr, "Failed to set a new session"); + ret = WS_FATAL_ERROR; + } + } + } + + signal(SIGCHLD, ConnClose); if (ret == WS_SUCCESS) { wolfSSH_Log(WS_LOG_INFO, "[SSHD] Starting to listen on port %d", port); tcp_listen(&listenFd, &port, 1); @@ -889,6 +957,7 @@ int main(int argc, char** argv) } } + CleanupCTX(conf, &ctx); wolfSSHD_ConfigFree(conf); wolfSSHD_AuthFreeUser(auth); wolfSSH_Cleanup(); From 7d58486a4289ecc37cd4dc3596d4a3f8106d7092 Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Sat, 30 Jul 2022 01:26:56 -0700 Subject: [PATCH 38/48] QNX shell login as user --- apps/wolfsshd/wolfsshd.c | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/apps/wolfsshd/wolfsshd.c b/apps/wolfsshd/wolfsshd.c index d8a7c497..f2662469 100644 --- a/apps/wolfsshd/wolfsshd.c +++ b/apps/wolfsshd/wolfsshd.c @@ -427,12 +427,22 @@ static int SHELL_Subsystem(WOLFSSHD_CONNECTION* conn, WOLFSSH* ssh) /* default to /bin/sh if user shell is not set */ WMEMSET(cmd, 0, sizeof(cmd)); if (XSTRLEN(p_passwd->pw_shell) == 0) { - XSNPRINTF(cmd, sizeof(cmd), "sudo runuser -u %s -- %s", userName, + #if defined(__QNX__) || defined(__QNXNTO__) + XSNPRINTF(cmd, sizeof(cmd), "su - %s -c %s", userName, "/bin/sh"); + #else + XSNPRINTF(cmd, sizeof(cmd), "runuser -u %s -- %s", userName, + "/bin/sh"); + #endif } else { - XSNPRINTF(cmd, sizeof(cmd), "sudo runuser -u %s -- %s", userName, + #if defined(__QNX__) || defined(__QNXNTO__) + XSNPRINTF(cmd, sizeof(cmd), "su - %s -c %s", userName, p_passwd->pw_shell); + #else + XSNPRINTF(cmd, sizeof(cmd), "runuser -u %s -- %s", userName, + p_passwd->pw_shell); + #endif } errno = 0; @@ -772,6 +782,7 @@ int main(int argc, char** argv) wolfSSL_Debugging_ON(); #endif + logFile = stderr; if (ret == WS_SUCCESS) { wolfSSH_Init(); } From f51375802bb0d44302910a494746ba8fdd70c985 Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Wed, 3 Aug 2022 15:04:34 -0700 Subject: [PATCH 39/48] add more comments and always print out error messages --- apps/wolfsshd/auth.c | 129 ++++++---------------------------- apps/wolfsshd/configuration.c | 17 +++++ apps/wolfsshd/wolfsshd.c | 55 +++++++-------- src/log.c | 10 +-- 4 files changed, 71 insertions(+), 140 deletions(-) diff --git a/apps/wolfsshd/auth.c b/apps/wolfsshd/auth.c index e5f799f2..2205680e 100644 --- a/apps/wolfsshd/auth.c +++ b/apps/wolfsshd/auth.c @@ -60,12 +60,16 @@ struct WOLFSSHD_AUTH { const WOLFSSHD_CONFIG* conf; int gid; int uid; + int attempts; void* heap; }; +#ifndef WOLFSSHD_MAX_PASSWORD_ATTEMPTS + #define WOLFSSHD_MAX_PASSWORD_ATTEMPTS 3 +#endif #if 0 -static byte passwdRetry = 3; +/* this could potentially be useful in a deeply embeded future port */ /* Map user names to passwords */ /* Use arrays for username and p. The password or public key can @@ -107,105 +111,6 @@ USER_NODE* AddNewUser(USER_NODE* list, byte type, const byte* username, return map; } - -int DefaultUserAuth(byte authType, WS_UserAuthData* authData, void* ctx) -{ - USER_NODE* map; - byte authHash[WC_SHA256_DIGEST_SIZE]; - int ret; - - if (authType != WOLFSSH_USERAUTH_PASSWORD && -#ifdef WOLFSSH_ALLOW_USERAUTH_NONE - authType != WOLFSSH_USERAUTH_NONE && -#endif - authType != WOLFSSH_USERAUTH_PUBLICKEY) { - - return WOLFSSH_USERAUTH_FAILURE; - } - map = (USER_NODE*)ctx; - - /* check if password on system */ - if (authData->type == WOLFSSH_USERAUTH_PASSWORD) { - if (CheckPassword(authData->username, authData->sf.password.password, - authData->sf.password.passwordSz) == WS_SUCCESS) { - wolfSSH_Log(WS_LOG_INFO, "[SSHD] Password and user on system"); - return WOLFSSH_USERAUTH_SUCCESS; - } - } - - if (authType == WOLFSSH_USERAUTH_PASSWORD) { - wc_Sha256Hash(authData->sf.password.password, - authData->sf.password.passwordSz, - authHash); - } - else if (authType == WOLFSSH_USERAUTH_PUBLICKEY) { - wc_Sha256Hash(authData->sf.publicKey.publicKey, - authData->sf.publicKey.publicKeySz, - authHash); - } - - while (map != NULL) { - if (authData->usernameSz == map->usernameSz && - WMEMCMP(authData->username, map->username, map->usernameSz) == 0 && - authData->type == map->type) { - - if (authData->type == WOLFSSH_USERAUTH_PUBLICKEY) { - if (WMEMCMP(map->fingerprint, authHash, - WC_SHA256_DIGEST_SIZE) == 0) { - return WOLFSSH_USERAUTH_SUCCESS; - } - else { - return WOLFSSH_USERAUTH_INVALID_PUBLICKEY; - } - } - else if (authData->type == WOLFSSH_USERAUTH_PASSWORD) { - if (WMEMCMP(map->fingerprint, authHash, - WC_SHA256_DIGEST_SIZE) == 0) { - return WOLFSSH_USERAUTH_SUCCESS; - } - else { - passwdRetry--; - return (passwdRetry > 0) ? - WOLFSSH_USERAUTH_INVALID_PASSWORD : - WOLFSSH_USERAUTH_REJECTED; - } - } -#ifdef WOLFSSH_ALLOW_USERAUTH_NONE - else if (authData->type == WOLFSSH_USERAUTH_NONE) { - return WOLFSSH_USERAUTH_SUCCESS; - } -#endif /* WOLFSSH_ALLOW_USERAUTH_NONE */ - else { - return WOLFSSH_USERAUTH_INVALID_AUTHTYPE; - } - - if (authData->type == map->type) { - if (WMEMCMP(map->fingerprint, authHash, - WC_SHA256_DIGEST_SIZE) == 0) { - return WOLFSSH_USERAUTH_SUCCESS; - } - else { - if (authType == WOLFSSH_USERAUTH_PASSWORD) { - passwdRetry--; - ret = (passwdRetry > 0) ? - WOLFSSH_USERAUTH_INVALID_PASSWORD : - WOLFSSH_USERAUTH_REJECTED; - } - else { - ret = WOLFSSH_USERAUTH_INVALID_PUBLICKEY; - } - return ret; - } - } - else { - return WOLFSSH_USERAUTH_INVALID_AUTHTYPE; - } - } - map = map->next; - } - - return WOLFSSH_USERAUTH_INVALID_USER; -} #endif enum { @@ -631,6 +536,7 @@ static int CheckPublicKeyUnix(const char* name, const byte* key, word32 keySz) #endif /* !_WIN32*/ +/* return WOLFSSH_USERAUTH_SUCCESS on success */ static int DoCheckUser(const char* usr, WOLFSSHD_AUTH* auth) { int ret = WOLFSSH_USERAUTH_FAILURE; @@ -674,7 +580,7 @@ static int RequestAuthentication(const char* usr, int type, const byte* data, ret = DoCheckUser(usr, auth); /* temporarily elevate permissions */ if (ret == WOLFSSH_USERAUTH_SUCCESS && - wolfSSHD_AuthRaisePermissions(auth) != 0) { + wolfSSHD_AuthRaisePermissions(auth) != WS_SUCCESS) { wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Failure to raise permissions for auth"); ret = WOLFSSH_USERAUTH_FAILURE; } @@ -689,7 +595,8 @@ static int RequestAuthentication(const char* usr, int type, const byte* data, } /* Check if password is valid for this user. */ /* first handle empty password cases */ - else if (dataSz == 0 && wolfSSHD_ConfigGetPermitEmptyPw(auth->conf) != 1) { + else if (dataSz == 0 && wolfSSHD_ConfigGetPermitEmptyPw(auth->conf) + != 1) { wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Empty passwords not allowed by " "configuration!"); ret = WOLFSSH_USERAUTH_FAILURE; @@ -702,6 +609,13 @@ static int RequestAuthentication(const char* usr, int type, const byte* data, else if (rc == WSSHD_AUTH_FAILURE) { wolfSSH_Log(WS_LOG_INFO, "[SSHD] Password incorrect."); ret = WOLFSSH_USERAUTH_INVALID_PASSWORD; + + auth->attempts--; + if (auth->attempts == 0) { + wolfSSH_Log(WS_LOG_ERROR, + "[SSHD] Too many bad password attempts!"); + ret = WOLFSSH_USERAUTH_REJECTED; + } } else { wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Error checking password."); @@ -730,7 +644,7 @@ static int RequestAuthentication(const char* usr, int type, const byte* data, } - if (wolfSSHD_AuthReducePermissions(auth) != 0) { + if (wolfSSHD_AuthReducePermissions(auth) != WS_SUCCESS) { /* stop everything if not able to reduce permissions level */ exit(1); } @@ -738,6 +652,7 @@ static int RequestAuthentication(const char* usr, int type, const byte* data, } +/* return WOLFSSH_USERAUTH_SUCCESS on success */ int DefaultUserAuth(byte authType, WS_UserAuthData* authData, void* ctx) { int ret = WOLFSSH_USERAUTH_SUCCESS; @@ -856,6 +771,7 @@ WOLFSSHD_AUTH* wolfSSHD_AuthCreateUser(void* heap, const WOLFSSHD_CONFIG* conf) auth->heap = heap; auth->conf = conf; + auth->attempts = WOLFSSHD_MAX_PASSWORD_ATTEMPTS; /* set the default user checking based on build */ ret = SetDefaultUserCheck(auth); @@ -917,7 +833,7 @@ int wolfSSHD_AuthFreeUser(WOLFSSHD_AUTH* auth) } -/* return 0 on success */ +/* return WS_SUCCESS on success */ int wolfSSHD_AuthRaisePermissions(WOLFSSHD_AUTH* auth) { int ret = 0; @@ -942,11 +858,11 @@ int wolfSSHD_AuthRaisePermissions(WOLFSSHD_AUTH* auth) } -/* return 0 on success */ +/* return WS_SUCCESS on success */ int wolfSSHD_AuthReducePermissions(WOLFSSHD_AUTH* auth) { byte flag = 0; - int ret = 0; + int ret = WS_SUCCESS; flag = wolfSSHD_ConfigGetPrivilegeSeparation(auth->conf); if (flag == WOLFSSHD_PRIV_SEPARAT || flag == WOLFSSHD_PRIV_SANDBOX) { @@ -969,6 +885,7 @@ int wolfSSHD_AuthReducePermissions(WOLFSSHD_AUTH* auth) return ret; } +/* return the time in seconds for grace timeout period */ long wolfSSHD_AuthGetGraceTime(const WOLFSSHD_AUTH* auth) { long ret = WS_BAD_ARGUMENT; diff --git a/apps/wolfsshd/configuration.c b/apps/wolfsshd/configuration.c index 1c6fa95d..181fdb86 100644 --- a/apps/wolfsshd/configuration.c +++ b/apps/wolfsshd/configuration.c @@ -147,6 +147,8 @@ static void FreeString(char** in, void* heap) (void)heap; } + +/* returns a new WOLFSSHD_CONFIG on success and NULL on failure */ WOLFSSHD_CONFIG* wolfSSHD_ConfigNew(void* heap) { WOLFSSHD_CONFIG* ret; @@ -229,6 +231,7 @@ static const CONFIG_OPTION options[NUM_OPTIONS] = { {OPT_USE_DNS, "UseDNS"} }; +/* returns WS_SUCCESS on success */ static int HandlePrivSep(WOLFSSHD_CONFIG* conf, const char* value) { int ret = WS_SUCCESS; @@ -261,6 +264,7 @@ static int HandlePrivSep(WOLFSSHD_CONFIG* conf, const char* value) return ret; } +/* returns WS_SUCCESS on success */ static int HandleLoginGraceTime(WOLFSSHD_CONFIG* conf, const char* value) { int ret = WS_SUCCESS; @@ -287,6 +291,7 @@ static int HandleLoginGraceTime(WOLFSSHD_CONFIG* conf, const char* value) return ret; } +/* returns WS_SUCCESS on success */ static int HandlePermitEmptyPw(WOLFSSHD_CONFIG* conf, const char* value) { int ret = WS_SUCCESS; @@ -310,6 +315,7 @@ static int HandlePermitEmptyPw(WOLFSSHD_CONFIG* conf, const char* value) return ret; } +/* returns WS_SUCCESS on success */ static int HandlePermitRoot(WOLFSSHD_CONFIG* conf, const char* value) { int ret = WS_SUCCESS; @@ -333,6 +339,7 @@ static int HandlePermitRoot(WOLFSSHD_CONFIG* conf, const char* value) return ret; } +/* returns WS_SUCCESS on success */ static int HandlePwAuth(WOLFSSHD_CONFIG* conf, const char* value) { int ret = WS_SUCCESS; @@ -357,6 +364,8 @@ static int HandlePwAuth(WOLFSSHD_CONFIG* conf, const char* value) } #define WOLFSSH_PROTOCOL_VERSION 2 + +/* returns WS_SUCCESS on success */ static int HandleProtocol(WOLFSSHD_CONFIG* conf, const char* value) { int ret = WS_SUCCESS; @@ -385,6 +394,7 @@ static int HandleProtocol(WOLFSSHD_CONFIG* conf, const char* value) return ret; } +/* returns WS_SUCCESS on success */ static int HandlePort(WOLFSSHD_CONFIG* conf, const char* value) { int ret = WS_SUCCESS; @@ -416,6 +426,8 @@ static int HandlePort(WOLFSSHD_CONFIG* conf, const char* value) return ret; } + +/* returns WS_SUCCESS on success */ static int HandleConfigOption(WOLFSSHD_CONFIG* conf, int opt, const char* value) { int ret = WS_BAD_ARGUMENT; @@ -485,6 +497,8 @@ static int HandleConfigOption(WOLFSSHD_CONFIG* conf, int opt, const char* value) return ret; } +/* helper function to count white spaces, returns the number of white spaces on + * success */ static int CountWhitespace(const char* in, int inSz, byte inv) { int i = 0; @@ -554,6 +568,9 @@ WOLFSSHD_STATIC int ParseConfigLine(WOLFSSHD_CONFIG* conf, const char* l, } +/* parses and loads in the given configuration file 'filename' + * returns WS_SUCCESS on success + */ int wolfSSHD_ConfigLoad(WOLFSSHD_CONFIG* conf, const char* filename) { XFILE f; diff --git a/apps/wolfsshd/wolfsshd.c b/apps/wolfsshd/wolfsshd.c index f2662469..21daeebf 100644 --- a/apps/wolfsshd/wolfsshd.c +++ b/apps/wolfsshd/wolfsshd.c @@ -102,13 +102,14 @@ typedef struct WOLFSSHD_CONNECTION { WOLFSSH_CTX* ctx; WOLFSSHD_AUTH* auth; int fd; + char ip[INET_ADDRSTRLEN]; } WOLFSSHD_CONNECTION; static void ShowUsage(void) { printf("wolfsshd %s\n", LIBWOLFSSH_VERSION_STRING); printf(" -? display this help and exit\n"); - printf(" -f Configuration file to use, default is /usr/local/etc/ssh/sshd_config\n"); + printf(" -f Configuration file to use, default is /etc/ssh/sshd_config\n"); printf(" -p Port number to listen on\n"); printf(" -d Turn on debug mode\n"); printf(" -D Run in foreground (do not detach)\n"); @@ -116,6 +117,8 @@ static void ShowUsage(void) printf(" -E append to log file\n"); } + +/* catch if interupted */ static void interruptCatch(int in) { (void)in; @@ -124,15 +127,21 @@ static void interruptCatch(int in) quit = 1; } + +/* redirect logging to a specific file and add the PID value */ static void wolfSSHDLoggingCb(enum wolfSSH_LogLevel lvl, const char *const str) { - if (debugMode) { + /* always log errors and optionally log other info/debug level messages */ + if (lvl == WS_LOG_ERROR) { + fprintf(logFile, "[PID %d]: %s\n", getpid(), str); + } + else if (debugMode) { fprintf(logFile, "[PID %d]: %s\n", getpid(), str); } - (void)lvl; } +/* Frees up the WOLFSSH_CTX struct */ static void CleanupCTX(WOLFSSHD_CONFIG* conf, WOLFSSH_CTX** ctx) { if (ctx != NULL && *ctx != NULL) { @@ -143,6 +152,9 @@ static void CleanupCTX(WOLFSSHD_CONFIG* conf, WOLFSSH_CTX** ctx) } +/* Initializes and sets up the WOLFSSH_CTX struct based on the configure options + * return WS_SUCCESS on success + */ static int SetupCTX(WOLFSSHD_CONFIG* conf, WOLFSSH_CTX** ctx) { int ret = WS_SUCCESS; @@ -172,24 +184,6 @@ static int SetupCTX(WOLFSSHD_CONFIG* conf, WOLFSSH_CTX** ctx) wolfSSH_CTX_SetBanner(*ctx, banner); } -#ifdef WOLFSSH_AGENT - /* check if using an agent is enabled */ - /* TODO: doesn't work - if (ret == WS_SUCCESS) { - wolfSSH_CTX_set_agent_cb(ctx, wolfSSH_AGENT_DefaultActions, NULL); - } - */ -#endif - -#ifdef WOLFSSH_FWD - /* check if port forwarding is enabled */ - /* TODO: doesn't work - if (ret == WS_SUCCESS) { - wolfSSH_CTX_SetFwdCb(ctx, wolfSSH_FwdDefaultActions, NULL); - } - */ -#endif - /* Load in host private key */ if (ret == WS_SUCCESS) { @@ -384,7 +378,7 @@ static int SHELL_Subsystem(WOLFSSHD_CONNECTION* conn, WOLFSSH* ssh) userName = wolfSSH_GetUsername(ssh); /* temporarily elevate permissions to get users information */ - if (wolfSSHD_AuthRaisePermissions(conn->auth) != 0) { + if (wolfSSHD_AuthRaisePermissions(conn->auth) != WS_SUCCESS) { wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Failure to raise permissions for auth"); return WS_FATAL_ERROR; } @@ -393,7 +387,7 @@ static int SHELL_Subsystem(WOLFSSHD_CONNECTION* conn, WOLFSSH* ssh) if (p_passwd == NULL) { /* Not actually a user on the system. */ wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Invalid user name found"); - if (wolfSSHD_AuthReducePermissions(conn->auth) != 0) { + if (wolfSSHD_AuthReducePermissions(conn->auth) != WS_SUCCESS) { /* stop everything if not able to reduce permissions level */ exit(1); } @@ -454,7 +448,7 @@ static int SHELL_Subsystem(WOLFSSHD_CONNECTION* conn, WOLFSSH* ssh) exit(0); /* exit child process and close down SSH connection */ } - if (wolfSSHD_AuthReducePermissions(conn->auth) != 0) { + if (wolfSSHD_AuthReducePermissions(conn->auth) != WS_SUCCESS) { /* stop everything if not able to reduce permissions level */ wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Issue reducing permissions level," " exiting now"); @@ -628,7 +622,8 @@ static void* HandleConnection(void* arg) if (ret != WS_SUCCESS && ret != WS_SFTP_COMPLETE) { wolfSSH_Log(WS_LOG_ERROR, - "[SSHD] Failed to accept WOLFSSH connection"); + "[SSHD] Failed to accept WOLFSSH connection from %s", + conn->ip); } } @@ -769,15 +764,13 @@ int main(int argc, char** argv) WOLFSSH_CTX* ctx = NULL; byte isDaemon = 1; - const char* configFile = "/usr/local/etc/ssh/sshd_config"; + const char* configFile = "/etc/ssh/sshd_config"; const char* hostKeyFile = NULL; signal(SIGINT, interruptCatch); wolfSSH_SetLoggingCb(wolfSSHDLoggingCb); -#ifdef DEBUG_WOLFSSH wolfSSH_Debugging_ON(); -#endif #ifdef DEBUG_WOLFSSL wolfSSL_Debugging_ON(); #endif @@ -885,7 +878,7 @@ int main(int argc, char** argv) /* seperate privlage permisions */ if (ret == WS_SUCCESS) { - if (wolfSSHD_AuthReducePermissions(auth) != 0) { + if (wolfSSHD_AuthReducePermissions(auth) != WS_SUCCESS) { wolfSSH_Log(WS_LOG_INFO, "[SSHD] Error lowering permissions level"); ret = WS_FATAL_ERROR; } @@ -942,6 +935,10 @@ int main(int argc, char** argv) #else conn.fd = accept(listenFd, (struct sockaddr*)&clientAddr, &clientAddrSz); + if (conn.fd >= 0) { + inet_ntop(AF_INET, &clientAddr.sin_addr, conn.ip, + INET_ADDRSTRLEN); + } #endif { diff --git a/src/log.c b/src/log.c index 45621f1d..e67ac970 100644 --- a/src/log.c +++ b/src/log.c @@ -57,7 +57,7 @@ #endif /* WOLFSSH_NO_DEFAULT_LOGGING_CB */ -#ifdef DEBUG_WOLFSSH +#if defined(DEBUG_WOLFSSH) || defined(WOLFSSH_SSHD) static enum wolfSSH_LogLevel logLevel = WS_LOG_DEFAULT; static int logEnable = 0; #endif @@ -66,7 +66,7 @@ /* turn debugging on if supported */ void wolfSSH_Debugging_ON(void) { -#ifdef DEBUG_WOLFSSH +#if defined(DEBUG_WOLFSSH) || defined(WOLFSSH_SSHD) logEnable = 1; #endif } @@ -75,7 +75,7 @@ void wolfSSH_Debugging_ON(void) /* turn debugging off */ void wolfSSH_Debugging_OFF(void) { -#ifdef DEBUG_WOLFSSH +#if defined(DEBUG_WOLFSSH) || defined(WOLFSSH_SSHD) logEnable = 0; #endif } @@ -91,7 +91,7 @@ void wolfSSH_SetLoggingCb(wolfSSH_LoggingCb logF) int wolfSSH_LogEnabled(void) { -#ifdef DEBUG_WOLFSSH +#if defined(DEBUG_WOLFSSH) || defined(WOLFSSH_SSHD) return logEnable; #else return 0; @@ -99,7 +99,7 @@ int wolfSSH_LogEnabled(void) } -#ifdef DEBUG_WOLFSSH +#if defined(DEBUG_WOLFSSH) || defined(WOLFSSH_SSHD) #ifndef WOLFSSH_NO_DEFAULT_LOGGING_CB /* log level string */ static const char* GetLogStr(enum wolfSSH_LogLevel level) From 8f3cdc8230a8c29350ecd63fb61acc584a6775f7 Mon Sep 17 00:00:00 2001 From: Jacob Barthelmeh Date: Fri, 5 Aug 2022 12:05:07 -0600 Subject: [PATCH 40/48] infer fixes, clang build fixes, initial build on OSX --- apps/wolfsshd/auth.c | 13 +++++++++++-- apps/wolfsshd/configuration.c | 14 +++++++------- apps/wolfsshd/test/test_configuration.c | 20 +++++++++++++++++--- apps/wolfsshd/wolfsshd.c | 8 ++++++-- configure.ac | 3 +++ 5 files changed, 44 insertions(+), 14 deletions(-) diff --git a/apps/wolfsshd/auth.c b/apps/wolfsshd/auth.c index 2205680e..26918f9a 100644 --- a/apps/wolfsshd/auth.c +++ b/apps/wolfsshd/auth.c @@ -49,10 +49,14 @@ #ifndef _WIN32 #include #include -#include #include #endif +#if !defined(_WIN32) && !(defined(__OSX__) || defined(__APPLE__)) +#include +#define HAVE_SHADOW +#endif + struct WOLFSSHD_AUTH { CallbackCheckUser CheckUserCb; CallbackCheckPassword CheckPasswordCb; @@ -289,7 +293,9 @@ static int CheckPasswordUnix(const char* usr, const byte* pw, word32 pwSz) int ret = WS_SUCCESS; char* pwStr = NULL; struct passwd* pwInfo; +#ifdef HAVE_SHADOW struct spwd* shadowInfo; +#endif /* The hash of the user's password stored on the system. */ char* storedHash; char* storedHashCpy = NULL; @@ -318,6 +324,7 @@ static int CheckPasswordUnix(const char* usr, const byte* pw, word32 pwSz) } if (ret == WS_SUCCESS) { + #ifdef HAVE_SHADOW if (pwInfo->pw_passwd[0] == 'x') { #ifdef WOLFSSH_HAVE_LIBCRYPT shadowInfo = getspnam((const char*)usr); @@ -336,7 +343,9 @@ static int CheckPasswordUnix(const char* usr, const byte* pw, word32 pwSz) storedHash = shadowInfo->sp_pwdp; } } - else { + else + #endif + { storedHash = pwInfo->pw_passwd; } } diff --git a/apps/wolfsshd/configuration.c b/apps/wolfsshd/configuration.c index 181fdb86..73be8063 100644 --- a/apps/wolfsshd/configuration.c +++ b/apps/wolfsshd/configuration.c @@ -275,11 +275,11 @@ static int HandleLoginGraceTime(WOLFSSHD_CONFIG* conf, const char* value) } if (ret == WS_SUCCESS) { - num = GetConfigInt(value, XSTRLEN(value), 1, conf->heap); + num = GetConfigInt(value, (int)XSTRLEN(value), 1, conf->heap); if (num < 0) { wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Issue getting login grace " "time"); - ret = num; + ret = (int)num; } else { conf->loginTimer = num; @@ -376,7 +376,7 @@ static int HandleProtocol(WOLFSSHD_CONFIG* conf, const char* value) } if (ret == WS_SUCCESS) { - portInt = GetConfigInt(value, WSTRLEN(value), 0, conf->heap); + portInt = GetConfigInt(value, (int)WSTRLEN(value), 0, conf->heap); if (portInt <= 0) { wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Invalid protocol number: %s.", value); @@ -405,7 +405,7 @@ static int HandlePort(WOLFSSHD_CONFIG* conf, const char* value) } if (ret == WS_SUCCESS) { - portInt = GetConfigInt(value, WSTRLEN(value), 0, conf->heap); + portInt = GetConfigInt(value, (int)WSTRLEN(value), 0, conf->heap); if (portInt <= 0) { wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Invalid port number: %s.", value); @@ -528,7 +528,7 @@ WOLFSSHD_STATIC int ParseConfigLine(WOLFSSHD_CONFIG* conf, const char* l, int lSz) { int ret = WS_BAD_ARGUMENT; - int sz; + int sz = 0; char tmp[MAX_FILENAME_SZ]; int idx; const CONFIG_OPTION* found = NULL; @@ -646,7 +646,7 @@ int wolfSSHD_ConfigSetAuthKeysFile(WOLFSSHD_CONFIG* conf, const char* file) if (file != NULL) { ret = CreateString(&conf->authKeysFile, file, - WSTRLEN(file), conf->heap); + (int)WSTRLEN(file), conf->heap); } } @@ -691,7 +691,7 @@ int wolfSSHD_ConfigSetHostKeyFile(WOLFSSHD_CONFIG* conf, const char* file) if (file != NULL) { ret = CreateString(&conf->hostKeyFile, file, - WSTRLEN(file), conf->heap); + (int)WSTRLEN(file), conf->heap); } } diff --git a/apps/wolfsshd/test/test_configuration.c b/apps/wolfsshd/test/test_configuration.c index c671803c..4b1fe5b7 100644 --- a/apps/wolfsshd/test/test_configuration.c +++ b/apps/wolfsshd/test/test_configuration.c @@ -3,12 +3,26 @@ #include #include -static void Log(const char* fmt, ...) +#ifndef WOLFSSH_DEFAULT_LOG_WIDTH + #define WOLFSSH_DEFAULT_LOG_WIDTH 120 +#endif + +#undef FMTCHECK +#ifdef __GNUC__ + #define FMTCHECK __attribute__((format(printf,1,2))) +#else + #define FMTCHECK +#endif /* __GNUC__ */ + + +void Log(const char *const, ...) FMTCHECK; +void Log(const char *const fmt, ...) { va_list vlist; + char msgStr[WOLFSSH_DEFAULT_LOG_WIDTH]; va_start(vlist, fmt); - vfprintf(stderr, fmt, vlist); + WVSNPRINTF(msgStr, sizeof(msgStr), fmt, vlist); va_end(vlist); } @@ -109,7 +123,7 @@ static int test_ParseConfigLine(void) Log(" Testing scenario: %s.", vectors[i].desc); ret = ParseConfigLine(conf, vectors[i].line, - WSTRLEN(vectors[i].line)); + (int)WSTRLEN(vectors[i].line)); if ((ret == WS_SUCCESS && !vectors[i].shouldFail) || (ret != WS_SUCCESS && vectors[i].shouldFail)) { diff --git a/apps/wolfsshd/wolfsshd.c b/apps/wolfsshd/wolfsshd.c index 21daeebf..8a21c3e5 100644 --- a/apps/wolfsshd/wolfsshd.c +++ b/apps/wolfsshd/wolfsshd.c @@ -376,10 +376,14 @@ static int SHELL_Subsystem(WOLFSSHD_CONNECTION* conn, WOLFSSH* ssh) byte channelBuffer[EXAMPLE_BUFFER_SZ]; userName = wolfSSH_GetUsername(ssh); + if (userName == NULL) { + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Failure get user name"); + return WS_FATAL_ERROR; + } /* temporarily elevate permissions to get users information */ if (wolfSSHD_AuthRaisePermissions(conn->auth) != WS_SUCCESS) { - wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Failure to raise permissions for auth"); + wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Failure to raise permissions for auth"); return WS_FATAL_ERROR; } @@ -597,7 +601,7 @@ static void* HandleConnection(void* arg) graceTime = wolfSSHD_AuthGetGraceTime(conn->auth); if (graceTime > 0) { signal(SIGALRM, alarmCatch); - alarm(graceTime); + alarm((unsigned int)graceTime); } ret = wolfSSH_accept(ssh); diff --git a/configure.ac b/configure.ac index 200ba7ff..7b11c829 100644 --- a/configure.ac +++ b/configure.ac @@ -272,6 +272,9 @@ if test "$ENABLED_SSHD" = "yes"; then LIBS="$LIBS -llogin"], [AC_MSG_ERROR(liblogin not found)]) ;; + *darwin*) + AM_CPPFLAGS="$AM_CPPFLAGS -DWOLFSSH_HAVE_LIBCRYPT" + ;; *) AC_CHECK_LIB([crypt], [crypt], [AM_CPPFLAGS="$AM_CPPFLAGS -DWOLFSSH_HAVE_LIBCRYPT"; From bef771b693dd49aaea2ed9efb74b28a91bd0f659 Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Mon, 8 Aug 2022 14:47:12 +0100 Subject: [PATCH 41/48] Implement Include directive Includes single files or directories, only in POSIX for now. --- apps/wolfsshd/configuration.c | 75 +++++++++++++++++++++++++++++++++-- 1 file changed, 72 insertions(+), 3 deletions(-) diff --git a/apps/wolfsshd/configuration.c b/apps/wolfsshd/configuration.c index 73be8063..485f115f 100644 --- a/apps/wolfsshd/configuration.c +++ b/apps/wolfsshd/configuration.c @@ -206,10 +206,11 @@ enum { OPT_PASSWORD_AUTH = 12, OPT_PORT = 13, OPT_PERMIT_ROOT = 14, - OPT_USE_DNS = 15 + OPT_USE_DNS = 15, + OPT_INCLUDE = 16 }; enum { - NUM_OPTIONS = 16 + NUM_OPTIONS = 17 }; static const CONFIG_OPTION options[NUM_OPTIONS] = { @@ -228,7 +229,8 @@ static const CONFIG_OPTION options[NUM_OPTIONS] = { {OPT_PASSWORD_AUTH, "PasswordAuthentication"}, {OPT_PORT, "Port"}, {OPT_PERMIT_ROOT, "PermitRootLogin"}, - {OPT_USE_DNS, "UseDNS"} + {OPT_USE_DNS, "UseDNS"}, + {OPT_INCLUDE, "Include"} }; /* returns WS_SUCCESS on success */ @@ -426,6 +428,70 @@ static int HandlePort(WOLFSSHD_CONFIG* conf, const char* value) return ret; } +static int HandleInclude(WOLFSSHD_CONFIG *conf, const char *value) +{ + const char *ptr; + /* No value, nothing to do */ + if (!value || value[0] == '\0') { + return WS_BAD_ARGUMENT; + } + + ptr = value + strlen(value) - 1; + while(ptr != value) { + if (!isspace(value)) { + ptr--; + } + else { + break; + } + } + if (*ptr == '*') { + /* Ending in wildcard */ + if (*(ptr - 1) != '/') { + /* TODO: This is a wildcard on files starting with X */ + } + else { +#ifdef __unix__ + int ret; + struct dirent *dir; + DIR *d; + char *path = WMALLOC(ptr - value, NULL, 0); + char *filepath = WMALLOC(PATH_MAX, NULL, 0); + memcpy(path, value, ptr - value - 1); + path[ptr - value - 1] = '\0'; + d = opendir(path); + if (d) { + while ((dir = readdir(d)) != NULL) { + if (dir->d_type == DT_DIR) { + /* Skip sub-directories */ + continue; + } + else { + snprintf(filepath, PATH_MAX, "%s/%s", path, dir->d_name); + ret = wolfSSHD_ConfigLoad(conf, filepath); + if (ret != WS_SUCCESS) { + return ret; + } + } + } + } + else { + /* Bad directory */ + WFREE(filepath, NULL, 0); + return WS_BAD_ARGUMENT; + } + WFREE(filepath, NULL, 0); +#else + /* Don't support wildcards here */ + return WS_BAD_ARGUMENT; +#endif + } + } + else { + return wolfSSHD_ConfigLoad(conf, value); + } + return WS_SUCCESS; +} /* returns WS_SUCCESS on success */ static int HandleConfigOption(WOLFSSHD_CONFIG* conf, int opt, const char* value) @@ -490,6 +556,9 @@ static int HandleConfigOption(WOLFSSHD_CONFIG* conf, int opt, const char* value) /* TODO */ ret = WS_SUCCESS; break; + case OPT_INCLUDE: + ret = HandleInclude(conf, value); + break; default: break; } From b1f26c84d09ce19d922c1ee649ad479225e5304a Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Mon, 8 Aug 2022 15:43:17 +0100 Subject: [PATCH 42/48] Add syslog support When going into daemon mode on a POSIX system, use syslog --- apps/wolfsshd/wolfsshd.c | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/apps/wolfsshd/wolfsshd.c b/apps/wolfsshd/wolfsshd.c index 8a21c3e5..08bede48 100644 --- a/apps/wolfsshd/wolfsshd.c +++ b/apps/wolfsshd/wolfsshd.c @@ -105,6 +105,40 @@ typedef struct WOLFSSHD_CONNECTION { char ip[INET_ADDRSTRLEN]; } WOLFSSHD_CONNECTION; +#ifdef __unix__ + +#include + +static void SyslogCb(enum wolfSSH_LogLevel level, const char *const msgStr) +{ + int priority = LOG_DAEMON; + + switch (level) { + case WS_LOG_WARN: + priority |= LOG_WARNING; + break; + case WS_LOG_ERROR: + priority |= LOG_ERR; + break; + case WS_LOG_DEBUG: + priority |= LOG_DEBUG; + break; + case WS_LOG_INFO: + case WS_LOG_USER: + case WS_LOG_SFTP: + case WS_LOG_SCP: + case WS_LOG_AGENT: + default: + priority |= LOG_INFO; + break; + } + openlog("sshd", LOG_PID, LOG_DAEMON); + syslog(priority, "%s", msgStr); + closelog(); +} + +#endif + static void ShowUsage(void) { printf("wolfsshd %s\n", LIBWOLFSSH_VERSION_STRING); @@ -894,6 +928,10 @@ int main(int argc, char** argv) /* run as a daemon */ if (ret == WS_SUCCESS && isDaemon) { +#ifdef __unix__ + /* Daemonizing in POSIX, so set a syslog based log */ + wolfSSH_SetLoggingCb(SyslogCb); +#endif pid_t p; p = fork(); From d2327d5acd1a24f3eb4512113f93873b35a42337 Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Mon, 8 Aug 2022 16:12:35 +0100 Subject: [PATCH 43/48] Fix syslog priority --- apps/wolfsshd/wolfsshd.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/apps/wolfsshd/wolfsshd.c b/apps/wolfsshd/wolfsshd.c index 08bede48..136a9a43 100644 --- a/apps/wolfsshd/wolfsshd.c +++ b/apps/wolfsshd/wolfsshd.c @@ -111,17 +111,17 @@ typedef struct WOLFSSHD_CONNECTION { static void SyslogCb(enum wolfSSH_LogLevel level, const char *const msgStr) { - int priority = LOG_DAEMON; + int priority; switch (level) { case WS_LOG_WARN: - priority |= LOG_WARNING; + priority = LOG_WARNING; break; case WS_LOG_ERROR: - priority |= LOG_ERR; + priority = LOG_ERR; break; case WS_LOG_DEBUG: - priority |= LOG_DEBUG; + priority = LOG_DEBUG; break; case WS_LOG_INFO: case WS_LOG_USER: @@ -129,7 +129,7 @@ static void SyslogCb(enum wolfSSH_LogLevel level, const char *const msgStr) case WS_LOG_SCP: case WS_LOG_AGENT: default: - priority |= LOG_INFO; + priority = LOG_INFO; break; } openlog("sshd", LOG_PID, LOG_DAEMON); From 97974e9af205c080a98f642110bd677de7afbd4d Mon Sep 17 00:00:00 2001 From: Andrew Hutchings Date: Tue, 9 Aug 2022 13:51:14 +0100 Subject: [PATCH 44/48] Better wildcard support for Include Check the prefix and postfix for a filename when a wildcard is used. --- apps/wolfsshd/configuration.c | 134 +++++++++++++++++++++++++--------- 1 file changed, 101 insertions(+), 33 deletions(-) diff --git a/apps/wolfsshd/configuration.c b/apps/wolfsshd/configuration.c index 485f115f..029b8b11 100644 --- a/apps/wolfsshd/configuration.c +++ b/apps/wolfsshd/configuration.c @@ -431,11 +431,17 @@ static int HandlePort(WOLFSSHD_CONFIG* conf, const char* value) static int HandleInclude(WOLFSSHD_CONFIG *conf, const char *value) { const char *ptr; + const char *ptr2; + const char *postfix = NULL; + const char *prefix = NULL; + int prefix_len = 0; + int found = 0; /* No value, nothing to do */ if (!value || value[0] == '\0') { return WS_BAD_ARGUMENT; } + /* Ignore trailing whitespace */ ptr = value + strlen(value) - 1; while(ptr != value) { if (!isspace(value)) { @@ -445,47 +451,109 @@ static int HandleInclude(WOLFSSHD_CONFIG *conf, const char *value) break; } } - if (*ptr == '*') { - /* Ending in wildcard */ - if (*(ptr - 1) != '/') { - /* TODO: This is a wildcard on files starting with X */ + /* Find wildcards */ + ptr2 = ptr; + while(ptr2 != value) { + if (*ptr2 == '*') { + /* Wildcard found */ + found = 1; + if (ptr != ptr2) { + postfix = ptr2 + 1; + } + break; } - else { + if (*ptr2 == '/') { + /* Found slash before wildcard directory-wildcards not supported */ + break; + } + ptr2--; + } + ptr = ptr2; + /* Use wildcard */ + if (found) { #ifdef __unix__ - int ret; - struct dirent *dir; - DIR *d; - char *path = WMALLOC(ptr - value, NULL, 0); - char *filepath = WMALLOC(PATH_MAX, NULL, 0); - memcpy(path, value, ptr - value - 1); - path[ptr - value - 1] = '\0'; - d = opendir(path); - if (d) { - while ((dir = readdir(d)) != NULL) { - if (dir->d_type == DT_DIR) { - /* Skip sub-directories */ - continue; + int ret; + struct dirent *dir; + DIR *d; + char *path; + char *filepath = WMALLOC(PATH_MAX, NULL, 0); + + /* Back find the full path */ + while (ptr2 != value) { + if (*ptr2 == '/') { + break; + } + ptr2--; + } + + if (ptr2 != value) { + path = WMALLOC(ptr2 - value + 1, NULL, 0); + memcpy(path, value, ptr2 - value); + path[ptr2 - value] = '\0'; + prefix = ptr2 + 1; + prefix_len = ptr - ptr2 - 1; + } else { + path = WMALLOC(2, NULL, 0); + memcpy(path, ".", 1); + path[1] = '\0'; + prefix = value; + prefix_len = ptr - value; + } + + d = opendir(path); + if (d) { + while ((dir = readdir(d)) != NULL) { + if (dir->d_type == DT_DIR) { + /* Skip sub-directories */ + continue; + } + else { + /* Check if filename prefix matches */ + if (prefix_len > 0) { + if (strlen(dir->d_name) <= prefix_len) { + continue; + } + if (strncmp(dir->d_name, prefix, prefix_len) != 0) { + continue; + } + } + if (postfix) { + /* Skip if file is too short */ + if (strlen(dir->d_name) <= strlen(postfix)) { + continue; + } + if (strncmp(dir->d_name + strlen(dir->d_name) - + strlen(postfix), postfix, strlen(postfix)) + == 0) { + snprintf(filepath, PATH_MAX, "%s/%s", path, + dir->d_name); + } + else { + /* Not a match */ + continue; + } } else { - snprintf(filepath, PATH_MAX, "%s/%s", path, dir->d_name); - ret = wolfSSHD_ConfigLoad(conf, filepath); - if (ret != WS_SUCCESS) { - return ret; - } + snprintf(filepath, PATH_MAX, "%s/%s", path, + dir->d_name); + } + ret = wolfSSHD_ConfigLoad(conf, filepath); + if (ret != WS_SUCCESS) { + return ret; } } } - else { - /* Bad directory */ - WFREE(filepath, NULL, 0); - return WS_BAD_ARGUMENT; - } - WFREE(filepath, NULL, 0); -#else - /* Don't support wildcards here */ - return WS_BAD_ARGUMENT; -#endif } + else { + /* Bad directory */ + WFREE(filepath, NULL, 0); + return WS_BAD_ARGUMENT; + } + WFREE(filepath, NULL, 0); +#else + /* Don't support wildcards here */ + return WS_BAD_ARGUMENT; +#endif } else { return wolfSSHD_ConfigLoad(conf, value); From 17f3a029e3b11a12227c5651ceb0645e5023fd93 Mon Sep 17 00:00:00 2001 From: Jacob Barthelmeh Date: Wed, 10 Aug 2022 14:58:02 -0600 Subject: [PATCH 45/48] cast on values and adjust isspace check --- apps/wolfsshd/configuration.c | 31 ++++++++++++++++++------------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/apps/wolfsshd/configuration.c b/apps/wolfsshd/configuration.c index 029b8b11..bd7b222f 100644 --- a/apps/wolfsshd/configuration.c +++ b/apps/wolfsshd/configuration.c @@ -434,26 +434,28 @@ static int HandleInclude(WOLFSSHD_CONFIG *conf, const char *value) const char *ptr2; const char *postfix = NULL; const char *prefix = NULL; - int prefix_len = 0; + int prefixLen = 0; int found = 0; + /* No value, nothing to do */ if (!value || value[0] == '\0') { return WS_BAD_ARGUMENT; } /* Ignore trailing whitespace */ - ptr = value + strlen(value) - 1; - while(ptr != value) { - if (!isspace(value)) { + ptr = value + WSTRLEN(value) - 1; + while (ptr != value) { + if (!isspace(*ptr)) { ptr--; } else { break; } } + /* Find wildcards */ ptr2 = ptr; - while(ptr2 != value) { + while (ptr2 != value) { if (*ptr2 == '*') { /* Wildcard found */ found = 1; @@ -469,6 +471,7 @@ static int HandleInclude(WOLFSSHD_CONFIG *conf, const char *value) ptr2--; } ptr = ptr2; + /* Use wildcard */ if (found) { #ifdef __unix__ @@ -491,13 +494,13 @@ static int HandleInclude(WOLFSSHD_CONFIG *conf, const char *value) memcpy(path, value, ptr2 - value); path[ptr2 - value] = '\0'; prefix = ptr2 + 1; - prefix_len = ptr - ptr2 - 1; + prefixLen = (int)(ptr - ptr2 - 1); } else { path = WMALLOC(2, NULL, 0); memcpy(path, ".", 1); path[1] = '\0'; prefix = value; - prefix_len = ptr - value; + prefixLen = (int)(ptr - value); } d = opendir(path); @@ -509,21 +512,21 @@ static int HandleInclude(WOLFSSHD_CONFIG *conf, const char *value) } else { /* Check if filename prefix matches */ - if (prefix_len > 0) { - if (strlen(dir->d_name) <= prefix_len) { + if (prefixLen > 0) { + if ((int)WSTRLEN(dir->d_name) <= prefixLen) { continue; } - if (strncmp(dir->d_name, prefix, prefix_len) != 0) { + if (WSTRNCMP(dir->d_name, prefix, prefixLen) != 0) { continue; } } if (postfix) { /* Skip if file is too short */ - if (strlen(dir->d_name) <= strlen(postfix)) { + if (WSTRLEN(dir->d_name) <= WSTRLEN(postfix)) { continue; } - if (strncmp(dir->d_name + strlen(dir->d_name) - - strlen(postfix), postfix, strlen(postfix)) + if (WSTRNCMP(dir->d_name + WSTRLEN(dir->d_name) - + WSTRLEN(postfix), postfix, WSTRLEN(postfix)) == 0) { snprintf(filepath, PATH_MAX, "%s/%s", path, dir->d_name); @@ -551,6 +554,8 @@ static int HandleInclude(WOLFSSHD_CONFIG *conf, const char *value) } WFREE(filepath, NULL, 0); #else + (void)prefixLen; + (void)prefix; /* Don't support wildcards here */ return WS_BAD_ARGUMENT; #endif From ebd0e51e5367cfc5b8cd1b2760898aa8ee50e5cb Mon Sep 17 00:00:00 2001 From: JacobBarthelmeh Date: Thu, 11 Aug 2022 15:40:22 -0700 Subject: [PATCH 46/48] handle basic absolute paths for authorized keys file --- apps/wolfsshd/auth.c | 37 ++++++++++++++++++++++++------------- 1 file changed, 24 insertions(+), 13 deletions(-) diff --git a/apps/wolfsshd/auth.c b/apps/wolfsshd/auth.c index 26918f9a..6472eb7b 100644 --- a/apps/wolfsshd/auth.c +++ b/apps/wolfsshd/auth.c @@ -72,6 +72,13 @@ struct WOLFSSHD_AUTH { #define WOLFSSHD_MAX_PASSWORD_ATTEMPTS 3 #endif +#ifndef MAX_LEN_SZ + #define MAX_LINE_SZ 500 +#endif +#ifndef MAX_PATH_SZ + #define MAX_PATH_SZ 80 +#endif + #if 0 /* this could potentially be useful in a deeply embeded future port */ @@ -400,7 +407,7 @@ static int CheckUserUnix(const char* name) { } static const char authKeysDefault[] = ".ssh/authorized_keys"; -static char authKeysPattern[32] = {0}; +static char authKeysPattern[MAX_PATH_SZ] = {0}; void SetAuthKeysPattern(const char* pattern) { @@ -425,22 +432,31 @@ static int ResolveAuthKeysPath(const char* homeDir, char* resolved) if (*authKeysPattern != 0) { /* TODO: token substitutions (e.g. %h) */ if (*authKeysPattern == '/') { - /* TODO: handle absolute path case */ - ret = WS_FATAL_ERROR; + WSTRNCPY(resolved, authKeysPattern, MAX_PATH_SZ - 1); + return WS_SUCCESS; } else { suffix = authKeysPattern; } } } + if (ret == WS_SUCCESS) { idx = resolved; homeDirSz = (int)XSTRLEN(homeDir); - XMEMCPY(idx, homeDir, homeDirSz); - idx += homeDirSz; - *(idx++) = '/'; - /* Intentionally copying the null term from suffix. */ - XMEMCPY(idx, suffix, WSTRLEN(suffix)); + if (homeDirSz + 1 + WSTRLEN(suffix) >= MAX_PATH_SZ) { + wolfSSH_Log(WS_LOG_ERROR, + "[SSHD] Path for key file larger than max allowed"); + ret = WS_FATAL_ERROR; + } + + if (ret == WS_SUCCESS) { + XMEMCPY(idx, homeDir, homeDirSz); + idx += homeDirSz; + *(idx++) = '/'; + /* Intentionally copying the null term from suffix. */ + XMEMCPY(idx, suffix, WSTRLEN(suffix)); + } } return ret; @@ -453,11 +469,6 @@ static int CheckPublicKeyUnix(const char* name, const byte* key, word32 keySz) struct passwd* pwInfo; char* authKeysFile = NULL; XFILE f = NULL; - enum { - /* TODO: Probably needs to be even bigger for larger key sizes. */ - MAX_LINE_SZ = 500, - MAX_PATH_SZ = 80 - }; char* lineBuf = NULL; char* current; word32 currentSz; From 387ac299b05f00c814ca389a0574428ba0acd198 Mon Sep 17 00:00:00 2001 From: Jacob Barthelmeh Date: Fri, 12 Aug 2022 10:22:18 -0600 Subject: [PATCH 47/48] fix for compiler warnings --- apps/wolfsshd/auth.c | 2 +- apps/wolfsshd/configuration.c | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/wolfsshd/auth.c b/apps/wolfsshd/auth.c index 6472eb7b..607b2034 100644 --- a/apps/wolfsshd/auth.c +++ b/apps/wolfsshd/auth.c @@ -432,7 +432,7 @@ static int ResolveAuthKeysPath(const char* homeDir, char* resolved) if (*authKeysPattern != 0) { /* TODO: token substitutions (e.g. %h) */ if (*authKeysPattern == '/') { - WSTRNCPY(resolved, authKeysPattern, MAX_PATH_SZ - 1); + WSTRNCPY(resolved, authKeysPattern, MAX_PATH_SZ); return WS_SUCCESS; } else { diff --git a/apps/wolfsshd/configuration.c b/apps/wolfsshd/configuration.c index bd7b222f..b556868e 100644 --- a/apps/wolfsshd/configuration.c +++ b/apps/wolfsshd/configuration.c @@ -554,6 +554,7 @@ static int HandleInclude(WOLFSSHD_CONFIG *conf, const char *value) } WFREE(filepath, NULL, 0); #else + (void)postfix; (void)prefixLen; (void)prefix; /* Don't support wildcards here */ From 5a1f42ba07dfc4744b6ddbad4e589e0983cc43bb Mon Sep 17 00:00:00 2001 From: Jacob Barthelmeh Date: Tue, 16 Aug 2022 13:28:06 -0600 Subject: [PATCH 48/48] update copyright, wrap isspace, fix formating --- apps/wolfsshd/auth.c | 5 +-- apps/wolfsshd/auth.h | 2 +- apps/wolfsshd/configuration.c | 8 ++--- apps/wolfsshd/configuration.h | 2 +- apps/wolfsshd/wolfsshd.c | 61 +++-------------------------------- configure.ac | 2 +- wolfssh/port.h | 9 ++++++ 7 files changed, 23 insertions(+), 66 deletions(-) diff --git a/apps/wolfsshd/auth.c b/apps/wolfsshd/auth.c index 607b2034..3befdbeb 100644 --- a/apps/wolfsshd/auth.c +++ b/apps/wolfsshd/auth.c @@ -1,6 +1,6 @@ /* auth.c * - * Copyright (C) 2014-2021 wolfSSL Inc. + * Copyright (C) 2014-2022 wolfSSL Inc. * * This file is part of wolfSSH. * @@ -601,7 +601,8 @@ static int RequestAuthentication(const char* usr, int type, const byte* data, /* temporarily elevate permissions */ if (ret == WOLFSSH_USERAUTH_SUCCESS && wolfSSHD_AuthRaisePermissions(auth) != WS_SUCCESS) { - wolfSSH_Log(WS_LOG_ERROR, "[SSHD] Failure to raise permissions for auth"); + wolfSSH_Log(WS_LOG_ERROR, + "[SSHD] Failure to raise permissions for auth"); ret = WOLFSSH_USERAUTH_FAILURE; } diff --git a/apps/wolfsshd/auth.h b/apps/wolfsshd/auth.h index 42dc9af5..01e41106 100644 --- a/apps/wolfsshd/auth.h +++ b/apps/wolfsshd/auth.h @@ -1,6 +1,6 @@ /* auth.h * - * Copyright (C) 2014-2021 wolfSSL Inc. + * Copyright (C) 2014-2022 wolfSSL Inc. * * This file is part of wolfSSH. * diff --git a/apps/wolfsshd/configuration.c b/apps/wolfsshd/configuration.c index b556868e..695f40b2 100644 --- a/apps/wolfsshd/configuration.c +++ b/apps/wolfsshd/configuration.c @@ -1,6 +1,6 @@ /* configuration.c * - * Copyright (C) 2014-2021 wolfSSL Inc. + * Copyright (C) 2014-2022 wolfSSL Inc. * * This file is part of wolfSSH. * @@ -445,7 +445,7 @@ static int HandleInclude(WOLFSSHD_CONFIG *conf, const char *value) /* Ignore trailing whitespace */ ptr = value + WSTRLEN(value) - 1; while (ptr != value) { - if (!isspace(*ptr)) { + if (!WISSPACE(*ptr)) { ptr--; } else { @@ -649,12 +649,12 @@ static int CountWhitespace(const char* in, int inSz, byte inv) if (in != NULL) { for (; i < inSz; ++i) { if (inv) { - if (isspace(in[i])) { + if (WISSPACE(in[i])) { break; } } else { - if (!isspace(in[i])) { + if (!WISSPACE(in[i])) { break; } } diff --git a/apps/wolfsshd/configuration.h b/apps/wolfsshd/configuration.h index 952a1f87..3d352408 100644 --- a/apps/wolfsshd/configuration.h +++ b/apps/wolfsshd/configuration.h @@ -1,6 +1,6 @@ /* configuration.h * - * Copyright (C) 2014-2021 wolfSSL Inc. + * Copyright (C) 2014-2022 wolfSSL Inc. * * This file is part of wolfSSH. * diff --git a/apps/wolfsshd/wolfsshd.c b/apps/wolfsshd/wolfsshd.c index 136a9a43..a2d265df 100644 --- a/apps/wolfsshd/wolfsshd.c +++ b/apps/wolfsshd/wolfsshd.c @@ -1,6 +1,6 @@ /* wolfsshd.c * - * Copyright (C) 2014-2021 wolfSSL Inc. + * Copyright (C) 2014-2022 wolfSSL Inc. * * This file is part of wolfSSH. * @@ -143,7 +143,8 @@ static void ShowUsage(void) { printf("wolfsshd %s\n", LIBWOLFSSH_VERSION_STRING); printf(" -? display this help and exit\n"); - printf(" -f Configuration file to use, default is /etc/ssh/sshd_config\n"); + printf(" -f Configuration file to use, default is " + "/etc/ssh/sshd_config\n"); printf(" -p Port number to listen on\n"); printf(" -d Turn on debug mode\n"); printf(" -D Run in foreground (do not detach)\n"); @@ -271,61 +272,7 @@ static int SetupCTX(WOLFSSHD_CONFIG* conf, WOLFSSH_CTX** ctx) } } - /* Load in host public key */ -// { -// if (userPubKey) { -// byte* userBuf = NULL; -// word32 userBufSz = 0; -// -// /* get the files size */ -// load_file(userPubKey, NULL, &userBufSz); -// -// /* create temp buffer and load in file */ -// if (userBufSz == 0) { -// fprintf(stderr, "Couldn't find size of file %s.\n", userPubKey); -// WEXIT(EXIT_FAILURE); -// } -// -// userBuf = (byte*)WMALLOC(userBufSz, NULL, 0); -// if (userBuf == NULL) { -// fprintf(stderr, "WMALLOC failed\n"); -// WEXIT(EXIT_FAILURE); -// } -// load_file(userPubKey, userBuf, &userBufSz); -// LoadPublicKeyBuffer(userBuf, userBufSz, &pwMapList); -// } -// -// bufSz = (word32)WSTRLEN(samplePasswordBuffer); -// WMEMCPY(keyLoadBuf, samplePasswordBuffer, bufSz); -// keyLoadBuf[bufSz] = 0; -// LoadPasswordBuffer(keyLoadBuf, bufSz, &pwMapList); -// -// if (userEcc) { -// #ifndef WOLFSSH_NO_ECC -// bufName = samplePublicKeyEccBuffer; -// #endif -// } -// else { -// #ifndef WOLFSSH_NO_RSA -// bufName = samplePublicKeyRsaBuffer; -// #endif -// } -// if (bufName != NULL) { -// bufSz = (word32)WSTRLEN(bufName); -// WMEMCPY(keyLoadBuf, bufName, bufSz); -// keyLoadBuf[bufSz] = 0; -// LoadPublicKeyBuffer(keyLoadBuf, bufSz, &pwMapList); -// } -// -// bufSz = (word32)WSTRLEN(sampleNoneBuffer); -// WMEMCPY(keyLoadBuf, sampleNoneBuffer, bufSz); -// keyLoadBuf[bufSz] = 0; -// LoadNoneBuffer(keyLoadBuf, bufSz, &pwMapList); -// -// #ifdef WOLFSSH_SMALL_STACK -// WFREE(keyLoadBuf, NULL, 0); -// #endif -// } + /* @TODO Load in host public key */ /* Set allowed connection type, i.e. public key / password */ diff --git a/configure.ac b/configure.ac index 7b11c829..8f052afb 100644 --- a/configure.ac +++ b/configure.ac @@ -223,7 +223,7 @@ AS_IF([test "x$ENABLED_DISTRO" = "xyes"], AS_IF([test "x$ENABLED_ALL" = "xyes"], [ENABLED_KEYGEN=yes; ENABLED_SCP=yes; ENABLED_SFTP=yes; ENABLED_FWD=yes; ENABLED_SHELL=yes; ENABLED_AGENT=yes; ENABLED_SSHD=yes]) AS_IF([test "x$ENABLED_SSHD" = "xyes"], - [ENABLED_SHELL=yes;]) + [ENABLED_SHELL=yes]) # Set the defined flags for the code. AS_IF([test "x$ENABLED_INLINE" = "xno"], diff --git a/wolfssh/port.h b/wolfssh/port.h index 7efb1e25..c89cffdd 100644 --- a/wolfssh/port.h +++ b/wolfssh/port.h @@ -41,6 +41,15 @@ extern "C" { /* This value needs to stay in sync with the actual value of DYNTYPE_STRING * from internal.h. */ +#ifdef WOLFSSH_SSHD + /* uses isspace (not always available from wolfSSL) */ + #ifdef XISSPACE + #define WISSPACE XISSPACE + #else + #define WISSPACE isspace + #endif +#endif + /* setup memory handling */ #ifndef WMALLOC_USER #ifdef WOLFSSL_USER_SETTINGS