ssl_pthread_server.c 15 KB

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