https_mbedtls_example_main.c 8.2 KB

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