2
0

mbedtls.c 39 KB

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