https_mbedtls_example_main.c 8.2 KB

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