123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681 |
- /* server.c
- *
- * Copyright (C) 2014-2019 wolfSSL Inc.
- *
- * This file is part of wolfSSH.
- *
- * wolfSSH is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 3 of the License, or
- * (at your option) any later version.
- *
- * wolfSSH is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with wolfSSH. If not, see <http://www.gnu.org/licenses/>.
- */
- #define WOLFSSH_TEST_SERVER
- #define WOLFSSH_TEST_THREADING
- #include <stdbool.h>
- #include "FreeRTOS.h"
- #include "task.h"
- #include "wolfssh_test.h"
- #include "cli.h"
- #include "CLI_Commands.h"
- #ifdef WOLFSSL_USER_SETTINGS
- #include <wolfssl/wolfcrypt/settings.h>
- #else
- #include <wolfssl/options.h>
- #endif
- #include <wolfssl/wolfcrypt/sha256.h>
- #include <wolfssl/wolfcrypt/coding.h>
- #include <wolfssh/ssh.h>
- //#include <wolfssh/test.h>
- #include <wolfssl/wolfcrypt/ecc.h>
- #include "examples/server/server.h"
- #ifdef NO_FILESYSTEM
- #include <wolfssh/certs_test.h>
- #endif
- static const char serverBanner[] = "BT-6709 command server\n";
- typedef struct {
- WOLFSSH* ssh;
- SOCKET_T fd;
- word32 id;
- char nonBlock;
- } thread_ctx_t;
- #ifndef EXAMPLE_HIGHWATER_MARK
- #define EXAMPLE_HIGHWATER_MARK 0x3FFF8000 /* 1GB - 32kB */
- #endif
- #ifndef EXAMPLE_BUFFER_SZ
- #define EXAMPLE_BUFFER_SZ 256
- #endif
- #define SCRATCH_BUFFER_SZ 1200
- static byte find_char(const byte* str, const byte* buf, word32 bufSz)
- {
- const byte* cur;
- while (bufSz) {
- cur = str;
- while (*cur != '\0') {
- if (*cur == *buf)
- return *cur;
- cur++;
- }
- buf++;
- bufSz--;
- }
- return 0;
- }
- /*
- static int dump_stats(thread_ctx_t* ctx)
- {
- char stats[1024];
- word32 statsSz;
- word32 txCount, rxCount, seq, peerSeq;
- wolfSSH_GetStats(ctx->ssh, &txCount, &rxCount, &seq, &peerSeq);
- WSNPRINTF(stats, sizeof(stats),
- "Statistics for Thread #%u:\r\n"
- " txCount = %u\r\n rxCount = %u\r\n"
- " seq = %u\r\n peerSeq = %u\r\n",
- ctx->id, txCount, rxCount, seq, peerSeq);
- statsSz = (word32)strlen(stats);
- fprintf(stderr, "%s", stats);
- return wolfSSH_stream_send(ctx->ssh, (byte*)stats, statsSz);
- }
- */
- static int NonBlockSSH_accept(WOLFSSH* ssh)
- {
- int ret;
- int error;
- SOCKET_T sockfd;
- int select_ret = 0;
- ret = wolfSSH_accept(ssh);
- error = wolfSSH_get_error(ssh);
- sockfd = (SOCKET_T)wolfSSH_get_fd(ssh);
- while (ret != WS_SUCCESS &&
- (error == WS_WANT_READ || error == WS_WANT_WRITE))
- {
- if (error == WS_WANT_READ)
- printf("... client would read block\n");
- else if (error == WS_WANT_WRITE)
- printf("... client would write block\n");
- select_ret = tcp_select(sockfd, 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;
- }
- return ret;
- }
- static void cli_send(intptr_t fd, const char *str, unsigned len)
- {
- wolfSSH_stream_send((WOLFSSH *)fd, str, len);
- }
- static void *server_worker(void* vArgs)
- {
- int ret;
- thread_ctx_t* threadCtx = (thread_ctx_t*)vArgs;
- if (!threadCtx->nonBlock)
- ret = wolfSSH_accept(threadCtx->ssh);
- else
- ret = NonBlockSSH_accept(threadCtx->ssh);
- cli_state_t *cli_state;
- // create the new CLI context
- if (ret == WS_SUCCESS && (cli_state = alloc_state())) {
- cli_state->num_connect = threadCtx->ssh;
- cli_state->input_state = CLI_CMD;
- cli_state->send = cli_send;
- cli_hello(cli_state);
- cli_state->state = STATE_NORMAL;
- bool stop = false;
- do {
- uint8_t buf[EXAMPLE_BUFFER_SZ];
- int rxSz = 0;
- do {
- rxSz = wolfSSH_stream_read(threadCtx->ssh, buf, sizeof(buf));
- if (rxSz <= 0) {
- rxSz = wolfSSH_get_error(threadCtx->ssh);
- }
- } while (rxSz == WS_WANT_READ || rxSz == WS_WANT_WRITE);
- if (rxSz > 0) {
- cli_getchar(cli_state, buf[0]); // TODO handle rxSz > 1
- if (buf[0] == 3 || buf[0] == 4 || cli_state->state == STATE_CLOSE) {
- stop = 1;
- }
- } else {
- stop = 1;
- }
- } while (!stop);
- cli_state->state = STATE_UNUSED;
- } else if (ret == WS_SCP_COMPLETE) {
- printf("scp file transfer completed\n");
- } else if (ret == WS_SFTP_COMPLETE) {
- printf("Use example/echoserver/echoserver for SFTP\n");
- }
- wolfSSH_stream_exit(threadCtx->ssh, 0);
- WCLOSESOCKET(threadCtx->fd);
- wolfSSH_free(threadCtx->ssh);
- free(threadCtx);
- return 0;
- }
- #ifndef NO_FILESYSTEM
- static int load_file(const char* fileName, byte* buf, word32 bufSz)
- {
- FILE* file;
- word32 fileSz;
- word32 readSz;
- if (fileName == NULL) return 0;
- if (WFOPEN(&file, fileName, "rb") != 0)
- return 0;
- fseek(file, 0, SEEK_END);
- fileSz = (word32)ftell(file);
- rewind(file);
- if (fileSz > bufSz) {
- fclose(file);
- return 0;
- }
- readSz = (word32)fread(buf, 1, fileSz, file);
- if (readSz < fileSz) {
- fclose(file);
- return 0;
- }
- fclose(file);
- return fileSz;
- }
- #endif /* !NO_FILESYSTEM */
- /* returns buffer size on success */
- static int load_key(byte isEcc, byte* buf, word32 bufSz)
- {
- word32 sz = 0;
- #ifndef NO_FILESYSTEM
- const char* bufName;
- bufName = isEcc ? "./keys/server-key-ecc.der" :
- "./keys/server-key-rsa.der" ;
- sz = load_file(bufName, buf, bufSz);
- #else
- /* using buffers instead */
- if (isEcc) {
- if (sizeof_ecc_key_der_256 > bufSz) {
- return 0;
- }
- WMEMCPY(buf, ecc_key_der_256, sizeof_ecc_key_der_256);
- sz = sizeof_ecc_key_der_256;
- }
- else {
- if (sizeof_rsa_key_der_2048 > bufSz) {
- return 0;
- }
- WMEMCPY(buf, rsa_key_der_2048, sizeof_rsa_key_der_2048);
- sz = sizeof_rsa_key_der_2048;
- }
- #endif
- return sz;
- }
- static INLINE void c32toa(word32 u32, byte* c)
- {
- c[0] = (u32 >> 24) & 0xff;
- c[1] = (u32 >> 16) & 0xff;
- c[2] = (u32 >> 8) & 0xff;
- c[3] = u32 & 0xff;
- }
- /* 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. */
- typedef struct PwMap {
- byte type;
- byte username[32];
- word32 usernameSz;
- byte p[SHA256_DIGEST_SIZE];
- struct PwMap* next;
- } PwMap;
- typedef struct PwMapList {
- PwMap* head;
- } PwMapList;
- static PwMap* PwMapNew(PwMapList* list, byte type, const byte* username,
- word32 usernameSz, const byte* p, word32 pSz)
- {
- PwMap* map;
- map = (PwMap*)malloc(sizeof(PwMap));
- if (map != NULL) {
- Sha256 sha;
- byte flatSz[4];
- map->type = type;
- if (usernameSz >= sizeof(map->username))
- usernameSz = sizeof(map->username) - 1;
- memcpy(map->username, username, usernameSz + 1);
- map->username[usernameSz] = 0;
- map->usernameSz = usernameSz;
- wc_InitSha256(&sha);
- c32toa(pSz, flatSz);
- wc_Sha256Update(&sha, flatSz, sizeof(flatSz));
- wc_Sha256Update(&sha, p, pSz);
- wc_Sha256Final(&sha, map->p);
- map->next = list->head;
- list->head = map;
- }
- return map;
- }
- static void PwMapListDelete(PwMapList* list)
- {
- if (list != NULL) {
- PwMap* head = list->head;
- while (head != NULL) {
- PwMap* cur = head;
- head = head->next;
- memset(cur, 0, sizeof(PwMap));
- free(cur);
- }
- }
- }
- static const char samplePasswordBuffer[] =
- "jill:upthehill\n"
- "jack:fetchapail\n";
- static const char samplePublicKeyEccBuffer[] =
- "ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAA"
- "BBBNkI5JTP6D0lF42tbxX19cE87hztUS6FSDoGvPfiU0CgeNSbI+aFdKIzTP5CQEJSvm25"
- "qUzgDtH7oyaQROUnNvk= hansel\n"
- "ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAA"
- "BBBKAtH8cqaDbtJFjtviLobHBmjCtG56DMkP6A4M2H9zX2/YCg1h9bYS7WHd9UQDwXO1Hh"
- "IZzRYecXh7SG9P4GhRY= gretel\n";
- static const char samplePublicKeyRsaBuffer[] =
- "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC9P3ZFowOsONXHD5MwWiCciXytBRZGho"
- "MNiisWSgUs5HdHcACuHYPi2W6Z1PBFmBWT9odOrGRjoZXJfDDoPi+j8SSfDGsc/hsCmc3G"
- "p2yEhUZUEkDhtOXyqjns1ickC9Gh4u80aSVtwHRnJZh9xPhSq5tLOhId4eP61s+a5pwjTj"
- "nEhBaIPUJO2C/M0pFnnbZxKgJlX7t1Doy7h5eXxviymOIvaCZKU+x5OopfzM/wFkey0EPW"
- "NmzI5y/+pzU5afsdeEWdiQDIQc80H6Pz8fsoFPvYSG+s4/wz0duu7yeeV1Ypoho65Zr+pE"
- "nIf7dO0B8EblgWt+ud+JI8wrAhfE4x hansel\n"
- "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCqDwRVTRVk/wjPhoo66+Mztrc31KsxDZ"
- "+kAV0139PHQ+wsueNpba6jNn5o6mUTEOrxrz0LMsDJOBM7CmG0983kF4gRIihECpQ0rcjO"
- "P6BSfbVTE9mfIK5IsUiZGd8SoE9kSV2pJ2FvZeBQENoAxEFk0zZL9tchPS+OCUGbK4SDjz"
- "uNZl/30Mczs73N3MBzi6J1oPo7sFlqzB6ecBjK2Kpjus4Y1rYFphJnUxtKvB0s+hoaadru"
- "biE57dK6BrH5iZwVLTQKux31uCJLPhiktI3iLbdlGZEctJkTasfVSsUizwVIyRjhVKmbdI"
- "RGwkU38D043AR1h0mUoGCPIKuqcFMf gretel\n";
- static int LoadPasswordBuffer(byte* buf, word32 bufSz, PwMapList* list)
- {
- char* str = (char*)buf;
- char* delimiter;
- char* username;
- char* password;
- /* Each line of passwd.txt is in the format
- * username:password\n
- * This function modifies the passed-in buffer. */
- if (list == NULL)
- return -1;
- if (buf == NULL || bufSz == 0)
- return 0;
- while (*str != 0) {
- delimiter = strchr(str, ':');
- if (delimiter == NULL) {
- return -1;
- }
- username = str;
- *delimiter = 0;
- password = delimiter + 1;
- str = strchr(password, '\n');
- if (str == NULL) {
- return -1;
- }
- *str = 0;
- str++;
- if (PwMapNew(list, WOLFSSH_USERAUTH_PASSWORD,
- (byte*)username, (word32)strlen(username),
- (byte*)password, (word32)strlen(password)) == NULL ) {
- return -1;
- }
- }
- return 0;
- }
- static int LoadPublicKeyBuffer(byte* buf, word32 bufSz, PwMapList* list)
- {
- char* str = (char*)buf;
- char* delimiter;
- byte* publicKey64;
- word32 publicKey64Sz;
- byte* username;
- word32 usernameSz;
- byte publicKey[300];
- word32 publicKeySz;
- /* Each line of passwd.txt is in the format
- * ssh-rsa AAAB3BASE64ENCODEDPUBLICKEYBLOB username\n
- * This function modifies the passed-in buffer. */
- if (list == NULL)
- return -1;
- if (buf == NULL || bufSz == 0)
- return 0;
- while (*str != 0) {
- /* Skip the public key type. This example will always be ssh-rsa. */
- delimiter = strchr(str, ' ');
- if (delimiter == NULL) {
- return -1;
- }
- str = delimiter + 1;
- delimiter = strchr(str, ' ');
- if (delimiter == NULL) {
- return -1;
- }
- publicKey64 = (byte*)str;
- *delimiter = 0;
- publicKey64Sz = (word32)(delimiter - str);
- str = delimiter + 1;
- delimiter = strchr(str, '\n');
- if (delimiter == NULL) {
- return -1;
- }
- username = (byte*)str;
- *delimiter = 0;
- usernameSz = (word32)(delimiter - str);
- str = delimiter + 1;
- publicKeySz = sizeof(publicKey);
- if (Base64_Decode(publicKey64, publicKey64Sz,
- publicKey, &publicKeySz) != 0) {
- return -1;
- }
- if (PwMapNew(list, WOLFSSH_USERAUTH_PUBLICKEY,
- username, usernameSz,
- publicKey, publicKeySz) == NULL ) {
- return -1;
- }
- }
- return 0;
- }
- static int wsUserAuth(byte authType,
- WS_UserAuthData* authData,
- void* ctx)
- {
- PwMapList* list;
- PwMap* map;
- byte authHash[SHA256_DIGEST_SIZE];
- if (ctx == NULL) {
- printf("wsUserAuth: ctx not set");
- return WOLFSSH_USERAUTH_FAILURE;
- }
- if (authType != WOLFSSH_USERAUTH_PASSWORD &&
- authType != WOLFSSH_USERAUTH_PUBLICKEY) {
- return WOLFSSH_USERAUTH_FAILURE;
- }
- /* Hash the password or public key with its length. */
- {
- Sha256 sha;
- byte flatSz[4];
- wc_InitSha256(&sha);
- if (authType == WOLFSSH_USERAUTH_PASSWORD) {
- c32toa(authData->sf.password.passwordSz, flatSz);
- wc_Sha256Update(&sha, flatSz, sizeof(flatSz));
- wc_Sha256Update(&sha,
- authData->sf.password.password,
- authData->sf.password.passwordSz);
- }
- else if (authType == WOLFSSH_USERAUTH_PUBLICKEY) {
- c32toa(authData->sf.publicKey.publicKeySz, flatSz);
- wc_Sha256Update(&sha, flatSz, sizeof(flatSz));
- wc_Sha256Update(&sha,
- authData->sf.publicKey.publicKey,
- authData->sf.publicKey.publicKeySz);
- }
- wc_Sha256Final(&sha, authHash);
- }
- list = (PwMapList*)ctx;
- map = list->head;
- while (map != NULL) {
- if (authData->usernameSz == map->usernameSz &&
- memcmp(authData->username, map->username, map->usernameSz) == 0) {
- if (authData->type == map->type) {
- if (memcmp(map->p, authHash, SHA256_DIGEST_SIZE) == 0) {
- return WOLFSSH_USERAUTH_SUCCESS;
- }
- else {
- return (authType == WOLFSSH_USERAUTH_PASSWORD ?
- WOLFSSH_USERAUTH_INVALID_PASSWORD :
- WOLFSSH_USERAUTH_INVALID_PUBLICKEY);
- }
- }
- else {
- return WOLFSSH_USERAUTH_INVALID_AUTHTYPE;
- }
- }
- map = map->next;
- }
- return WOLFSSH_USERAUTH_INVALID_USER;
- }
- static void ssh_server(void *arg)
- {
- (void)arg;
- WSTARTTCP();
- #ifdef DEBUG_WOLFSSH
- wolfSSH_Debugging_ON();
- #endif
- wolfSSH_Init();
- WOLFSSH_CTX* ctx = NULL;
- PwMapList pwMapList;
- SOCKET_T listenFd = 0;
- word32 defaultHighwater = EXAMPLE_HIGHWATER_MARK;
- word32 threadCount = 0;
- word16 port = 22;
- const char multipleConnections = 1;
- char useEcc = 1;
- int ch;
- char nonBlock = 0;
- if (wolfSSH_Init() != WS_SUCCESS) {
- printf("Couldn't initialize wolfSSH.\n");
- exit(EXIT_FAILURE);
- }
- ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
- if (ctx == NULL) {
- printf("Couldn't allocate SSH CTX data.\n");
- exit(EXIT_FAILURE);
- }
- memset(&pwMapList, 0, sizeof(pwMapList));
- wolfSSH_SetUserAuth(ctx, wsUserAuth);
- wolfSSH_CTX_SetBanner(ctx, serverBanner);
- {
- const char* bufName;
- byte buf[SCRATCH_BUFFER_SZ];
- word32 bufSz;
- bufSz = load_key(useEcc, buf, SCRATCH_BUFFER_SZ);
- if (bufSz == 0) {
- printf("Couldn't load key.\n");
- exit(EXIT_FAILURE);
- }
- if (wolfSSH_CTX_UsePrivateKey_buffer(ctx, buf, bufSz,
- WOLFSSH_FORMAT_ASN1) < 0) {
- printf("Couldn't use key buffer.\n");
- exit(EXIT_FAILURE);
- }
- bufSz = (word32)strlen(samplePasswordBuffer);
- memcpy(buf, samplePasswordBuffer, bufSz);
- buf[bufSz] = 0;
- LoadPasswordBuffer(buf, bufSz, &pwMapList);
- bufName = useEcc ? samplePublicKeyEccBuffer :
- samplePublicKeyRsaBuffer;
- bufSz = (word32)strlen(bufName);
- memcpy(buf, bufName, bufSz);
- buf[bufSz] = 0;
- LoadPublicKeyBuffer(buf, bufSz, &pwMapList);
- }
- tcp_listen(&listenFd, &port, 1, false, false);
- do {
- SOCKET_T clientFd = 0;
- SOCKADDR_IN_T clientAddr;
- socklen_t clientAddrSz = sizeof(clientAddr);
- #ifndef SINGLE_THREADED
- THREAD_TYPE thread;
- #endif
- WOLFSSH* ssh;
- thread_ctx_t* threadCtx;
- threadCtx = (thread_ctx_t*)malloc(sizeof(thread_ctx_t));
- if (threadCtx == NULL) {
- printf("Couldn't allocate thread context data.\n");
- exit(EXIT_FAILURE);
- }
- ssh = wolfSSH_new(ctx);
- if (ssh == NULL) {
- printf("Couldn't allocate SSH data.\n");
- exit(EXIT_FAILURE);
- }
- wolfSSH_SetUserAuthCtx(ssh, &pwMapList);
- /* Use the session object for its own highwater callback ctx */
- if (defaultHighwater > 0) {
- wolfSSH_SetHighwaterCtx(ssh, (void*)ssh);
- wolfSSH_SetHighwater(ssh, defaultHighwater);
- }
- clientFd = accept(listenFd, (struct sockaddr*)&clientAddr,
- &clientAddrSz);
- if (clientFd == -1)
- err_sys("tcp accept failed");
- if (nonBlock)
- tcp_set_nonblocking(&clientFd);
- wolfSSH_set_fd(ssh, (int)clientFd);
- threadCtx->ssh = ssh;
- threadCtx->fd = clientFd;
- threadCtx->id = threadCount++;
- threadCtx->nonBlock = nonBlock;
- #ifndef SINGLE_THREADED
- ThreadStart(server_worker, threadCtx, &thread);
- if (multipleConnections)
- ThreadDetach(thread);
- else
- ThreadJoin(thread);
- #else
- server_worker(threadCtx);
- #endif /* SINGLE_THREADED */
- } while (multipleConnections);
- PwMapListDelete(&pwMapList);
- wolfSSH_CTX_free(ctx);
- if (wolfSSH_Cleanup() != WS_SUCCESS) {
- printf("Couldn't clean up wolfSSH.\n");
- exit(EXIT_FAILURE);
- }
- #if defined(HAVE_ECC) && defined(FP_ECC) && defined(HAVE_THREAD_LS)
- wc_ecc_fp_free(); /* free per thread cache */
- #endif
- return 0;
- }
- void ssh_server_init(void)
- {
- vRegisterCLICommands();
- xTaskCreate(ssh_server, ( char * ) "ssh_server", 24*configMINIMAL_STACK_SIZE + EXAMPLE_BUFFER_SZ, NULL, tskIDLE_PRIORITY + 1, NULL);
- }
|