wolfssl.c 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at https://curl.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. * SPDX-License-Identifier: curl
  22. *
  23. ***************************************************************************/
  24. /*
  25. * Source file for all wolfSSL specific code for the TLS/SSL layer. No code
  26. * but vtls.c should ever call or use these functions.
  27. *
  28. */
  29. #include "curl_setup.h"
  30. #ifdef USE_WOLFSSL
  31. #define WOLFSSL_OPTIONS_IGNORE_SYS
  32. #include <wolfssl/version.h>
  33. #include <wolfssl/options.h>
  34. #if LIBWOLFSSL_VERSION_HEX < 0x03004006 /* wolfSSL 3.4.6 (2015) */
  35. #error "wolfSSL version should be at least 3.4.6"
  36. #endif
  37. /* To determine what functions are available we rely on one or both of:
  38. - the user's options.h generated by wolfSSL
  39. - the symbols detected by curl's configure
  40. Since they are markedly different from one another, and one or the other may
  41. not be available, we do some checking below to bring things in sync. */
  42. /* HAVE_ALPN is wolfSSL's build time symbol for enabling ALPN in options.h. */
  43. #ifndef HAVE_ALPN
  44. #ifdef HAVE_WOLFSSL_USEALPN
  45. #define HAVE_ALPN
  46. #endif
  47. #endif
  48. #include <limits.h>
  49. #include "urldata.h"
  50. #include "sendf.h"
  51. #include "inet_pton.h"
  52. #include "vtls.h"
  53. #include "vtls_int.h"
  54. #include "keylog.h"
  55. #include "parsedate.h"
  56. #include "connect.h" /* for the connect timeout */
  57. #include "select.h"
  58. #include "strcase.h"
  59. #include "x509asn1.h"
  60. #include "curl_printf.h"
  61. #include "multiif.h"
  62. #include <wolfssl/openssl/ssl.h>
  63. #include <wolfssl/ssl.h>
  64. #include <wolfssl/error-ssl.h>
  65. #include "wolfssl.h"
  66. /* The last #include files should be: */
  67. #include "curl_memory.h"
  68. #include "memdebug.h"
  69. #ifdef USE_ECH
  70. # include "curl_base64.h"
  71. # define ECH_ENABLED(__data__) \
  72. (__data__->set.tls_ech && \
  73. !(__data__->set.tls_ech & CURLECH_DISABLE)\
  74. )
  75. #endif /* USE_ECH */
  76. /* KEEP_PEER_CERT is a product of the presence of build time symbol
  77. OPENSSL_EXTRA without NO_CERTS, depending on the version. KEEP_PEER_CERT is
  78. in wolfSSL's settings.h, and the latter two are build time symbols in
  79. options.h. */
  80. #ifndef KEEP_PEER_CERT
  81. #if defined(HAVE_WOLFSSL_GET_PEER_CERTIFICATE) || \
  82. (defined(OPENSSL_EXTRA) && !defined(NO_CERTS))
  83. #define KEEP_PEER_CERT
  84. #endif
  85. #endif
  86. #ifdef HAVE_WOLFSSL_BIO
  87. #define USE_BIO_CHAIN
  88. #ifdef HAVE_WOLFSSL_FULL_BIO
  89. #define USE_FULL_BIO
  90. #else /* HAVE_WOLFSSL_FULL_BIO */
  91. #undef USE_FULL_BIO
  92. #endif
  93. /* wolfSSL 5.7.4 and older do not have these symbols, but only the
  94. * OpenSSL ones. */
  95. #ifndef WOLFSSL_BIO_CTRL_GET_CLOSE
  96. #define WOLFSSL_BIO_CTRL_GET_CLOSE BIO_CTRL_GET_CLOSE
  97. #define WOLFSSL_BIO_CTRL_SET_CLOSE BIO_CTRL_SET_CLOSE
  98. #define WOLFSSL_BIO_CTRL_FLUSH BIO_CTRL_FLUSH
  99. #define WOLFSSL_BIO_CTRL_DUP BIO_CTRL_DUP
  100. #define wolfSSL_BIO_set_retry_write BIO_set_retry_write
  101. #define wolfSSL_BIO_set_retry_read BIO_set_retry_read
  102. #endif /* !WOLFSSL_BIO_CTRL_GET_CLOSE */
  103. #else /* HAVE_WOLFSSL_BIO */
  104. #undef USE_BIO_CHAIN
  105. #endif
  106. #ifdef OPENSSL_EXTRA
  107. /*
  108. * Availability note:
  109. * The TLS 1.3 secret callback (wolfSSL_set_tls13_secret_cb) was added in
  110. * wolfSSL 4.4.0, but requires the -DHAVE_SECRET_CALLBACK build option. If that
  111. * option is not set, then TLS 1.3 will not be logged.
  112. * For TLS 1.2 and before, we use wolfSSL_get_keys().
  113. * SSL_get_client_random and wolfSSL_get_keys require OPENSSL_EXTRA
  114. * (--enable-opensslextra or --enable-all).
  115. */
  116. #if defined(HAVE_SECRET_CALLBACK) && defined(WOLFSSL_TLS13)
  117. static int
  118. wolfssl_tls13_secret_callback(SSL *ssl, int id, const unsigned char *secret,
  119. int secretSz, void *ctx)
  120. {
  121. const char *label;
  122. unsigned char client_random[SSL3_RANDOM_SIZE];
  123. (void)ctx;
  124. if(!ssl || !Curl_tls_keylog_enabled()) {
  125. return 0;
  126. }
  127. switch(id) {
  128. case CLIENT_EARLY_TRAFFIC_SECRET:
  129. label = "CLIENT_EARLY_TRAFFIC_SECRET";
  130. break;
  131. case CLIENT_HANDSHAKE_TRAFFIC_SECRET:
  132. label = "CLIENT_HANDSHAKE_TRAFFIC_SECRET";
  133. break;
  134. case SERVER_HANDSHAKE_TRAFFIC_SECRET:
  135. label = "SERVER_HANDSHAKE_TRAFFIC_SECRET";
  136. break;
  137. case CLIENT_TRAFFIC_SECRET:
  138. label = "CLIENT_TRAFFIC_SECRET_0";
  139. break;
  140. case SERVER_TRAFFIC_SECRET:
  141. label = "SERVER_TRAFFIC_SECRET_0";
  142. break;
  143. case EARLY_EXPORTER_SECRET:
  144. label = "EARLY_EXPORTER_SECRET";
  145. break;
  146. case EXPORTER_SECRET:
  147. label = "EXPORTER_SECRET";
  148. break;
  149. default:
  150. return 0;
  151. }
  152. if(SSL_get_client_random(ssl, client_random, SSL3_RANDOM_SIZE) == 0) {
  153. /* Should never happen as wolfSSL_KeepArrays() was called before. */
  154. return 0;
  155. }
  156. Curl_tls_keylog_write(label, client_random, secret, secretSz);
  157. return 0;
  158. }
  159. #endif /* defined(HAVE_SECRET_CALLBACK) && defined(WOLFSSL_TLS13) */
  160. static void
  161. wolfssl_log_tls12_secret(WOLFSSL *ssl)
  162. {
  163. unsigned char *ms, *sr, *cr;
  164. unsigned int msLen, srLen, crLen, i, x = 0;
  165. #if LIBWOLFSSL_VERSION_HEX >= 0x0300d000 /* >= 3.13.0 */
  166. /* wolfSSL_GetVersion is available since 3.13, we use it instead of
  167. * SSL_version since the latter relies on OPENSSL_ALL (--enable-opensslall or
  168. * --enable-all). Failing to perform this check could result in an unusable
  169. * key log line when TLS 1.3 is actually negotiated. */
  170. switch(wolfSSL_GetVersion(ssl)) {
  171. case WOLFSSL_SSLV3:
  172. case WOLFSSL_TLSV1:
  173. case WOLFSSL_TLSV1_1:
  174. case WOLFSSL_TLSV1_2:
  175. break;
  176. default:
  177. /* TLS 1.3 does not use this mechanism, the "master secret" returned below
  178. * is not directly usable. */
  179. return;
  180. }
  181. #endif
  182. if(wolfSSL_get_keys(ssl, &ms, &msLen, &sr, &srLen, &cr, &crLen) !=
  183. WOLFSSL_SUCCESS) {
  184. return;
  185. }
  186. /* Check for a missing master secret and skip logging. That can happen if
  187. * curl rejects the server certificate and aborts the handshake.
  188. */
  189. for(i = 0; i < msLen; i++) {
  190. x |= ms[i];
  191. }
  192. if(x == 0) {
  193. return;
  194. }
  195. Curl_tls_keylog_write("CLIENT_RANDOM", cr, ms, msLen);
  196. }
  197. #endif /* OPENSSL_EXTRA */
  198. static int wolfssl_do_file_type(const char *type)
  199. {
  200. if(!type || !type[0])
  201. return WOLFSSL_FILETYPE_PEM;
  202. if(strcasecompare(type, "PEM"))
  203. return WOLFSSL_FILETYPE_PEM;
  204. if(strcasecompare(type, "DER"))
  205. return WOLFSSL_FILETYPE_ASN1;
  206. return -1;
  207. }
  208. #ifdef WOLFSSL_HAVE_KYBER
  209. struct group_name_map {
  210. const word16 group;
  211. const char *name;
  212. };
  213. static const struct group_name_map gnm[] = {
  214. { WOLFSSL_KYBER_LEVEL1, "KYBER_LEVEL1" },
  215. { WOLFSSL_KYBER_LEVEL3, "KYBER_LEVEL3" },
  216. { WOLFSSL_KYBER_LEVEL5, "KYBER_LEVEL5" },
  217. { WOLFSSL_P256_KYBER_LEVEL1, "P256_KYBER_LEVEL1" },
  218. { WOLFSSL_P384_KYBER_LEVEL3, "P384_KYBER_LEVEL3" },
  219. { WOLFSSL_P521_KYBER_LEVEL5, "P521_KYBER_LEVEL5" },
  220. { 0, NULL }
  221. };
  222. #endif
  223. #ifdef USE_BIO_CHAIN
  224. static int wolfssl_bio_cf_create(WOLFSSL_BIO *bio)
  225. {
  226. #ifdef USE_FULL_BIO
  227. wolfSSL_BIO_set_shutdown(bio, 1);
  228. #endif
  229. wolfSSL_BIO_set_data(bio, NULL);
  230. return 1;
  231. }
  232. static int wolfssl_bio_cf_destroy(WOLFSSL_BIO *bio)
  233. {
  234. if(!bio)
  235. return 0;
  236. return 1;
  237. }
  238. static long wolfssl_bio_cf_ctrl(WOLFSSL_BIO *bio, int cmd, long num, void *ptr)
  239. {
  240. struct Curl_cfilter *cf = wolfSSL_BIO_get_data(bio);
  241. long ret = 1;
  242. (void)cf;
  243. (void)ptr;
  244. (void)num;
  245. switch(cmd) {
  246. case WOLFSSL_BIO_CTRL_GET_CLOSE:
  247. #ifdef USE_FULL_BIO
  248. ret = (long)wolfSSL_BIO_get_shutdown(bio);
  249. #else
  250. ret = 0;
  251. #endif
  252. break;
  253. case WOLFSSL_BIO_CTRL_SET_CLOSE:
  254. #ifdef USE_FULL_BIO
  255. wolfSSL_BIO_set_shutdown(bio, (int)num);
  256. #endif
  257. break;
  258. case WOLFSSL_BIO_CTRL_FLUSH:
  259. /* we do no delayed writes, but if we ever would, this
  260. * needs to trigger it. */
  261. ret = 1;
  262. break;
  263. case WOLFSSL_BIO_CTRL_DUP:
  264. ret = 1;
  265. break;
  266. #ifdef WOLFSSL_BIO_CTRL_EOF
  267. case WOLFSSL_BIO_CTRL_EOF:
  268. /* EOF has been reached on input? */
  269. return (!cf->next || !cf->next->connected);
  270. #endif
  271. default:
  272. ret = 0;
  273. break;
  274. }
  275. return ret;
  276. }
  277. static int wolfssl_bio_cf_out_write(WOLFSSL_BIO *bio,
  278. const char *buf, int blen)
  279. {
  280. struct Curl_cfilter *cf = wolfSSL_BIO_get_data(bio);
  281. struct ssl_connect_data *connssl = cf->ctx;
  282. struct wolfssl_ctx *backend =
  283. (struct wolfssl_ctx *)connssl->backend;
  284. struct Curl_easy *data = CF_DATA_CURRENT(cf);
  285. ssize_t nwritten, skiplen = 0;
  286. CURLcode result = CURLE_OK;
  287. DEBUGASSERT(data);
  288. if(backend->shutting_down && backend->io_send_blocked_len &&
  289. (backend->io_send_blocked_len < blen)) {
  290. /* bug in wolfSSL: <https://github.com/wolfSSL/wolfssl/issues/7784>
  291. * It adds the close notify message again every time we retry
  292. * sending during shutdown. */
  293. CURL_TRC_CF(data, cf, "bio_write, shutdown restrict send of %d"
  294. " to %d bytes", blen, backend->io_send_blocked_len);
  295. skiplen = (ssize_t)(blen - backend->io_send_blocked_len);
  296. blen = backend->io_send_blocked_len;
  297. }
  298. nwritten = Curl_conn_cf_send(cf->next, data, buf, blen, FALSE, &result);
  299. backend->io_result = result;
  300. CURL_TRC_CF(data, cf, "bio_write(len=%d) -> %zd, %d",
  301. blen, nwritten, result);
  302. #ifdef USE_FULL_BIO
  303. wolfSSL_BIO_clear_retry_flags(bio);
  304. #endif
  305. if(nwritten < 0 && CURLE_AGAIN == result) {
  306. wolfSSL_BIO_set_retry_write(bio);
  307. if(backend->shutting_down && !backend->io_send_blocked_len)
  308. backend->io_send_blocked_len = blen;
  309. }
  310. else if(!result && skiplen)
  311. nwritten += skiplen;
  312. return (int)nwritten;
  313. }
  314. static int wolfssl_bio_cf_in_read(WOLFSSL_BIO *bio, char *buf, int blen)
  315. {
  316. struct Curl_cfilter *cf = wolfSSL_BIO_get_data(bio);
  317. struct ssl_connect_data *connssl = cf->ctx;
  318. struct wolfssl_ctx *backend =
  319. (struct wolfssl_ctx *)connssl->backend;
  320. struct Curl_easy *data = CF_DATA_CURRENT(cf);
  321. ssize_t nread;
  322. CURLcode result = CURLE_OK;
  323. DEBUGASSERT(data);
  324. /* OpenSSL catches this case, so should we. */
  325. if(!buf)
  326. return 0;
  327. nread = Curl_conn_cf_recv(cf->next, data, buf, blen, &result);
  328. backend->io_result = result;
  329. CURL_TRC_CF(data, cf, "bio_read(len=%d) -> %zd, %d", blen, nread, result);
  330. #ifdef USE_FULL_BIO
  331. wolfSSL_BIO_clear_retry_flags(bio);
  332. #endif
  333. if(nread < 0 && CURLE_AGAIN == result)
  334. wolfSSL_BIO_set_retry_read(bio);
  335. else if(nread == 0)
  336. connssl->peer_closed = TRUE;
  337. return (int)nread;
  338. }
  339. static WOLFSSL_BIO_METHOD *wolfssl_bio_cf_method = NULL;
  340. static void wolfssl_bio_cf_init_methods(void)
  341. {
  342. wolfssl_bio_cf_method = wolfSSL_BIO_meth_new(WOLFSSL_BIO_MEMORY,
  343. "wolfSSL CF BIO");
  344. wolfSSL_BIO_meth_set_write(wolfssl_bio_cf_method, &wolfssl_bio_cf_out_write);
  345. wolfSSL_BIO_meth_set_read(wolfssl_bio_cf_method, &wolfssl_bio_cf_in_read);
  346. wolfSSL_BIO_meth_set_ctrl(wolfssl_bio_cf_method, &wolfssl_bio_cf_ctrl);
  347. wolfSSL_BIO_meth_set_create(wolfssl_bio_cf_method, &wolfssl_bio_cf_create);
  348. wolfSSL_BIO_meth_set_destroy(wolfssl_bio_cf_method, &wolfssl_bio_cf_destroy);
  349. }
  350. static void wolfssl_bio_cf_free_methods(void)
  351. {
  352. wolfSSL_BIO_meth_free(wolfssl_bio_cf_method);
  353. }
  354. #else /* USE_BIO_CHAIN */
  355. #define wolfssl_bio_cf_init_methods() Curl_nop_stmt
  356. #define wolfssl_bio_cf_free_methods() Curl_nop_stmt
  357. #endif /* !USE_BIO_CHAIN */
  358. static void wolfssl_session_free(void *sdata, size_t slen)
  359. {
  360. (void)slen;
  361. free(sdata);
  362. }
  363. CURLcode wssl_cache_session(struct Curl_cfilter *cf,
  364. struct Curl_easy *data,
  365. struct ssl_peer *peer,
  366. WOLFSSL_SESSION *session)
  367. {
  368. CURLcode result = CURLE_OK;
  369. unsigned char *sdata = NULL;
  370. unsigned int slen;
  371. if(!session)
  372. goto out;
  373. slen = wolfSSL_i2d_SSL_SESSION(session, NULL);
  374. if(slen <= 0) {
  375. CURL_TRC_CF(data, cf, "fail to assess session length: %u", slen);
  376. result = CURLE_FAILED_INIT;
  377. goto out;
  378. }
  379. sdata = calloc(1, slen);
  380. if(!sdata) {
  381. failf(data, "unable to allocate session buffer of %u bytes", slen);
  382. result = CURLE_OUT_OF_MEMORY;
  383. goto out;
  384. }
  385. slen = wolfSSL_i2d_SSL_SESSION(session, &sdata);
  386. if(slen <= 0) {
  387. CURL_TRC_CF(data, cf, "fail to serialize session: %u", slen);
  388. result = CURLE_FAILED_INIT;
  389. goto out;
  390. }
  391. Curl_ssl_sessionid_lock(data);
  392. result = Curl_ssl_set_sessionid(cf, data, peer, NULL,
  393. sdata, slen, wolfssl_session_free);
  394. Curl_ssl_sessionid_unlock(data);
  395. if(result)
  396. failf(data, "failed to add new ssl session to cache (%d)", result);
  397. else {
  398. CURL_TRC_CF(data, cf, "added new session to cache");
  399. sdata = NULL;
  400. }
  401. out:
  402. free(sdata);
  403. return 0;
  404. }
  405. static int wssl_vtls_new_session_cb(WOLFSSL *ssl, WOLFSSL_SESSION *session)
  406. {
  407. struct Curl_cfilter *cf;
  408. cf = (struct Curl_cfilter*)wolfSSL_get_app_data(ssl);
  409. DEBUGASSERT(cf != NULL);
  410. if(cf && session) {
  411. struct ssl_connect_data *connssl = cf->ctx;
  412. struct Curl_easy *data = CF_DATA_CURRENT(cf);
  413. DEBUGASSERT(connssl);
  414. DEBUGASSERT(data);
  415. if(connssl && data) {
  416. (void)wssl_cache_session(cf, data, &connssl->peer, session);
  417. }
  418. }
  419. return 0;
  420. }
  421. CURLcode wssl_setup_session(struct Curl_cfilter *cf,
  422. struct Curl_easy *data,
  423. struct wolfssl_ctx *wss,
  424. struct ssl_peer *peer)
  425. {
  426. void *psdata;
  427. const unsigned char *sdata = NULL;
  428. size_t slen = 0;
  429. CURLcode result = CURLE_OK;
  430. Curl_ssl_sessionid_lock(data);
  431. if(!Curl_ssl_getsessionid(cf, data, peer, &psdata, &slen, NULL)) {
  432. WOLFSSL_SESSION *session;
  433. sdata = psdata;
  434. session = wolfSSL_d2i_SSL_SESSION(NULL, &sdata, (long)slen);
  435. if(session) {
  436. int ret = wolfSSL_set_session(wss->handle, session);
  437. if(ret != WOLFSSL_SUCCESS) {
  438. Curl_ssl_delsessionid(data, psdata);
  439. infof(data, "previous session not accepted (%d), "
  440. "removing from cache", ret);
  441. }
  442. else
  443. infof(data, "SSL reusing session ID");
  444. wolfSSL_SESSION_free(session);
  445. }
  446. else {
  447. failf(data, "could not decode previous session");
  448. }
  449. }
  450. Curl_ssl_sessionid_unlock(data);
  451. return result;
  452. }
  453. static CURLcode populate_x509_store(struct Curl_cfilter *cf,
  454. struct Curl_easy *data,
  455. WOLFSSL_X509_STORE *store,
  456. struct wolfssl_ctx *wssl)
  457. {
  458. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  459. const struct curl_blob *ca_info_blob = conn_config->ca_info_blob;
  460. const char * const ssl_cafile =
  461. /* CURLOPT_CAINFO_BLOB overrides CURLOPT_CAINFO */
  462. (ca_info_blob ? NULL : conn_config->CAfile);
  463. const char * const ssl_capath = conn_config->CApath;
  464. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  465. bool imported_native_ca = FALSE;
  466. #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_SYS_CA_CERTS)
  467. /* load native CA certificates */
  468. if(ssl_config->native_ca_store) {
  469. if(wolfSSL_CTX_load_system_CA_certs(wssl->ctx) != WOLFSSL_SUCCESS) {
  470. infof(data, "error importing native CA store, continuing anyway");
  471. }
  472. else {
  473. imported_native_ca = TRUE;
  474. infof(data, "successfully imported native CA store");
  475. wssl->x509_store_setup = TRUE;
  476. }
  477. }
  478. #endif /* !NO_FILESYSTEM */
  479. /* load certificate blob */
  480. if(ca_info_blob) {
  481. if(wolfSSL_CTX_load_verify_buffer(wssl->ctx, ca_info_blob->data,
  482. (long)ca_info_blob->len,
  483. WOLFSSL_FILETYPE_PEM) !=
  484. WOLFSSL_SUCCESS) {
  485. if(imported_native_ca) {
  486. infof(data, "error importing CA certificate blob, continuing anyway");
  487. }
  488. else {
  489. failf(data, "error importing CA certificate blob");
  490. return CURLE_SSL_CACERT_BADFILE;
  491. }
  492. }
  493. else {
  494. infof(data, "successfully imported CA certificate blob");
  495. wssl->x509_store_setup = TRUE;
  496. }
  497. }
  498. #ifndef NO_FILESYSTEM
  499. /* load trusted cacert from file if not blob */
  500. CURL_TRC_CF(data, cf, "populate_x509_store, path=%s, blob=%d",
  501. ssl_cafile ? ssl_cafile : "none", !!ca_info_blob);
  502. if(!store)
  503. return CURLE_OUT_OF_MEMORY;
  504. if((ssl_cafile || ssl_capath) && (!wssl->x509_store_setup)) {
  505. int rc =
  506. wolfSSL_CTX_load_verify_locations_ex(wssl->ctx,
  507. ssl_cafile,
  508. ssl_capath,
  509. WOLFSSL_LOAD_FLAG_IGNORE_ERR);
  510. if(WOLFSSL_SUCCESS != rc) {
  511. if(conn_config->verifypeer) {
  512. /* Fail if we insist on successfully verifying the server. */
  513. failf(data, "error setting certificate verify locations:"
  514. " CAfile: %s CApath: %s",
  515. ssl_cafile ? ssl_cafile : "none",
  516. ssl_capath ? ssl_capath : "none");
  517. return CURLE_SSL_CACERT_BADFILE;
  518. }
  519. else {
  520. /* Just continue with a warning if no strict certificate
  521. verification is required. */
  522. infof(data, "error setting certificate verify locations,"
  523. " continuing anyway:");
  524. }
  525. }
  526. else {
  527. /* Everything is fine. */
  528. infof(data, "successfully set certificate verify locations:");
  529. }
  530. infof(data, " CAfile: %s", ssl_cafile ? ssl_cafile : "none");
  531. infof(data, " CApath: %s", ssl_capath ? ssl_capath : "none");
  532. }
  533. #endif
  534. (void)store;
  535. wssl->x509_store_setup = TRUE;
  536. return CURLE_OK;
  537. }
  538. /* key to use at `multi->proto_hash` */
  539. #define MPROTO_WSSL_X509_KEY "tls:wssl:x509:share"
  540. struct wssl_x509_share {
  541. char *CAfile; /* CAfile path used to generate X509 store */
  542. WOLFSSL_X509_STORE *store; /* cached X509 store or NULL if none */
  543. struct curltime time; /* when the cached store was created */
  544. };
  545. static void wssl_x509_share_free(void *key, size_t key_len, void *p)
  546. {
  547. struct wssl_x509_share *share = p;
  548. DEBUGASSERT(key_len == (sizeof(MPROTO_WSSL_X509_KEY)-1));
  549. DEBUGASSERT(!memcmp(MPROTO_WSSL_X509_KEY, key, key_len));
  550. (void)key;
  551. (void)key_len;
  552. if(share->store) {
  553. wolfSSL_X509_STORE_free(share->store);
  554. }
  555. free(share->CAfile);
  556. free(share);
  557. }
  558. static bool
  559. cached_x509_store_expired(const struct Curl_easy *data,
  560. const struct wssl_x509_share *mb)
  561. {
  562. const struct ssl_general_config *cfg = &data->set.general_ssl;
  563. struct curltime now = Curl_now();
  564. timediff_t elapsed_ms = Curl_timediff(now, mb->time);
  565. timediff_t timeout_ms = cfg->ca_cache_timeout * (timediff_t)1000;
  566. if(timeout_ms < 0)
  567. return FALSE;
  568. return elapsed_ms >= timeout_ms;
  569. }
  570. static bool
  571. cached_x509_store_different(struct Curl_cfilter *cf,
  572. const struct wssl_x509_share *mb)
  573. {
  574. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  575. if(!mb->CAfile || !conn_config->CAfile)
  576. return mb->CAfile != conn_config->CAfile;
  577. return strcmp(mb->CAfile, conn_config->CAfile);
  578. }
  579. static WOLFSSL_X509_STORE *get_cached_x509_store(struct Curl_cfilter *cf,
  580. const struct Curl_easy *data)
  581. {
  582. struct Curl_multi *multi = data->multi;
  583. struct wssl_x509_share *share;
  584. WOLFSSL_X509_STORE *store = NULL;
  585. DEBUGASSERT(multi);
  586. share = multi ? Curl_hash_pick(&multi->proto_hash,
  587. (void *)MPROTO_WSSL_X509_KEY,
  588. sizeof(MPROTO_WSSL_X509_KEY)-1) : NULL;
  589. if(share && share->store &&
  590. !cached_x509_store_expired(data, share) &&
  591. !cached_x509_store_different(cf, share)) {
  592. store = share->store;
  593. }
  594. return store;
  595. }
  596. static void set_cached_x509_store(struct Curl_cfilter *cf,
  597. const struct Curl_easy *data,
  598. WOLFSSL_X509_STORE *store)
  599. {
  600. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  601. struct Curl_multi *multi = data->multi;
  602. struct wssl_x509_share *share;
  603. DEBUGASSERT(multi);
  604. if(!multi)
  605. return;
  606. share = Curl_hash_pick(&multi->proto_hash,
  607. (void *)MPROTO_WSSL_X509_KEY,
  608. sizeof(MPROTO_WSSL_X509_KEY)-1);
  609. if(!share) {
  610. share = calloc(1, sizeof(*share));
  611. if(!share)
  612. return;
  613. if(!Curl_hash_add2(&multi->proto_hash,
  614. (void *)MPROTO_WSSL_X509_KEY,
  615. sizeof(MPROTO_WSSL_X509_KEY)-1,
  616. share, wssl_x509_share_free)) {
  617. free(share);
  618. return;
  619. }
  620. }
  621. if(wolfSSL_X509_STORE_up_ref(store)) {
  622. char *CAfile = NULL;
  623. if(conn_config->CAfile) {
  624. CAfile = strdup(conn_config->CAfile);
  625. if(!CAfile) {
  626. wolfSSL_X509_STORE_free(store);
  627. return;
  628. }
  629. }
  630. if(share->store) {
  631. wolfSSL_X509_STORE_free(share->store);
  632. free(share->CAfile);
  633. }
  634. share->time = Curl_now();
  635. share->store = store;
  636. share->CAfile = CAfile;
  637. }
  638. }
  639. CURLcode Curl_wssl_setup_x509_store(struct Curl_cfilter *cf,
  640. struct Curl_easy *data,
  641. struct wolfssl_ctx *wssl)
  642. {
  643. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  644. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  645. CURLcode result = CURLE_OK;
  646. WOLFSSL_X509_STORE *cached_store;
  647. bool cache_criteria_met;
  648. /* Consider the X509 store cacheable if it comes exclusively from a CAfile,
  649. or no source is provided and we are falling back to wolfSSL's built-in
  650. default. */
  651. cache_criteria_met = (data->set.general_ssl.ca_cache_timeout != 0) &&
  652. conn_config->verifypeer &&
  653. !conn_config->CApath &&
  654. !conn_config->ca_info_blob &&
  655. !ssl_config->primary.CRLfile &&
  656. !ssl_config->native_ca_store;
  657. cached_store = cache_criteria_met ? get_cached_x509_store(cf, data) : NULL;
  658. if(cached_store && wolfSSL_CTX_get_cert_store(wssl->ctx) == cached_store) {
  659. /* The cached store is already in use, do nothing. */
  660. }
  661. else if(cached_store && wolfSSL_X509_STORE_up_ref(cached_store)) {
  662. wolfSSL_CTX_set_cert_store(wssl->ctx, cached_store);
  663. }
  664. else if(cache_criteria_met) {
  665. /* wolfSSL's initial store in CTX is not shareable by default.
  666. * Make a new one, suitable for adding to the cache. See #14278 */
  667. WOLFSSL_X509_STORE *store = wolfSSL_X509_STORE_new();
  668. if(!store) {
  669. failf(data, "SSL: could not create a X509 store");
  670. return CURLE_OUT_OF_MEMORY;
  671. }
  672. wolfSSL_CTX_set_cert_store(wssl->ctx, store);
  673. result = populate_x509_store(cf, data, store, wssl);
  674. if(!result) {
  675. set_cached_x509_store(cf, data, store);
  676. }
  677. }
  678. else {
  679. /* We never share the CTX's store, use it. */
  680. WOLFSSL_X509_STORE *store = wolfSSL_CTX_get_cert_store(wssl->ctx);
  681. result = populate_x509_store(cf, data, store, wssl);
  682. }
  683. return result;
  684. }
  685. #ifdef WOLFSSL_TLS13
  686. static CURLcode
  687. wssl_add_default_ciphers(bool tls13, struct dynbuf *buf)
  688. {
  689. int i;
  690. char *str;
  691. for(i = 0; (str = wolfSSL_get_cipher_list(i)); i++) {
  692. size_t n;
  693. if((strncmp(str, "TLS13", 5) == 0) != tls13)
  694. continue;
  695. /* if there already is data in the string, add colon separator */
  696. if(Curl_dyn_len(buf)) {
  697. CURLcode result = Curl_dyn_addn(buf, ":", 1);
  698. if(result)
  699. return result;
  700. }
  701. n = strlen(str);
  702. if(Curl_dyn_addn(buf, str, n))
  703. return CURLE_OUT_OF_MEMORY;
  704. }
  705. return CURLE_OK;
  706. }
  707. #endif
  708. /* 4.2.0 (2019) */
  709. #if LIBWOLFSSL_VERSION_HEX < 0x04002000 || !defined(OPENSSL_EXTRA)
  710. static int
  711. wssl_legacy_CTX_set_min_proto_version(WOLFSSL_CTX* ctx, int version)
  712. {
  713. int res;
  714. switch(version) {
  715. default:
  716. case TLS1_VERSION:
  717. res = wolfSSL_CTX_SetMinVersion(ctx, WOLFSSL_TLSV1);
  718. if(res == WOLFSSL_SUCCESS)
  719. return res;
  720. FALLTHROUGH();
  721. case TLS1_1_VERSION:
  722. res = wolfSSL_CTX_SetMinVersion(ctx, WOLFSSL_TLSV1_1);
  723. if(res == WOLFSSL_SUCCESS)
  724. return res;
  725. FALLTHROUGH();
  726. case TLS1_2_VERSION:
  727. res = wolfSSL_CTX_SetMinVersion(ctx, WOLFSSL_TLSV1_2);
  728. #ifdef WOLFSSL_TLS13
  729. if(res == WOLFSSL_SUCCESS)
  730. return res;
  731. FALLTHROUGH();
  732. case TLS1_3_VERSION:
  733. res = wolfSSL_CTX_SetMinVersion(ctx, WOLFSSL_TLSV1_3);
  734. #endif
  735. }
  736. return res;
  737. }
  738. static int
  739. wssl_legacy_CTX_set_max_proto_version(WOLFSSL_CTX* ctx, int version)
  740. {
  741. (void) ctx, (void) version;
  742. return WOLFSSL_NOT_IMPLEMENTED;
  743. }
  744. #define wolfSSL_CTX_set_min_proto_version wssl_legacy_CTX_set_min_proto_version
  745. #define wolfSSL_CTX_set_max_proto_version wssl_legacy_CTX_set_max_proto_version
  746. #endif
  747. /*
  748. * This function loads all the client/CA certificates and CRLs. Setup the TLS
  749. * layer and do all necessary magic.
  750. */
  751. static CURLcode
  752. wolfssl_connect_step1(struct Curl_cfilter *cf, struct Curl_easy *data)
  753. {
  754. int res;
  755. char *curves;
  756. struct ssl_connect_data *connssl = cf->ctx;
  757. struct wolfssl_ctx *backend =
  758. (struct wolfssl_ctx *)connssl->backend;
  759. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  760. const struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  761. WOLFSSL_METHOD* req_method = NULL;
  762. #ifdef WOLFSSL_HAVE_KYBER
  763. word16 pqkem = 0;
  764. size_t idx = 0;
  765. #endif
  766. DEBUGASSERT(backend);
  767. if(connssl->state == ssl_connection_complete)
  768. return CURLE_OK;
  769. #if LIBWOLFSSL_VERSION_HEX < 0x04002000 /* 4.2.0 (2019) */
  770. req_method = wolfSSLv23_client_method();
  771. #else
  772. req_method = wolfTLS_client_method();
  773. #endif
  774. if(!req_method) {
  775. failf(data, "wolfSSL: could not create a client method");
  776. return CURLE_OUT_OF_MEMORY;
  777. }
  778. if(backend->ctx)
  779. wolfSSL_CTX_free(backend->ctx);
  780. backend->ctx = wolfSSL_CTX_new(req_method);
  781. if(!backend->ctx) {
  782. failf(data, "wolfSSL: could not create a context");
  783. return CURLE_OUT_OF_MEMORY;
  784. }
  785. switch(conn_config->version) {
  786. case CURL_SSLVERSION_DEFAULT:
  787. case CURL_SSLVERSION_TLSv1:
  788. case CURL_SSLVERSION_TLSv1_0:
  789. res = wolfSSL_CTX_set_min_proto_version(backend->ctx, TLS1_VERSION);
  790. break;
  791. case CURL_SSLVERSION_TLSv1_1:
  792. res = wolfSSL_CTX_set_min_proto_version(backend->ctx, TLS1_1_VERSION);
  793. break;
  794. case CURL_SSLVERSION_TLSv1_2:
  795. res = wolfSSL_CTX_set_min_proto_version(backend->ctx, TLS1_2_VERSION);
  796. break;
  797. #ifdef WOLFSSL_TLS13
  798. case CURL_SSLVERSION_TLSv1_3:
  799. res = wolfSSL_CTX_set_min_proto_version(backend->ctx, TLS1_3_VERSION);
  800. break;
  801. #endif
  802. default:
  803. failf(data, "wolfSSL: unsupported minimum TLS version value");
  804. return CURLE_SSL_CONNECT_ERROR;
  805. }
  806. if(res != WOLFSSL_SUCCESS) {
  807. failf(data, "wolfSSL: failed set the minimum TLS version");
  808. return CURLE_SSL_CONNECT_ERROR;
  809. }
  810. switch(conn_config->version_max) {
  811. #ifdef WOLFSSL_TLS13
  812. case CURL_SSLVERSION_MAX_TLSv1_3:
  813. res = wolfSSL_CTX_set_max_proto_version(backend->ctx, TLS1_3_VERSION);
  814. break;
  815. #endif
  816. case CURL_SSLVERSION_MAX_TLSv1_2:
  817. res = wolfSSL_CTX_set_max_proto_version(backend->ctx, TLS1_2_VERSION);
  818. break;
  819. case CURL_SSLVERSION_MAX_TLSv1_1:
  820. res = wolfSSL_CTX_set_max_proto_version(backend->ctx, TLS1_1_VERSION);
  821. break;
  822. case CURL_SSLVERSION_MAX_TLSv1_0:
  823. res = wolfSSL_CTX_set_max_proto_version(backend->ctx, TLS1_VERSION);
  824. break;
  825. case CURL_SSLVERSION_MAX_DEFAULT:
  826. case CURL_SSLVERSION_MAX_NONE:
  827. res = WOLFSSL_SUCCESS;
  828. break;
  829. default:
  830. failf(data, "wolfSSL: unsupported maximum TLS version value");
  831. return CURLE_SSL_CONNECT_ERROR;
  832. }
  833. if(res != WOLFSSL_SUCCESS) {
  834. failf(data, "wolfSSL: failed set the maximum TLS version");
  835. return CURLE_SSL_CONNECT_ERROR;
  836. }
  837. #ifndef WOLFSSL_TLS13
  838. {
  839. char *ciphers = conn_config->cipher_list;
  840. if(ciphers) {
  841. if(!SSL_CTX_set_cipher_list(backend->ctx, ciphers)) {
  842. failf(data, "failed setting cipher list: %s", ciphers);
  843. return CURLE_SSL_CIPHER;
  844. }
  845. infof(data, "Cipher selection: %s", ciphers);
  846. }
  847. }
  848. #else
  849. #define MAX_CIPHER_LEN 4096
  850. if(conn_config->cipher_list || conn_config->cipher_list13) {
  851. const char *ciphers12 = conn_config->cipher_list;
  852. const char *ciphers13 = conn_config->cipher_list13;
  853. struct dynbuf c;
  854. CURLcode result;
  855. Curl_dyn_init(&c, MAX_CIPHER_LEN);
  856. if(ciphers13)
  857. result = Curl_dyn_add(&c, ciphers13);
  858. else
  859. result = wssl_add_default_ciphers(TRUE, &c);
  860. if(!result) {
  861. if(ciphers12) {
  862. if(Curl_dyn_len(&c))
  863. result = Curl_dyn_addn(&c, ":", 1);
  864. if(!result)
  865. result = Curl_dyn_add(&c, ciphers12);
  866. }
  867. else
  868. result = wssl_add_default_ciphers(FALSE, &c);
  869. }
  870. if(result)
  871. return result;
  872. if(!wolfSSL_CTX_set_cipher_list(backend->ctx, Curl_dyn_ptr(&c))) {
  873. failf(data, "failed setting cipher list: %s", Curl_dyn_ptr(&c));
  874. Curl_dyn_free(&c);
  875. return CURLE_SSL_CIPHER;
  876. }
  877. infof(data, "Cipher selection: %s", Curl_dyn_ptr(&c));
  878. Curl_dyn_free(&c);
  879. }
  880. #endif
  881. curves = conn_config->curves;
  882. if(curves) {
  883. #ifdef WOLFSSL_HAVE_KYBER
  884. for(idx = 0; gnm[idx].name != NULL; idx++) {
  885. if(strncmp(curves, gnm[idx].name, strlen(gnm[idx].name)) == 0) {
  886. pqkem = gnm[idx].group;
  887. break;
  888. }
  889. }
  890. if(pqkem == 0)
  891. #endif
  892. {
  893. if(!wolfSSL_CTX_set1_curves_list(backend->ctx, curves)) {
  894. failf(data, "failed setting curves list: '%s'", curves);
  895. return CURLE_SSL_CIPHER;
  896. }
  897. }
  898. }
  899. /* Load the client certificate, and private key */
  900. #ifndef NO_FILESYSTEM
  901. if(ssl_config->primary.cert_blob || ssl_config->primary.clientcert) {
  902. const char *cert_file = ssl_config->primary.clientcert;
  903. const char *key_file = ssl_config->key;
  904. const struct curl_blob *cert_blob = ssl_config->primary.cert_blob;
  905. const struct curl_blob *key_blob = ssl_config->key_blob;
  906. int file_type = wolfssl_do_file_type(ssl_config->cert_type);
  907. int rc;
  908. switch(file_type) {
  909. case WOLFSSL_FILETYPE_PEM:
  910. rc = cert_blob ?
  911. wolfSSL_CTX_use_certificate_chain_buffer(backend->ctx,
  912. cert_blob->data,
  913. (long)cert_blob->len) :
  914. wolfSSL_CTX_use_certificate_chain_file(backend->ctx, cert_file);
  915. break;
  916. case WOLFSSL_FILETYPE_ASN1:
  917. rc = cert_blob ?
  918. wolfSSL_CTX_use_certificate_buffer(backend->ctx, cert_blob->data,
  919. (long)cert_blob->len, file_type) :
  920. wolfSSL_CTX_use_certificate_file(backend->ctx, cert_file, file_type);
  921. break;
  922. default:
  923. failf(data, "unknown cert type");
  924. return CURLE_BAD_FUNCTION_ARGUMENT;
  925. }
  926. if(rc != 1) {
  927. failf(data, "unable to use client certificate");
  928. return CURLE_SSL_CONNECT_ERROR;
  929. }
  930. if(!key_blob && !key_file) {
  931. key_blob = cert_blob;
  932. key_file = cert_file;
  933. }
  934. else
  935. file_type = wolfssl_do_file_type(ssl_config->key_type);
  936. rc = key_blob ?
  937. wolfSSL_CTX_use_PrivateKey_buffer(backend->ctx, key_blob->data,
  938. (long)key_blob->len, file_type) :
  939. wolfSSL_CTX_use_PrivateKey_file(backend->ctx, key_file, file_type);
  940. if(rc != 1) {
  941. failf(data, "unable to set private key");
  942. return CURLE_SSL_CONNECT_ERROR;
  943. }
  944. }
  945. #else /* NO_FILESYSTEM */
  946. if(ssl_config->primary.cert_blob) {
  947. const struct curl_blob *cert_blob = ssl_config->primary.cert_blob;
  948. const struct curl_blob *key_blob = ssl_config->key_blob;
  949. int file_type = wolfssl_do_file_type(ssl_config->cert_type);
  950. int rc;
  951. switch(file_type) {
  952. case WOLFSSL_FILETYPE_PEM:
  953. rc = wolfSSL_CTX_use_certificate_chain_buffer(backend->ctx,
  954. cert_blob->data,
  955. (long)cert_blob->len);
  956. break;
  957. case WOLFSSL_FILETYPE_ASN1:
  958. rc = wolfSSL_CTX_use_certificate_buffer(backend->ctx, cert_blob->data,
  959. (long)cert_blob->len, file_type);
  960. break;
  961. default:
  962. failf(data, "unknown cert type");
  963. return CURLE_BAD_FUNCTION_ARGUMENT;
  964. }
  965. if(rc != 1) {
  966. failf(data, "unable to use client certificate");
  967. return CURLE_SSL_CONNECT_ERROR;
  968. }
  969. if(!key_blob)
  970. key_blob = cert_blob;
  971. else
  972. file_type = wolfssl_do_file_type(ssl_config->key_type);
  973. if(wolfSSL_CTX_use_PrivateKey_buffer(backend->ctx, key_blob->data,
  974. (long)key_blob->len,
  975. file_type) != 1) {
  976. failf(data, "unable to set private key");
  977. return CURLE_SSL_CONNECT_ERROR;
  978. }
  979. }
  980. #endif /* !NO_FILESYSTEM */
  981. /* SSL always tries to verify the peer, this only says whether it should
  982. * fail to connect if the verification fails, or if it should continue
  983. * anyway. In the latter case the result of the verification is checked with
  984. * SSL_get_verify_result() below. */
  985. wolfSSL_CTX_set_verify(backend->ctx,
  986. conn_config->verifypeer ? WOLFSSL_VERIFY_PEER :
  987. WOLFSSL_VERIFY_NONE, NULL);
  988. #ifdef HAVE_SNI
  989. if(connssl->peer.sni) {
  990. size_t sni_len = strlen(connssl->peer.sni);
  991. if((sni_len < USHRT_MAX)) {
  992. if(wolfSSL_CTX_UseSNI(backend->ctx, WOLFSSL_SNI_HOST_NAME,
  993. connssl->peer.sni,
  994. (unsigned short)sni_len) != 1) {
  995. failf(data, "Failed to set SNI");
  996. return CURLE_SSL_CONNECT_ERROR;
  997. }
  998. }
  999. }
  1000. #endif
  1001. /* give application a chance to interfere with SSL set up. */
  1002. if(data->set.ssl.fsslctx) {
  1003. CURLcode result;
  1004. if(!backend->x509_store_setup) {
  1005. result = Curl_wssl_setup_x509_store(cf, data, backend);
  1006. if(result)
  1007. return result;
  1008. }
  1009. result = (*data->set.ssl.fsslctx)(data, backend->ctx,
  1010. data->set.ssl.fsslctxp);
  1011. if(result) {
  1012. failf(data, "error signaled by ssl ctx callback");
  1013. return result;
  1014. }
  1015. }
  1016. #ifdef NO_FILESYSTEM
  1017. else if(conn_config->verifypeer) {
  1018. failf(data, "SSL: Certificates cannot be loaded because wolfSSL was built"
  1019. " with \"no filesystem\". Either disable peer verification"
  1020. " (insecure) or if you are building an application with libcurl you"
  1021. " can load certificates via CURLOPT_SSL_CTX_FUNCTION.");
  1022. return CURLE_SSL_CONNECT_ERROR;
  1023. }
  1024. #endif
  1025. /* Let's make an SSL structure */
  1026. if(backend->handle)
  1027. wolfSSL_free(backend->handle);
  1028. backend->handle = wolfSSL_new(backend->ctx);
  1029. if(!backend->handle) {
  1030. failf(data, "SSL: could not create a handle");
  1031. return CURLE_OUT_OF_MEMORY;
  1032. }
  1033. #ifdef WOLFSSL_HAVE_KYBER
  1034. if(pqkem) {
  1035. if(wolfSSL_UseKeyShare(backend->handle, pqkem) != WOLFSSL_SUCCESS) {
  1036. failf(data, "unable to use PQ KEM");
  1037. }
  1038. }
  1039. #endif
  1040. #ifdef HAVE_ALPN
  1041. if(connssl->alpn) {
  1042. struct alpn_proto_buf proto;
  1043. CURLcode result;
  1044. result = Curl_alpn_to_proto_str(&proto, connssl->alpn);
  1045. if(result ||
  1046. wolfSSL_UseALPN(backend->handle,
  1047. (char *)proto.data, (unsigned int)proto.len,
  1048. WOLFSSL_ALPN_CONTINUE_ON_MISMATCH) != WOLFSSL_SUCCESS) {
  1049. failf(data, "SSL: failed setting ALPN protocols");
  1050. return CURLE_SSL_CONNECT_ERROR;
  1051. }
  1052. infof(data, VTLS_INFOF_ALPN_OFFER_1STR, proto.data);
  1053. }
  1054. #endif /* HAVE_ALPN */
  1055. #ifdef OPENSSL_EXTRA
  1056. if(Curl_tls_keylog_enabled()) {
  1057. /* Ensure the Client Random is preserved. */
  1058. wolfSSL_KeepArrays(backend->handle);
  1059. #if defined(HAVE_SECRET_CALLBACK) && defined(WOLFSSL_TLS13)
  1060. wolfSSL_set_tls13_secret_cb(backend->handle,
  1061. wolfssl_tls13_secret_callback, NULL);
  1062. #endif
  1063. }
  1064. #endif /* OPENSSL_EXTRA */
  1065. #ifdef HAVE_SECURE_RENEGOTIATION
  1066. if(wolfSSL_UseSecureRenegotiation(backend->handle) != SSL_SUCCESS) {
  1067. failf(data, "SSL: failed setting secure renegotiation");
  1068. return CURLE_SSL_CONNECT_ERROR;
  1069. }
  1070. #endif /* HAVE_SECURE_RENEGOTIATION */
  1071. /* Check if there is a cached ID we can/should use here! */
  1072. if(ssl_config->primary.cache_session) {
  1073. /* Set session from cache if there is one */
  1074. (void)wssl_setup_session(cf, data, backend, &connssl->peer);
  1075. /* Register to get notified when a new session is received */
  1076. wolfSSL_set_app_data(backend->handle, cf);
  1077. wolfSSL_CTX_sess_set_new_cb(backend->ctx, wssl_vtls_new_session_cb);
  1078. }
  1079. #ifdef USE_ECH
  1080. if(ECH_ENABLED(data)) {
  1081. int trying_ech_now = 0;
  1082. if(data->set.str[STRING_ECH_PUBLIC]) {
  1083. infof(data, "ECH: outername not (yet) supported with wolfSSL");
  1084. return CURLE_SSL_CONNECT_ERROR;
  1085. }
  1086. if(data->set.tls_ech == CURLECH_GREASE) {
  1087. infof(data, "ECH: GREASE'd ECH not yet supported for wolfSSL");
  1088. return CURLE_SSL_CONNECT_ERROR;
  1089. }
  1090. if(data->set.tls_ech & CURLECH_CLA_CFG
  1091. && data->set.str[STRING_ECH_CONFIG]) {
  1092. char *b64val = data->set.str[STRING_ECH_CONFIG];
  1093. word32 b64len = 0;
  1094. b64len = (word32) strlen(b64val);
  1095. if(b64len
  1096. && wolfSSL_SetEchConfigsBase64(backend->handle, b64val, b64len)
  1097. != WOLFSSL_SUCCESS) {
  1098. if(data->set.tls_ech & CURLECH_HARD)
  1099. return CURLE_SSL_CONNECT_ERROR;
  1100. }
  1101. else {
  1102. trying_ech_now = 1;
  1103. infof(data, "ECH: ECHConfig from command line");
  1104. }
  1105. }
  1106. else {
  1107. struct Curl_dns_entry *dns = NULL;
  1108. dns = Curl_fetch_addr(data, connssl->peer.hostname, connssl->peer.port);
  1109. if(!dns) {
  1110. infof(data, "ECH: requested but no DNS info available");
  1111. if(data->set.tls_ech & CURLECH_HARD)
  1112. return CURLE_SSL_CONNECT_ERROR;
  1113. }
  1114. else {
  1115. struct Curl_https_rrinfo *rinfo = NULL;
  1116. rinfo = dns->hinfo;
  1117. if(rinfo && rinfo->echconfiglist) {
  1118. unsigned char *ecl = rinfo->echconfiglist;
  1119. size_t elen = rinfo->echconfiglist_len;
  1120. infof(data, "ECH: ECHConfig from DoH HTTPS RR");
  1121. if(wolfSSL_SetEchConfigs(backend->handle, ecl, (word32) elen) !=
  1122. WOLFSSL_SUCCESS) {
  1123. infof(data, "ECH: wolfSSL_SetEchConfigs failed");
  1124. if(data->set.tls_ech & CURLECH_HARD)
  1125. return CURLE_SSL_CONNECT_ERROR;
  1126. }
  1127. else {
  1128. trying_ech_now = 1;
  1129. infof(data, "ECH: imported ECHConfigList of length %ld", elen);
  1130. }
  1131. }
  1132. else {
  1133. infof(data, "ECH: requested but no ECHConfig available");
  1134. if(data->set.tls_ech & CURLECH_HARD)
  1135. return CURLE_SSL_CONNECT_ERROR;
  1136. }
  1137. Curl_resolv_unlink(data, &dns);
  1138. }
  1139. }
  1140. if(trying_ech_now
  1141. && SSL_set_min_proto_version(backend->handle, TLS1_3_VERSION) != 1) {
  1142. infof(data, "ECH: cannot force TLSv1.3 [ERROR]");
  1143. return CURLE_SSL_CONNECT_ERROR;
  1144. }
  1145. }
  1146. #endif /* USE_ECH */
  1147. #ifdef USE_BIO_CHAIN
  1148. {
  1149. WOLFSSL_BIO *bio;
  1150. bio = wolfSSL_BIO_new(wolfssl_bio_cf_method);
  1151. if(!bio)
  1152. return CURLE_OUT_OF_MEMORY;
  1153. wolfSSL_BIO_set_data(bio, cf);
  1154. wolfSSL_set_bio(backend->handle, bio, bio);
  1155. }
  1156. #else /* USE_BIO_CHAIN */
  1157. /* pass the raw socket into the SSL layer */
  1158. if(!wolfSSL_set_fd(backend->handle,
  1159. (int)Curl_conn_cf_get_socket(cf, data))) {
  1160. failf(data, "SSL: SSL_set_fd failed");
  1161. return CURLE_SSL_CONNECT_ERROR;
  1162. }
  1163. #endif /* !USE_BIO_CHAIN */
  1164. connssl->connecting_state = ssl_connect_2;
  1165. return CURLE_OK;
  1166. }
  1167. static char *wolfssl_strerror(unsigned long error, char *buf,
  1168. unsigned long size)
  1169. {
  1170. DEBUGASSERT(size > 40);
  1171. *buf = '\0';
  1172. wolfSSL_ERR_error_string_n(error, buf, size);
  1173. if(!*buf) {
  1174. const char *msg = error ? "Unknown error" : "No error";
  1175. /* the string fits because the assert above assures this */
  1176. strcpy(buf, msg);
  1177. }
  1178. return buf;
  1179. }
  1180. static CURLcode
  1181. wolfssl_connect_step2(struct Curl_cfilter *cf, struct Curl_easy *data)
  1182. {
  1183. int ret = -1;
  1184. struct ssl_connect_data *connssl = cf->ctx;
  1185. struct wolfssl_ctx *backend =
  1186. (struct wolfssl_ctx *)connssl->backend;
  1187. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  1188. #ifndef CURL_DISABLE_PROXY
  1189. const char * const pinnedpubkey = Curl_ssl_cf_is_proxy(cf) ?
  1190. data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY] :
  1191. data->set.str[STRING_SSL_PINNEDPUBLICKEY];
  1192. #else
  1193. const char * const pinnedpubkey = data->set.str[STRING_SSL_PINNEDPUBLICKEY];
  1194. #endif
  1195. DEBUGASSERT(backend);
  1196. wolfSSL_ERR_clear_error();
  1197. /* Enable RFC2818 checks */
  1198. if(conn_config->verifyhost) {
  1199. char *snihost = connssl->peer.sni ?
  1200. connssl->peer.sni : connssl->peer.hostname;
  1201. if(wolfSSL_check_domain_name(backend->handle, snihost) == WOLFSSL_FAILURE)
  1202. return CURLE_SSL_CONNECT_ERROR;
  1203. }
  1204. if(!backend->x509_store_setup) {
  1205. /* After having send off the ClientHello, we prepare the x509
  1206. * store to verify the coming certificate from the server */
  1207. CURLcode result;
  1208. result = Curl_wssl_setup_x509_store(cf, data, backend);
  1209. if(result)
  1210. return result;
  1211. }
  1212. connssl->io_need = CURL_SSL_IO_NEED_NONE;
  1213. ret = wolfSSL_connect(backend->handle);
  1214. #ifdef OPENSSL_EXTRA
  1215. if(Curl_tls_keylog_enabled()) {
  1216. /* If key logging is enabled, wait for the handshake to complete and then
  1217. * proceed with logging secrets (for TLS 1.2 or older).
  1218. *
  1219. * During the handshake (ret==-1), wolfSSL_want_read() is true as it waits
  1220. * for the server response. At that point the master secret is not yet
  1221. * available, so we must not try to read it.
  1222. * To log the secret on completion with a handshake failure, detect
  1223. * completion via the observation that there is nothing to read or write.
  1224. * Note that OpenSSL SSL_want_read() is always true here. If wolfSSL ever
  1225. * changes, the worst case is that no key is logged on error.
  1226. */
  1227. if(ret == WOLFSSL_SUCCESS ||
  1228. (!wolfSSL_want_read(backend->handle) &&
  1229. !wolfSSL_want_write(backend->handle))) {
  1230. wolfssl_log_tls12_secret(backend->handle);
  1231. /* Client Random and master secrets are no longer needed, erase these.
  1232. * Ignored while the handshake is still in progress. */
  1233. wolfSSL_FreeArrays(backend->handle);
  1234. }
  1235. }
  1236. #endif /* OPENSSL_EXTRA */
  1237. if(ret != 1) {
  1238. int detail = wolfSSL_get_error(backend->handle, ret);
  1239. if(WOLFSSL_ERROR_WANT_READ == detail) {
  1240. connssl->io_need = CURL_SSL_IO_NEED_RECV;
  1241. return CURLE_OK;
  1242. }
  1243. else if(WOLFSSL_ERROR_WANT_WRITE == detail) {
  1244. connssl->io_need = CURL_SSL_IO_NEED_SEND;
  1245. return CURLE_OK;
  1246. }
  1247. /* There is no easy way to override only the CN matching.
  1248. * This will enable the override of both mismatching SubjectAltNames
  1249. * as also mismatching CN fields */
  1250. else if(DOMAIN_NAME_MISMATCH == detail) {
  1251. #if 1
  1252. failf(data, " subject alt name(s) or common name do not match \"%s\"",
  1253. connssl->peer.dispname);
  1254. return CURLE_PEER_FAILED_VERIFICATION;
  1255. #else
  1256. /* When the wolfssl_check_domain_name() is used and you desire to
  1257. * continue on a DOMAIN_NAME_MISMATCH, i.e. 'ssl_config.verifyhost
  1258. * == 0', CyaSSL version 2.4.0 will fail with an INCOMPLETE_DATA
  1259. * error. The only way to do this is currently to switch the
  1260. * Wolfssl_check_domain_name() in and out based on the
  1261. * 'ssl_config.verifyhost' value. */
  1262. if(conn_config->verifyhost) {
  1263. failf(data,
  1264. " subject alt name(s) or common name do not match \"%s\"\n",
  1265. connssl->dispname);
  1266. return CURLE_PEER_FAILED_VERIFICATION;
  1267. }
  1268. else {
  1269. infof(data,
  1270. " subject alt name(s) and/or common name do not match \"%s\"",
  1271. connssl->dispname);
  1272. return CURLE_OK;
  1273. }
  1274. #endif
  1275. }
  1276. else if(ASN_NO_SIGNER_E == detail) {
  1277. if(conn_config->verifypeer) {
  1278. failf(data, " CA signer not available for verification");
  1279. return CURLE_SSL_CACERT_BADFILE;
  1280. }
  1281. else {
  1282. /* Just continue with a warning if no strict certificate
  1283. verification is required. */
  1284. infof(data, "CA signer not available for verification, "
  1285. "continuing anyway");
  1286. }
  1287. }
  1288. else if(ASN_AFTER_DATE_E == detail) {
  1289. failf(data, "server verification failed: certificate has expired.");
  1290. return CURLE_PEER_FAILED_VERIFICATION;
  1291. }
  1292. else if(ASN_BEFORE_DATE_E == detail) {
  1293. failf(data, "server verification failed: certificate not valid yet.");
  1294. return CURLE_PEER_FAILED_VERIFICATION;
  1295. }
  1296. #ifdef USE_ECH
  1297. else if(-1 == detail) {
  1298. /* try access a retry_config ECHConfigList for tracing */
  1299. byte echConfigs[1000];
  1300. word32 echConfigsLen = 1000;
  1301. int rv = 0;
  1302. /* this currently does not produce the retry_configs */
  1303. rv = wolfSSL_GetEchConfigs(backend->handle, echConfigs,
  1304. &echConfigsLen);
  1305. if(rv != WOLFSSL_SUCCESS) {
  1306. infof(data, "Failed to get ECHConfigs");
  1307. }
  1308. else {
  1309. char *b64str = NULL;
  1310. size_t blen = 0;
  1311. rv = Curl_base64_encode((const char *)echConfigs, echConfigsLen,
  1312. &b64str, &blen);
  1313. if(!rv && b64str)
  1314. infof(data, "ECH: (not yet) retry_configs %s", b64str);
  1315. free(b64str);
  1316. }
  1317. }
  1318. #endif
  1319. else if(backend->io_result == CURLE_AGAIN) {
  1320. return CURLE_OK;
  1321. }
  1322. else {
  1323. char error_buffer[256];
  1324. failf(data, "SSL_connect failed with error %d: %s", detail,
  1325. wolfssl_strerror((unsigned long)detail, error_buffer,
  1326. sizeof(error_buffer)));
  1327. return CURLE_SSL_CONNECT_ERROR;
  1328. }
  1329. }
  1330. if(pinnedpubkey) {
  1331. #ifdef KEEP_PEER_CERT
  1332. WOLFSSL_X509 *x509;
  1333. const char *x509_der;
  1334. int x509_der_len;
  1335. struct Curl_X509certificate x509_parsed;
  1336. struct Curl_asn1Element *pubkey;
  1337. CURLcode result;
  1338. x509 = wolfSSL_get_peer_certificate(backend->handle);
  1339. if(!x509) {
  1340. failf(data, "SSL: failed retrieving server certificate");
  1341. return CURLE_SSL_PINNEDPUBKEYNOTMATCH;
  1342. }
  1343. x509_der = (const char *)wolfSSL_X509_get_der(x509, &x509_der_len);
  1344. if(!x509_der) {
  1345. failf(data, "SSL: failed retrieving ASN.1 server certificate");
  1346. return CURLE_SSL_PINNEDPUBKEYNOTMATCH;
  1347. }
  1348. memset(&x509_parsed, 0, sizeof(x509_parsed));
  1349. if(Curl_parseX509(&x509_parsed, x509_der, x509_der + x509_der_len))
  1350. return CURLE_SSL_PINNEDPUBKEYNOTMATCH;
  1351. pubkey = &x509_parsed.subjectPublicKeyInfo;
  1352. if(!pubkey->header || pubkey->end <= pubkey->header) {
  1353. failf(data, "SSL: failed retrieving public key from server certificate");
  1354. return CURLE_SSL_PINNEDPUBKEYNOTMATCH;
  1355. }
  1356. result = Curl_pin_peer_pubkey(data,
  1357. pinnedpubkey,
  1358. (const unsigned char *)pubkey->header,
  1359. (size_t)(pubkey->end - pubkey->header));
  1360. wolfSSL_FreeX509(x509);
  1361. if(result) {
  1362. failf(data, "SSL: public key does not match pinned public key");
  1363. return result;
  1364. }
  1365. #else
  1366. failf(data, "Library lacks pinning support built-in");
  1367. return CURLE_NOT_BUILT_IN;
  1368. #endif
  1369. }
  1370. #ifdef HAVE_ALPN
  1371. if(connssl->alpn) {
  1372. int rc;
  1373. char *protocol = NULL;
  1374. unsigned short protocol_len = 0;
  1375. rc = wolfSSL_ALPN_GetProtocol(backend->handle, &protocol, &protocol_len);
  1376. if(rc == WOLFSSL_SUCCESS) {
  1377. Curl_alpn_set_negotiated(cf, data, connssl,
  1378. (const unsigned char *)protocol, protocol_len);
  1379. }
  1380. else if(rc == WOLFSSL_ALPN_NOT_FOUND)
  1381. Curl_alpn_set_negotiated(cf, data, connssl, NULL, 0);
  1382. else {
  1383. failf(data, "ALPN, failure getting protocol, error %d", rc);
  1384. return CURLE_SSL_CONNECT_ERROR;
  1385. }
  1386. }
  1387. #endif /* HAVE_ALPN */
  1388. connssl->connecting_state = ssl_connect_3;
  1389. #if (LIBWOLFSSL_VERSION_HEX >= 0x03009010)
  1390. infof(data, "SSL connection using %s / %s",
  1391. wolfSSL_get_version(backend->handle),
  1392. wolfSSL_get_cipher_name(backend->handle));
  1393. #else
  1394. infof(data, "SSL connected");
  1395. #endif
  1396. return CURLE_OK;
  1397. }
  1398. static ssize_t wolfssl_send(struct Curl_cfilter *cf,
  1399. struct Curl_easy *data,
  1400. const void *mem,
  1401. size_t len,
  1402. CURLcode *curlcode)
  1403. {
  1404. struct ssl_connect_data *connssl = cf->ctx;
  1405. struct wolfssl_ctx *backend =
  1406. (struct wolfssl_ctx *)connssl->backend;
  1407. int memlen = (len > (size_t)INT_MAX) ? INT_MAX : (int)len;
  1408. int rc;
  1409. DEBUGASSERT(backend);
  1410. wolfSSL_ERR_clear_error();
  1411. rc = wolfSSL_write(backend->handle, mem, memlen);
  1412. if(rc <= 0) {
  1413. int err = wolfSSL_get_error(backend->handle, rc);
  1414. switch(err) {
  1415. case WOLFSSL_ERROR_WANT_READ:
  1416. case WOLFSSL_ERROR_WANT_WRITE:
  1417. /* there is data pending, re-invoke SSL_write() */
  1418. CURL_TRC_CF(data, cf, "wolfssl_send(len=%zu) -> AGAIN", len);
  1419. *curlcode = CURLE_AGAIN;
  1420. return -1;
  1421. default:
  1422. if(backend->io_result == CURLE_AGAIN) {
  1423. CURL_TRC_CF(data, cf, "wolfssl_send(len=%zu) -> AGAIN", len);
  1424. *curlcode = CURLE_AGAIN;
  1425. return -1;
  1426. }
  1427. CURL_TRC_CF(data, cf, "wolfssl_send(len=%zu) -> %d, %d", len, rc, err);
  1428. {
  1429. char error_buffer[256];
  1430. failf(data, "SSL write: %s, errno %d",
  1431. wolfssl_strerror((unsigned long)err, error_buffer,
  1432. sizeof(error_buffer)),
  1433. SOCKERRNO);
  1434. }
  1435. *curlcode = CURLE_SEND_ERROR;
  1436. return -1;
  1437. }
  1438. }
  1439. CURL_TRC_CF(data, cf, "wolfssl_send(len=%zu) -> %d", len, rc);
  1440. return rc;
  1441. }
  1442. static CURLcode wolfssl_shutdown(struct Curl_cfilter *cf,
  1443. struct Curl_easy *data,
  1444. bool send_shutdown, bool *done)
  1445. {
  1446. struct ssl_connect_data *connssl = cf->ctx;
  1447. struct wolfssl_ctx *wctx = (struct wolfssl_ctx *)connssl->backend;
  1448. CURLcode result = CURLE_OK;
  1449. char buf[1024];
  1450. char error_buffer[256];
  1451. int nread = -1, err;
  1452. size_t i;
  1453. int detail;
  1454. DEBUGASSERT(wctx);
  1455. if(!wctx->handle || cf->shutdown) {
  1456. *done = TRUE;
  1457. goto out;
  1458. }
  1459. wctx->shutting_down = TRUE;
  1460. connssl->io_need = CURL_SSL_IO_NEED_NONE;
  1461. *done = FALSE;
  1462. if(!(wolfSSL_get_shutdown(wctx->handle) & WOLFSSL_SENT_SHUTDOWN)) {
  1463. /* We have not started the shutdown from our side yet. Check
  1464. * if the server already sent us one. */
  1465. wolfSSL_ERR_clear_error();
  1466. nread = wolfSSL_read(wctx->handle, buf, (int)sizeof(buf));
  1467. err = wolfSSL_get_error(wctx->handle, nread);
  1468. CURL_TRC_CF(data, cf, "wolfSSL_read, nread=%d, err=%d", nread, err);
  1469. if(!nread && err == WOLFSSL_ERROR_ZERO_RETURN) {
  1470. bool input_pending;
  1471. /* Yes, it did. */
  1472. if(!send_shutdown) {
  1473. CURL_TRC_CF(data, cf, "SSL shutdown received, not sending");
  1474. *done = TRUE;
  1475. goto out;
  1476. }
  1477. else if(!cf->next->cft->is_alive(cf->next, data, &input_pending)) {
  1478. /* Server closed the connection after its closy notify. It
  1479. * seems not interested to see our close notify, so do not
  1480. * send it. We are done. */
  1481. CURL_TRC_CF(data, cf, "peer closed connection");
  1482. connssl->peer_closed = TRUE;
  1483. *done = TRUE;
  1484. goto out;
  1485. }
  1486. }
  1487. }
  1488. /* SSL should now have started the shutdown from our side. Since it
  1489. * was not complete, we are lacking the close notify from the server. */
  1490. if(send_shutdown) {
  1491. wolfSSL_ERR_clear_error();
  1492. if(wolfSSL_shutdown(wctx->handle) == 1) {
  1493. CURL_TRC_CF(data, cf, "SSL shutdown finished");
  1494. *done = TRUE;
  1495. goto out;
  1496. }
  1497. if(WOLFSSL_ERROR_WANT_WRITE == wolfSSL_get_error(wctx->handle, nread)) {
  1498. CURL_TRC_CF(data, cf, "SSL shutdown still wants to send");
  1499. connssl->io_need = CURL_SSL_IO_NEED_SEND;
  1500. goto out;
  1501. }
  1502. /* Having sent the close notify, we use wolfSSL_read() to get the
  1503. * missing close notify from the server. */
  1504. }
  1505. for(i = 0; i < 10; ++i) {
  1506. wolfSSL_ERR_clear_error();
  1507. nread = wolfSSL_read(wctx->handle, buf, (int)sizeof(buf));
  1508. if(nread <= 0)
  1509. break;
  1510. }
  1511. err = wolfSSL_get_error(wctx->handle, nread);
  1512. switch(err) {
  1513. case WOLFSSL_ERROR_ZERO_RETURN: /* no more data */
  1514. CURL_TRC_CF(data, cf, "SSL shutdown received");
  1515. *done = TRUE;
  1516. break;
  1517. case WOLFSSL_ERROR_NONE: /* just did not get anything */
  1518. case WOLFSSL_ERROR_WANT_READ:
  1519. /* SSL has send its notify and now wants to read the reply
  1520. * from the server. We are not really interested in that. */
  1521. CURL_TRC_CF(data, cf, "SSL shutdown sent, want receive");
  1522. connssl->io_need = CURL_SSL_IO_NEED_RECV;
  1523. break;
  1524. case WOLFSSL_ERROR_WANT_WRITE:
  1525. CURL_TRC_CF(data, cf, "SSL shutdown send blocked");
  1526. connssl->io_need = CURL_SSL_IO_NEED_SEND;
  1527. break;
  1528. default:
  1529. detail = wolfSSL_get_error(wctx->handle, err);
  1530. CURL_TRC_CF(data, cf, "SSL shutdown, error: '%s'(%d)",
  1531. wolfssl_strerror((unsigned long)err, error_buffer,
  1532. sizeof(error_buffer)),
  1533. detail);
  1534. result = CURLE_RECV_ERROR;
  1535. break;
  1536. }
  1537. out:
  1538. cf->shutdown = (result || *done);
  1539. return result;
  1540. }
  1541. static void wolfssl_close(struct Curl_cfilter *cf, struct Curl_easy *data)
  1542. {
  1543. struct ssl_connect_data *connssl = cf->ctx;
  1544. struct wolfssl_ctx *backend =
  1545. (struct wolfssl_ctx *)connssl->backend;
  1546. (void) data;
  1547. DEBUGASSERT(backend);
  1548. if(backend->handle) {
  1549. wolfSSL_free(backend->handle);
  1550. backend->handle = NULL;
  1551. }
  1552. if(backend->ctx) {
  1553. wolfSSL_CTX_free(backend->ctx);
  1554. backend->ctx = NULL;
  1555. }
  1556. }
  1557. static ssize_t wolfssl_recv(struct Curl_cfilter *cf,
  1558. struct Curl_easy *data,
  1559. char *buf, size_t blen,
  1560. CURLcode *curlcode)
  1561. {
  1562. struct ssl_connect_data *connssl = cf->ctx;
  1563. struct wolfssl_ctx *backend =
  1564. (struct wolfssl_ctx *)connssl->backend;
  1565. int buffsize = (blen > (size_t)INT_MAX) ? INT_MAX : (int)blen;
  1566. int nread;
  1567. DEBUGASSERT(backend);
  1568. wolfSSL_ERR_clear_error();
  1569. *curlcode = CURLE_OK;
  1570. nread = wolfSSL_read(backend->handle, buf, buffsize);
  1571. if(nread <= 0) {
  1572. int err = wolfSSL_get_error(backend->handle, nread);
  1573. switch(err) {
  1574. case WOLFSSL_ERROR_ZERO_RETURN: /* no more data */
  1575. CURL_TRC_CF(data, cf, "wolfssl_recv(len=%zu) -> CLOSED", blen);
  1576. *curlcode = CURLE_OK;
  1577. return 0;
  1578. case WOLFSSL_ERROR_NONE:
  1579. case WOLFSSL_ERROR_WANT_READ:
  1580. case WOLFSSL_ERROR_WANT_WRITE:
  1581. if(!backend->io_result && connssl->peer_closed) {
  1582. CURL_TRC_CF(data, cf, "wolfssl_recv(len=%zu) -> CLOSED", blen);
  1583. *curlcode = CURLE_OK;
  1584. return 0;
  1585. }
  1586. /* there is data pending, re-invoke wolfSSL_read() */
  1587. CURL_TRC_CF(data, cf, "wolfssl_recv(len=%zu) -> AGAIN", blen);
  1588. *curlcode = CURLE_AGAIN;
  1589. return -1;
  1590. default:
  1591. if(backend->io_result == CURLE_AGAIN) {
  1592. CURL_TRC_CF(data, cf, "wolfssl_recv(len=%zu) -> AGAIN", blen);
  1593. *curlcode = CURLE_AGAIN;
  1594. return -1;
  1595. }
  1596. else if(!backend->io_result && connssl->peer_closed) {
  1597. CURL_TRC_CF(data, cf, "wolfssl_recv(len=%zu) -> CLOSED", blen);
  1598. *curlcode = CURLE_OK;
  1599. return 0;
  1600. }
  1601. else {
  1602. char error_buffer[256];
  1603. failf(data, "SSL read: %s, errno %d",
  1604. wolfssl_strerror((unsigned long)err, error_buffer,
  1605. sizeof(error_buffer)),
  1606. SOCKERRNO);
  1607. }
  1608. *curlcode = CURLE_RECV_ERROR;
  1609. return -1;
  1610. }
  1611. }
  1612. CURL_TRC_CF(data, cf, "wolfssl_recv(len=%zu) -> %d", blen, nread);
  1613. return nread;
  1614. }
  1615. static size_t wolfssl_version(char *buffer, size_t size)
  1616. {
  1617. #if LIBWOLFSSL_VERSION_HEX >= 0x03006000
  1618. return msnprintf(buffer, size, "wolfSSL/%s", wolfSSL_lib_version());
  1619. #elif defined(WOLFSSL_VERSION)
  1620. return msnprintf(buffer, size, "wolfSSL/%s", WOLFSSL_VERSION);
  1621. #endif
  1622. }
  1623. static int wolfssl_init(void)
  1624. {
  1625. int ret;
  1626. #ifdef OPENSSL_EXTRA
  1627. Curl_tls_keylog_open();
  1628. #endif
  1629. ret = (wolfSSL_Init() == WOLFSSL_SUCCESS);
  1630. wolfssl_bio_cf_init_methods();
  1631. return ret;
  1632. }
  1633. static void wolfssl_cleanup(void)
  1634. {
  1635. wolfssl_bio_cf_free_methods();
  1636. wolfSSL_Cleanup();
  1637. #ifdef OPENSSL_EXTRA
  1638. Curl_tls_keylog_close();
  1639. #endif
  1640. }
  1641. static bool wolfssl_data_pending(struct Curl_cfilter *cf,
  1642. const struct Curl_easy *data)
  1643. {
  1644. struct ssl_connect_data *ctx = cf->ctx;
  1645. struct wolfssl_ctx *backend;
  1646. (void)data;
  1647. DEBUGASSERT(ctx && ctx->backend);
  1648. backend = (struct wolfssl_ctx *)ctx->backend;
  1649. if(backend->handle) /* SSL is in use */
  1650. return wolfSSL_pending(backend->handle);
  1651. else
  1652. return FALSE;
  1653. }
  1654. static CURLcode
  1655. wolfssl_connect_common(struct Curl_cfilter *cf,
  1656. struct Curl_easy *data,
  1657. bool nonblocking,
  1658. bool *done)
  1659. {
  1660. CURLcode result;
  1661. struct ssl_connect_data *connssl = cf->ctx;
  1662. curl_socket_t sockfd = Curl_conn_cf_get_socket(cf, data);
  1663. /* check if the connection has already been established */
  1664. if(ssl_connection_complete == connssl->state) {
  1665. *done = TRUE;
  1666. return CURLE_OK;
  1667. }
  1668. if(ssl_connect_1 == connssl->connecting_state) {
  1669. /* Find out how much more time we are allowed */
  1670. const timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE);
  1671. if(timeout_ms < 0) {
  1672. /* no need to continue if time already is up */
  1673. failf(data, "SSL connection timeout");
  1674. return CURLE_OPERATION_TIMEDOUT;
  1675. }
  1676. result = wolfssl_connect_step1(cf, data);
  1677. if(result)
  1678. return result;
  1679. }
  1680. while(ssl_connect_2 == connssl->connecting_state) {
  1681. /* check allowed time left */
  1682. const timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE);
  1683. if(timeout_ms < 0) {
  1684. /* no need to continue if time already is up */
  1685. failf(data, "SSL connection timeout");
  1686. return CURLE_OPERATION_TIMEDOUT;
  1687. }
  1688. /* if ssl is expecting something, check if it is available. */
  1689. if(connssl->io_need) {
  1690. curl_socket_t writefd = (connssl->io_need & CURL_SSL_IO_NEED_SEND) ?
  1691. sockfd : CURL_SOCKET_BAD;
  1692. curl_socket_t readfd = (connssl->io_need & CURL_SSL_IO_NEED_RECV) ?
  1693. sockfd : CURL_SOCKET_BAD;
  1694. int what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
  1695. nonblocking ? 0 : timeout_ms);
  1696. if(what < 0) {
  1697. /* fatal error */
  1698. failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
  1699. return CURLE_SSL_CONNECT_ERROR;
  1700. }
  1701. else if(0 == what) {
  1702. if(nonblocking) {
  1703. *done = FALSE;
  1704. return CURLE_OK;
  1705. }
  1706. else {
  1707. /* timeout */
  1708. failf(data, "SSL connection timeout");
  1709. return CURLE_OPERATION_TIMEDOUT;
  1710. }
  1711. }
  1712. /* socket is readable or writable */
  1713. }
  1714. /* Run transaction, and return to the caller if it failed or if
  1715. * this connection is part of a multi handle and this loop would
  1716. * execute again. This permits the owner of a multi handle to
  1717. * abort a connection attempt before step2 has completed while
  1718. * ensuring that a client using select() or epoll() will always
  1719. * have a valid fdset to wait on.
  1720. */
  1721. result = wolfssl_connect_step2(cf, data);
  1722. if(result || (nonblocking && (ssl_connect_2 == connssl->connecting_state)))
  1723. return result;
  1724. } /* repeat step2 until all transactions are done. */
  1725. if(ssl_connect_3 == connssl->connecting_state) {
  1726. /* In other backends, this is where we verify the certificate, but
  1727. * wolfSSL already does that as part of the handshake. */
  1728. connssl->connecting_state = ssl_connect_done;
  1729. }
  1730. if(ssl_connect_done == connssl->connecting_state) {
  1731. connssl->state = ssl_connection_complete;
  1732. *done = TRUE;
  1733. }
  1734. else
  1735. *done = FALSE;
  1736. /* Reset our connect state machine */
  1737. connssl->connecting_state = ssl_connect_1;
  1738. return CURLE_OK;
  1739. }
  1740. static CURLcode wolfssl_connect_nonblocking(struct Curl_cfilter *cf,
  1741. struct Curl_easy *data,
  1742. bool *done)
  1743. {
  1744. return wolfssl_connect_common(cf, data, TRUE, done);
  1745. }
  1746. static CURLcode wolfssl_connect(struct Curl_cfilter *cf,
  1747. struct Curl_easy *data)
  1748. {
  1749. CURLcode result;
  1750. bool done = FALSE;
  1751. result = wolfssl_connect_common(cf, data, FALSE, &done);
  1752. if(result)
  1753. return result;
  1754. DEBUGASSERT(done);
  1755. return CURLE_OK;
  1756. }
  1757. static CURLcode wolfssl_random(struct Curl_easy *data,
  1758. unsigned char *entropy, size_t length)
  1759. {
  1760. WC_RNG rng;
  1761. (void)data;
  1762. if(wc_InitRng(&rng))
  1763. return CURLE_FAILED_INIT;
  1764. if(length > UINT_MAX)
  1765. return CURLE_FAILED_INIT;
  1766. if(wc_RNG_GenerateBlock(&rng, entropy, (unsigned)length))
  1767. return CURLE_FAILED_INIT;
  1768. if(wc_FreeRng(&rng))
  1769. return CURLE_FAILED_INIT;
  1770. return CURLE_OK;
  1771. }
  1772. static CURLcode wolfssl_sha256sum(const unsigned char *tmp, /* input */
  1773. size_t tmplen,
  1774. unsigned char *sha256sum /* output */,
  1775. size_t unused)
  1776. {
  1777. wc_Sha256 SHA256pw;
  1778. (void)unused;
  1779. if(wc_InitSha256(&SHA256pw))
  1780. return CURLE_FAILED_INIT;
  1781. wc_Sha256Update(&SHA256pw, tmp, (word32)tmplen);
  1782. wc_Sha256Final(&SHA256pw, sha256sum);
  1783. return CURLE_OK;
  1784. }
  1785. static void *wolfssl_get_internals(struct ssl_connect_data *connssl,
  1786. CURLINFO info UNUSED_PARAM)
  1787. {
  1788. struct wolfssl_ctx *backend =
  1789. (struct wolfssl_ctx *)connssl->backend;
  1790. (void)info;
  1791. DEBUGASSERT(backend);
  1792. return backend->handle;
  1793. }
  1794. const struct Curl_ssl Curl_ssl_wolfssl = {
  1795. { CURLSSLBACKEND_WOLFSSL, "wolfssl" }, /* info */
  1796. #ifdef KEEP_PEER_CERT
  1797. SSLSUPP_PINNEDPUBKEY |
  1798. #endif
  1799. #ifdef USE_BIO_CHAIN
  1800. SSLSUPP_HTTPS_PROXY |
  1801. #endif
  1802. SSLSUPP_CA_PATH |
  1803. SSLSUPP_CAINFO_BLOB |
  1804. #ifdef USE_ECH
  1805. SSLSUPP_ECH |
  1806. #endif
  1807. SSLSUPP_SSL_CTX |
  1808. #ifdef WOLFSSL_TLS13
  1809. SSLSUPP_TLS13_CIPHERSUITES |
  1810. #endif
  1811. SSLSUPP_CA_CACHE |
  1812. SSLSUPP_CIPHER_LIST,
  1813. sizeof(struct wolfssl_ctx),
  1814. wolfssl_init, /* init */
  1815. wolfssl_cleanup, /* cleanup */
  1816. wolfssl_version, /* version */
  1817. Curl_none_check_cxn, /* check_cxn */
  1818. wolfssl_shutdown, /* shutdown */
  1819. wolfssl_data_pending, /* data_pending */
  1820. wolfssl_random, /* random */
  1821. Curl_none_cert_status_request, /* cert_status_request */
  1822. wolfssl_connect, /* connect */
  1823. wolfssl_connect_nonblocking, /* connect_nonblocking */
  1824. Curl_ssl_adjust_pollset, /* adjust_pollset */
  1825. wolfssl_get_internals, /* get_internals */
  1826. wolfssl_close, /* close_one */
  1827. Curl_none_close_all, /* close_all */
  1828. Curl_none_set_engine, /* set_engine */
  1829. Curl_none_set_engine_default, /* set_engine_default */
  1830. Curl_none_engines_list, /* engines_list */
  1831. Curl_none_false_start, /* false_start */
  1832. wolfssl_sha256sum, /* sha256sum */
  1833. NULL, /* associate_connection */
  1834. NULL, /* disassociate_connection */
  1835. wolfssl_recv, /* recv decrypted data */
  1836. wolfssl_send, /* send data to encrypt */
  1837. NULL, /* get_channel_binding */
  1838. };
  1839. #endif