mbedtls.c 38 KB

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