https_mbedtls_example_main.c 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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. * Original Copyright (C) 2006-2016, ARM Limited, All Rights Reserved, Apache 2.0 License.
  9. * Additions Copyright (C) Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD, Apache 2.0 License.
  10. *
  11. *
  12. * Licensed under the Apache License, Version 2.0 (the "License");
  13. * you may not use this file except in compliance with the License.
  14. * You may obtain a copy of the License at
  15. *
  16. * http://www.apache.org/licenses/LICENSE-2.0
  17. *
  18. * Unless required by applicable law or agreed to in writing, software
  19. * distributed under the License is distributed on an "AS IS" BASIS,
  20. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21. * See the License for the specific language governing permissions and
  22. * limitations under the License.
  23. */
  24. #include <string.h>
  25. #include <stdlib.h>
  26. #include "freertos/FreeRTOS.h"
  27. #include "freertos/task.h"
  28. #include "esp_wifi.h"
  29. #include "esp_event.h"
  30. #include "esp_log.h"
  31. #include "esp_system.h"
  32. #include "nvs_flash.h"
  33. #include "protocol_examples_common.h"
  34. #include "esp_netif.h"
  35. #include "lwip/err.h"
  36. #include "lwip/sockets.h"
  37. #include "lwip/sys.h"
  38. #include "lwip/netdb.h"
  39. #include "lwip/dns.h"
  40. #include "mbedtls/platform.h"
  41. #include "mbedtls/net_sockets.h"
  42. #include "mbedtls/esp_debug.h"
  43. #include "mbedtls/ssl.h"
  44. #include "mbedtls/entropy.h"
  45. #include "mbedtls/ctr_drbg.h"
  46. #include "mbedtls/error.h"
  47. #include "mbedtls/certs.h"
  48. #include "esp_crt_bundle.h"
  49. /* Constants that aren't configurable in menuconfig */
  50. #define WEB_SERVER "www.howsmyssl.com"
  51. #define WEB_PORT "443"
  52. #define WEB_URL "https://www.howsmyssl.com/a/check"
  53. static const char *TAG = "example";
  54. static const char *REQUEST = "GET " WEB_URL " HTTP/1.0\r\n"
  55. "Host: "WEB_SERVER"\r\n"
  56. "User-Agent: esp-idf/1.0 esp32\r\n"
  57. "\r\n";
  58. static void https_get_task(void *pvParameters)
  59. {
  60. char buf[512];
  61. int ret, flags, len;
  62. mbedtls_entropy_context entropy;
  63. mbedtls_ctr_drbg_context ctr_drbg;
  64. mbedtls_ssl_context ssl;
  65. mbedtls_x509_crt cacert;
  66. mbedtls_ssl_config conf;
  67. mbedtls_net_context server_fd;
  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\n\n", -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_VERIFY_OPTIONAL is bad for security, in this example it will print
  104. a warning if CA verification fails but it will continue to connect.
  105. You should consider using MBEDTLS_SSL_VERIFY_REQUIRED in your own code.
  106. */
  107. mbedtls_ssl_conf_authmode(&conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
  108. mbedtls_ssl_conf_ca_chain(&conf, &cacert, NULL);
  109. mbedtls_ssl_conf_rng(&conf, mbedtls_ctr_drbg_random, &ctr_drbg);
  110. #ifdef CONFIG_MBEDTLS_DEBUG
  111. mbedtls_esp_enable_debug_log(&conf, CONFIG_MBEDTLS_DEBUG_LEVEL);
  112. #endif
  113. if ((ret = mbedtls_ssl_setup(&ssl, &conf)) != 0)
  114. {
  115. ESP_LOGE(TAG, "mbedtls_ssl_setup returned -0x%x\n\n", -ret);
  116. goto exit;
  117. }
  118. while(1) {
  119. mbedtls_net_init(&server_fd);
  120. ESP_LOGI(TAG, "Connecting to %s:%s...", WEB_SERVER, WEB_PORT);
  121. if ((ret = mbedtls_net_connect(&server_fd, WEB_SERVER,
  122. WEB_PORT, MBEDTLS_NET_PROTO_TCP)) != 0)
  123. {
  124. ESP_LOGE(TAG, "mbedtls_net_connect returned -%x", -ret);
  125. goto exit;
  126. }
  127. ESP_LOGI(TAG, "Connected.");
  128. mbedtls_ssl_set_bio(&ssl, &server_fd, mbedtls_net_send, mbedtls_net_recv, NULL);
  129. ESP_LOGI(TAG, "Performing the SSL/TLS handshake...");
  130. while ((ret = mbedtls_ssl_handshake(&ssl)) != 0)
  131. {
  132. if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE)
  133. {
  134. ESP_LOGE(TAG, "mbedtls_ssl_handshake returned -0x%x", -ret);
  135. goto exit;
  136. }
  137. }
  138. ESP_LOGI(TAG, "Verifying peer X.509 certificate...");
  139. if ((flags = mbedtls_ssl_get_verify_result(&ssl)) != 0)
  140. {
  141. /* In real life, we probably want to close connection if ret != 0 */
  142. ESP_LOGW(TAG, "Failed to verify peer certificate!");
  143. bzero(buf, sizeof(buf));
  144. mbedtls_x509_crt_verify_info(buf, sizeof(buf), " ! ", flags);
  145. ESP_LOGW(TAG, "verification info: %s", buf);
  146. }
  147. else {
  148. ESP_LOGI(TAG, "Certificate verified.");
  149. }
  150. ESP_LOGI(TAG, "Cipher suite is %s", mbedtls_ssl_get_ciphersuite(&ssl));
  151. ESP_LOGI(TAG, "Writing HTTP request...");
  152. size_t written_bytes = 0;
  153. do {
  154. ret = mbedtls_ssl_write(&ssl,
  155. (const unsigned char *)REQUEST + written_bytes,
  156. strlen(REQUEST) - written_bytes);
  157. if (ret >= 0) {
  158. ESP_LOGI(TAG, "%d bytes written", ret);
  159. written_bytes += ret;
  160. } else if (ret != MBEDTLS_ERR_SSL_WANT_WRITE && ret != MBEDTLS_ERR_SSL_WANT_READ) {
  161. ESP_LOGE(TAG, "mbedtls_ssl_write returned -0x%x", -ret);
  162. goto exit;
  163. }
  164. } while(written_bytes < strlen(REQUEST));
  165. ESP_LOGI(TAG, "Reading HTTP response...");
  166. do
  167. {
  168. len = sizeof(buf) - 1;
  169. bzero(buf, sizeof(buf));
  170. ret = mbedtls_ssl_read(&ssl, (unsigned char *)buf, len);
  171. if(ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE)
  172. continue;
  173. if(ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  174. ret = 0;
  175. break;
  176. }
  177. if(ret < 0)
  178. {
  179. ESP_LOGE(TAG, "mbedtls_ssl_read returned -0x%x", -ret);
  180. break;
  181. }
  182. if(ret == 0)
  183. {
  184. ESP_LOGI(TAG, "connection closed");
  185. break;
  186. }
  187. len = ret;
  188. ESP_LOGD(TAG, "%d bytes read", len);
  189. /* Print response directly to stdout as it is read */
  190. for(int i = 0; i < len; i++) {
  191. putchar(buf[i]);
  192. }
  193. } while(1);
  194. mbedtls_ssl_close_notify(&ssl);
  195. exit:
  196. mbedtls_ssl_session_reset(&ssl);
  197. mbedtls_net_free(&server_fd);
  198. if(ret != 0)
  199. {
  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: %d 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. }