mbedtls.c 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 2012 - 2022, Daniel Stenberg, <daniel@haxx.se>, et al.
  9. * Copyright (C) 2010 - 2011, 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 ssl_connect_data *connssl = cf->ctx;
  139. struct Curl_easy *data = connssl->call_data;
  140. ssize_t nwritten;
  141. CURLcode result;
  142. DEBUGASSERT(data);
  143. nwritten = Curl_conn_cf_send(cf->next, data, (char *)buf, blen, &result);
  144. /* DEBUGF(infof(data, CFMSG(cf, "bio_cf_out_write(len=%d) -> %d, err=%d"),
  145. blen, (int)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 bio_cf_read(void *bio, unsigned char *buf, size_t blen)
  152. {
  153. struct Curl_cfilter *cf = bio;
  154. struct ssl_connect_data *connssl = cf->ctx;
  155. struct Curl_easy *data = connssl->call_data;
  156. ssize_t nread;
  157. CURLcode result;
  158. DEBUGASSERT(data);
  159. /* OpenSSL catches this case, so should we. */
  160. if(!buf)
  161. return 0;
  162. nread = Curl_conn_cf_recv(cf->next, data, (char *)buf, blen, &result);
  163. /* DEBUGF(infof(data, CFMSG(cf, "bio_cf_in_read(len=%d) -> %d, err=%d"),
  164. blen, (int)nread, result)); */
  165. if(nread < 0 && CURLE_AGAIN == result) {
  166. nread = MBEDTLS_ERR_SSL_WANT_READ;
  167. }
  168. return (int)nread;
  169. }
  170. /*
  171. * profile
  172. */
  173. static const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_fr =
  174. {
  175. /* Hashes from SHA-1 and above */
  176. MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA1) |
  177. MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_RIPEMD160) |
  178. MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA224) |
  179. MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA256) |
  180. MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA384) |
  181. MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA512),
  182. 0xFFFFFFF, /* Any PK alg */
  183. 0xFFFFFFF, /* Any curve */
  184. 1024, /* RSA min key len */
  185. };
  186. /* See https://tls.mbed.org/discussions/generic/
  187. howto-determine-exact-buffer-len-for-mbedtls_pk_write_pubkey_der
  188. */
  189. #define RSA_PUB_DER_MAX_BYTES (38 + 2 * MBEDTLS_MPI_MAX_SIZE)
  190. #define ECP_PUB_DER_MAX_BYTES (30 + 2 * MBEDTLS_ECP_MAX_BYTES)
  191. #define PUB_DER_MAX_BYTES (RSA_PUB_DER_MAX_BYTES > ECP_PUB_DER_MAX_BYTES ? \
  192. RSA_PUB_DER_MAX_BYTES : ECP_PUB_DER_MAX_BYTES)
  193. static CURLcode mbedtls_version_from_curl(int *mbedver, long version)
  194. {
  195. #if MBEDTLS_VERSION_NUMBER >= 0x03000000
  196. switch(version) {
  197. case CURL_SSLVERSION_TLSv1_0:
  198. case CURL_SSLVERSION_TLSv1_1:
  199. case CURL_SSLVERSION_TLSv1_2:
  200. *mbedver = MBEDTLS_SSL_MINOR_VERSION_3;
  201. return CURLE_OK;
  202. case CURL_SSLVERSION_TLSv1_3:
  203. break;
  204. }
  205. #else
  206. switch(version) {
  207. case CURL_SSLVERSION_TLSv1_0:
  208. *mbedver = MBEDTLS_SSL_MINOR_VERSION_1;
  209. return CURLE_OK;
  210. case CURL_SSLVERSION_TLSv1_1:
  211. *mbedver = MBEDTLS_SSL_MINOR_VERSION_2;
  212. return CURLE_OK;
  213. case CURL_SSLVERSION_TLSv1_2:
  214. *mbedver = MBEDTLS_SSL_MINOR_VERSION_3;
  215. return CURLE_OK;
  216. case CURL_SSLVERSION_TLSv1_3:
  217. break;
  218. }
  219. #endif
  220. return CURLE_SSL_CONNECT_ERROR;
  221. }
  222. static CURLcode
  223. set_ssl_version_min_max(struct Curl_cfilter *cf, struct Curl_easy *data)
  224. {
  225. struct ssl_connect_data *connssl = cf->ctx;
  226. struct ssl_backend_data *backend = 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 ssl_backend_data *backend = 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:%ld", 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(cf->conn->bits.tls_enable_alpn) {
  569. const char **p = &backend->protocols[0];
  570. #ifdef USE_HTTP2
  571. if(data->state.httpwant >= CURL_HTTP_VERSION_2)
  572. *p++ = ALPN_H2;
  573. #endif
  574. *p++ = ALPN_HTTP_1_1;
  575. *p = NULL;
  576. /* this function doesn't clone the protocols array, which is why we need
  577. to keep it around */
  578. if(mbedtls_ssl_conf_alpn_protocols(&backend->config,
  579. &backend->protocols[0])) {
  580. failf(data, "Failed setting ALPN protocols");
  581. return CURLE_SSL_CONNECT_ERROR;
  582. }
  583. for(p = &backend->protocols[0]; *p; ++p)
  584. infof(data, VTLS_INFOF_ALPN_OFFER_1STR, *p);
  585. }
  586. #endif
  587. #ifdef MBEDTLS_DEBUG
  588. /* In order to make that work in mbedtls MBEDTLS_DEBUG_C must be defined. */
  589. mbedtls_ssl_conf_dbg(&backend->config, mbed_debug, data);
  590. /* - 0 No debug
  591. * - 1 Error
  592. * - 2 State change
  593. * - 3 Informational
  594. * - 4 Verbose
  595. */
  596. mbedtls_debug_set_threshold(4);
  597. #endif
  598. /* give application a chance to interfere with mbedTLS set up. */
  599. if(data->set.ssl.fsslctx) {
  600. ret = (*data->set.ssl.fsslctx)(data, &backend->config,
  601. data->set.ssl.fsslctxp);
  602. if(ret) {
  603. failf(data, "error signaled by ssl ctx callback");
  604. return ret;
  605. }
  606. }
  607. connssl->connecting_state = ssl_connect_2;
  608. return CURLE_OK;
  609. }
  610. static CURLcode
  611. mbed_connect_step2(struct Curl_cfilter *cf, struct Curl_easy *data)
  612. {
  613. int ret;
  614. struct ssl_connect_data *connssl = cf->ctx;
  615. struct ssl_backend_data *backend = connssl->backend;
  616. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  617. const mbedtls_x509_crt *peercert;
  618. const char * const pinnedpubkey = Curl_ssl_cf_is_proxy(cf)?
  619. data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY]:
  620. data->set.str[STRING_SSL_PINNEDPUBLICKEY];
  621. DEBUGASSERT(backend);
  622. ret = mbedtls_ssl_handshake(&backend->ssl);
  623. if(ret == MBEDTLS_ERR_SSL_WANT_READ) {
  624. connssl->connecting_state = ssl_connect_2_reading;
  625. return CURLE_OK;
  626. }
  627. else if(ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  628. connssl->connecting_state = ssl_connect_2_writing;
  629. return CURLE_OK;
  630. }
  631. else if(ret) {
  632. char errorbuf[128];
  633. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  634. failf(data, "ssl_handshake returned - mbedTLS: (-0x%04X) %s",
  635. -ret, errorbuf);
  636. return CURLE_SSL_CONNECT_ERROR;
  637. }
  638. infof(data, "mbedTLS: Handshake complete, cipher is %s",
  639. mbedtls_ssl_get_ciphersuite(&backend->ssl));
  640. ret = mbedtls_ssl_get_verify_result(&backend->ssl);
  641. if(!conn_config->verifyhost)
  642. /* Ignore hostname errors if verifyhost is disabled */
  643. ret &= ~MBEDTLS_X509_BADCERT_CN_MISMATCH;
  644. if(ret && conn_config->verifypeer) {
  645. if(ret & MBEDTLS_X509_BADCERT_EXPIRED)
  646. failf(data, "Cert verify failed: BADCERT_EXPIRED");
  647. else if(ret & MBEDTLS_X509_BADCERT_REVOKED)
  648. failf(data, "Cert verify failed: BADCERT_REVOKED");
  649. else if(ret & MBEDTLS_X509_BADCERT_CN_MISMATCH)
  650. failf(data, "Cert verify failed: BADCERT_CN_MISMATCH");
  651. else if(ret & MBEDTLS_X509_BADCERT_NOT_TRUSTED)
  652. failf(data, "Cert verify failed: BADCERT_NOT_TRUSTED");
  653. else if(ret & MBEDTLS_X509_BADCERT_FUTURE)
  654. failf(data, "Cert verify failed: BADCERT_FUTURE");
  655. return CURLE_PEER_FAILED_VERIFICATION;
  656. }
  657. peercert = mbedtls_ssl_get_peer_cert(&backend->ssl);
  658. if(peercert && data->set.verbose) {
  659. const size_t bufsize = 16384;
  660. char *buffer = malloc(bufsize);
  661. if(!buffer)
  662. return CURLE_OUT_OF_MEMORY;
  663. if(mbedtls_x509_crt_info(buffer, bufsize, "* ", peercert) > 0)
  664. infof(data, "Dumping cert info: %s", buffer);
  665. else
  666. infof(data, "Unable to dump certificate information");
  667. free(buffer);
  668. }
  669. if(pinnedpubkey) {
  670. int size;
  671. CURLcode result;
  672. mbedtls_x509_crt *p = NULL;
  673. unsigned char *pubkey = NULL;
  674. #if MBEDTLS_VERSION_NUMBER == 0x03000000
  675. if(!peercert || !peercert->MBEDTLS_PRIVATE(raw).MBEDTLS_PRIVATE(p) ||
  676. !peercert->MBEDTLS_PRIVATE(raw).MBEDTLS_PRIVATE(len)) {
  677. #else
  678. if(!peercert || !peercert->raw.p || !peercert->raw.len) {
  679. #endif
  680. failf(data, "Failed due to missing peer certificate");
  681. return CURLE_SSL_PINNEDPUBKEYNOTMATCH;
  682. }
  683. p = calloc(1, sizeof(*p));
  684. if(!p)
  685. return CURLE_OUT_OF_MEMORY;
  686. pubkey = malloc(PUB_DER_MAX_BYTES);
  687. if(!pubkey) {
  688. result = CURLE_OUT_OF_MEMORY;
  689. goto pinnedpubkey_error;
  690. }
  691. mbedtls_x509_crt_init(p);
  692. /* Make a copy of our const peercert because mbedtls_pk_write_pubkey_der
  693. needs a non-const key, for now.
  694. https://github.com/ARMmbed/mbedtls/issues/396 */
  695. #if MBEDTLS_VERSION_NUMBER == 0x03000000
  696. if(mbedtls_x509_crt_parse_der(p,
  697. peercert->MBEDTLS_PRIVATE(raw).MBEDTLS_PRIVATE(p),
  698. peercert->MBEDTLS_PRIVATE(raw).MBEDTLS_PRIVATE(len))) {
  699. #else
  700. if(mbedtls_x509_crt_parse_der(p, peercert->raw.p, peercert->raw.len)) {
  701. #endif
  702. failf(data, "Failed copying peer certificate");
  703. result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
  704. goto pinnedpubkey_error;
  705. }
  706. #if MBEDTLS_VERSION_NUMBER == 0x03000000
  707. size = mbedtls_pk_write_pubkey_der(&p->MBEDTLS_PRIVATE(pk), pubkey,
  708. PUB_DER_MAX_BYTES);
  709. #else
  710. size = mbedtls_pk_write_pubkey_der(&p->pk, pubkey, PUB_DER_MAX_BYTES);
  711. #endif
  712. if(size <= 0) {
  713. failf(data, "Failed copying public key from peer certificate");
  714. result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
  715. goto pinnedpubkey_error;
  716. }
  717. /* mbedtls_pk_write_pubkey_der writes data at the end of the buffer. */
  718. result = Curl_pin_peer_pubkey(data,
  719. pinnedpubkey,
  720. &pubkey[PUB_DER_MAX_BYTES - size], size);
  721. pinnedpubkey_error:
  722. mbedtls_x509_crt_free(p);
  723. free(p);
  724. free(pubkey);
  725. if(result) {
  726. return result;
  727. }
  728. }
  729. #ifdef HAS_ALPN
  730. if(cf->conn->bits.tls_enable_alpn) {
  731. const char *next_protocol = mbedtls_ssl_get_alpn_protocol(&backend->ssl);
  732. if(next_protocol) {
  733. infof(data, VTLS_INFOF_ALPN_ACCEPTED_1STR, next_protocol);
  734. #ifdef USE_HTTP2
  735. if(!strncmp(next_protocol, ALPN_H2, ALPN_H2_LENGTH) &&
  736. !next_protocol[ALPN_H2_LENGTH]) {
  737. cf->conn->alpn = CURL_HTTP_VERSION_2;
  738. }
  739. else
  740. #endif
  741. if(!strncmp(next_protocol, ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH) &&
  742. !next_protocol[ALPN_HTTP_1_1_LENGTH]) {
  743. cf->conn->alpn = CURL_HTTP_VERSION_1_1;
  744. }
  745. }
  746. else {
  747. infof(data, VTLS_INFOF_NO_ALPN);
  748. }
  749. Curl_multiuse_state(data, cf->conn->alpn == CURL_HTTP_VERSION_2 ?
  750. BUNDLE_MULTIPLEX : BUNDLE_NO_MULTIUSE);
  751. }
  752. #endif
  753. connssl->connecting_state = ssl_connect_3;
  754. infof(data, "SSL connected");
  755. return CURLE_OK;
  756. }
  757. static CURLcode
  758. mbed_connect_step3(struct Curl_cfilter *cf, struct Curl_easy *data)
  759. {
  760. CURLcode retcode = CURLE_OK;
  761. struct ssl_connect_data *connssl = cf->ctx;
  762. struct ssl_backend_data *backend = connssl->backend;
  763. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  764. DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
  765. DEBUGASSERT(backend);
  766. if(ssl_config->primary.sessionid) {
  767. int ret;
  768. mbedtls_ssl_session *our_ssl_sessionid;
  769. void *old_ssl_sessionid = NULL;
  770. bool added = FALSE;
  771. our_ssl_sessionid = malloc(sizeof(mbedtls_ssl_session));
  772. if(!our_ssl_sessionid)
  773. return CURLE_OUT_OF_MEMORY;
  774. mbedtls_ssl_session_init(our_ssl_sessionid);
  775. ret = mbedtls_ssl_get_session(&backend->ssl, our_ssl_sessionid);
  776. if(ret) {
  777. if(ret != MBEDTLS_ERR_SSL_ALLOC_FAILED)
  778. mbedtls_ssl_session_free(our_ssl_sessionid);
  779. free(our_ssl_sessionid);
  780. failf(data, "mbedtls_ssl_get_session returned -0x%x", -ret);
  781. return CURLE_SSL_CONNECT_ERROR;
  782. }
  783. /* If there's already a matching session in the cache, delete it */
  784. Curl_ssl_sessionid_lock(data);
  785. if(!Curl_ssl_getsessionid(cf, data, &old_ssl_sessionid, NULL))
  786. Curl_ssl_delsessionid(data, old_ssl_sessionid);
  787. retcode = Curl_ssl_addsessionid(cf, data, our_ssl_sessionid,
  788. 0, &added);
  789. Curl_ssl_sessionid_unlock(data);
  790. if(!added) {
  791. mbedtls_ssl_session_free(our_ssl_sessionid);
  792. free(our_ssl_sessionid);
  793. }
  794. if(retcode) {
  795. failf(data, "failed to store ssl session");
  796. return retcode;
  797. }
  798. }
  799. connssl->connecting_state = ssl_connect_done;
  800. return CURLE_OK;
  801. }
  802. static ssize_t mbed_send(struct Curl_cfilter *cf, struct Curl_easy *data,
  803. const void *mem, size_t len,
  804. CURLcode *curlcode)
  805. {
  806. struct ssl_connect_data *connssl = cf->ctx;
  807. struct ssl_backend_data *backend = connssl->backend;
  808. int ret = -1;
  809. (void)data;
  810. DEBUGASSERT(backend);
  811. ret = mbedtls_ssl_write(&backend->ssl, (unsigned char *)mem, len);
  812. if(ret < 0) {
  813. *curlcode = (ret == MBEDTLS_ERR_SSL_WANT_WRITE) ?
  814. CURLE_AGAIN : CURLE_SEND_ERROR;
  815. ret = -1;
  816. }
  817. return ret;
  818. }
  819. static void mbedtls_close_all(struct Curl_easy *data)
  820. {
  821. (void)data;
  822. }
  823. static void mbedtls_close(struct Curl_cfilter *cf, struct Curl_easy *data)
  824. {
  825. struct ssl_connect_data *connssl = cf->ctx;
  826. struct ssl_backend_data *backend = connssl->backend;
  827. char buf[32];
  828. (void)data;
  829. DEBUGASSERT(backend);
  830. /* Maybe the server has already sent a close notify alert.
  831. Read it to avoid an RST on the TCP connection. */
  832. (void)mbedtls_ssl_read(&backend->ssl, (unsigned char *)buf, sizeof(buf));
  833. mbedtls_pk_free(&backend->pk);
  834. mbedtls_x509_crt_free(&backend->clicert);
  835. mbedtls_x509_crt_free(&backend->cacert);
  836. #ifdef MBEDTLS_X509_CRL_PARSE_C
  837. mbedtls_x509_crl_free(&backend->crl);
  838. #endif
  839. mbedtls_ssl_config_free(&backend->config);
  840. mbedtls_ssl_free(&backend->ssl);
  841. mbedtls_ctr_drbg_free(&backend->ctr_drbg);
  842. #ifndef THREADING_SUPPORT
  843. mbedtls_entropy_free(&backend->entropy);
  844. #endif /* THREADING_SUPPORT */
  845. }
  846. static ssize_t mbed_recv(struct Curl_cfilter *cf, struct Curl_easy *data,
  847. char *buf, size_t buffersize,
  848. CURLcode *curlcode)
  849. {
  850. struct ssl_connect_data *connssl = cf->ctx;
  851. struct ssl_backend_data *backend = connssl->backend;
  852. int ret = -1;
  853. ssize_t len = -1;
  854. (void)data;
  855. DEBUGASSERT(backend);
  856. ret = mbedtls_ssl_read(&backend->ssl, (unsigned char *)buf,
  857. buffersize);
  858. if(ret <= 0) {
  859. if(ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY)
  860. return 0;
  861. *curlcode = (ret == MBEDTLS_ERR_SSL_WANT_READ) ?
  862. CURLE_AGAIN : CURLE_RECV_ERROR;
  863. return -1;
  864. }
  865. len = ret;
  866. return len;
  867. }
  868. static void mbedtls_session_free(void *ptr)
  869. {
  870. mbedtls_ssl_session_free(ptr);
  871. free(ptr);
  872. }
  873. static size_t mbedtls_version(char *buffer, size_t size)
  874. {
  875. #ifdef MBEDTLS_VERSION_C
  876. /* if mbedtls_version_get_number() is available it is better */
  877. unsigned int version = mbedtls_version_get_number();
  878. return msnprintf(buffer, size, "mbedTLS/%u.%u.%u", version>>24,
  879. (version>>16)&0xff, (version>>8)&0xff);
  880. #else
  881. return msnprintf(buffer, size, "mbedTLS/%s", MBEDTLS_VERSION_STRING);
  882. #endif
  883. }
  884. static CURLcode mbedtls_random(struct Curl_easy *data,
  885. unsigned char *entropy, size_t length)
  886. {
  887. #if defined(MBEDTLS_CTR_DRBG_C)
  888. int ret = -1;
  889. char errorbuf[128];
  890. mbedtls_entropy_context ctr_entropy;
  891. mbedtls_ctr_drbg_context ctr_drbg;
  892. mbedtls_entropy_init(&ctr_entropy);
  893. mbedtls_ctr_drbg_init(&ctr_drbg);
  894. ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func,
  895. &ctr_entropy, NULL, 0);
  896. if(ret) {
  897. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  898. failf(data, "mbedtls_ctr_drbg_seed returned (-0x%04X) %s",
  899. -ret, errorbuf);
  900. }
  901. else {
  902. ret = mbedtls_ctr_drbg_random(&ctr_drbg, entropy, length);
  903. if(ret) {
  904. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  905. failf(data, "mbedtls_ctr_drbg_random returned (-0x%04X) %s",
  906. -ret, errorbuf);
  907. }
  908. }
  909. mbedtls_ctr_drbg_free(&ctr_drbg);
  910. mbedtls_entropy_free(&ctr_entropy);
  911. return ret == 0 ? CURLE_OK : CURLE_FAILED_INIT;
  912. #elif defined(MBEDTLS_HAVEGE_C)
  913. mbedtls_havege_state hs;
  914. mbedtls_havege_init(&hs);
  915. mbedtls_havege_random(&hs, entropy, length);
  916. mbedtls_havege_free(&hs);
  917. return CURLE_OK;
  918. #else
  919. return CURLE_NOT_BUILT_IN;
  920. #endif
  921. }
  922. static CURLcode
  923. mbed_connect_common(struct Curl_cfilter *cf, struct Curl_easy *data,
  924. bool nonblocking,
  925. bool *done)
  926. {
  927. CURLcode retcode;
  928. struct ssl_connect_data *connssl = cf->ctx;
  929. curl_socket_t sockfd = cf->conn->sock[cf->sockindex];
  930. timediff_t timeout_ms;
  931. int what;
  932. /* check if the connection has already been established */
  933. if(ssl_connection_complete == connssl->state) {
  934. *done = TRUE;
  935. return CURLE_OK;
  936. }
  937. if(ssl_connect_1 == connssl->connecting_state) {
  938. /* Find out how much more time we're allowed */
  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. retcode = mbed_connect_step1(cf, data);
  946. if(retcode)
  947. return retcode;
  948. }
  949. while(ssl_connect_2 == connssl->connecting_state ||
  950. ssl_connect_2_reading == connssl->connecting_state ||
  951. ssl_connect_2_writing == connssl->connecting_state) {
  952. /* check allowed time left */
  953. timeout_ms = Curl_timeleft(data, NULL, TRUE);
  954. if(timeout_ms < 0) {
  955. /* no need to continue if time already is up */
  956. failf(data, "SSL connection timeout");
  957. return CURLE_OPERATION_TIMEDOUT;
  958. }
  959. /* if ssl is expecting something, check if it's available. */
  960. if(connssl->connecting_state == ssl_connect_2_reading
  961. || connssl->connecting_state == ssl_connect_2_writing) {
  962. curl_socket_t writefd = ssl_connect_2_writing ==
  963. connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
  964. curl_socket_t readfd = ssl_connect_2_reading ==
  965. connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
  966. what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
  967. nonblocking ? 0 : timeout_ms);
  968. if(what < 0) {
  969. /* fatal error */
  970. failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
  971. return CURLE_SSL_CONNECT_ERROR;
  972. }
  973. else if(0 == what) {
  974. if(nonblocking) {
  975. *done = FALSE;
  976. return CURLE_OK;
  977. }
  978. else {
  979. /* timeout */
  980. failf(data, "SSL connection timeout");
  981. return CURLE_OPERATION_TIMEDOUT;
  982. }
  983. }
  984. /* socket is readable or writable */
  985. }
  986. /* Run transaction, and return to the caller if it failed or if
  987. * this connection is part of a multi handle and this loop would
  988. * execute again. This permits the owner of a multi handle to
  989. * abort a connection attempt before step2 has completed while
  990. * ensuring that a client using select() or epoll() will always
  991. * have a valid fdset to wait on.
  992. */
  993. retcode = mbed_connect_step2(cf, data);
  994. if(retcode || (nonblocking &&
  995. (ssl_connect_2 == connssl->connecting_state ||
  996. ssl_connect_2_reading == connssl->connecting_state ||
  997. ssl_connect_2_writing == connssl->connecting_state)))
  998. return retcode;
  999. } /* repeat step2 until all transactions are done. */
  1000. if(ssl_connect_3 == connssl->connecting_state) {
  1001. retcode = mbed_connect_step3(cf, data);
  1002. if(retcode)
  1003. return retcode;
  1004. }
  1005. if(ssl_connect_done == connssl->connecting_state) {
  1006. connssl->state = ssl_connection_complete;
  1007. *done = TRUE;
  1008. }
  1009. else
  1010. *done = FALSE;
  1011. /* Reset our connect state machine */
  1012. connssl->connecting_state = ssl_connect_1;
  1013. return CURLE_OK;
  1014. }
  1015. static CURLcode mbedtls_connect_nonblocking(struct Curl_cfilter *cf,
  1016. struct Curl_easy *data,
  1017. bool *done)
  1018. {
  1019. return mbed_connect_common(cf, data, TRUE, done);
  1020. }
  1021. static CURLcode mbedtls_connect(struct Curl_cfilter *cf,
  1022. struct Curl_easy *data)
  1023. {
  1024. CURLcode retcode;
  1025. bool done = FALSE;
  1026. retcode = mbed_connect_common(cf, data, FALSE, &done);
  1027. if(retcode)
  1028. return retcode;
  1029. DEBUGASSERT(done);
  1030. return CURLE_OK;
  1031. }
  1032. /*
  1033. * return 0 error initializing SSL
  1034. * return 1 SSL initialized successfully
  1035. */
  1036. static int mbedtls_init(void)
  1037. {
  1038. return Curl_mbedtlsthreadlock_thread_setup();
  1039. }
  1040. static void mbedtls_cleanup(void)
  1041. {
  1042. (void)Curl_mbedtlsthreadlock_thread_cleanup();
  1043. }
  1044. static bool mbedtls_data_pending(struct Curl_cfilter *cf,
  1045. const struct Curl_easy *data)
  1046. {
  1047. struct ssl_connect_data *ctx = cf->ctx;
  1048. (void)data;
  1049. DEBUGASSERT(ctx && ctx->backend);
  1050. return mbedtls_ssl_get_bytes_avail(&ctx->backend->ssl) != 0;
  1051. }
  1052. static CURLcode mbedtls_sha256sum(const unsigned char *input,
  1053. size_t inputlen,
  1054. unsigned char *sha256sum,
  1055. size_t sha256len UNUSED_PARAM)
  1056. {
  1057. /* TODO: explain this for different mbedtls 2.x vs 3 version */
  1058. (void)sha256len;
  1059. #if MBEDTLS_VERSION_NUMBER < 0x02070000
  1060. mbedtls_sha256(input, inputlen, sha256sum, 0);
  1061. #else
  1062. /* returns 0 on success, otherwise failure */
  1063. #if MBEDTLS_VERSION_NUMBER >= 0x03000000
  1064. if(mbedtls_sha256(input, inputlen, sha256sum, 0) != 0)
  1065. #else
  1066. if(mbedtls_sha256_ret(input, inputlen, sha256sum, 0) != 0)
  1067. #endif
  1068. return CURLE_BAD_FUNCTION_ARGUMENT;
  1069. #endif
  1070. return CURLE_OK;
  1071. }
  1072. static void *mbedtls_get_internals(struct ssl_connect_data *connssl,
  1073. CURLINFO info UNUSED_PARAM)
  1074. {
  1075. struct ssl_backend_data *backend = connssl->backend;
  1076. (void)info;
  1077. DEBUGASSERT(backend);
  1078. return &backend->ssl;
  1079. }
  1080. const struct Curl_ssl Curl_ssl_mbedtls = {
  1081. { CURLSSLBACKEND_MBEDTLS, "mbedtls" }, /* info */
  1082. SSLSUPP_CA_PATH |
  1083. SSLSUPP_CAINFO_BLOB |
  1084. SSLSUPP_PINNEDPUBKEY |
  1085. SSLSUPP_SSL_CTX |
  1086. SSLSUPP_HTTPS_PROXY,
  1087. sizeof(struct ssl_backend_data),
  1088. mbedtls_init, /* init */
  1089. mbedtls_cleanup, /* cleanup */
  1090. mbedtls_version, /* version */
  1091. Curl_none_check_cxn, /* check_cxn */
  1092. Curl_none_shutdown, /* shutdown */
  1093. mbedtls_data_pending, /* data_pending */
  1094. mbedtls_random, /* random */
  1095. Curl_none_cert_status_request, /* cert_status_request */
  1096. mbedtls_connect, /* connect */
  1097. mbedtls_connect_nonblocking, /* connect_nonblocking */
  1098. Curl_ssl_get_select_socks, /* getsock */
  1099. mbedtls_get_internals, /* get_internals */
  1100. mbedtls_close, /* close_one */
  1101. mbedtls_close_all, /* close_all */
  1102. mbedtls_session_free, /* session_free */
  1103. Curl_none_set_engine, /* set_engine */
  1104. Curl_none_set_engine_default, /* set_engine_default */
  1105. Curl_none_engines_list, /* engines_list */
  1106. Curl_none_false_start, /* false_start */
  1107. mbedtls_sha256sum, /* sha256sum */
  1108. NULL, /* associate_connection */
  1109. NULL, /* disassociate_connection */
  1110. NULL, /* free_multi_ssl_backend_data */
  1111. mbed_recv, /* recv decrypted data */
  1112. mbed_send, /* send data to encrypt */
  1113. };
  1114. #endif /* USE_MBEDTLS */