mbedtls.c 39 KB

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