server-tls.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. /* server-tls.c
  2. *
  3. * Copyright (C) 2006-2024 wolfSSL Inc.
  4. *
  5. * This file is part of wolfSSL.
  6. *
  7. * wolfSSL 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 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * wolfSSL 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 this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
  20. */
  21. #include "server-tls.h"
  22. /* Espressif FreeRTOS */
  23. #ifndef SINGLE_THREADED
  24. #include <freertos/FreeRTOS.h>
  25. #include <freertos/task.h>
  26. #include <freertos/event_groups.h>
  27. #endif
  28. /* socket includes */
  29. #include <lwip/netdb.h>
  30. #include <lwip/sockets.h>
  31. #include <netinet/tcp.h> /* For TCP options */
  32. #include <sys/socket.h>
  33. #ifndef TCP_RTO_MIN
  34. #define TCP_RTO_MIN 1500
  35. #endif
  36. /* wolfSSL */
  37. /* Always include wolfcrypt/settings.h before any other wolfSSL file. */
  38. /* Reminder: settings.h pulls in user_settings.h; don't include it here. */
  39. #ifdef WOLFSSL_USER_SETTINGS
  40. #include <wolfssl/wolfcrypt/settings.h>
  41. #ifndef WOLFSSL_ESPIDF
  42. #warning "Problem with wolfSSL user_settings."
  43. #warning "Check components/wolfssl/include"
  44. #endif
  45. #include <wolfssl/ssl.h>
  46. #else
  47. /* Define WOLFSSL_USER_SETTINGS project wide for settings.h to include */
  48. /* wolfSSL user settings in ./components/wolfssl/include/user_settings.h */
  49. #error "Missing WOLFSSL_USER_SETTINGS in CMakeLists or Makefile:\
  50. CFLAGS +=-DWOLFSSL_USER_SETTINGS"
  51. #endif
  52. #if defined(WOLFSSL_WC_KYBER)
  53. #include <wolfssl/wolfcrypt/kyber.h>
  54. #include <wolfssl/wolfcrypt/wc_kyber.h>
  55. #endif
  56. #if defined(USE_CERT_BUFFERS_2048) || defined(USE_CERT_BUFFERS_1024)
  57. #include <wolfssl/certs_test.h>
  58. #endif
  59. #ifdef WOLFSSL_TRACK_MEMORY
  60. #include <wolfssl/wolfcrypt/mem_track.h>
  61. #endif
  62. #ifndef NO_DH
  63. /* see also wolfssl/test.h */
  64. #undef DEFAULT_MIN_DHKEY_BITS
  65. #define DEFAULT_MIN_DHKEY_BITS 1024
  66. #undef DEFAULT_MAX_DHKEY_BITS
  67. #define DEFAULT_MAX_DHKEY_BITS 2048
  68. #endif
  69. /* Project */
  70. #include "wifi_connect.h"
  71. #include "time_helper.h"
  72. static const char* const TAG = "server-tls";
  73. int stack_start = -1;
  74. int ShowCiphers(WOLFSSL* ssl)
  75. {
  76. #define CLIENT_TLS_MAX_CIPHER_LENGTH 4096
  77. char ciphers[CLIENT_TLS_MAX_CIPHER_LENGTH];
  78. const char* cipher_used;
  79. int ret = 0;
  80. if (ssl == NULL) {
  81. ESP_LOGI(TAG, "WOLFSSL* ssl is NULL, so no cipher in use");
  82. ret = wolfSSL_get_ciphers(ciphers, (int)sizeof(ciphers));
  83. if (ret == WOLFSSL_SUCCESS) {
  84. for (int i = 0; i < CLIENT_TLS_MAX_CIPHER_LENGTH; i++) {
  85. if (ciphers[i] == ':') {
  86. ciphers[i] = '\n';
  87. }
  88. }
  89. ESP_LOGI(TAG, "Available Ciphers:\n%s\n", ciphers);
  90. }
  91. else {
  92. ESP_LOGE(TAG, "Failed to call wolfSSL_get_ciphers. Error: %d", ret);
  93. }
  94. }
  95. else {
  96. cipher_used = wolfSSL_get_cipher_name(ssl);
  97. ESP_LOGI(TAG, "WOLFSSL* ssl using %s", cipher_used);
  98. }
  99. return ret;
  100. }
  101. /* FreeRTOS */
  102. /* server task */
  103. WOLFSSL_ESP_TASK tls_smp_server_task(void *args)
  104. {
  105. #if defined(SINGLE_THREADED)
  106. #define TLS_SMP_SERVER_TASK_RET ret
  107. #else
  108. #define TLS_SMP_SERVER_TASK_RET
  109. #endif
  110. char buff[256];
  111. const char msg[] = "I hear you fa shizzle!";
  112. struct sockaddr_in servAddr;
  113. struct sockaddr_in clientAddr;
  114. int sockfd;
  115. int connd;
  116. int shutdown = 0;
  117. int ret;
  118. socklen_t size = sizeof(clientAddr);
  119. size_t len;
  120. #if 0
  121. /* optionally set TCP RTO. See also below. */
  122. int rto_min = 200; /* Minimum TCP RTO in milliseconds */
  123. #endif
  124. /* declare wolfSSL objects */
  125. WOLFSSL_CTX* ctx;
  126. WOLFSSL* ssl;
  127. WOLFSSL_ENTER("tls_smp_server_task");
  128. #ifdef DEBUG_WOLFSSL
  129. wolfSSL_Debugging_ON();
  130. ShowCiphers(NULL);
  131. #endif
  132. /* Initialize wolfSSL */
  133. WOLFSSL_MSG("Start wolfSSL_Init()");
  134. wolfSSL_Init();
  135. /* Create a socket that uses an internet IPv4 address,
  136. * Sets the socket to be stream based (TCP),
  137. * 0 means choose the default protocol. */
  138. WOLFSSL_MSG( "start socket())");
  139. if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
  140. ESP_LOGE(TAG, "ERROR: failed to create the socket");
  141. }
  142. /* Optionally set TCP RTO
  143. setsockopt(sockfd, IPPROTO_TCP, TCP_RTO_MIN, &rto_min, sizeof(rto_min)); */
  144. /* Create and initialize WOLFSSL_CTX */
  145. WOLFSSL_MSG("Create and initialize WOLFSSL_CTX");
  146. #if defined(WOLFSSL_SM2) || defined(WOLFSSL_SM3) || defined(WOLFSSL_SM4)
  147. ctx = wolfSSL_CTX_new(wolfSSLv23_server_method());
  148. /* ctx = wolfSSL_CTX_new(wolfTLSv1_3_client_method()); for only TLS 1.3 */
  149. if (ctx == NULL) {
  150. ESP_LOGE(TAG, "ERROR: failed to create WOLFSSL_CTX");
  151. }
  152. #else
  153. if ((ctx = wolfSSL_CTX_new(wolfSSLv23_server_method())) == NULL) {
  154. ESP_LOGE(TAG, "ERROR: failed to create WOLFSSL_CTX");
  155. }
  156. #endif
  157. #if defined(WOLFSSL_SM2) || defined(WOLFSSL_SM3) || defined(WOLFSSL_SM4)
  158. ESP_LOGI(TAG, "Start SM3\n");
  159. /* Optional set explicit ciphers
  160. ret = wolfSSL_CTX_set_cipher_list(ctx, WOLFSSL_ESP32_CIPHER_SUITE);
  161. if (ret == SSL_SUCCESS) {
  162. ESP_LOGI(TAG, "Set cipher list: "WOLFSSL_ESP32_CIPHER_SUITE"\n");
  163. }
  164. else {
  165. ESP_LOGE(TAG, "ERROR: failed to set cipher list: "WOLFSSL_ESP32_CIPHER_SUITE"\n");
  166. }
  167. */
  168. ShowCiphers(NULL);
  169. ESP_LOGI(TAG, "Stack used: %d\n", CONFIG_ESP_MAIN_TASK_STACK_SIZE
  170. - uxTaskGetStackHighWaterMark(NULL));
  171. WOLFSSL_MSG("Loading certificate...");
  172. /* -c Load server certificates into WOLFSSL_CTX */
  173. ret = wolfSSL_CTX_use_certificate_chain_buffer_format(ctx,
  174. CTX_SERVER_CERT,
  175. CTX_SERVER_CERT_SIZE,
  176. CTX_SERVER_CERT_TYPE
  177. );
  178. /* optional wolfSSL_CTX_use_certificate_buffer
  179. ret = wolfSSL_CTX_use_certificate_buffer(ctx,
  180. server_sm2,
  181. sizeof_server_sm2,
  182. WOLFSSL_FILETYPE_PEM);
  183. */
  184. if (ret == SSL_SUCCESS) {
  185. ESP_LOGI(TAG, "Loaded server_sm2\n");
  186. }
  187. else {
  188. ESP_LOGE(TAG, "ERROR: failed to load cert\n");
  189. }
  190. ESP_LOGI(TAG, "Stack used: %d\n", CONFIG_ESP_MAIN_TASK_STACK_SIZE
  191. - uxTaskGetStackHighWaterMark(NULL));
  192. #ifndef NO_DH
  193. #define DEFAULT_MIN_DHKEY_BITS 1024
  194. #define DEFAULT_MAX_DHKEY_BITS 2048
  195. int minDhKeyBits = DEFAULT_MIN_DHKEY_BITS;
  196. ret = wolfSSL_CTX_SetMinDhKey_Sz(ctx, (word16)minDhKeyBits);
  197. #endif
  198. #ifndef NO_RSA
  199. #define DEFAULT_MIN_RSAKEY_BITS 1024
  200. short minRsaKeyBits = DEFAULT_MIN_RSAKEY_BITS;
  201. ret = wolfSSL_CTX_SetMinRsaKey_Sz(ctx, minRsaKeyBits);
  202. #endif
  203. WOLFSSL_MSG("Loading key info...");
  204. /* -k Load server key into WOLFSSL_CTX */
  205. ret = wolfSSL_CTX_use_PrivateKey_buffer(ctx,
  206. CTX_SERVER_KEY,
  207. CTX_SERVER_KEY_SIZE,
  208. CTX_SERVER_KEY_TYPE);
  209. if (ret == SSL_SUCCESS) {
  210. ESP_LOGI(TAG, "Loaded PrivateKey_buffer server_sm2_priv\n");
  211. }
  212. else {
  213. ESP_LOGE(TAG, "ERROR: failed to load "
  214. "PrivateKey_buffer server_sm2_priv\n");
  215. }
  216. ESP_LOGI(TAG, "Stack used: %d\n", CONFIG_ESP_MAIN_TASK_STACK_SIZE
  217. - uxTaskGetStackHighWaterMark(NULL));
  218. /* -A load authority */
  219. ret = wolfSSL_CTX_load_verify_buffer(ctx,
  220. client_sm2,
  221. sizeof_client_sm2,
  222. WOLFSSL_FILETYPE_PEM);
  223. if (ret == SSL_SUCCESS) {
  224. ESP_LOGI(TAG, "Success: load verify buffer\n");
  225. }
  226. else {
  227. ESP_LOGE(TAG, "ERROR: failed to load verify buffer\n");
  228. }
  229. ESP_LOGI(TAG, "Finish SM2\n");
  230. #else
  231. WOLFSSL_MSG("Loading certificate...");
  232. /* Load server certificates into WOLFSSL_CTX */
  233. if ((ret = wolfSSL_CTX_use_certificate_buffer(ctx, server_cert_der_2048,
  234. sizeof_server_cert_der_2048,
  235. WOLFSSL_FILETYPE_ASN1)) != SSL_SUCCESS) {
  236. ESP_LOGE(TAG, "ERROR: failed to load cert");
  237. }
  238. WOLFSSL_MSG("Loading key info...");
  239. /* Load server key into WOLFSSL_CTX */
  240. if((ret=wolfSSL_CTX_use_PrivateKey_buffer(ctx,
  241. server_key_der_2048, sizeof_server_key_der_2048,
  242. WOLFSSL_FILETYPE_ASN1)) != SSL_SUCCESS) {
  243. ESP_LOGE(TAG, "ERROR: failed to load privatekey");
  244. }
  245. #endif
  246. /* TODO when using ECDSA,it loads the provisioned certificate and present it.
  247. TODO when using ECDSA,it uses the generated key instead of loading key */
  248. /* Initialize the server address struct with zeros */
  249. memset(&servAddr, 0, sizeof(servAddr));
  250. /* Fill in the server address */
  251. servAddr.sin_family = AF_INET; /* using IPv4 */
  252. servAddr.sin_port = htons(TLS_SMP_DEFAULT_PORT); /* on port */
  253. servAddr.sin_addr.s_addr = INADDR_ANY; /* from anywhere */
  254. /* Bind the server socket to our port */
  255. if (bind(sockfd, (struct sockaddr*)&servAddr, sizeof(servAddr)) == -1) {
  256. ESP_LOGE(TAG, "ERROR: failed to bind");
  257. }
  258. /* Listen for a new connection, allow 5 pending connections */
  259. if (listen(sockfd, 5) == -1) {
  260. ESP_LOGE(TAG, "ERROR: failed to listen");
  261. }
  262. #if defined(WOLFSSL_ESPWROOM32SE) && defined(HAVE_PK_CALLBACKS) \
  263. && defined(WOLFSSL_ATECC508A)
  264. atcatls_set_callbacks(ctx);
  265. /* when using a custom slot allocation */
  266. #if defined(CUSTOM_SLOT_ALLOCATION)
  267. my_atmel_slotInit();
  268. atmel_set_slot_allocator(my_atmel_alloc, my_atmel_free);
  269. #endif
  270. #endif
  271. #ifdef WOLFSSL_EXAMPLE_VERBOSITY
  272. ESP_LOGI(TAG, "Initial stack used: %d\n",
  273. TLS_SMP_SERVER_TASK_BYTES - uxTaskGetStackHighWaterMark(NULL) );
  274. #endif
  275. ESP_LOGI(TAG, "accept clients...");
  276. /* Continue to accept clients until shutdown is issued */
  277. while (!shutdown) {
  278. WOLFSSL_MSG("Waiting for a connection...");
  279. #if ESP_IDF_VERSION_MAJOR >=4
  280. /* TODO: IP Address is problematic in RTOS SDK 3.4 */
  281. wifi_show_ip();
  282. #endif
  283. /* Accept client socket connections */
  284. if ((connd = accept(sockfd, (struct sockaddr*)&clientAddr, &size))
  285. == -1) {
  286. ESP_LOGE(TAG, "ERROR: failed to accept the connection");
  287. }
  288. #if defined(WOLFSSL_EXPERIMENTAL_SETTINGS)
  289. ESP_LOGW(TAG, "WOLFSSL_EXPERIMENTAL_SETTINGS is enabled");
  290. #endif
  291. /* Create a WOLFSSL object */
  292. if ((ssl = wolfSSL_new(ctx)) == NULL) {
  293. ESP_LOGE(TAG, "ERROR: failed to create WOLFSSL object");
  294. }
  295. #if defined(WOLFSSL_HAVE_KYBER)
  296. else {
  297. /* If success creating CTX and Kyber enabled, set key share: */
  298. ret = wolfSSL_UseKeyShare(ssl, WOLFSSL_P521_KYBER_LEVEL5);
  299. if (ret == SSL_SUCCESS) {
  300. ESP_LOGI(TAG, "UseKeyShare WOLFSSL_P521_KYBER_LEVEL5 success");
  301. }
  302. else {
  303. ESP_LOGE(TAG, "UseKeyShare WOLFSSL_P521_KYBER_LEVEL5 failed");
  304. }
  305. }
  306. #else
  307. ESP_LOGI(TAG, "WOLFSSL_HAVE_KYBER is not enabled, not using PQ.");
  308. #endif
  309. /* show what cipher connected for this WOLFSSL* object */
  310. ShowCiphers(ssl);
  311. /* Attach wolfSSL to the socket */
  312. wolfSSL_set_fd(ssl, connd);
  313. /* Establish TLS connection */
  314. ret = wolfSSL_accept(ssl);
  315. if (ret == SSL_SUCCESS) {
  316. ShowCiphers(ssl);
  317. }
  318. else {
  319. ESP_LOGE(TAG, "wolfSSL_accept error %d",
  320. wolfSSL_get_error(ssl, ret));
  321. }
  322. ESP_LOGI(TAG, "Client connected successfully");
  323. /* Read the client data into our buff array */
  324. memset(buff, 0, sizeof(buff));
  325. if (wolfSSL_read(ssl, buff, sizeof(buff)-1) == -1) {
  326. ESP_LOGE(TAG, "ERROR: failed to read");
  327. }
  328. ESP_LOGI(TAG, "Client sends: %s", buff);
  329. /* Check for server shutdown command */
  330. if (strncmp(buff, "shutdown", 8) == 0) {
  331. ESP_LOGI(TAG, "Shutdown command issued!");
  332. shutdown = 1;
  333. }
  334. /* Write our reply into buff */
  335. memset(buff, 0, sizeof(buff));
  336. memcpy(buff, msg, sizeof(msg));
  337. len = strnlen(buff, sizeof(buff));
  338. /* Reply back to the client */
  339. if (wolfSSL_write(ssl, buff, len) != len) {
  340. ESP_LOGE(TAG, "ERROR: failed to write");
  341. }
  342. ESP_LOGI(TAG, "Done! Cleanup...");
  343. /* Cleanup after this connection */
  344. wolfSSL_free(ssl); /* Free the wolfSSL object */
  345. close(connd); /* Close the connection to the client */
  346. #ifdef WOLFSSL_EXAMPLE_VERBOSITY
  347. ESP_LOGI(TAG, "Stack used: %d\n",
  348. TLS_SMP_SERVER_TASK_BYTES - uxTaskGetStackHighWaterMark(NULL));
  349. #endif
  350. } /* !shutdown */
  351. /* Cleanup and return */
  352. wolfSSL_free(ssl); /* Free the wolfSSL object */
  353. wolfSSL_CTX_free(ctx); /* Free the wolfSSL context object */
  354. wolfSSL_Cleanup(); /* Cleanup the wolfSSL environment */
  355. close(sockfd); /* Close the socket listening for clients */
  356. vTaskDelete(NULL);
  357. return TLS_SMP_SERVER_TASK_RET;
  358. }
  359. #if defined(SINGLE_THREADED)
  360. /* we don't initialize a thread */
  361. #else
  362. /* create task */
  363. WOLFSSL_ESP_TASK tls_smp_server_init(void* args)
  364. {
  365. #if defined(SINGLE_THREADED)
  366. #define TLS_SMP_CLIENT_TASK_RET ret
  367. #else
  368. #define TLS_SMP_CLIENT_TASK_RET
  369. #endif
  370. int thisPort = 0;
  371. int ret_i = 0; /* interim return result */
  372. if (thisPort == 0) {
  373. thisPort = TLS_SMP_DEFAULT_PORT;
  374. }
  375. #if ESP_IDF_VERSION_MAJOR >= 4
  376. TaskHandle_t _handle;
  377. #else
  378. xTaskHandle _handle;
  379. #endif
  380. /* Note that despite vanilla FreeRTOS using WORDS for a parameter,
  381. * Espressif uses BYTES for the task stack size here. */
  382. ESP_LOGI(TAG, "Creating tls_smp_server_task with stack size = %d",
  383. TLS_SMP_SERVER_TASK_BYTES);
  384. ret_i = xTaskCreate(tls_smp_server_task,
  385. TLS_SMP_SERVER_TASK_NAME,
  386. TLS_SMP_SERVER_TASK_BYTES,
  387. (void*)&thisPort,
  388. TLS_SMP_SERVER_TASK_PRIORITY,
  389. &_handle);
  390. if (ret_i != pdPASS) {
  391. ESP_LOGI(TAG, "create thread %s failed", TLS_SMP_SERVER_TASK_NAME);
  392. }
  393. /* vTaskStartScheduler(); called automatically in ESP-IDF */
  394. return TLS_SMP_CLIENT_TASK_RET;
  395. }
  396. #endif