mbedtls.c 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
  9. * Copyright (C) Hoi-Ho Chan, <hoiho.chan@gmail.com>
  10. *
  11. * This software is licensed as described in the file COPYING, which
  12. * you should have received as part of this distribution. The terms
  13. * are also available at https://curl.se/docs/copyright.html.
  14. *
  15. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  16. * copies of the Software, and permit persons to whom the Software is
  17. * furnished to do so, under the terms of the COPYING file.
  18. *
  19. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  20. * KIND, either express or implied.
  21. *
  22. * SPDX-License-Identifier: curl
  23. *
  24. ***************************************************************************/
  25. /*
  26. * Source file for all mbedTLS-specific code for the TLS/SSL layer. No code
  27. * but vtls.c should ever call or use these functions.
  28. *
  29. */
  30. #include "curl_setup.h"
  31. #ifdef USE_MBEDTLS
  32. /* Define this to enable lots of debugging for mbedTLS */
  33. /* #define MBEDTLS_DEBUG */
  34. #ifdef __GNUC__
  35. #pragma GCC diagnostic push
  36. /* mbedTLS (as of v3.5.1) has a duplicate function declaration
  37. in its public headers. Disable the warning that detects it. */
  38. #pragma GCC diagnostic ignored "-Wredundant-decls"
  39. #endif
  40. #include <mbedtls/version.h>
  41. #if MBEDTLS_VERSION_NUMBER >= 0x02040000
  42. #include <mbedtls/net_sockets.h>
  43. #else
  44. #include <mbedtls/net.h>
  45. #endif
  46. #include <mbedtls/ssl.h>
  47. #include <mbedtls/x509.h>
  48. #include <mbedtls/error.h>
  49. #include <mbedtls/entropy.h>
  50. #include <mbedtls/ctr_drbg.h>
  51. #include <mbedtls/sha256.h>
  52. #if MBEDTLS_VERSION_MAJOR >= 2
  53. # ifdef MBEDTLS_DEBUG
  54. # include <mbedtls/debug.h>
  55. # endif
  56. #endif
  57. #ifdef __GNUC__
  58. #pragma GCC diagnostic pop
  59. #endif
  60. #include "cipher_suite.h"
  61. #include "strcase.h"
  62. #include "urldata.h"
  63. #include "sendf.h"
  64. #include "inet_pton.h"
  65. #include "mbedtls.h"
  66. #include "vtls.h"
  67. #include "vtls_int.h"
  68. #include "parsedate.h"
  69. #include "connect.h" /* for the connect timeout */
  70. #include "select.h"
  71. #include "multiif.h"
  72. #include "mbedtls_threadlock.h"
  73. #include "strdup.h"
  74. /* The last 3 #include files should be in this order */
  75. #include "curl_printf.h"
  76. #include "curl_memory.h"
  77. #include "memdebug.h"
  78. /* ALPN for http2 */
  79. #ifdef USE_HTTP2
  80. # undef HAS_ALPN
  81. # ifdef MBEDTLS_SSL_ALPN
  82. # define HAS_ALPN
  83. # endif
  84. #endif
  85. struct mbed_ssl_backend_data {
  86. mbedtls_ctr_drbg_context ctr_drbg;
  87. mbedtls_entropy_context entropy;
  88. mbedtls_ssl_context ssl;
  89. mbedtls_x509_crt cacert;
  90. mbedtls_x509_crt clicert;
  91. #ifdef MBEDTLS_X509_CRL_PARSE_C
  92. mbedtls_x509_crl crl;
  93. #endif
  94. mbedtls_pk_context pk;
  95. mbedtls_ssl_config config;
  96. #ifdef HAS_ALPN
  97. const char *protocols[3];
  98. #endif
  99. int *ciphersuites;
  100. };
  101. /* apply threading? */
  102. #if (defined(USE_THREADS_POSIX) && defined(HAVE_PTHREAD_H)) || \
  103. defined(_WIN32)
  104. #define THREADING_SUPPORT
  105. #endif
  106. #ifndef MBEDTLS_ERROR_C
  107. #define mbedtls_strerror(a,b,c) b[0] = 0
  108. #endif
  109. #if defined(MBEDTLS_SSL_PROTO_TLS1_3) && MBEDTLS_VERSION_NUMBER >= 0x03060000
  110. #define TLS13_SUPPORT
  111. #endif
  112. #if defined(THREADING_SUPPORT)
  113. static mbedtls_entropy_context ts_entropy;
  114. static int entropy_init_initialized = 0;
  115. static void entropy_init_mutex(mbedtls_entropy_context *ctx)
  116. {
  117. /* lock 0 = entropy_init_mutex() */
  118. Curl_mbedtlsthreadlock_lock_function(0);
  119. if(entropy_init_initialized == 0) {
  120. mbedtls_entropy_init(ctx);
  121. entropy_init_initialized = 1;
  122. }
  123. Curl_mbedtlsthreadlock_unlock_function(0);
  124. }
  125. static void entropy_cleanup_mutex(mbedtls_entropy_context *ctx)
  126. {
  127. /* lock 0 = use same lock as init */
  128. Curl_mbedtlsthreadlock_lock_function(0);
  129. if(entropy_init_initialized == 1) {
  130. mbedtls_entropy_free(ctx);
  131. entropy_init_initialized = 0;
  132. }
  133. Curl_mbedtlsthreadlock_unlock_function(0);
  134. }
  135. static int entropy_func_mutex(void *data, unsigned char *output, size_t len)
  136. {
  137. int ret;
  138. /* lock 1 = entropy_func_mutex() */
  139. Curl_mbedtlsthreadlock_lock_function(1);
  140. ret = mbedtls_entropy_func(data, output, len);
  141. Curl_mbedtlsthreadlock_unlock_function(1);
  142. return ret;
  143. }
  144. #endif /* THREADING_SUPPORT */
  145. #ifdef MBEDTLS_DEBUG
  146. static void mbed_debug(void *context, int level, const char *f_name,
  147. int line_nb, const char *line)
  148. {
  149. struct Curl_easy *data = (struct Curl_easy *)context;
  150. (void) level;
  151. (void) line_nb;
  152. (void) f_name;
  153. if(data) {
  154. size_t len = strlen(line);
  155. if(len && (line[len - 1] == '\n'))
  156. /* discount any trailing newline */
  157. len--;
  158. infof(data, "%.*s", (int)len, line);
  159. }
  160. }
  161. #endif
  162. static int mbedtls_bio_cf_write(void *bio,
  163. const unsigned char *buf, size_t blen)
  164. {
  165. struct Curl_cfilter *cf = bio;
  166. struct Curl_easy *data = CF_DATA_CURRENT(cf);
  167. ssize_t nwritten;
  168. CURLcode result;
  169. DEBUGASSERT(data);
  170. if(!data)
  171. return 0;
  172. nwritten = Curl_conn_cf_send(cf->next, data, (char *)buf, blen, &result);
  173. CURL_TRC_CF(data, cf, "mbedtls_bio_cf_out_write(len=%zu) -> %zd, err=%d",
  174. blen, nwritten, result);
  175. if(nwritten < 0 && CURLE_AGAIN == result) {
  176. nwritten = MBEDTLS_ERR_SSL_WANT_WRITE;
  177. }
  178. return (int)nwritten;
  179. }
  180. static int mbedtls_bio_cf_read(void *bio, unsigned char *buf, size_t blen)
  181. {
  182. struct Curl_cfilter *cf = bio;
  183. struct Curl_easy *data = CF_DATA_CURRENT(cf);
  184. ssize_t nread;
  185. CURLcode result;
  186. DEBUGASSERT(data);
  187. if(!data)
  188. return 0;
  189. /* OpenSSL catches this case, so should we. */
  190. if(!buf)
  191. return 0;
  192. nread = Curl_conn_cf_recv(cf->next, data, (char *)buf, blen, &result);
  193. CURL_TRC_CF(data, cf, "mbedtls_bio_cf_in_read(len=%zu) -> %zd, err=%d",
  194. blen, nread, result);
  195. if(nread < 0 && CURLE_AGAIN == result) {
  196. nread = MBEDTLS_ERR_SSL_WANT_READ;
  197. }
  198. return (int)nread;
  199. }
  200. /*
  201. * profile
  202. */
  203. static const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_fr =
  204. {
  205. /* Hashes from SHA-1 and above */
  206. MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA1) |
  207. MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_RIPEMD160) |
  208. MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA224) |
  209. MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA256) |
  210. MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA384) |
  211. MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA512),
  212. 0xFFFFFFF, /* Any PK alg */
  213. 0xFFFFFFF, /* Any curve */
  214. 1024, /* RSA min key len */
  215. };
  216. /* See https://tls.mbed.org/discussions/generic/
  217. howto-determine-exact-buffer-len-for-mbedtls_pk_write_pubkey_der
  218. */
  219. #define RSA_PUB_DER_MAX_BYTES (38 + 2 * MBEDTLS_MPI_MAX_SIZE)
  220. #define ECP_PUB_DER_MAX_BYTES (30 + 2 * MBEDTLS_ECP_MAX_BYTES)
  221. #define PUB_DER_MAX_BYTES (RSA_PUB_DER_MAX_BYTES > ECP_PUB_DER_MAX_BYTES ? \
  222. RSA_PUB_DER_MAX_BYTES : ECP_PUB_DER_MAX_BYTES)
  223. #if MBEDTLS_VERSION_NUMBER >= 0x03020000
  224. static CURLcode mbedtls_version_from_curl(
  225. mbedtls_ssl_protocol_version* mbedver, long version)
  226. {
  227. switch(version) {
  228. case CURL_SSLVERSION_TLSv1_0:
  229. case CURL_SSLVERSION_TLSv1_1:
  230. case CURL_SSLVERSION_TLSv1_2:
  231. *mbedver = MBEDTLS_SSL_VERSION_TLS1_2;
  232. return CURLE_OK;
  233. case CURL_SSLVERSION_TLSv1_3:
  234. #ifdef TLS13_SUPPORT
  235. *mbedver = MBEDTLS_SSL_VERSION_TLS1_3;
  236. return CURLE_OK;
  237. #else
  238. break;
  239. #endif
  240. }
  241. return CURLE_SSL_CONNECT_ERROR;
  242. }
  243. #else
  244. static CURLcode mbedtls_version_from_curl(int *mbedver, long version)
  245. {
  246. #if MBEDTLS_VERSION_NUMBER >= 0x03000000
  247. switch(version) {
  248. case CURL_SSLVERSION_TLSv1_0:
  249. case CURL_SSLVERSION_TLSv1_1:
  250. case CURL_SSLVERSION_TLSv1_2:
  251. *mbedver = MBEDTLS_SSL_MINOR_VERSION_3;
  252. return CURLE_OK;
  253. case CURL_SSLVERSION_TLSv1_3:
  254. break;
  255. }
  256. #else
  257. switch(version) {
  258. case CURL_SSLVERSION_TLSv1_0:
  259. *mbedver = MBEDTLS_SSL_MINOR_VERSION_1;
  260. return CURLE_OK;
  261. case CURL_SSLVERSION_TLSv1_1:
  262. *mbedver = MBEDTLS_SSL_MINOR_VERSION_2;
  263. return CURLE_OK;
  264. case CURL_SSLVERSION_TLSv1_2:
  265. *mbedver = MBEDTLS_SSL_MINOR_VERSION_3;
  266. return CURLE_OK;
  267. case CURL_SSLVERSION_TLSv1_3:
  268. break;
  269. }
  270. #endif
  271. return CURLE_SSL_CONNECT_ERROR;
  272. }
  273. #endif
  274. static CURLcode
  275. set_ssl_version_min_max(struct Curl_cfilter *cf, struct Curl_easy *data)
  276. {
  277. struct ssl_connect_data *connssl = cf->ctx;
  278. struct mbed_ssl_backend_data *backend =
  279. (struct mbed_ssl_backend_data *)connssl->backend;
  280. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  281. #if MBEDTLS_VERSION_NUMBER >= 0x03020000
  282. mbedtls_ssl_protocol_version mbedtls_ver_min = MBEDTLS_SSL_VERSION_TLS1_2;
  283. #ifdef TLS13_SUPPORT
  284. mbedtls_ssl_protocol_version mbedtls_ver_max = MBEDTLS_SSL_VERSION_TLS1_3;
  285. #else
  286. mbedtls_ssl_protocol_version mbedtls_ver_max = MBEDTLS_SSL_VERSION_TLS1_2;
  287. #endif
  288. #elif MBEDTLS_VERSION_NUMBER >= 0x03000000
  289. int mbedtls_ver_min = MBEDTLS_SSL_MINOR_VERSION_3;
  290. int mbedtls_ver_max = MBEDTLS_SSL_MINOR_VERSION_3;
  291. #else
  292. int mbedtls_ver_min = MBEDTLS_SSL_MINOR_VERSION_1;
  293. int mbedtls_ver_max = MBEDTLS_SSL_MINOR_VERSION_1;
  294. #endif
  295. long ssl_version = conn_config->version;
  296. long ssl_version_max = conn_config->version_max;
  297. CURLcode result = CURLE_OK;
  298. DEBUGASSERT(backend);
  299. switch(ssl_version) {
  300. case CURL_SSLVERSION_DEFAULT:
  301. case CURL_SSLVERSION_TLSv1:
  302. ssl_version = CURL_SSLVERSION_TLSv1_0;
  303. break;
  304. }
  305. switch(ssl_version_max) {
  306. case CURL_SSLVERSION_MAX_NONE:
  307. case CURL_SSLVERSION_MAX_DEFAULT:
  308. #ifdef TLS13_SUPPORT
  309. ssl_version_max = CURL_SSLVERSION_MAX_TLSv1_3;
  310. #else
  311. ssl_version_max = CURL_SSLVERSION_MAX_TLSv1_2;
  312. #endif
  313. break;
  314. }
  315. result = mbedtls_version_from_curl(&mbedtls_ver_min, ssl_version);
  316. if(result) {
  317. failf(data, "unsupported min version passed via CURLOPT_SSLVERSION");
  318. return result;
  319. }
  320. result = mbedtls_version_from_curl(&mbedtls_ver_max, ssl_version_max >> 16);
  321. if(result) {
  322. failf(data, "unsupported max version passed via CURLOPT_SSLVERSION");
  323. return result;
  324. }
  325. #if MBEDTLS_VERSION_NUMBER >= 0x03020000
  326. mbedtls_ssl_conf_min_tls_version(&backend->config, mbedtls_ver_min);
  327. mbedtls_ssl_conf_max_tls_version(&backend->config, mbedtls_ver_max);
  328. #else
  329. mbedtls_ssl_conf_min_version(&backend->config, MBEDTLS_SSL_MAJOR_VERSION_3,
  330. mbedtls_ver_min);
  331. mbedtls_ssl_conf_max_version(&backend->config, MBEDTLS_SSL_MAJOR_VERSION_3,
  332. mbedtls_ver_max);
  333. #endif
  334. #ifdef TLS13_SUPPORT
  335. if(mbedtls_ver_min == MBEDTLS_SSL_VERSION_TLS1_3) {
  336. mbedtls_ssl_conf_authmode(&backend->config, MBEDTLS_SSL_VERIFY_REQUIRED);
  337. }
  338. else {
  339. mbedtls_ssl_conf_authmode(&backend->config, MBEDTLS_SSL_VERIFY_OPTIONAL);
  340. }
  341. #else
  342. mbedtls_ssl_conf_authmode(&backend->config, MBEDTLS_SSL_VERIFY_OPTIONAL);
  343. #endif
  344. return result;
  345. }
  346. /* TLS_ECJPAKE_WITH_AES_128_CCM_8 (0xC0FF) is marked experimental
  347. in mbedTLS. The number is not reserved by IANA nor is the
  348. cipher suite present in other SSL implementations. Provide
  349. provisional support for specifying the cipher suite here. */
  350. #ifdef MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8
  351. static int
  352. mbed_cipher_suite_get_str(uint16_t id, char *buf, size_t buf_size,
  353. bool prefer_rfc)
  354. {
  355. if(id == MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8)
  356. msnprintf(buf, buf_size, "%s", "TLS_ECJPAKE_WITH_AES_128_CCM_8");
  357. else
  358. return Curl_cipher_suite_get_str(id, buf, buf_size, prefer_rfc);
  359. return 0;
  360. }
  361. static uint16_t
  362. mbed_cipher_suite_walk_str(const char **str, const char **end)
  363. {
  364. uint16_t id = Curl_cipher_suite_walk_str(str, end);
  365. size_t len = *end - *str;
  366. if(!id) {
  367. if(strncasecompare("TLS_ECJPAKE_WITH_AES_128_CCM_8", *str, len))
  368. id = MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8;
  369. }
  370. return id;
  371. }
  372. #else
  373. #define mbed_cipher_suite_get_str Curl_cipher_suite_get_str
  374. #define mbed_cipher_suite_walk_str Curl_cipher_suite_walk_str
  375. #endif
  376. static CURLcode
  377. mbed_set_selected_ciphers(struct Curl_easy *data,
  378. struct mbed_ssl_backend_data *backend,
  379. const char *ciphers)
  380. {
  381. const int *supported;
  382. int *selected;
  383. size_t supported_len, count = 0, i;
  384. const char *ptr, *end;
  385. supported = mbedtls_ssl_list_ciphersuites();
  386. for(i = 0; supported[i] != 0; i++);
  387. supported_len = i;
  388. selected = malloc(sizeof(int) * (supported_len + 1));
  389. if(!selected)
  390. return CURLE_OUT_OF_MEMORY;
  391. for(ptr = ciphers; ptr[0] != '\0' && count < supported_len; ptr = end) {
  392. uint16_t id = mbed_cipher_suite_walk_str(&ptr, &end);
  393. /* Check if cipher is supported */
  394. if(id) {
  395. for(i = 0; i < supported_len && supported[i] != id; i++);
  396. if(i == supported_len)
  397. id = 0;
  398. }
  399. if(!id) {
  400. if(ptr[0] != '\0')
  401. infof(data, "mbedTLS: unknown cipher in list: \"%.*s\"",
  402. (int) (end - ptr), ptr);
  403. continue;
  404. }
  405. /* No duplicates allowed (so selected cannot overflow) */
  406. for(i = 0; i < count && selected[i] != id; i++);
  407. if(i < count) {
  408. infof(data, "mbedTLS: duplicate cipher in list: \"%.*s\"",
  409. (int) (end - ptr), ptr);
  410. continue;
  411. }
  412. selected[count++] = id;
  413. }
  414. selected[count] = 0;
  415. if(count == 0) {
  416. free(selected);
  417. failf(data, "mbedTLS: no supported cipher in list");
  418. return CURLE_SSL_CIPHER;
  419. }
  420. /* mbedtls_ssl_conf_ciphersuites(): The ciphersuites array is not copied.
  421. It must remain valid for the lifetime of the SSL configuration */
  422. backend->ciphersuites = selected;
  423. mbedtls_ssl_conf_ciphersuites(&backend->config, backend->ciphersuites);
  424. return CURLE_OK;
  425. }
  426. static CURLcode
  427. mbed_connect_step1(struct Curl_cfilter *cf, struct Curl_easy *data)
  428. {
  429. struct ssl_connect_data *connssl = cf->ctx;
  430. struct mbed_ssl_backend_data *backend =
  431. (struct mbed_ssl_backend_data *)connssl->backend;
  432. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  433. const struct curl_blob *ca_info_blob = conn_config->ca_info_blob;
  434. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  435. const char * const ssl_cafile =
  436. /* CURLOPT_CAINFO_BLOB overrides CURLOPT_CAINFO */
  437. (ca_info_blob ? NULL : conn_config->CAfile);
  438. const bool verifypeer = conn_config->verifypeer;
  439. const char * const ssl_capath = conn_config->CApath;
  440. char * const ssl_cert = ssl_config->primary.clientcert;
  441. const struct curl_blob *ssl_cert_blob = ssl_config->primary.cert_blob;
  442. const char * const ssl_crlfile = ssl_config->primary.CRLfile;
  443. const char *hostname = connssl->peer.hostname;
  444. int ret = -1;
  445. char errorbuf[128];
  446. DEBUGASSERT(backend);
  447. if((conn_config->version == CURL_SSLVERSION_SSLv2) ||
  448. (conn_config->version == CURL_SSLVERSION_SSLv3)) {
  449. failf(data, "Not supported SSL version");
  450. return CURLE_NOT_BUILT_IN;
  451. }
  452. #ifdef TLS13_SUPPORT
  453. ret = psa_crypto_init();
  454. if(ret != PSA_SUCCESS) {
  455. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  456. failf(data, "mbedTLS psa_crypto_init returned (-0x%04X) %s",
  457. -ret, errorbuf);
  458. return CURLE_SSL_CONNECT_ERROR;
  459. }
  460. #endif /* TLS13_SUPPORT */
  461. #ifdef THREADING_SUPPORT
  462. mbedtls_ctr_drbg_init(&backend->ctr_drbg);
  463. ret = mbedtls_ctr_drbg_seed(&backend->ctr_drbg, entropy_func_mutex,
  464. &ts_entropy, NULL, 0);
  465. if(ret) {
  466. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  467. failf(data, "mbedtls_ctr_drbg_seed returned (-0x%04X) %s",
  468. -ret, errorbuf);
  469. return CURLE_FAILED_INIT;
  470. }
  471. #else
  472. mbedtls_entropy_init(&backend->entropy);
  473. mbedtls_ctr_drbg_init(&backend->ctr_drbg);
  474. ret = mbedtls_ctr_drbg_seed(&backend->ctr_drbg, mbedtls_entropy_func,
  475. &backend->entropy, NULL, 0);
  476. if(ret) {
  477. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  478. failf(data, "mbedtls_ctr_drbg_seed returned (-0x%04X) %s",
  479. -ret, errorbuf);
  480. return CURLE_FAILED_INIT;
  481. }
  482. #endif /* THREADING_SUPPORT */
  483. /* Load the trusted CA */
  484. mbedtls_x509_crt_init(&backend->cacert);
  485. if(ca_info_blob && verifypeer) {
  486. /* Unfortunately, mbedtls_x509_crt_parse() requires the data to be null
  487. terminated even when provided the exact length, forcing us to waste
  488. extra memory here. */
  489. unsigned char *newblob = Curl_memdup0(ca_info_blob->data,
  490. ca_info_blob->len);
  491. if(!newblob)
  492. return CURLE_OUT_OF_MEMORY;
  493. ret = mbedtls_x509_crt_parse(&backend->cacert, newblob,
  494. ca_info_blob->len + 1);
  495. free(newblob);
  496. if(ret<0) {
  497. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  498. failf(data, "Error importing ca cert blob - mbedTLS: (-0x%04X) %s",
  499. -ret, errorbuf);
  500. return CURLE_SSL_CERTPROBLEM;
  501. }
  502. }
  503. if(ssl_cafile && verifypeer) {
  504. #ifdef MBEDTLS_FS_IO
  505. ret = mbedtls_x509_crt_parse_file(&backend->cacert, ssl_cafile);
  506. if(ret<0) {
  507. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  508. failf(data, "Error reading ca cert file %s - mbedTLS: (-0x%04X) %s",
  509. ssl_cafile, -ret, errorbuf);
  510. return CURLE_SSL_CACERT_BADFILE;
  511. }
  512. #else
  513. failf(data, "mbedtls: functions that use the filesystem not built in");
  514. return CURLE_NOT_BUILT_IN;
  515. #endif
  516. }
  517. if(ssl_capath) {
  518. #ifdef MBEDTLS_FS_IO
  519. ret = mbedtls_x509_crt_parse_path(&backend->cacert, ssl_capath);
  520. if(ret<0) {
  521. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  522. failf(data, "Error reading ca cert path %s - mbedTLS: (-0x%04X) %s",
  523. ssl_capath, -ret, errorbuf);
  524. if(verifypeer)
  525. return CURLE_SSL_CACERT_BADFILE;
  526. }
  527. #else
  528. failf(data, "mbedtls: functions that use the filesystem not built in");
  529. return CURLE_NOT_BUILT_IN;
  530. #endif
  531. }
  532. /* Load the client certificate */
  533. mbedtls_x509_crt_init(&backend->clicert);
  534. if(ssl_cert) {
  535. #ifdef MBEDTLS_FS_IO
  536. ret = mbedtls_x509_crt_parse_file(&backend->clicert, ssl_cert);
  537. if(ret) {
  538. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  539. failf(data, "Error reading client cert file %s - mbedTLS: (-0x%04X) %s",
  540. ssl_cert, -ret, errorbuf);
  541. return CURLE_SSL_CERTPROBLEM;
  542. }
  543. #else
  544. failf(data, "mbedtls: functions that use the filesystem not built in");
  545. return CURLE_NOT_BUILT_IN;
  546. #endif
  547. }
  548. if(ssl_cert_blob) {
  549. /* Unfortunately, mbedtls_x509_crt_parse() requires the data to be null
  550. terminated even when provided the exact length, forcing us to waste
  551. extra memory here. */
  552. unsigned char *newblob = Curl_memdup0(ssl_cert_blob->data,
  553. ssl_cert_blob->len);
  554. if(!newblob)
  555. return CURLE_OUT_OF_MEMORY;
  556. ret = mbedtls_x509_crt_parse(&backend->clicert, newblob,
  557. ssl_cert_blob->len + 1);
  558. free(newblob);
  559. if(ret) {
  560. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  561. failf(data, "Error reading private key %s - mbedTLS: (-0x%04X) %s",
  562. ssl_config->key, -ret, errorbuf);
  563. return CURLE_SSL_CERTPROBLEM;
  564. }
  565. }
  566. /* Load the client private key */
  567. mbedtls_pk_init(&backend->pk);
  568. if(ssl_config->key || ssl_config->key_blob) {
  569. if(ssl_config->key) {
  570. #ifdef MBEDTLS_FS_IO
  571. #if MBEDTLS_VERSION_NUMBER >= 0x03000000
  572. ret = mbedtls_pk_parse_keyfile(&backend->pk, ssl_config->key,
  573. ssl_config->key_passwd,
  574. mbedtls_ctr_drbg_random,
  575. &backend->ctr_drbg);
  576. #else
  577. ret = mbedtls_pk_parse_keyfile(&backend->pk, ssl_config->key,
  578. ssl_config->key_passwd);
  579. #endif
  580. if(ret) {
  581. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  582. failf(data, "Error reading private key %s - mbedTLS: (-0x%04X) %s",
  583. ssl_config->key, -ret, errorbuf);
  584. return CURLE_SSL_CERTPROBLEM;
  585. }
  586. #else
  587. failf(data, "mbedtls: functions that use the filesystem not built in");
  588. return CURLE_NOT_BUILT_IN;
  589. #endif
  590. }
  591. else {
  592. const struct curl_blob *ssl_key_blob = ssl_config->key_blob;
  593. const unsigned char *key_data =
  594. (const unsigned char *)ssl_key_blob->data;
  595. const char *passwd = ssl_config->key_passwd;
  596. #if MBEDTLS_VERSION_NUMBER >= 0x03000000
  597. ret = mbedtls_pk_parse_key(&backend->pk, key_data, ssl_key_blob->len,
  598. (const unsigned char *)passwd,
  599. passwd ? strlen(passwd) : 0,
  600. mbedtls_ctr_drbg_random,
  601. &backend->ctr_drbg);
  602. #else
  603. ret = mbedtls_pk_parse_key(&backend->pk, key_data, ssl_key_blob->len,
  604. (const unsigned char *)passwd,
  605. passwd ? strlen(passwd) : 0);
  606. #endif
  607. if(ret) {
  608. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  609. failf(data, "Error parsing private key - mbedTLS: (-0x%04X) %s",
  610. -ret, errorbuf);
  611. return CURLE_SSL_CERTPROBLEM;
  612. }
  613. }
  614. if(ret == 0 && !(mbedtls_pk_can_do(&backend->pk, MBEDTLS_PK_RSA) ||
  615. mbedtls_pk_can_do(&backend->pk, MBEDTLS_PK_ECKEY)))
  616. ret = MBEDTLS_ERR_PK_TYPE_MISMATCH;
  617. }
  618. /* Load the CRL */
  619. #ifdef MBEDTLS_X509_CRL_PARSE_C
  620. mbedtls_x509_crl_init(&backend->crl);
  621. if(ssl_crlfile) {
  622. #ifdef MBEDTLS_FS_IO
  623. ret = mbedtls_x509_crl_parse_file(&backend->crl, ssl_crlfile);
  624. if(ret) {
  625. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  626. failf(data, "Error reading CRL file %s - mbedTLS: (-0x%04X) %s",
  627. ssl_crlfile, -ret, errorbuf);
  628. return CURLE_SSL_CRL_BADFILE;
  629. }
  630. #else
  631. failf(data, "mbedtls: functions that use the filesystem not built in");
  632. return CURLE_NOT_BUILT_IN;
  633. #endif
  634. }
  635. #else
  636. if(ssl_crlfile) {
  637. failf(data, "mbedtls: crl support not built in");
  638. return CURLE_NOT_BUILT_IN;
  639. }
  640. #endif
  641. infof(data, "mbedTLS: Connecting to %s:%d", hostname, connssl->peer.port);
  642. mbedtls_ssl_config_init(&backend->config);
  643. ret = mbedtls_ssl_config_defaults(&backend->config,
  644. MBEDTLS_SSL_IS_CLIENT,
  645. MBEDTLS_SSL_TRANSPORT_STREAM,
  646. MBEDTLS_SSL_PRESET_DEFAULT);
  647. if(ret) {
  648. failf(data, "mbedTLS: ssl_config failed");
  649. return CURLE_SSL_CONNECT_ERROR;
  650. }
  651. mbedtls_ssl_init(&backend->ssl);
  652. /* new profile with RSA min key len = 1024 ... */
  653. mbedtls_ssl_conf_cert_profile(&backend->config,
  654. &mbedtls_x509_crt_profile_fr);
  655. switch(conn_config->version) {
  656. case CURL_SSLVERSION_DEFAULT:
  657. case CURL_SSLVERSION_TLSv1:
  658. #if MBEDTLS_VERSION_NUMBER < 0x03000000
  659. mbedtls_ssl_conf_min_version(&backend->config, MBEDTLS_SSL_MAJOR_VERSION_3,
  660. MBEDTLS_SSL_MINOR_VERSION_1);
  661. infof(data, "mbedTLS: Set min SSL version to TLS 1.0");
  662. break;
  663. #endif
  664. case CURL_SSLVERSION_TLSv1_0:
  665. case CURL_SSLVERSION_TLSv1_1:
  666. case CURL_SSLVERSION_TLSv1_2:
  667. case CURL_SSLVERSION_TLSv1_3:
  668. {
  669. CURLcode result = set_ssl_version_min_max(cf, data);
  670. if(result != CURLE_OK)
  671. return result;
  672. break;
  673. }
  674. default:
  675. failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
  676. return CURLE_SSL_CONNECT_ERROR;
  677. }
  678. mbedtls_ssl_conf_rng(&backend->config, mbedtls_ctr_drbg_random,
  679. &backend->ctr_drbg);
  680. ret = mbedtls_ssl_setup(&backend->ssl, &backend->config);
  681. if(ret) {
  682. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  683. failf(data, "ssl_setup failed - mbedTLS: (-0x%04X) %s",
  684. -ret, errorbuf);
  685. return CURLE_SSL_CONNECT_ERROR;
  686. }
  687. mbedtls_ssl_set_bio(&backend->ssl, cf,
  688. mbedtls_bio_cf_write,
  689. mbedtls_bio_cf_read,
  690. NULL /* rev_timeout() */);
  691. if(conn_config->cipher_list) {
  692. ret = mbed_set_selected_ciphers(data, backend, conn_config->cipher_list);
  693. if(ret) {
  694. failf(data, "mbedTLS: failed to set cipher suites");
  695. return ret;
  696. }
  697. }
  698. else {
  699. mbedtls_ssl_conf_ciphersuites(&backend->config,
  700. mbedtls_ssl_list_ciphersuites());
  701. }
  702. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  703. mbedtls_ssl_conf_renegotiation(&backend->config,
  704. MBEDTLS_SSL_RENEGOTIATION_ENABLED);
  705. #endif
  706. #if defined(MBEDTLS_SSL_SESSION_TICKETS)
  707. mbedtls_ssl_conf_session_tickets(&backend->config,
  708. MBEDTLS_SSL_SESSION_TICKETS_DISABLED);
  709. #endif
  710. /* Check if there's a cached ID we can/should use here! */
  711. if(ssl_config->primary.sessionid) {
  712. void *old_session = NULL;
  713. Curl_ssl_sessionid_lock(data);
  714. if(!Curl_ssl_getsessionid(cf, data, &connssl->peer, &old_session, NULL)) {
  715. ret = mbedtls_ssl_set_session(&backend->ssl, old_session);
  716. if(ret) {
  717. Curl_ssl_sessionid_unlock(data);
  718. failf(data, "mbedtls_ssl_set_session returned -0x%x", -ret);
  719. return CURLE_SSL_CONNECT_ERROR;
  720. }
  721. infof(data, "mbedTLS reusing session");
  722. }
  723. Curl_ssl_sessionid_unlock(data);
  724. }
  725. mbedtls_ssl_conf_ca_chain(&backend->config,
  726. &backend->cacert,
  727. #ifdef MBEDTLS_X509_CRL_PARSE_C
  728. &backend->crl);
  729. #else
  730. NULL);
  731. #endif
  732. if(ssl_config->key || ssl_config->key_blob) {
  733. mbedtls_ssl_conf_own_cert(&backend->config,
  734. &backend->clicert, &backend->pk);
  735. }
  736. if(mbedtls_ssl_set_hostname(&backend->ssl, connssl->peer.sni?
  737. connssl->peer.sni : connssl->peer.hostname)) {
  738. /* mbedtls_ssl_set_hostname() sets the name to use in CN/SAN checks and
  739. the name to set in the SNI extension. So even if curl connects to a
  740. host specified as an IP address, this function must be used. */
  741. failf(data, "Failed to set SNI");
  742. return CURLE_SSL_CONNECT_ERROR;
  743. }
  744. #ifdef HAS_ALPN
  745. if(connssl->alpn) {
  746. struct alpn_proto_buf proto;
  747. size_t i;
  748. for(i = 0; i < connssl->alpn->count; ++i) {
  749. backend->protocols[i] = connssl->alpn->entries[i];
  750. }
  751. /* this function doesn't clone the protocols array, which is why we need
  752. to keep it around */
  753. if(mbedtls_ssl_conf_alpn_protocols(&backend->config,
  754. &backend->protocols[0])) {
  755. failf(data, "Failed setting ALPN protocols");
  756. return CURLE_SSL_CONNECT_ERROR;
  757. }
  758. Curl_alpn_to_proto_str(&proto, connssl->alpn);
  759. infof(data, VTLS_INFOF_ALPN_OFFER_1STR, proto.data);
  760. }
  761. #endif
  762. #ifdef MBEDTLS_DEBUG
  763. /* In order to make that work in mbedtls MBEDTLS_DEBUG_C must be defined. */
  764. mbedtls_ssl_conf_dbg(&backend->config, mbed_debug, data);
  765. /* - 0 No debug
  766. * - 1 Error
  767. * - 2 State change
  768. * - 3 Informational
  769. * - 4 Verbose
  770. */
  771. mbedtls_debug_set_threshold(4);
  772. #endif
  773. /* give application a chance to interfere with mbedTLS set up. */
  774. if(data->set.ssl.fsslctx) {
  775. ret = (*data->set.ssl.fsslctx)(data, &backend->config,
  776. data->set.ssl.fsslctxp);
  777. if(ret) {
  778. failf(data, "error signaled by ssl ctx callback");
  779. return ret;
  780. }
  781. }
  782. connssl->connecting_state = ssl_connect_2;
  783. return CURLE_OK;
  784. }
  785. static CURLcode
  786. mbed_connect_step2(struct Curl_cfilter *cf, struct Curl_easy *data)
  787. {
  788. int ret;
  789. struct ssl_connect_data *connssl = cf->ctx;
  790. struct mbed_ssl_backend_data *backend =
  791. (struct mbed_ssl_backend_data *)connssl->backend;
  792. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  793. const mbedtls_x509_crt *peercert;
  794. char cipher_str[64];
  795. uint16_t cipher_id;
  796. #ifndef CURL_DISABLE_PROXY
  797. const char * const pinnedpubkey = Curl_ssl_cf_is_proxy(cf)?
  798. data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY]:
  799. data->set.str[STRING_SSL_PINNEDPUBLICKEY];
  800. #else
  801. const char * const pinnedpubkey = data->set.str[STRING_SSL_PINNEDPUBLICKEY];
  802. #endif
  803. DEBUGASSERT(backend);
  804. ret = mbedtls_ssl_handshake(&backend->ssl);
  805. if(ret == MBEDTLS_ERR_SSL_WANT_READ) {
  806. connssl->connecting_state = ssl_connect_2_reading;
  807. return CURLE_OK;
  808. }
  809. else if(ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  810. connssl->connecting_state = ssl_connect_2_writing;
  811. return CURLE_OK;
  812. }
  813. else if(ret) {
  814. char errorbuf[128];
  815. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  816. failf(data, "ssl_handshake returned - mbedTLS: (-0x%04X) %s",
  817. -ret, errorbuf);
  818. return CURLE_SSL_CONNECT_ERROR;
  819. }
  820. cipher_id = (uint16_t)
  821. mbedtls_ssl_get_ciphersuite_id_from_ssl(&backend->ssl);
  822. mbed_cipher_suite_get_str(cipher_id, cipher_str, sizeof(cipher_str), true);
  823. infof(data, "mbedTLS: Handshake complete, cipher is %s", cipher_str);
  824. ret = mbedtls_ssl_get_verify_result(&backend->ssl);
  825. if(!conn_config->verifyhost)
  826. /* Ignore hostname errors if verifyhost is disabled */
  827. ret &= ~MBEDTLS_X509_BADCERT_CN_MISMATCH;
  828. if(ret && conn_config->verifypeer) {
  829. if(ret & MBEDTLS_X509_BADCERT_EXPIRED)
  830. failf(data, "Cert verify failed: BADCERT_EXPIRED");
  831. else if(ret & MBEDTLS_X509_BADCERT_REVOKED)
  832. failf(data, "Cert verify failed: BADCERT_REVOKED");
  833. else if(ret & MBEDTLS_X509_BADCERT_CN_MISMATCH)
  834. failf(data, "Cert verify failed: BADCERT_CN_MISMATCH");
  835. else if(ret & MBEDTLS_X509_BADCERT_NOT_TRUSTED)
  836. failf(data, "Cert verify failed: BADCERT_NOT_TRUSTED");
  837. else if(ret & MBEDTLS_X509_BADCERT_FUTURE)
  838. failf(data, "Cert verify failed: BADCERT_FUTURE");
  839. return CURLE_PEER_FAILED_VERIFICATION;
  840. }
  841. peercert = mbedtls_ssl_get_peer_cert(&backend->ssl);
  842. if(peercert && data->set.verbose) {
  843. #ifndef MBEDTLS_X509_REMOVE_INFO
  844. const size_t bufsize = 16384;
  845. char *buffer = malloc(bufsize);
  846. if(!buffer)
  847. return CURLE_OUT_OF_MEMORY;
  848. if(mbedtls_x509_crt_info(buffer, bufsize, "* ", peercert) > 0)
  849. infof(data, "Dumping cert info: %s", buffer);
  850. else
  851. infof(data, "Unable to dump certificate information");
  852. free(buffer);
  853. #else
  854. infof(data, "Unable to dump certificate information");
  855. #endif
  856. }
  857. if(pinnedpubkey) {
  858. int size;
  859. CURLcode result;
  860. mbedtls_x509_crt *p = NULL;
  861. unsigned char *pubkey = NULL;
  862. #if MBEDTLS_VERSION_NUMBER == 0x03000000
  863. if(!peercert || !peercert->MBEDTLS_PRIVATE(raw).MBEDTLS_PRIVATE(p) ||
  864. !peercert->MBEDTLS_PRIVATE(raw).MBEDTLS_PRIVATE(len)) {
  865. #else
  866. if(!peercert || !peercert->raw.p || !peercert->raw.len) {
  867. #endif
  868. failf(data, "Failed due to missing peer certificate");
  869. return CURLE_SSL_PINNEDPUBKEYNOTMATCH;
  870. }
  871. p = calloc(1, sizeof(*p));
  872. if(!p)
  873. return CURLE_OUT_OF_MEMORY;
  874. pubkey = malloc(PUB_DER_MAX_BYTES);
  875. if(!pubkey) {
  876. result = CURLE_OUT_OF_MEMORY;
  877. goto pinnedpubkey_error;
  878. }
  879. mbedtls_x509_crt_init(p);
  880. /* Make a copy of our const peercert because mbedtls_pk_write_pubkey_der
  881. needs a non-const key, for now.
  882. https://github.com/ARMmbed/mbedtls/issues/396 */
  883. #if MBEDTLS_VERSION_NUMBER == 0x03000000
  884. if(mbedtls_x509_crt_parse_der(p,
  885. peercert->MBEDTLS_PRIVATE(raw).MBEDTLS_PRIVATE(p),
  886. peercert->MBEDTLS_PRIVATE(raw).MBEDTLS_PRIVATE(len))) {
  887. #else
  888. if(mbedtls_x509_crt_parse_der(p, peercert->raw.p, peercert->raw.len)) {
  889. #endif
  890. failf(data, "Failed copying peer certificate");
  891. result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
  892. goto pinnedpubkey_error;
  893. }
  894. #if MBEDTLS_VERSION_NUMBER == 0x03000000
  895. size = mbedtls_pk_write_pubkey_der(&p->MBEDTLS_PRIVATE(pk), pubkey,
  896. PUB_DER_MAX_BYTES);
  897. #else
  898. size = mbedtls_pk_write_pubkey_der(&p->pk, pubkey, PUB_DER_MAX_BYTES);
  899. #endif
  900. if(size <= 0) {
  901. failf(data, "Failed copying public key from peer certificate");
  902. result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
  903. goto pinnedpubkey_error;
  904. }
  905. /* mbedtls_pk_write_pubkey_der writes data at the end of the buffer. */
  906. result = Curl_pin_peer_pubkey(data,
  907. pinnedpubkey,
  908. &pubkey[PUB_DER_MAX_BYTES - size], size);
  909. pinnedpubkey_error:
  910. mbedtls_x509_crt_free(p);
  911. free(p);
  912. free(pubkey);
  913. if(result) {
  914. return result;
  915. }
  916. }
  917. #ifdef HAS_ALPN
  918. if(connssl->alpn) {
  919. const char *proto = mbedtls_ssl_get_alpn_protocol(&backend->ssl);
  920. Curl_alpn_set_negotiated(cf, data, (const unsigned char *)proto,
  921. proto? strlen(proto) : 0);
  922. }
  923. #endif
  924. connssl->connecting_state = ssl_connect_3;
  925. infof(data, "SSL connected");
  926. return CURLE_OK;
  927. }
  928. static void mbedtls_session_free(void *sessionid, size_t idsize)
  929. {
  930. (void)idsize;
  931. mbedtls_ssl_session_free(sessionid);
  932. free(sessionid);
  933. }
  934. static CURLcode
  935. mbed_connect_step3(struct Curl_cfilter *cf, struct Curl_easy *data)
  936. {
  937. CURLcode retcode = CURLE_OK;
  938. struct ssl_connect_data *connssl = cf->ctx;
  939. struct mbed_ssl_backend_data *backend =
  940. (struct mbed_ssl_backend_data *)connssl->backend;
  941. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  942. DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
  943. DEBUGASSERT(backend);
  944. if(ssl_config->primary.sessionid) {
  945. int ret;
  946. mbedtls_ssl_session *our_ssl_sessionid;
  947. void *old_ssl_sessionid = NULL;
  948. our_ssl_sessionid = malloc(sizeof(mbedtls_ssl_session));
  949. if(!our_ssl_sessionid)
  950. return CURLE_OUT_OF_MEMORY;
  951. mbedtls_ssl_session_init(our_ssl_sessionid);
  952. ret = mbedtls_ssl_get_session(&backend->ssl, our_ssl_sessionid);
  953. if(ret) {
  954. if(ret != MBEDTLS_ERR_SSL_ALLOC_FAILED)
  955. mbedtls_ssl_session_free(our_ssl_sessionid);
  956. free(our_ssl_sessionid);
  957. failf(data, "mbedtls_ssl_get_session returned -0x%x", -ret);
  958. return CURLE_SSL_CONNECT_ERROR;
  959. }
  960. /* If there's already a matching session in the cache, delete it */
  961. Curl_ssl_sessionid_lock(data);
  962. if(!Curl_ssl_getsessionid(cf, data, &connssl->peer,
  963. &old_ssl_sessionid, NULL))
  964. Curl_ssl_delsessionid(data, old_ssl_sessionid);
  965. retcode = Curl_ssl_addsessionid(cf, data, &connssl->peer,
  966. our_ssl_sessionid, 0,
  967. mbedtls_session_free);
  968. Curl_ssl_sessionid_unlock(data);
  969. if(retcode)
  970. return retcode;
  971. }
  972. connssl->connecting_state = ssl_connect_done;
  973. return CURLE_OK;
  974. }
  975. static ssize_t mbed_send(struct Curl_cfilter *cf, struct Curl_easy *data,
  976. const void *mem, size_t len,
  977. CURLcode *curlcode)
  978. {
  979. struct ssl_connect_data *connssl = cf->ctx;
  980. struct mbed_ssl_backend_data *backend =
  981. (struct mbed_ssl_backend_data *)connssl->backend;
  982. int ret = -1;
  983. (void)data;
  984. DEBUGASSERT(backend);
  985. ret = mbedtls_ssl_write(&backend->ssl, (unsigned char *)mem, len);
  986. if(ret < 0) {
  987. *curlcode = (ret == MBEDTLS_ERR_SSL_WANT_WRITE) ?
  988. CURLE_AGAIN : CURLE_SEND_ERROR;
  989. ret = -1;
  990. }
  991. return ret;
  992. }
  993. static void mbedtls_close_all(struct Curl_easy *data)
  994. {
  995. (void)data;
  996. }
  997. static void mbedtls_close(struct Curl_cfilter *cf, struct Curl_easy *data)
  998. {
  999. struct ssl_connect_data *connssl = cf->ctx;
  1000. struct mbed_ssl_backend_data *backend =
  1001. (struct mbed_ssl_backend_data *)connssl->backend;
  1002. char buf[32];
  1003. (void)data;
  1004. DEBUGASSERT(backend);
  1005. /* Maybe the server has already sent a close notify alert.
  1006. Read it to avoid an RST on the TCP connection. */
  1007. (void)mbedtls_ssl_read(&backend->ssl, (unsigned char *)buf, sizeof(buf));
  1008. mbedtls_pk_free(&backend->pk);
  1009. mbedtls_x509_crt_free(&backend->clicert);
  1010. mbedtls_x509_crt_free(&backend->cacert);
  1011. #ifdef MBEDTLS_X509_CRL_PARSE_C
  1012. mbedtls_x509_crl_free(&backend->crl);
  1013. #endif
  1014. Curl_safefree(backend->ciphersuites);
  1015. mbedtls_ssl_config_free(&backend->config);
  1016. mbedtls_ssl_free(&backend->ssl);
  1017. mbedtls_ctr_drbg_free(&backend->ctr_drbg);
  1018. #ifndef THREADING_SUPPORT
  1019. mbedtls_entropy_free(&backend->entropy);
  1020. #endif /* THREADING_SUPPORT */
  1021. }
  1022. static ssize_t mbed_recv(struct Curl_cfilter *cf, struct Curl_easy *data,
  1023. char *buf, size_t buffersize,
  1024. CURLcode *curlcode)
  1025. {
  1026. struct ssl_connect_data *connssl = cf->ctx;
  1027. struct mbed_ssl_backend_data *backend =
  1028. (struct mbed_ssl_backend_data *)connssl->backend;
  1029. int ret = -1;
  1030. ssize_t len = -1;
  1031. (void)data;
  1032. DEBUGASSERT(backend);
  1033. ret = mbedtls_ssl_read(&backend->ssl, (unsigned char *)buf,
  1034. buffersize);
  1035. if(ret <= 0) {
  1036. if(ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY)
  1037. return 0;
  1038. *curlcode = ((ret == MBEDTLS_ERR_SSL_WANT_READ)
  1039. #ifdef TLS13_SUPPORT
  1040. || (ret == MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET)
  1041. #endif
  1042. ) ? CURLE_AGAIN : CURLE_RECV_ERROR;
  1043. return -1;
  1044. }
  1045. len = ret;
  1046. return len;
  1047. }
  1048. static size_t mbedtls_version(char *buffer, size_t size)
  1049. {
  1050. #ifdef MBEDTLS_VERSION_C
  1051. /* if mbedtls_version_get_number() is available it is better */
  1052. unsigned int version = mbedtls_version_get_number();
  1053. return msnprintf(buffer, size, "mbedTLS/%u.%u.%u", version>>24,
  1054. (version>>16)&0xff, (version>>8)&0xff);
  1055. #else
  1056. return msnprintf(buffer, size, "mbedTLS/%s", MBEDTLS_VERSION_STRING);
  1057. #endif
  1058. }
  1059. static CURLcode mbedtls_random(struct Curl_easy *data,
  1060. unsigned char *entropy, size_t length)
  1061. {
  1062. #if defined(MBEDTLS_CTR_DRBG_C)
  1063. int ret = -1;
  1064. char errorbuf[128];
  1065. mbedtls_entropy_context ctr_entropy;
  1066. mbedtls_ctr_drbg_context ctr_drbg;
  1067. mbedtls_entropy_init(&ctr_entropy);
  1068. mbedtls_ctr_drbg_init(&ctr_drbg);
  1069. ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func,
  1070. &ctr_entropy, NULL, 0);
  1071. if(ret) {
  1072. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  1073. failf(data, "mbedtls_ctr_drbg_seed returned (-0x%04X) %s",
  1074. -ret, errorbuf);
  1075. }
  1076. else {
  1077. ret = mbedtls_ctr_drbg_random(&ctr_drbg, entropy, length);
  1078. if(ret) {
  1079. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  1080. failf(data, "mbedtls_ctr_drbg_random returned (-0x%04X) %s",
  1081. -ret, errorbuf);
  1082. }
  1083. }
  1084. mbedtls_ctr_drbg_free(&ctr_drbg);
  1085. mbedtls_entropy_free(&ctr_entropy);
  1086. return ret == 0 ? CURLE_OK : CURLE_FAILED_INIT;
  1087. #elif defined(MBEDTLS_HAVEGE_C)
  1088. mbedtls_havege_state hs;
  1089. mbedtls_havege_init(&hs);
  1090. mbedtls_havege_random(&hs, entropy, length);
  1091. mbedtls_havege_free(&hs);
  1092. return CURLE_OK;
  1093. #else
  1094. return CURLE_NOT_BUILT_IN;
  1095. #endif
  1096. }
  1097. static CURLcode
  1098. mbed_connect_common(struct Curl_cfilter *cf, struct Curl_easy *data,
  1099. bool nonblocking,
  1100. bool *done)
  1101. {
  1102. CURLcode retcode;
  1103. struct ssl_connect_data *connssl = cf->ctx;
  1104. curl_socket_t sockfd = Curl_conn_cf_get_socket(cf, data);
  1105. timediff_t timeout_ms;
  1106. int what;
  1107. /* check if the connection has already been established */
  1108. if(ssl_connection_complete == connssl->state) {
  1109. *done = TRUE;
  1110. return CURLE_OK;
  1111. }
  1112. if(ssl_connect_1 == connssl->connecting_state) {
  1113. /* Find out how much more time we're allowed */
  1114. timeout_ms = Curl_timeleft(data, NULL, TRUE);
  1115. if(timeout_ms < 0) {
  1116. /* no need to continue if time already is up */
  1117. failf(data, "SSL connection timeout");
  1118. return CURLE_OPERATION_TIMEDOUT;
  1119. }
  1120. retcode = mbed_connect_step1(cf, data);
  1121. if(retcode)
  1122. return retcode;
  1123. }
  1124. while(ssl_connect_2 == connssl->connecting_state ||
  1125. ssl_connect_2_reading == connssl->connecting_state ||
  1126. ssl_connect_2_writing == connssl->connecting_state) {
  1127. /* check allowed time left */
  1128. timeout_ms = Curl_timeleft(data, NULL, TRUE);
  1129. if(timeout_ms < 0) {
  1130. /* no need to continue if time already is up */
  1131. failf(data, "SSL connection timeout");
  1132. return CURLE_OPERATION_TIMEDOUT;
  1133. }
  1134. /* if ssl is expecting something, check if it's available. */
  1135. if(connssl->connecting_state == ssl_connect_2_reading
  1136. || connssl->connecting_state == ssl_connect_2_writing) {
  1137. curl_socket_t writefd = ssl_connect_2_writing ==
  1138. connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
  1139. curl_socket_t readfd = ssl_connect_2_reading ==
  1140. connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
  1141. what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
  1142. nonblocking ? 0 : timeout_ms);
  1143. if(what < 0) {
  1144. /* fatal error */
  1145. failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
  1146. return CURLE_SSL_CONNECT_ERROR;
  1147. }
  1148. else if(0 == what) {
  1149. if(nonblocking) {
  1150. *done = FALSE;
  1151. return CURLE_OK;
  1152. }
  1153. else {
  1154. /* timeout */
  1155. failf(data, "SSL connection timeout");
  1156. return CURLE_OPERATION_TIMEDOUT;
  1157. }
  1158. }
  1159. /* socket is readable or writable */
  1160. }
  1161. /* Run transaction, and return to the caller if it failed or if
  1162. * this connection is part of a multi handle and this loop would
  1163. * execute again. This permits the owner of a multi handle to
  1164. * abort a connection attempt before step2 has completed while
  1165. * ensuring that a client using select() or epoll() will always
  1166. * have a valid fdset to wait on.
  1167. */
  1168. retcode = mbed_connect_step2(cf, data);
  1169. if(retcode || (nonblocking &&
  1170. (ssl_connect_2 == connssl->connecting_state ||
  1171. ssl_connect_2_reading == connssl->connecting_state ||
  1172. ssl_connect_2_writing == connssl->connecting_state)))
  1173. return retcode;
  1174. } /* repeat step2 until all transactions are done. */
  1175. if(ssl_connect_3 == connssl->connecting_state) {
  1176. retcode = mbed_connect_step3(cf, data);
  1177. if(retcode)
  1178. return retcode;
  1179. }
  1180. if(ssl_connect_done == connssl->connecting_state) {
  1181. connssl->state = ssl_connection_complete;
  1182. *done = TRUE;
  1183. }
  1184. else
  1185. *done = FALSE;
  1186. /* Reset our connect state machine */
  1187. connssl->connecting_state = ssl_connect_1;
  1188. return CURLE_OK;
  1189. }
  1190. static CURLcode mbedtls_connect_nonblocking(struct Curl_cfilter *cf,
  1191. struct Curl_easy *data,
  1192. bool *done)
  1193. {
  1194. return mbed_connect_common(cf, data, TRUE, done);
  1195. }
  1196. static CURLcode mbedtls_connect(struct Curl_cfilter *cf,
  1197. struct Curl_easy *data)
  1198. {
  1199. CURLcode retcode;
  1200. bool done = FALSE;
  1201. retcode = mbed_connect_common(cf, data, FALSE, &done);
  1202. if(retcode)
  1203. return retcode;
  1204. DEBUGASSERT(done);
  1205. return CURLE_OK;
  1206. }
  1207. /*
  1208. * return 0 error initializing SSL
  1209. * return 1 SSL initialized successfully
  1210. */
  1211. static int mbedtls_init(void)
  1212. {
  1213. if(!Curl_mbedtlsthreadlock_thread_setup())
  1214. return 0;
  1215. #ifdef THREADING_SUPPORT
  1216. entropy_init_mutex(&ts_entropy);
  1217. #endif
  1218. return 1;
  1219. }
  1220. static void mbedtls_cleanup(void)
  1221. {
  1222. #ifdef THREADING_SUPPORT
  1223. entropy_cleanup_mutex(&ts_entropy);
  1224. #endif
  1225. (void)Curl_mbedtlsthreadlock_thread_cleanup();
  1226. }
  1227. static bool mbedtls_data_pending(struct Curl_cfilter *cf,
  1228. const struct Curl_easy *data)
  1229. {
  1230. struct ssl_connect_data *ctx = cf->ctx;
  1231. struct mbed_ssl_backend_data *backend;
  1232. (void)data;
  1233. DEBUGASSERT(ctx && ctx->backend);
  1234. backend = (struct mbed_ssl_backend_data *)ctx->backend;
  1235. return mbedtls_ssl_get_bytes_avail(&backend->ssl) != 0;
  1236. }
  1237. static CURLcode mbedtls_sha256sum(const unsigned char *input,
  1238. size_t inputlen,
  1239. unsigned char *sha256sum,
  1240. size_t sha256len UNUSED_PARAM)
  1241. {
  1242. /* TODO: explain this for different mbedtls 2.x vs 3 version */
  1243. (void)sha256len;
  1244. #if MBEDTLS_VERSION_NUMBER < 0x02070000
  1245. mbedtls_sha256(input, inputlen, sha256sum, 0);
  1246. #else
  1247. /* returns 0 on success, otherwise failure */
  1248. #if MBEDTLS_VERSION_NUMBER >= 0x03000000
  1249. if(mbedtls_sha256(input, inputlen, sha256sum, 0) != 0)
  1250. #else
  1251. if(mbedtls_sha256_ret(input, inputlen, sha256sum, 0) != 0)
  1252. #endif
  1253. return CURLE_BAD_FUNCTION_ARGUMENT;
  1254. #endif
  1255. return CURLE_OK;
  1256. }
  1257. static void *mbedtls_get_internals(struct ssl_connect_data *connssl,
  1258. CURLINFO info UNUSED_PARAM)
  1259. {
  1260. struct mbed_ssl_backend_data *backend =
  1261. (struct mbed_ssl_backend_data *)connssl->backend;
  1262. (void)info;
  1263. DEBUGASSERT(backend);
  1264. return &backend->ssl;
  1265. }
  1266. const struct Curl_ssl Curl_ssl_mbedtls = {
  1267. { CURLSSLBACKEND_MBEDTLS, "mbedtls" }, /* info */
  1268. SSLSUPP_CA_PATH |
  1269. SSLSUPP_CAINFO_BLOB |
  1270. SSLSUPP_PINNEDPUBKEY |
  1271. SSLSUPP_SSL_CTX |
  1272. SSLSUPP_HTTPS_PROXY,
  1273. sizeof(struct mbed_ssl_backend_data),
  1274. mbedtls_init, /* init */
  1275. mbedtls_cleanup, /* cleanup */
  1276. mbedtls_version, /* version */
  1277. Curl_none_check_cxn, /* check_cxn */
  1278. Curl_none_shutdown, /* shutdown */
  1279. mbedtls_data_pending, /* data_pending */
  1280. mbedtls_random, /* random */
  1281. Curl_none_cert_status_request, /* cert_status_request */
  1282. mbedtls_connect, /* connect */
  1283. mbedtls_connect_nonblocking, /* connect_nonblocking */
  1284. Curl_ssl_adjust_pollset, /* adjust_pollset */
  1285. mbedtls_get_internals, /* get_internals */
  1286. mbedtls_close, /* close_one */
  1287. mbedtls_close_all, /* close_all */
  1288. Curl_none_set_engine, /* set_engine */
  1289. Curl_none_set_engine_default, /* set_engine_default */
  1290. Curl_none_engines_list, /* engines_list */
  1291. Curl_none_false_start, /* false_start */
  1292. mbedtls_sha256sum, /* sha256sum */
  1293. NULL, /* associate_connection */
  1294. NULL, /* disassociate_connection */
  1295. NULL, /* free_multi_ssl_backend_data */
  1296. mbed_recv, /* recv decrypted data */
  1297. mbed_send, /* send data to encrypt */
  1298. };
  1299. #endif /* USE_MBEDTLS */