https_mbedtls_example_main.c 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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. if ((ret = mbedtls_ssl_setup(&ssl, &conf)) != 0)
  103. {
  104. ESP_LOGE(TAG, "mbedtls_ssl_setup returned -0x%x\n\n", -ret);
  105. goto exit;
  106. }
  107. while(1) {
  108. mbedtls_net_init(&server_fd);
  109. ESP_LOGI(TAG, "Connecting to %s:%s...", WEB_SERVER, WEB_PORT);
  110. if ((ret = mbedtls_net_connect(&server_fd, WEB_SERVER,
  111. WEB_PORT, MBEDTLS_NET_PROTO_TCP)) != 0)
  112. {
  113. ESP_LOGE(TAG, "mbedtls_net_connect returned -%x", -ret);
  114. goto exit;
  115. }
  116. ESP_LOGI(TAG, "Connected.");
  117. mbedtls_ssl_set_bio(&ssl, &server_fd, mbedtls_net_send, mbedtls_net_recv, NULL);
  118. ESP_LOGI(TAG, "Performing the SSL/TLS handshake...");
  119. while ((ret = mbedtls_ssl_handshake(&ssl)) != 0)
  120. {
  121. if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE)
  122. {
  123. ESP_LOGE(TAG, "mbedtls_ssl_handshake returned -0x%x", -ret);
  124. goto exit;
  125. }
  126. }
  127. ESP_LOGI(TAG, "Verifying peer X.509 certificate...");
  128. if ((flags = mbedtls_ssl_get_verify_result(&ssl)) != 0)
  129. {
  130. /* In real life, we probably want to close connection if ret != 0 */
  131. ESP_LOGW(TAG, "Failed to verify peer certificate!");
  132. bzero(buf, sizeof(buf));
  133. mbedtls_x509_crt_verify_info(buf, sizeof(buf), " ! ", flags);
  134. ESP_LOGW(TAG, "verification info: %s", buf);
  135. }
  136. else {
  137. ESP_LOGI(TAG, "Certificate verified.");
  138. }
  139. ESP_LOGI(TAG, "Cipher suite is %s", mbedtls_ssl_get_ciphersuite(&ssl));
  140. ESP_LOGI(TAG, "Writing HTTP request...");
  141. size_t written_bytes = 0;
  142. do {
  143. ret = mbedtls_ssl_write(&ssl,
  144. (const unsigned char *)REQUEST + written_bytes,
  145. strlen(REQUEST) - written_bytes);
  146. if (ret >= 0) {
  147. ESP_LOGI(TAG, "%d bytes written", ret);
  148. written_bytes += ret;
  149. } else if (ret != MBEDTLS_ERR_SSL_WANT_WRITE && ret != MBEDTLS_ERR_SSL_WANT_READ) {
  150. ESP_LOGE(TAG, "mbedtls_ssl_write returned -0x%x", -ret);
  151. goto exit;
  152. }
  153. } while(written_bytes < strlen(REQUEST));
  154. ESP_LOGI(TAG, "Reading HTTP response...");
  155. do
  156. {
  157. len = sizeof(buf) - 1;
  158. bzero(buf, sizeof(buf));
  159. ret = mbedtls_ssl_read(&ssl, (unsigned char *)buf, len);
  160. if(ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE)
  161. continue;
  162. if(ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  163. ret = 0;
  164. break;
  165. }
  166. if(ret < 0)
  167. {
  168. ESP_LOGE(TAG, "mbedtls_ssl_read returned -0x%x", -ret);
  169. break;
  170. }
  171. if(ret == 0)
  172. {
  173. ESP_LOGI(TAG, "connection closed");
  174. break;
  175. }
  176. len = ret;
  177. ESP_LOGD(TAG, "%d bytes read", len);
  178. /* Print response directly to stdout as it is read */
  179. for(int i = 0; i < len; i++) {
  180. putchar(buf[i]);
  181. }
  182. } while(1);
  183. mbedtls_ssl_close_notify(&ssl);
  184. exit:
  185. mbedtls_ssl_session_reset(&ssl);
  186. mbedtls_net_free(&server_fd);
  187. if(ret != 0)
  188. {
  189. mbedtls_strerror(ret, buf, 100);
  190. ESP_LOGE(TAG, "Last error was: -0x%x - %s", -ret, buf);
  191. }
  192. putchar('\n'); // JSON output doesn't have a newline at end
  193. static int request_count;
  194. ESP_LOGI(TAG, "Completed %d requests", ++request_count);
  195. printf("Minimum free heap size: %d bytes\n", esp_get_minimum_free_heap_size());
  196. for(int countdown = 10; countdown >= 0; countdown--) {
  197. ESP_LOGI(TAG, "%d...", countdown);
  198. vTaskDelay(1000 / portTICK_PERIOD_MS);
  199. }
  200. ESP_LOGI(TAG, "Starting again!");
  201. }
  202. }
  203. void app_main(void)
  204. {
  205. ESP_ERROR_CHECK( nvs_flash_init() );
  206. ESP_ERROR_CHECK(esp_netif_init());
  207. ESP_ERROR_CHECK(esp_event_loop_create_default());
  208. /* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig.
  209. * Read "Establishing Wi-Fi or Ethernet Connection" section in
  210. * examples/protocols/README.md for more information about this function.
  211. */
  212. ESP_ERROR_CHECK(example_connect());
  213. xTaskCreate(&https_get_task, "https_get_task", 8192, NULL, 5, NULL);
  214. }