server-tls.c 14 KB

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