test_esp_crt_bundle.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. /* SSL server using plain mbedTLS sockets
  2. *
  3. * Adapted from the ssl_server example in mbedtls.
  4. *
  5. * SPDX-FileCopyrightText: The Mbed TLS Contributors
  6. *
  7. * SPDX-License-Identifier: Apache-2.0
  8. *
  9. * SPDX-FileContributor: 2019-2022 Espressif Systems (Shanghai) CO LTD
  10. */
  11. #include "esp_err.h"
  12. #include "esp_log.h"
  13. #include "freertos/FreeRTOS.h"
  14. #include "freertos/task.h"
  15. #include "freertos/semphr.h"
  16. #include "mbedtls/entropy.h"
  17. #include "mbedtls/ctr_drbg.h"
  18. #include "mbedtls/x509.h"
  19. #include "mbedtls/ssl.h"
  20. #include "entropy_poll.h"
  21. #include "mbedtls/net_sockets.h"
  22. #include "mbedtls/error.h"
  23. #include "mbedtls/debug.h"
  24. #include "esp_crt_bundle.h"
  25. #include "esp_random.h"
  26. #include "unity.h"
  27. #include "test_utils.h"
  28. #define SERVER_ADDRESS "localhost"
  29. #define SERVER_PORT "4433"
  30. extern const uint8_t server_cert_chain_pem_start[] asm("_binary_server_cert_chain_pem_start");
  31. extern const uint8_t server_cert_chain_pem_end[] asm("_binary_server_cert_chain_pem_end");
  32. extern const uint8_t server_pk_start[] asm("_binary_prvtkey_pem_start");
  33. extern const uint8_t server_pk_end[] asm("_binary_prvtkey_pem_end");
  34. extern const uint8_t server_cert_bundle_start[] asm("_binary_server_cert_bundle_start");
  35. extern const uint8_t server_cert_bundle_end[] asm("_binary_server_cert_bundle_end");
  36. extern const uint8_t bad_md_crt_pem_start[] asm("_binary_bad_md_crt_pem_start");
  37. extern const uint8_t bad_md_crt_pem_end[] asm("_binary_bad_md_crt_pem_end");
  38. extern const uint8_t wrong_sig_crt_pem_start[] asm("_binary_wrong_sig_crt_esp32_com_pem_start");
  39. extern const uint8_t wrong_sig_crt_pem_end[] asm("_binary_wrong_sig_crt_esp32_com_pem_end");
  40. extern const uint8_t correct_sig_crt_pem_start[] asm("_binary_correct_sig_crt_esp32_com_pem_start");
  41. extern const uint8_t correct_sig_crt_pem_end[] asm("_binary_correct_sig_crt_esp32_com_pem_end");
  42. typedef struct {
  43. mbedtls_ssl_context ssl;
  44. mbedtls_net_context listen_fd;
  45. mbedtls_net_context client_fd;
  46. mbedtls_entropy_context entropy;
  47. mbedtls_ctr_drbg_context ctr_drbg;
  48. mbedtls_ssl_config conf;
  49. mbedtls_x509_crt cert;
  50. mbedtls_pk_context pkey;
  51. } mbedtls_endpoint_t;
  52. typedef enum {
  53. ESP_CRT_VALIDATE_UNKNOWN,
  54. ESP_CRT_VALIDATE_OK,
  55. ESP_CRT_VALIDATE_FAIL,
  56. }esp_crt_validate_res_t;
  57. int esp_crt_verify_callback(void *buf, mbedtls_x509_crt *crt, int data, uint32_t *flags);
  58. static const char *TAG = "cert_bundle_test";
  59. static volatile bool exit_flag;
  60. esp_err_t endpoint_teardown(mbedtls_endpoint_t *endpoint);
  61. static int myrand(void *rng_state, unsigned char *output, size_t len)
  62. {
  63. size_t olen;
  64. return mbedtls_hardware_poll(rng_state, output, len, &olen);
  65. }
  66. esp_err_t server_setup(mbedtls_endpoint_t *server)
  67. {
  68. int ret;
  69. mbedtls_ssl_config_init( &server->conf );
  70. mbedtls_net_init( &server->listen_fd );
  71. mbedtls_net_init( &server->client_fd );
  72. mbedtls_ssl_init( &server->ssl );
  73. mbedtls_x509_crt_init( &server->cert );
  74. mbedtls_pk_init( &server->pkey );
  75. mbedtls_entropy_init( &server->entropy );
  76. mbedtls_ctr_drbg_init( &server->ctr_drbg );
  77. ESP_LOGI(TAG, "Loading the server cert and key");
  78. ret = mbedtls_x509_crt_parse( &server->cert, server_cert_chain_pem_start,
  79. server_cert_chain_pem_end - server_cert_chain_pem_start);
  80. if ( ret != 0 ) {
  81. ESP_LOGE(TAG, "mbedtls_x509_crt_parse returned %d", ret );
  82. return ESP_FAIL;
  83. }
  84. ret = mbedtls_pk_parse_key( &server->pkey, (const unsigned char *)server_pk_start,
  85. server_pk_end - server_pk_start, NULL, 0, myrand, NULL );
  86. if ( ret != 0 ) {
  87. ESP_LOGE(TAG, "mbedtls_pk_parse_key returned %d", ret );
  88. return ESP_FAIL;
  89. }
  90. ESP_LOGI(TAG, "Bind on https://%s:%s/", SERVER_ADDRESS, SERVER_PORT );
  91. if ( ( ret = mbedtls_net_bind( &server->listen_fd, NULL, SERVER_PORT, MBEDTLS_NET_PROTO_TCP ) ) != 0 ) {
  92. ESP_LOGE(TAG, "mbedtls_net_bind returned %d", ret );
  93. return ESP_FAIL;
  94. }
  95. mbedtls_net_set_nonblock(&server->listen_fd);
  96. ESP_LOGI(TAG, "Seeding the random number generator");
  97. if ( ( ret = mbedtls_ctr_drbg_seed( &server->ctr_drbg, mbedtls_entropy_func, &server->entropy,
  98. NULL, 0) ) != 0 ) {
  99. ESP_LOGE(TAG, "mbedtls_ctr_drbg_seed returned %d", ret );
  100. return ESP_FAIL;
  101. }
  102. ESP_LOGI(TAG, "Setting up the SSL data");
  103. if ( ( ret = mbedtls_ssl_config_defaults( &server->conf,
  104. MBEDTLS_SSL_IS_SERVER,
  105. MBEDTLS_SSL_TRANSPORT_STREAM,
  106. MBEDTLS_SSL_PRESET_DEFAULT ) ) != 0 ) {
  107. ESP_LOGE(TAG, "mbedtls_ssl_config_defaults returned %d", ret );
  108. return ESP_FAIL;
  109. }
  110. mbedtls_ssl_conf_rng( &server->conf, mbedtls_ctr_drbg_random, &server->ctr_drbg );
  111. if (( ret = mbedtls_ssl_conf_own_cert( &server->conf, &server->cert, &server->pkey ) ) != 0 ) {
  112. ESP_LOGE(TAG, "mbedtls_ssl_conf_own_cert returned %d", ret );
  113. return ESP_FAIL;
  114. }
  115. if (( ret = mbedtls_ssl_setup( &server->ssl, &server->conf ) ) != 0 ) {
  116. ESP_LOGE(TAG, "mbedtls_ssl_setup returned %d", ret );
  117. return ESP_FAIL;
  118. }
  119. return ESP_OK;
  120. }
  121. void server_task(void *pvParameters)
  122. {
  123. int ret;
  124. mbedtls_endpoint_t server;
  125. SemaphoreHandle_t *sema = (SemaphoreHandle_t *) pvParameters;
  126. if (server_setup(&server) != ESP_OK) {
  127. ESP_LOGE(TAG, "SSL server setup failed");
  128. goto exit;
  129. }
  130. /* Signal that server is up and hence client task can start now */
  131. xSemaphoreGive(*sema);
  132. bool connected = false;
  133. while (!exit_flag) {
  134. ret = mbedtls_net_accept( &server.listen_fd, &server.client_fd, NULL, 0, NULL );
  135. if (ret == 0) {
  136. connected = true;
  137. }
  138. if (connected) {
  139. mbedtls_ssl_set_bio( &server.ssl, &server.client_fd, mbedtls_net_send, mbedtls_net_recv, NULL );
  140. ret = mbedtls_ssl_handshake( &server.ssl );
  141. mbedtls_ssl_session_reset(&server.ssl);
  142. connected = false;
  143. }
  144. vTaskDelay(20 / portTICK_PERIOD_MS);
  145. }
  146. ESP_LOGE(TAG, "Server shutdown");
  147. exit:
  148. endpoint_teardown(&server);
  149. xSemaphoreGive(*sema);
  150. vTaskDelete(NULL);
  151. }
  152. esp_err_t endpoint_teardown(mbedtls_endpoint_t *endpoint)
  153. {
  154. mbedtls_net_free( &endpoint->client_fd );
  155. mbedtls_net_free( &endpoint->listen_fd );
  156. mbedtls_x509_crt_free( &endpoint->cert );
  157. mbedtls_pk_free( &endpoint->pkey );
  158. mbedtls_ssl_free( &endpoint->ssl );
  159. mbedtls_ssl_config_free( &endpoint->conf );
  160. mbedtls_ctr_drbg_free( &endpoint->ctr_drbg );
  161. mbedtls_entropy_free( &endpoint->entropy );
  162. return ESP_OK;
  163. }
  164. esp_err_t client_setup(mbedtls_endpoint_t *client)
  165. {
  166. int ret;
  167. mbedtls_ssl_config_init( &client->conf );
  168. mbedtls_net_init( &client->client_fd );
  169. mbedtls_ssl_init( &client->ssl );
  170. mbedtls_x509_crt_init( &client->cert );
  171. mbedtls_pk_init( &client->pkey );
  172. mbedtls_entropy_init( &client->entropy );
  173. mbedtls_ctr_drbg_init( &client->ctr_drbg );
  174. ESP_LOGI(TAG, "Seeding the random number generator");
  175. if ((ret = mbedtls_ctr_drbg_seed(&client->ctr_drbg, mbedtls_entropy_func, &client->entropy,
  176. NULL, 0)) != 0) {
  177. ESP_LOGE(TAG, "mbedtls_ctr_drbg_seed returned %d", ret);
  178. return ESP_FAIL;
  179. }
  180. ESP_LOGI(TAG, "Setting hostname for TLS session...");
  181. /* Hostname set here should match CN in server certificate */
  182. if ((ret = mbedtls_ssl_set_hostname(&client->ssl, SERVER_ADDRESS)) != 0) {
  183. ESP_LOGE(TAG, "mbedtls_ssl_set_hostname returned -0x%x", -ret);
  184. return ESP_FAIL;
  185. }
  186. ESP_LOGI(TAG, "Setting up the SSL/TLS structure...");
  187. if ((ret = mbedtls_ssl_config_defaults(&client->conf,
  188. MBEDTLS_SSL_IS_CLIENT,
  189. MBEDTLS_SSL_TRANSPORT_STREAM,
  190. MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
  191. ESP_LOGE(TAG, "mbedtls_ssl_config_defaults returned %d", ret);
  192. return ESP_FAIL;
  193. }
  194. mbedtls_ssl_conf_rng(&client->conf, mbedtls_ctr_drbg_random, &client->ctr_drbg);
  195. if ((ret = mbedtls_ssl_setup(&client->ssl, &client->conf)) != 0) {
  196. ESP_LOGE(TAG, "mbedtls_ssl_setup returned -0x%x\n\n", -ret);
  197. return ESP_FAIL;
  198. }
  199. return ESP_OK;
  200. }
  201. int client_task(const uint8_t *bundle, size_t bundle_size, esp_crt_validate_res_t *res)
  202. {
  203. int ret = ESP_FAIL;
  204. mbedtls_endpoint_t client;
  205. *res = ESP_CRT_VALIDATE_UNKNOWN;
  206. if (client_setup(&client) != ESP_OK) {
  207. ESP_LOGE(TAG, "SSL client setup failed");
  208. goto exit;
  209. }
  210. esp_crt_bundle_attach(&client.conf);
  211. if (bundle) {
  212. /* Set a bundle different from the menuconfig bundle */
  213. esp_crt_bundle_set(bundle, bundle_size);
  214. }
  215. ESP_LOGI(TAG, "Connecting to %s:%s...", SERVER_ADDRESS, SERVER_PORT);
  216. if ((ret = mbedtls_net_connect(&client.client_fd, SERVER_ADDRESS, SERVER_PORT, MBEDTLS_NET_PROTO_TCP)) != 0) {
  217. ESP_LOGE(TAG, "mbedtls_net_connect returned -%x", -ret);
  218. goto exit;
  219. }
  220. ESP_LOGI(TAG, "Connected.");
  221. mbedtls_ssl_set_bio(&client.ssl, &client.client_fd, mbedtls_net_send, mbedtls_net_recv, NULL);
  222. ESP_LOGI(TAG, "Performing the SSL/TLS handshake with bundle that is missing the server root certificate");
  223. while ( ( ret = mbedtls_ssl_handshake( &client.ssl ) ) != 0 ) {
  224. if ( ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE ) {
  225. printf( "mbedtls_ssl_handshake failed with -0x%x\n", -ret );
  226. break;
  227. }
  228. }
  229. ESP_LOGI(TAG, "Verifying peer X.509 certificate for bundle ...");
  230. ret = mbedtls_ssl_get_verify_result(&client.ssl);
  231. *res = (ret == 0) ? ESP_CRT_VALIDATE_OK : ESP_CRT_VALIDATE_FAIL;
  232. if (*res == ESP_CRT_VALIDATE_OK) {
  233. ESP_LOGI(TAG, "Certificate verification passed!");
  234. } else {
  235. ESP_LOGE(TAG, "Certificate verification failed!");
  236. }
  237. // Reset session before new connection
  238. mbedtls_ssl_close_notify(&client.ssl);
  239. mbedtls_ssl_session_reset(&client.ssl);
  240. mbedtls_net_free( &client.client_fd);
  241. exit:
  242. mbedtls_ssl_close_notify(&client.ssl);
  243. mbedtls_ssl_session_reset(&client.ssl);
  244. esp_crt_bundle_detach(&client.conf);
  245. endpoint_teardown(&client);
  246. return ret;
  247. }
  248. TEST_CASE("custom certificate bundle", "[mbedtls]")
  249. {
  250. esp_crt_validate_res_t validate_res;
  251. test_case_uses_tcpip();
  252. SemaphoreHandle_t signal_sem = xSemaphoreCreateBinary();
  253. TEST_ASSERT_NOT_NULL(signal_sem);
  254. exit_flag = false;
  255. xTaskCreate(server_task, "server task", 8192, &signal_sem, 10, NULL);
  256. // Wait for the server to start up
  257. if (!xSemaphoreTake(signal_sem, 10000 / portTICK_PERIOD_MS)) {
  258. TEST_FAIL_MESSAGE("signal_sem not released, server start failed");
  259. }
  260. /* Test with default crt bundle that doesnt contain the ca crt */
  261. client_task(NULL, 0, &validate_res);
  262. TEST_ASSERT(validate_res == ESP_CRT_VALIDATE_FAIL);
  263. /* Test with bundle that does contain the CA crt */
  264. client_task(server_cert_bundle_start, server_cert_bundle_end - server_cert_bundle_start, &validate_res);
  265. TEST_ASSERT(validate_res == ESP_CRT_VALIDATE_OK);
  266. exit_flag = true;
  267. if (!xSemaphoreTake(signal_sem, 10000 / portTICK_PERIOD_MS)) {
  268. TEST_FAIL_MESSAGE("signal_sem not released, server exit failed");
  269. }
  270. vSemaphoreDelete(signal_sem);
  271. }
  272. TEST_CASE("custom certificate bundle - weak hash", "[mbedtls]")
  273. {
  274. /* A weak signature hash on the trusted certificate should not stop
  275. us from verifying the chain, since we already trust it a weak signature hash is
  276. not a security issue */
  277. mbedtls_x509_crt crt;
  278. uint32_t flags = 0;
  279. esp_crt_bundle_attach(NULL);
  280. mbedtls_x509_crt_init( &crt );
  281. mbedtls_x509_crt_parse(&crt, bad_md_crt_pem_start, bad_md_crt_pem_end - bad_md_crt_pem_start);
  282. TEST_ASSERT(mbedtls_x509_crt_verify(&crt, NULL, NULL, NULL, &flags, esp_crt_verify_callback, NULL) == 0);
  283. mbedtls_x509_crt_free(&crt);
  284. esp_crt_bundle_detach(NULL);
  285. }
  286. TEST_CASE("custom certificate bundle - wrong signature", "[mbedtls]")
  287. {
  288. /* Check that the bundle will not verify a valid certificate from trusted root where the signature is wrong */
  289. mbedtls_x509_crt crt;
  290. uint32_t flags = 0;
  291. esp_crt_bundle_attach(NULL);
  292. mbedtls_x509_crt_init( &crt );
  293. /* esp32.com cert chain where 1 byte in the signature is changed */
  294. printf("Testing certificate with wrong signature\n");
  295. mbedtls_x509_crt_parse(&crt, wrong_sig_crt_pem_start, wrong_sig_crt_pem_end - wrong_sig_crt_pem_start);
  296. TEST_ASSERT(mbedtls_x509_crt_verify(&crt, NULL, NULL, NULL, &flags, esp_crt_verify_callback, NULL) != 0);
  297. mbedtls_x509_crt_free(&crt);
  298. mbedtls_x509_crt_init( &crt );
  299. /* the correct esp32.com cert chain*/
  300. printf("Testing certificate with correct signature\n");
  301. mbedtls_x509_crt_parse(&crt, correct_sig_crt_pem_start, correct_sig_crt_pem_end - correct_sig_crt_pem_start);
  302. TEST_ASSERT(mbedtls_x509_crt_verify(&crt, NULL, NULL, NULL, &flags, esp_crt_verify_callback, NULL) == 0);
  303. mbedtls_x509_crt_free(&crt);
  304. esp_crt_bundle_detach(NULL);
  305. }
  306. TEST_CASE("custom certificate bundle init API - bound checking", "[mbedtls]")
  307. {
  308. uint8_t test_bundle[256] = {0};
  309. esp_err_t esp_ret;
  310. /* The API should fail with bundle size given as 1 */
  311. esp_ret = esp_crt_bundle_set(test_bundle, 1);
  312. TEST_ASSERT( esp_ret == ESP_ERR_INVALID_ARG);
  313. /* Check that the esp_crt_bundle_set API will not accept a bundle
  314. * which has more no. of certs than configured in
  315. * CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_MAX_CERTS */
  316. uint8_t rand;
  317. esp_fill_random(&rand, 1);
  318. test_bundle[0] = rand;
  319. /* Make sure that the number of certs will always be greater than
  320. * CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_MAX_CERTS */
  321. test_bundle[1] = rand + CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_MAX_CERTS;
  322. esp_ret = esp_crt_bundle_set(test_bundle, sizeof(test_bundle));
  323. TEST_ASSERT( esp_ret == ESP_ERR_INVALID_ARG);
  324. /* The API should fail with bundle_size < BUNDLE_HEADER_OFFSET (2) + CRT_HEADER_OFFSET (4) */
  325. test_bundle[0] = 0;
  326. test_bundle[1] = 1; /* set num_certs = 1 */
  327. esp_ret = esp_crt_bundle_set(test_bundle, 5);
  328. TEST_ASSERT(esp_ret == ESP_ERR_INVALID_ARG);
  329. /* Cert number is greater than actual certs present, The API should fail */
  330. /* Actual No. of certs present in bundle = 1, setting num_certs to 5 */
  331. test_bundle[1] = 5; /* num_certs */
  332. test_bundle[3] = 5; /* cert_1_name_len */
  333. test_bundle[5] = 10; /* cert_1_pub_key_len */
  334. /* Actual bundle size becomes BUNDLE_HEADER_OFFSET (2) + CRT_HEADER_OFFSET (4) + cert_1_name_len(5) + cert_1_pub_key_len(10)
  335. * i.e. 21 bytes */
  336. esp_ret = esp_crt_bundle_set(test_bundle, 21);
  337. TEST_ASSERT(esp_ret == ESP_ERR_INVALID_ARG);
  338. /* The API should fail if bundle_size < BUNDLE_HEADER_OFFSET (2) + CRT_HEADER_OFFSET (4) + cert_1_name_len(5) + cert_1_pub_key_len(10) */
  339. esp_ret = esp_crt_bundle_set(test_bundle, 20);
  340. TEST_ASSERT(esp_ret == ESP_ERR_INVALID_ARG);
  341. esp_crt_bundle_detach(NULL);
  342. }