server.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. /* server.c
  2. *
  3. * Copyright (C) 2014-2019 wolfSSL Inc.
  4. *
  5. * This file is part of wolfSSH.
  6. *
  7. * wolfSSH is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * wolfSSH is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with wolfSSH. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. #pragma GCC diagnostic error "-Wall"
  21. #define WOLFSSH_TEST_SERVER
  22. #define WOLFSSH_TEST_THREADING
  23. #include <stdbool.h>
  24. #include "FreeRTOS.h"
  25. #include "task.h"
  26. #include "semphr.h"
  27. #include "wolfssh_test.h"
  28. #include "cli.h"
  29. #include "CLI_Commands.h"
  30. #include "settings_api.h"
  31. #ifdef WOLFSSL_USER_SETTINGS
  32. #include <wolfssl/wolfcrypt/settings.h>
  33. #else
  34. #include <wolfssl/options.h>
  35. #endif
  36. #include <wolfssl/wolfcrypt/sha256.h>
  37. #include <wolfssl/wolfcrypt/coding.h>
  38. #include <wolfssh/ssh.h>
  39. //#include <wolfssh/test.h>
  40. #include <wolfssl/wolfcrypt/ecc.h>
  41. #include "examples/server/server.h"
  42. #ifdef NO_FILESYSTEM
  43. #include <wolfssh/certs_test.h>
  44. #endif
  45. bool fl_reinit_ssh = false; //флаг разрешение переинициализации ssh сервера
  46. static const char serverBanner[] = "BT-6709 command server\n";
  47. typedef struct {
  48. WOLFSSH* ssh;
  49. SOCKET_T fd;
  50. word32 id;
  51. } thread_ctx_t;
  52. static const bool nonBlock = true;
  53. #ifndef EXAMPLE_HIGHWATER_MARK
  54. #define EXAMPLE_HIGHWATER_MARK 0x3FFF8000 /* 1GB - 32kB */
  55. #endif
  56. #ifndef EXAMPLE_BUFFER_SZ
  57. #define EXAMPLE_BUFFER_SZ 256
  58. #endif
  59. #define SCRATCH_BUFFER_SZ 1200
  60. /*
  61. static int dump_stats(thread_ctx_t* ctx)
  62. {
  63. char stats[1024];
  64. word32 statsSz;
  65. word32 txCount, rxCount, seq, peerSeq;
  66. wolfSSH_GetStats(ctx->ssh, &txCount, &rxCount, &seq, &peerSeq);
  67. WSNPRINTF(stats, sizeof(stats),
  68. "Statistics for Thread #%u:\r\n"
  69. " txCount = %u\r\n rxCount = %u\r\n"
  70. " seq = %u\r\n peerSeq = %u\r\n",
  71. ctx->id, txCount, rxCount, seq, peerSeq);
  72. statsSz = (word32)strlen(stats);
  73. fprintf(stderr, "%s", stats);
  74. return wolfSSH_stream_send(ctx->ssh, (byte*)stats, statsSz);
  75. }
  76. */
  77. static int NonBlockSSH_accept(WOLFSSH* ssh)
  78. {
  79. int ret;
  80. int error;
  81. SOCKET_T sockfd;
  82. int select_ret = 0;
  83. ret = wolfSSH_accept(ssh);
  84. error = wolfSSH_get_error(ssh);
  85. sockfd = (SOCKET_T)wolfSSH_get_fd(ssh);
  86. while (ret != WS_SUCCESS &&
  87. (error == WS_WANT_READ || error == WS_WANT_WRITE))
  88. {
  89. #if DEBUG
  90. if (error == WS_WANT_READ)
  91. printf("... client would read block\n");
  92. else if (error == WS_WANT_WRITE)
  93. printf("... client would write block\n");
  94. #endif
  95. select_ret = tcp_select(sockfd, 1);
  96. if (select_ret == WS_SELECT_RECV_READY ||
  97. select_ret == WS_SELECT_ERROR_READY ||
  98. error == WS_WANT_WRITE)
  99. {
  100. ret = wolfSSH_accept(ssh);
  101. error = wolfSSH_get_error(ssh);
  102. }
  103. else if (select_ret == WS_SELECT_TIMEOUT)
  104. error = WS_WANT_READ;
  105. else
  106. error = WS_FATAL_ERROR;
  107. }
  108. return ret;
  109. }
  110. static void cli_send(intptr_t fd, const char *str, unsigned len)
  111. {
  112. wolfSSH_stream_send((WOLFSSH *)fd, str, len);
  113. }
  114. static void *server_worker(void* vArgs)
  115. {
  116. int ret;
  117. thread_ctx_t* threadCtx = (thread_ctx_t*)vArgs;
  118. user_level_t user_id;
  119. wolfSSH_SetUserAuthCtx(threadCtx->ssh, &user_id);
  120. if (!nonBlock)
  121. ret = wolfSSH_accept(threadCtx->ssh);
  122. else
  123. ret = NonBlockSSH_accept(threadCtx->ssh);
  124. fl_reinit_ssh = true;
  125. cli_state_t *cli_state;
  126. if (!sSettings.sSSH.SSHEnable) {
  127. // kick the client out
  128. } else if (ret == WS_SUCCESS) {
  129. if ((cli_state = alloc_state())) {
  130. // create the new CLI contex
  131. cli_state->num_connect = threadCtx->ssh;
  132. cli_state->input_state = CLI_CMD;
  133. cli_state->send = cli_send;
  134. cli_state->user_id = user_id;
  135. cli_hello(cli_state);
  136. bool stop = false;
  137. do {
  138. uint8_t buf[EXAMPLE_BUFFER_SZ];
  139. int rxSz = 0;
  140. do {
  141. if (nonBlock) {
  142. SOCKET_T sockfd;
  143. int select_ret = 0;
  144. sockfd = (SOCKET_T)wolfSSH_get_fd(threadCtx->ssh);
  145. select_ret = tcp_select(sockfd, 1);
  146. if (!sSettings.sSSH.SSHEnable ||
  147. (select_ret != WS_SELECT_RECV_READY &&
  148. select_ret != WS_SELECT_ERROR_READY &&
  149. select_ret != WS_SELECT_TIMEOUT)) {
  150. break;
  151. }
  152. }
  153. rxSz = wolfSSH_stream_read(threadCtx->ssh, buf, sizeof(buf));
  154. if (rxSz <= 0) {
  155. rxSz = wolfSSH_get_error(threadCtx->ssh);
  156. }
  157. } while ((rxSz == WS_WANT_READ || rxSz == WS_WANT_WRITE) && sSettings.sSSH.SSHEnable);
  158. if (!sSettings.sSSH.SSHEnable) {
  159. stop = true;
  160. break;
  161. }
  162. if (rxSz > 0) {
  163. cli_getchar(cli_state, buf[0], true); // TODO handle rxSz > 1
  164. if (buf[0] == 4 || cli_state->state == STATE_CLOSE) { // EOF
  165. stop = 1;
  166. }
  167. } else {
  168. stop = 1;
  169. }
  170. } while (!stop);
  171. free_state(cli_state);
  172. } else {
  173. cli_send(threadCtx->ssh, pcWarningMessage, pcWarningMessageLen);
  174. }
  175. }
  176. wolfSSH_stream_exit(threadCtx->ssh, 0);
  177. WCLOSESOCKET(threadCtx->fd);
  178. wolfSSH_free(threadCtx->ssh);
  179. free(threadCtx);
  180. return 0;
  181. }
  182. #ifndef NO_FILESYSTEM
  183. static int load_file(const char* fileName, byte* buf, word32 bufSz)
  184. {
  185. FILE* file;
  186. word32 fileSz;
  187. word32 readSz;
  188. if (fileName == NULL) return 0;
  189. if (WFOPEN(&file, fileName, "rb") != 0)
  190. return 0;
  191. fseek(file, 0, SEEK_END);
  192. fileSz = (word32)ftell(file);
  193. rewind(file);
  194. if (fileSz > bufSz) {
  195. fclose(file);
  196. return 0;
  197. }
  198. readSz = (word32)fread(buf, 1, fileSz, file);
  199. if (readSz < fileSz) {
  200. fclose(file);
  201. return 0;
  202. }
  203. fclose(file);
  204. return fileSz;
  205. }
  206. #endif /* !NO_FILESYSTEM */
  207. /* returns buffer size on success */
  208. static int load_key(byte isEcc, byte* buf, word32 bufSz)
  209. {
  210. word32 sz = 0;
  211. #ifndef NO_FILESYSTEM
  212. const char* bufName;
  213. bufName = isEcc ? "./keys/server-key-ecc.der" :
  214. "./keys/server-key-rsa.der" ;
  215. sz = load_file(bufName, buf, bufSz);
  216. #else
  217. /* using buffers instead */
  218. if (isEcc) {
  219. if (sizeof_ecc_key_der_256 > bufSz) {
  220. return 0;
  221. }
  222. WMEMCPY(buf, ecc_key_der_256, sizeof_ecc_key_der_256);
  223. sz = sizeof_ecc_key_der_256;
  224. }
  225. else {
  226. if (sizeof_rsa_key_der_2048 > bufSz) {
  227. return 0;
  228. }
  229. WMEMCPY(buf, rsa_key_der_2048, sizeof_rsa_key_der_2048);
  230. sz = sizeof_rsa_key_der_2048;
  231. }
  232. #endif
  233. return sz;
  234. }
  235. static INLINE void c32toa(word32 u32, byte* c)
  236. {
  237. c[0] = (u32 >> 24) & 0xff;
  238. c[1] = (u32 >> 16) & 0xff;
  239. c[2] = (u32 >> 8) & 0xff;
  240. c[3] = u32 & 0xff;
  241. }
  242. static int wsUserAuth(byte authType, WS_UserAuthData* authData, void* ctx)
  243. {
  244. user_level_t *user_id = ctx;
  245. if (ctx == NULL) {
  246. printf("wsUserAuth: ctx not set");
  247. return WOLFSSH_USERAUTH_FAILURE;
  248. }
  249. if (authType != WOLFSSH_USERAUTH_PASSWORD) {
  250. return WOLFSSH_USERAUTH_FAILURE;
  251. }
  252. // the incoming password is not zero-terminated
  253. char password[MAX_WEB_PASSWD_LEN];
  254. strncpy(password, (char *)authData->sf.password.password, sizeof(password));
  255. password[min(MAX_WEB_PASSWD_LEN - 1, authData->sf.password.passwordSz)] = 0;
  256. *user_id = cli_auth_user((const char *)authData->username, password, LOG_LOGIN_SSH);
  257. if (*user_id != MAX_USER_LEVELS) {
  258. return WOLFSSH_USERAUTH_SUCCESS;
  259. }
  260. return WOLFSSH_USERAUTH_INVALID_USER;
  261. }
  262. static void ssh_server(void *arg)
  263. {
  264. (void)arg;
  265. WSTARTTCP();
  266. #ifdef DEBUG_WOLFSSH
  267. wolfSSH_Debugging_ON();
  268. #endif
  269. wolfSSH_Init();
  270. WOLFSSH_CTX* ctx = NULL;
  271. static SOCKET_T ssh_listen_fd = 0;
  272. word32 defaultHighwater = EXAMPLE_HIGHWATER_MARK;
  273. word32 threadCount = 0;
  274. const char multipleConnections = 0;
  275. char useEcc = 1;
  276. if (wolfSSH_Init() != WS_SUCCESS) {
  277. printf("Couldn't initialize wolfSSH.\n");
  278. exit(EXIT_FAILURE);
  279. }
  280. ctx = wolfSSH_CTX_new(WOLFSSH_ENDPOINT_SERVER, NULL);
  281. if (ctx == NULL) {
  282. printf("Couldn't allocate SSH CTX data.\n");
  283. exit(EXIT_FAILURE);
  284. }
  285. wolfSSH_SetUserAuth(ctx, wsUserAuth);
  286. wolfSSH_CTX_SetBanner(ctx, TELNET_CLI_WELCOME_MESSAGE);
  287. {
  288. byte buf[SCRATCH_BUFFER_SZ];
  289. word32 bufSz;
  290. bufSz = load_key(useEcc, buf, SCRATCH_BUFFER_SZ);
  291. if (bufSz == 0) {
  292. printf("Couldn't load key.\n");
  293. exit(EXIT_FAILURE);
  294. }
  295. if (wolfSSH_CTX_UsePrivateKey_buffer(ctx, buf, bufSz,
  296. WOLFSSH_FORMAT_ASN1) < 0) {
  297. printf("Couldn't use key buffer.\n");
  298. exit(EXIT_FAILURE);
  299. }
  300. }
  301. while (sSettings.sSSH.SSHEnable) {
  302. fl_reinit_ssh = false;
  303. word16 port = sSettings.sSSH.port;
  304. tcp_listen(&ssh_listen_fd, &port, 1, false, false);
  305. do {
  306. SOCKET_T clientFd = 0;
  307. SOCKADDR_IN_T clientAddr;
  308. socklen_t clientAddrSz = sizeof(clientAddr);
  309. #ifndef SINGLE_THREADED
  310. THREAD_TYPE thread;
  311. #endif
  312. WOLFSSH* ssh;
  313. thread_ctx_t* threadCtx;
  314. threadCtx = (thread_ctx_t*)malloc(sizeof(thread_ctx_t));
  315. if (threadCtx == NULL) {
  316. printf("Couldn't allocate thread context data.\n");
  317. exit(EXIT_FAILURE);
  318. }
  319. ssh = wolfSSH_new(ctx);
  320. if (ssh == NULL) {
  321. printf("Couldn't allocate SSH data.\n");
  322. exit(EXIT_FAILURE);
  323. }
  324. /* Use the session object for its own highwater callback ctx */
  325. if (defaultHighwater > 0) {
  326. wolfSSH_SetHighwaterCtx(ssh, (void*)ssh);
  327. wolfSSH_SetHighwater(ssh, defaultHighwater);
  328. }
  329. clientFd = accept(ssh_listen_fd, (struct sockaddr*)&clientAddr,
  330. &clientAddrSz);
  331. if (clientFd == -1)
  332. err_sys("tcp accept failed");
  333. if (nonBlock)
  334. tcp_set_nonblocking(&clientFd);
  335. wolfSSH_set_fd(ssh, (int)clientFd);
  336. threadCtx->ssh = ssh;
  337. threadCtx->fd = clientFd;
  338. threadCtx->id = threadCount++;
  339. #ifndef SINGLE_THREADED
  340. ThreadStart(server_worker, threadCtx, &thread);
  341. if (multipleConnections)
  342. ThreadDetach(thread);
  343. else
  344. ThreadJoin(thread);
  345. #else
  346. server_worker(threadCtx);
  347. #endif /* SINGLE_THREADED */
  348. } while (multipleConnections);
  349. if (ssh_listen_fd) {
  350. WCLOSESOCKET(ssh_listen_fd);
  351. ssh_listen_fd = 0;
  352. }
  353. }
  354. wolfSSH_CTX_free(ctx);
  355. if (wolfSSH_Cleanup() != WS_SUCCESS) {
  356. printf("Couldn't clean up wolfSSH.\n");
  357. exit(EXIT_FAILURE);
  358. }
  359. #if defined(HAVE_ECC) && defined(FP_ECC) && defined(HAVE_THREAD_LS)
  360. wc_ecc_fp_free(); /* free per thread cache */
  361. #endif
  362. vTaskDelete(NULL);
  363. }
  364. void ssh_server_init(void)
  365. {
  366. xTaskCreate(ssh_server, ( char * ) "ssh_server", 24*configMINIMAL_STACK_SIZE + EXAMPLE_BUFFER_SZ, NULL, tskIDLE_PRIORITY + 1, NULL);
  367. }
  368. void ssh_server_restart(void)
  369. {
  370. }