wolfssl.c 63 KB

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