https_mbedtls_example_main.c 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. /* HTTPS GET Example using plain mbedTLS sockets
  2. *
  3. * Contacts the howsmyssl.com API via TLS v1.2 and reads a JSON
  4. * response.
  5. *
  6. * Adapted from the ssl_client1 example in mbedtls.
  7. *
  8. * SPDX-FileCopyrightText: The Mbed TLS Contributors
  9. *
  10. * SPDX-License-Identifier: Apache-2.0
  11. *
  12. * SPDX-FileContributor: 2015-2021 Espressif Systems (Shanghai) CO LTD
  13. */
  14. #include <string.h>
  15. #include <stdlib.h>
  16. #include <inttypes.h>
  17. #include "freertos/FreeRTOS.h"
  18. #include "freertos/task.h"
  19. #include "esp_wifi.h"
  20. #include "esp_event.h"
  21. #include "esp_log.h"
  22. #include "esp_system.h"
  23. #include "nvs_flash.h"
  24. #include "protocol_examples_common.h"
  25. #include "esp_netif.h"
  26. #include "lwip/err.h"
  27. #include "lwip/sockets.h"
  28. #include "lwip/sys.h"
  29. #include "lwip/netdb.h"
  30. #include "lwip/dns.h"
  31. #include "mbedtls/platform.h"
  32. #include "mbedtls/net_sockets.h"
  33. #include "mbedtls/esp_debug.h"
  34. #include "mbedtls/ssl.h"
  35. #include "mbedtls/entropy.h"
  36. #include "mbedtls/ctr_drbg.h"
  37. #include "mbedtls/error.h"
  38. #ifdef CONFIG_MBEDTLS_SSL_PROTO_TLS1_3
  39. #include "psa/crypto.h"
  40. #endif
  41. #include "esp_crt_bundle.h"
  42. /* Constants that aren't configurable in menuconfig */
  43. #define WEB_SERVER "www.howsmyssl.com"
  44. #define WEB_PORT "443"
  45. #define WEB_URL "https://www.howsmyssl.com/a/check"
  46. static const char *TAG = "example";
  47. static const char *REQUEST = "GET " WEB_URL " HTTP/1.0\r\n"
  48. "Host: "WEB_SERVER"\r\n"
  49. "User-Agent: esp-idf/1.0 esp32\r\n"
  50. "\r\n";
  51. static void https_get_task(void *pvParameters)
  52. {
  53. char buf[512];
  54. int ret, flags, len;
  55. mbedtls_entropy_context entropy;
  56. mbedtls_ctr_drbg_context ctr_drbg;
  57. mbedtls_ssl_context ssl;
  58. mbedtls_x509_crt cacert;
  59. mbedtls_ssl_config conf;
  60. mbedtls_net_context server_fd;
  61. #ifdef CONFIG_MBEDTLS_SSL_PROTO_TLS1_3
  62. psa_status_t status = psa_crypto_init();
  63. if (status != PSA_SUCCESS) {
  64. ESP_LOGE(TAG, "Failed to initialize PSA crypto, returned %d", (int) status);
  65. return;
  66. }
  67. #endif
  68. mbedtls_ssl_init(&ssl);
  69. mbedtls_x509_crt_init(&cacert);
  70. mbedtls_ctr_drbg_init(&ctr_drbg);
  71. ESP_LOGI(TAG, "Seeding the random number generator");
  72. mbedtls_ssl_config_init(&conf);
  73. mbedtls_entropy_init(&entropy);
  74. if((ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy,
  75. NULL, 0)) != 0)
  76. {
  77. ESP_LOGE(TAG, "mbedtls_ctr_drbg_seed returned %d", ret);
  78. abort();
  79. }
  80. ESP_LOGI(TAG, "Attaching the certificate bundle...");
  81. ret = esp_crt_bundle_attach(&conf);
  82. if(ret < 0)
  83. {
  84. ESP_LOGE(TAG, "esp_crt_bundle_attach returned -0x%x", -ret);
  85. abort();
  86. }
  87. ESP_LOGI(TAG, "Setting hostname for TLS session...");
  88. /* Hostname set here should match CN in server certificate */
  89. if((ret = mbedtls_ssl_set_hostname(&ssl, WEB_SERVER)) != 0)
  90. {
  91. ESP_LOGE(TAG, "mbedtls_ssl_set_hostname returned -0x%x", -ret);
  92. abort();
  93. }
  94. ESP_LOGI(TAG, "Setting up the SSL/TLS structure...");
  95. if((ret = mbedtls_ssl_config_defaults(&conf,
  96. MBEDTLS_SSL_IS_CLIENT,
  97. MBEDTLS_SSL_TRANSPORT_STREAM,
  98. MBEDTLS_SSL_PRESET_DEFAULT)) != 0)
  99. {
  100. ESP_LOGE(TAG, "mbedtls_ssl_config_defaults returned %d", ret);
  101. goto exit;
  102. }
  103. mbedtls_ssl_conf_authmode(&conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  104. mbedtls_ssl_conf_ca_chain(&conf, &cacert, NULL);
  105. mbedtls_ssl_conf_rng(&conf, mbedtls_ctr_drbg_random, &ctr_drbg);
  106. #ifdef CONFIG_MBEDTLS_DEBUG
  107. mbedtls_esp_enable_debug_log(&conf, CONFIG_MBEDTLS_DEBUG_LEVEL);
  108. #endif
  109. if ((ret = mbedtls_ssl_setup(&ssl, &conf)) != 0)
  110. {
  111. ESP_LOGE(TAG, "mbedtls_ssl_setup returned -0x%x", -ret);
  112. goto exit;
  113. }
  114. while(1) {
  115. mbedtls_net_init(&server_fd);
  116. ESP_LOGI(TAG, "Connecting to %s:%s...", WEB_SERVER, WEB_PORT);
  117. if ((ret = mbedtls_net_connect(&server_fd, WEB_SERVER,
  118. WEB_PORT, MBEDTLS_NET_PROTO_TCP)) != 0)
  119. {
  120. ESP_LOGE(TAG, "mbedtls_net_connect returned -%x", -ret);
  121. goto exit;
  122. }
  123. ESP_LOGI(TAG, "Connected.");
  124. mbedtls_ssl_set_bio(&ssl, &server_fd, mbedtls_net_send, mbedtls_net_recv, NULL);
  125. ESP_LOGI(TAG, "Performing the SSL/TLS handshake...");
  126. while ((ret = mbedtls_ssl_handshake(&ssl)) != 0)
  127. {
  128. if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE)
  129. {
  130. ESP_LOGE(TAG, "mbedtls_ssl_handshake returned -0x%x", -ret);
  131. goto exit;
  132. }
  133. }
  134. ESP_LOGI(TAG, "Verifying peer X.509 certificate...");
  135. if ((flags = mbedtls_ssl_get_verify_result(&ssl)) != 0)
  136. {
  137. /* In real life, we probably want to close connection if ret != 0 */
  138. ESP_LOGW(TAG, "Failed to verify peer certificate!");
  139. bzero(buf, sizeof(buf));
  140. mbedtls_x509_crt_verify_info(buf, sizeof(buf), " ! ", flags);
  141. ESP_LOGW(TAG, "verification info: %s", buf);
  142. }
  143. else {
  144. ESP_LOGI(TAG, "Certificate verified.");
  145. }
  146. ESP_LOGI(TAG, "Cipher suite is %s", mbedtls_ssl_get_ciphersuite(&ssl));
  147. ESP_LOGI(TAG, "Writing HTTP request...");
  148. size_t written_bytes = 0;
  149. do {
  150. ret = mbedtls_ssl_write(&ssl,
  151. (const unsigned char *)REQUEST + written_bytes,
  152. strlen(REQUEST) - written_bytes);
  153. if (ret >= 0) {
  154. ESP_LOGI(TAG, "%d bytes written", ret);
  155. written_bytes += ret;
  156. } else if (ret != MBEDTLS_ERR_SSL_WANT_WRITE && ret != MBEDTLS_ERR_SSL_WANT_READ) {
  157. ESP_LOGE(TAG, "mbedtls_ssl_write returned -0x%x", -ret);
  158. goto exit;
  159. }
  160. } while(written_bytes < strlen(REQUEST));
  161. ESP_LOGI(TAG, "Reading HTTP response...");
  162. do
  163. {
  164. len = sizeof(buf) - 1;
  165. bzero(buf, sizeof(buf));
  166. ret = mbedtls_ssl_read(&ssl, (unsigned char *)buf, len);
  167. #if CONFIG_MBEDTLS_SSL_PROTO_TLS1_3 && CONFIG_MBEDTLS_CLIENT_SSL_SESSION_TICKETS
  168. if (ret == MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET) {
  169. ESP_LOGD(TAG, "got session ticket in TLS 1.3 connection, retry read");
  170. continue;
  171. }
  172. #endif // CONFIG_MBEDTLS_SSL_PROTO_TLS1_3 && CONFIG_MBEDTLS_CLIENT_SSL_SESSION_TICKETS
  173. if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  174. continue;
  175. }
  176. if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  177. ret = 0;
  178. break;
  179. }
  180. if (ret < 0) {
  181. ESP_LOGE(TAG, "mbedtls_ssl_read returned -0x%x", -ret);
  182. break;
  183. }
  184. if (ret == 0) {
  185. ESP_LOGI(TAG, "connection closed");
  186. break;
  187. }
  188. len = ret;
  189. ESP_LOGD(TAG, "%d bytes read", len);
  190. /* Print response directly to stdout as it is read */
  191. for (int i = 0; i < len; i++) {
  192. putchar(buf[i]);
  193. }
  194. } while(1);
  195. mbedtls_ssl_close_notify(&ssl);
  196. exit:
  197. mbedtls_ssl_session_reset(&ssl);
  198. mbedtls_net_free(&server_fd);
  199. if (ret != 0) {
  200. mbedtls_strerror(ret, buf, 100);
  201. ESP_LOGE(TAG, "Last error was: -0x%x - %s", -ret, buf);
  202. }
  203. putchar('\n'); // JSON output doesn't have a newline at end
  204. static int request_count;
  205. ESP_LOGI(TAG, "Completed %d requests", ++request_count);
  206. printf("Minimum free heap size: %" PRIu32 " bytes\n", esp_get_minimum_free_heap_size());
  207. for (int countdown = 10; countdown >= 0; countdown--) {
  208. ESP_LOGI(TAG, "%d...", countdown);
  209. vTaskDelay(1000 / portTICK_PERIOD_MS);
  210. }
  211. ESP_LOGI(TAG, "Starting again!");
  212. }
  213. }
  214. void app_main(void)
  215. {
  216. ESP_ERROR_CHECK( nvs_flash_init() );
  217. ESP_ERROR_CHECK(esp_netif_init());
  218. ESP_ERROR_CHECK(esp_event_loop_create_default());
  219. /* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig.
  220. * Read "Establishing Wi-Fi or Ethernet Connection" section in
  221. * examples/protocols/README.md for more information about this function.
  222. */
  223. ESP_ERROR_CHECK(example_connect());
  224. xTaskCreate(&https_get_task, "https_get_task", 8192, NULL, 5, NULL);
  225. }