ssl_pthread_server.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. /*
  2. * SSL server demonstration program using pthread for handling multiple
  3. * clients.
  4. *
  5. * Copyright The Mbed TLS Contributors
  6. * SPDX-License-Identifier: Apache-2.0
  7. *
  8. * Licensed under the Apache License, Version 2.0 (the "License"); you may
  9. * not use this file except in compliance with the License.
  10. * You may obtain a copy of the License at
  11. *
  12. * http://www.apache.org/licenses/LICENSE-2.0
  13. *
  14. * Unless required by applicable law or agreed to in writing, software
  15. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  16. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17. * See the License for the specific language governing permissions and
  18. * limitations under the License.
  19. */
  20. #include "mbedtls/build_info.h"
  21. #include "mbedtls/platform.h"
  22. #if !defined(MBEDTLS_BIGNUM_C) || !defined(MBEDTLS_ENTROPY_C) || \
  23. !defined(MBEDTLS_SSL_TLS_C) || !defined(MBEDTLS_SSL_SRV_C) || \
  24. !defined(MBEDTLS_NET_C) || !defined(MBEDTLS_RSA_C) || \
  25. !defined(MBEDTLS_CTR_DRBG_C) || !defined(MBEDTLS_X509_CRT_PARSE_C) || \
  26. !defined(MBEDTLS_FS_IO) || !defined(MBEDTLS_THREADING_C) || \
  27. !defined(MBEDTLS_THREADING_PTHREAD) || !defined(MBEDTLS_PEM_PARSE_C)
  28. int main(void)
  29. {
  30. mbedtls_printf("MBEDTLS_BIGNUM_C and/or MBEDTLS_ENTROPY_C "
  31. "and/or MBEDTLS_SSL_TLS_C and/or MBEDTLS_SSL_SRV_C and/or "
  32. "MBEDTLS_NET_C and/or MBEDTLS_RSA_C and/or "
  33. "MBEDTLS_CTR_DRBG_C and/or MBEDTLS_X509_CRT_PARSE_C and/or "
  34. "MBEDTLS_THREADING_C and/or MBEDTLS_THREADING_PTHREAD "
  35. "and/or MBEDTLS_PEM_PARSE_C not defined.\n");
  36. mbedtls_exit(0);
  37. }
  38. #else
  39. #include <stdlib.h>
  40. #include <string.h>
  41. #if defined(_WIN32)
  42. #include <windows.h>
  43. #endif
  44. #include "mbedtls/entropy.h"
  45. #include "mbedtls/ctr_drbg.h"
  46. #include "mbedtls/x509.h"
  47. #include "mbedtls/ssl.h"
  48. #include "mbedtls/net_sockets.h"
  49. #include "mbedtls/error.h"
  50. #include "test/certs.h"
  51. #if defined(MBEDTLS_SSL_CACHE_C)
  52. #include "mbedtls/ssl_cache.h"
  53. #endif
  54. #if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C)
  55. #include "mbedtls/memory_buffer_alloc.h"
  56. #endif
  57. #define HTTP_RESPONSE \
  58. "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n" \
  59. "<h2>mbed TLS Test Server</h2>\r\n" \
  60. "<p>Successful connection using: %s</p>\r\n"
  61. #define DEBUG_LEVEL 0
  62. #define MAX_NUM_THREADS 5
  63. mbedtls_threading_mutex_t debug_mutex;
  64. static void my_mutexed_debug(void *ctx, int level,
  65. const char *file, int line,
  66. const char *str)
  67. {
  68. long int thread_id = (long int) pthread_self();
  69. mbedtls_mutex_lock(&debug_mutex);
  70. ((void) level);
  71. mbedtls_fprintf((FILE *) ctx, "%s:%04d: [ #%ld ] %s",
  72. file, line, thread_id, str);
  73. fflush((FILE *) ctx);
  74. mbedtls_mutex_unlock(&debug_mutex);
  75. }
  76. typedef struct {
  77. mbedtls_net_context client_fd;
  78. int thread_complete;
  79. const mbedtls_ssl_config *config;
  80. } thread_info_t;
  81. typedef struct {
  82. int active;
  83. thread_info_t data;
  84. pthread_t thread;
  85. } pthread_info_t;
  86. static thread_info_t base_info;
  87. static pthread_info_t threads[MAX_NUM_THREADS];
  88. static void *handle_ssl_connection(void *data)
  89. {
  90. int ret, len;
  91. thread_info_t *thread_info = (thread_info_t *) data;
  92. mbedtls_net_context *client_fd = &thread_info->client_fd;
  93. long int thread_id = (long int) pthread_self();
  94. unsigned char buf[1024];
  95. mbedtls_ssl_context ssl;
  96. /* Make sure memory references are valid */
  97. mbedtls_ssl_init(&ssl);
  98. mbedtls_printf(" [ #%ld ] Setting up SSL/TLS data\n", thread_id);
  99. /*
  100. * 4. Get the SSL context ready
  101. */
  102. if ((ret = mbedtls_ssl_setup(&ssl, thread_info->config)) != 0) {
  103. mbedtls_printf(" [ #%ld ] failed: mbedtls_ssl_setup returned -0x%04x\n",
  104. thread_id, (unsigned int) -ret);
  105. goto thread_exit;
  106. }
  107. mbedtls_ssl_set_bio(&ssl, client_fd, mbedtls_net_send, mbedtls_net_recv, NULL);
  108. /*
  109. * 5. Handshake
  110. */
  111. mbedtls_printf(" [ #%ld ] Performing the SSL/TLS handshake\n", thread_id);
  112. while ((ret = mbedtls_ssl_handshake(&ssl)) != 0) {
  113. if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  114. mbedtls_printf(" [ #%ld ] failed: mbedtls_ssl_handshake returned -0x%04x\n",
  115. thread_id, (unsigned int) -ret);
  116. goto thread_exit;
  117. }
  118. }
  119. mbedtls_printf(" [ #%ld ] ok\n", thread_id);
  120. /*
  121. * 6. Read the HTTP Request
  122. */
  123. mbedtls_printf(" [ #%ld ] < Read from client\n", thread_id);
  124. do {
  125. len = sizeof(buf) - 1;
  126. memset(buf, 0, sizeof(buf));
  127. ret = mbedtls_ssl_read(&ssl, buf, len);
  128. if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  129. continue;
  130. }
  131. if (ret <= 0) {
  132. switch (ret) {
  133. case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
  134. mbedtls_printf(" [ #%ld ] connection was closed gracefully\n",
  135. thread_id);
  136. goto thread_exit;
  137. case MBEDTLS_ERR_NET_CONN_RESET:
  138. mbedtls_printf(" [ #%ld ] connection was reset by peer\n",
  139. thread_id);
  140. goto thread_exit;
  141. default:
  142. mbedtls_printf(" [ #%ld ] mbedtls_ssl_read returned -0x%04x\n",
  143. thread_id, (unsigned int) -ret);
  144. goto thread_exit;
  145. }
  146. }
  147. len = ret;
  148. mbedtls_printf(" [ #%ld ] %d bytes read\n=====\n%s\n=====\n",
  149. thread_id, len, (char *) buf);
  150. if (ret > 0) {
  151. break;
  152. }
  153. } while (1);
  154. /*
  155. * 7. Write the 200 Response
  156. */
  157. mbedtls_printf(" [ #%ld ] > Write to client:\n", thread_id);
  158. len = sprintf((char *) buf, HTTP_RESPONSE,
  159. mbedtls_ssl_get_ciphersuite(&ssl));
  160. while ((ret = mbedtls_ssl_write(&ssl, buf, len)) <= 0) {
  161. if (ret == MBEDTLS_ERR_NET_CONN_RESET) {
  162. mbedtls_printf(" [ #%ld ] failed: peer closed the connection\n",
  163. thread_id);
  164. goto thread_exit;
  165. }
  166. if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  167. mbedtls_printf(" [ #%ld ] failed: mbedtls_ssl_write returned -0x%04x\n",
  168. thread_id, (unsigned int) ret);
  169. goto thread_exit;
  170. }
  171. }
  172. len = ret;
  173. mbedtls_printf(" [ #%ld ] %d bytes written\n=====\n%s\n=====\n",
  174. thread_id, len, (char *) buf);
  175. mbedtls_printf(" [ #%ld ] . Closing the connection...", thread_id);
  176. while ((ret = mbedtls_ssl_close_notify(&ssl)) < 0) {
  177. if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
  178. ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  179. mbedtls_printf(" [ #%ld ] failed: mbedtls_ssl_close_notify returned -0x%04x\n",
  180. thread_id, (unsigned int) ret);
  181. goto thread_exit;
  182. }
  183. }
  184. mbedtls_printf(" ok\n");
  185. ret = 0;
  186. thread_exit:
  187. #ifdef MBEDTLS_ERROR_C
  188. if (ret != 0) {
  189. char error_buf[100];
  190. mbedtls_strerror(ret, error_buf, 100);
  191. mbedtls_printf(" [ #%ld ] Last error was: -0x%04x - %s\n\n",
  192. thread_id, (unsigned int) -ret, error_buf);
  193. }
  194. #endif
  195. mbedtls_net_free(client_fd);
  196. mbedtls_ssl_free(&ssl);
  197. thread_info->thread_complete = 1;
  198. return NULL;
  199. }
  200. static int thread_create(mbedtls_net_context *client_fd)
  201. {
  202. int ret, i;
  203. /*
  204. * Find in-active or finished thread slot
  205. */
  206. for (i = 0; i < MAX_NUM_THREADS; i++) {
  207. if (threads[i].active == 0) {
  208. break;
  209. }
  210. if (threads[i].data.thread_complete == 1) {
  211. mbedtls_printf(" [ main ] Cleaning up thread %d\n", i);
  212. pthread_join(threads[i].thread, NULL);
  213. memset(&threads[i], 0, sizeof(pthread_info_t));
  214. break;
  215. }
  216. }
  217. if (i == MAX_NUM_THREADS) {
  218. return -1;
  219. }
  220. /*
  221. * Fill thread-info for thread
  222. */
  223. memcpy(&threads[i].data, &base_info, sizeof(base_info));
  224. threads[i].active = 1;
  225. memcpy(&threads[i].data.client_fd, client_fd, sizeof(mbedtls_net_context));
  226. if ((ret = pthread_create(&threads[i].thread, NULL, handle_ssl_connection,
  227. &threads[i].data)) != 0) {
  228. return ret;
  229. }
  230. return 0;
  231. }
  232. int main(void)
  233. {
  234. int ret;
  235. mbedtls_net_context listen_fd, client_fd;
  236. const char pers[] = "ssl_pthread_server";
  237. mbedtls_entropy_context entropy;
  238. mbedtls_ctr_drbg_context ctr_drbg;
  239. mbedtls_ssl_config conf;
  240. mbedtls_x509_crt srvcert;
  241. mbedtls_x509_crt cachain;
  242. mbedtls_pk_context pkey;
  243. #if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C)
  244. unsigned char alloc_buf[100000];
  245. #endif
  246. #if defined(MBEDTLS_SSL_CACHE_C)
  247. mbedtls_ssl_cache_context cache;
  248. #endif
  249. #if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C)
  250. mbedtls_memory_buffer_alloc_init(alloc_buf, sizeof(alloc_buf));
  251. #endif
  252. #if defined(MBEDTLS_SSL_CACHE_C)
  253. mbedtls_ssl_cache_init(&cache);
  254. #endif
  255. mbedtls_x509_crt_init(&srvcert);
  256. mbedtls_x509_crt_init(&cachain);
  257. mbedtls_ssl_config_init(&conf);
  258. mbedtls_ctr_drbg_init(&ctr_drbg);
  259. memset(threads, 0, sizeof(threads));
  260. mbedtls_net_init(&listen_fd);
  261. mbedtls_net_init(&client_fd);
  262. mbedtls_mutex_init(&debug_mutex);
  263. base_info.config = &conf;
  264. /*
  265. * We use only a single entropy source that is used in all the threads.
  266. */
  267. mbedtls_entropy_init(&entropy);
  268. /*
  269. * 1a. Seed the random number generator
  270. */
  271. mbedtls_printf(" . Seeding the random number generator...");
  272. if ((ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy,
  273. (const unsigned char *) pers,
  274. strlen(pers))) != 0) {
  275. mbedtls_printf(" failed: mbedtls_ctr_drbg_seed returned -0x%04x\n",
  276. (unsigned int) -ret);
  277. goto exit;
  278. }
  279. mbedtls_printf(" ok\n");
  280. /*
  281. * 1b. Load the certificates and private RSA key
  282. */
  283. mbedtls_printf("\n . Loading the server cert. and key...");
  284. fflush(stdout);
  285. /*
  286. * This demonstration program uses embedded test certificates.
  287. * Instead, you may want to use mbedtls_x509_crt_parse_file() to read the
  288. * server and CA certificates, as well as mbedtls_pk_parse_keyfile().
  289. */
  290. ret = mbedtls_x509_crt_parse(&srvcert, (const unsigned char *) mbedtls_test_srv_crt,
  291. mbedtls_test_srv_crt_len);
  292. if (ret != 0) {
  293. mbedtls_printf(" failed\n ! mbedtls_x509_crt_parse returned %d\n\n", ret);
  294. goto exit;
  295. }
  296. ret = mbedtls_x509_crt_parse(&cachain, (const unsigned char *) mbedtls_test_cas_pem,
  297. mbedtls_test_cas_pem_len);
  298. if (ret != 0) {
  299. mbedtls_printf(" failed\n ! mbedtls_x509_crt_parse returned %d\n\n", ret);
  300. goto exit;
  301. }
  302. mbedtls_pk_init(&pkey);
  303. ret = mbedtls_pk_parse_key(&pkey, (const unsigned char *) mbedtls_test_srv_key,
  304. mbedtls_test_srv_key_len, NULL, 0,
  305. mbedtls_ctr_drbg_random, &ctr_drbg);
  306. if (ret != 0) {
  307. mbedtls_printf(" failed\n ! mbedtls_pk_parse_key returned %d\n\n", ret);
  308. goto exit;
  309. }
  310. mbedtls_printf(" ok\n");
  311. /*
  312. * 1c. Prepare SSL configuration
  313. */
  314. mbedtls_printf(" . Setting up the SSL data....");
  315. if ((ret = mbedtls_ssl_config_defaults(&conf,
  316. MBEDTLS_SSL_IS_SERVER,
  317. MBEDTLS_SSL_TRANSPORT_STREAM,
  318. MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
  319. mbedtls_printf(" failed: mbedtls_ssl_config_defaults returned -0x%04x\n",
  320. (unsigned int) -ret);
  321. goto exit;
  322. }
  323. mbedtls_ssl_conf_rng(&conf, mbedtls_ctr_drbg_random, &ctr_drbg);
  324. mbedtls_ssl_conf_dbg(&conf, my_mutexed_debug, stdout);
  325. /* mbedtls_ssl_cache_get() and mbedtls_ssl_cache_set() are thread-safe if
  326. * MBEDTLS_THREADING_C is set.
  327. */
  328. #if defined(MBEDTLS_SSL_CACHE_C)
  329. mbedtls_ssl_conf_session_cache(&conf, &cache,
  330. mbedtls_ssl_cache_get,
  331. mbedtls_ssl_cache_set);
  332. #endif
  333. mbedtls_ssl_conf_ca_chain(&conf, &cachain, NULL);
  334. if ((ret = mbedtls_ssl_conf_own_cert(&conf, &srvcert, &pkey)) != 0) {
  335. mbedtls_printf(" failed\n ! mbedtls_ssl_conf_own_cert returned %d\n\n", ret);
  336. goto exit;
  337. }
  338. mbedtls_printf(" ok\n");
  339. /*
  340. * 2. Setup the listening TCP socket
  341. */
  342. mbedtls_printf(" . Bind on https://localhost:4433/ ...");
  343. fflush(stdout);
  344. if ((ret = mbedtls_net_bind(&listen_fd, NULL, "4433", MBEDTLS_NET_PROTO_TCP)) != 0) {
  345. mbedtls_printf(" failed\n ! mbedtls_net_bind returned %d\n\n", ret);
  346. goto exit;
  347. }
  348. mbedtls_printf(" ok\n");
  349. reset:
  350. #ifdef MBEDTLS_ERROR_C
  351. if (ret != 0) {
  352. char error_buf[100];
  353. mbedtls_strerror(ret, error_buf, 100);
  354. mbedtls_printf(" [ main ] Last error was: -0x%04x - %s\n", (unsigned int) -ret,
  355. error_buf);
  356. }
  357. #endif
  358. /*
  359. * 3. Wait until a client connects
  360. */
  361. mbedtls_printf(" [ main ] Waiting for a remote connection\n");
  362. if ((ret = mbedtls_net_accept(&listen_fd, &client_fd,
  363. NULL, 0, NULL)) != 0) {
  364. mbedtls_printf(" [ main ] failed: mbedtls_net_accept returned -0x%04x\n",
  365. (unsigned int) ret);
  366. goto exit;
  367. }
  368. mbedtls_printf(" [ main ] ok\n");
  369. mbedtls_printf(" [ main ] Creating a new thread\n");
  370. if ((ret = thread_create(&client_fd)) != 0) {
  371. mbedtls_printf(" [ main ] failed: thread_create returned %d\n", ret);
  372. mbedtls_net_free(&client_fd);
  373. goto reset;
  374. }
  375. ret = 0;
  376. goto reset;
  377. exit:
  378. mbedtls_x509_crt_free(&srvcert);
  379. mbedtls_pk_free(&pkey);
  380. #if defined(MBEDTLS_SSL_CACHE_C)
  381. mbedtls_ssl_cache_free(&cache);
  382. #endif
  383. mbedtls_ctr_drbg_free(&ctr_drbg);
  384. mbedtls_entropy_free(&entropy);
  385. mbedtls_ssl_config_free(&conf);
  386. mbedtls_net_free(&listen_fd);
  387. mbedtls_mutex_free(&debug_mutex);
  388. #if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C)
  389. mbedtls_memory_buffer_alloc_free();
  390. #endif
  391. mbedtls_exit(ret);
  392. }
  393. #endif /* MBEDTLS_BIGNUM_C && MBEDTLS_ENTROPY_C &&
  394. MBEDTLS_SSL_TLS_C && MBEDTLS_SSL_SRV_C && MBEDTLS_NET_C &&
  395. MBEDTLS_RSA_C && MBEDTLS_CTR_DRBG_C && MBEDTLS_THREADING_C &&
  396. MBEDTLS_THREADING_PTHREAD && MBEDTLS_PEM_PARSE_C */