2
0

wolfssl.c 59 KB

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