2
0

gtls.c 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024
  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 GnuTLS-specific code for the TLS/SSL layer. No code
  26. * but vtls.c should ever call or use these functions.
  27. *
  28. * Note: do not use the GnuTLS' *_t variable type names in this source code,
  29. * since they were not present in 1.0.X.
  30. */
  31. #include "curl_setup.h"
  32. #ifdef USE_GNUTLS
  33. #include <gnutls/abstract.h>
  34. #include <gnutls/gnutls.h>
  35. #include <gnutls/x509.h>
  36. #include <gnutls/crypto.h>
  37. #include <nettle/sha2.h>
  38. #include "urldata.h"
  39. #include "sendf.h"
  40. #include "inet_pton.h"
  41. #include "keylog.h"
  42. #include "gtls.h"
  43. #include "vtls.h"
  44. #include "vtls_int.h"
  45. #include "vauth/vauth.h"
  46. #include "parsedate.h"
  47. #include "connect.h" /* for the connect timeout */
  48. #include "select.h"
  49. #include "strcase.h"
  50. #include "warnless.h"
  51. #include "x509asn1.h"
  52. #include "multiif.h"
  53. #include "curl_printf.h"
  54. #include "curl_memory.h"
  55. /* The last #include file should be: */
  56. #include "memdebug.h"
  57. #ifndef ARRAYSIZE
  58. #define ARRAYSIZE(A) (sizeof(A)/sizeof((A)[0]))
  59. #endif
  60. #define QUIC_PRIORITY \
  61. "NORMAL:-VERS-ALL:+VERS-TLS1.3:-CIPHER-ALL:+AES-128-GCM:+AES-256-GCM:" \
  62. "+CHACHA20-POLY1305:+AES-128-CCM:-GROUP-ALL:+GROUP-SECP256R1:" \
  63. "+GROUP-X25519:+GROUP-SECP384R1:+GROUP-SECP521R1:" \
  64. "%DISABLE_TLS13_COMPAT_MODE"
  65. /* Enable GnuTLS debugging by defining GTLSDEBUG */
  66. /*#define GTLSDEBUG */
  67. #ifdef GTLSDEBUG
  68. static void tls_log_func(int level, const char *str)
  69. {
  70. fprintf(stderr, "|<%d>| %s", level, str);
  71. }
  72. #endif
  73. static bool gtls_inited = FALSE;
  74. #if !defined(GNUTLS_VERSION_NUMBER) || (GNUTLS_VERSION_NUMBER < 0x03010a)
  75. #error "too old GnuTLS version"
  76. #endif
  77. # include <gnutls/ocsp.h>
  78. struct gtls_ssl_backend_data {
  79. struct gtls_ctx gtls;
  80. };
  81. static ssize_t gtls_push(void *s, const void *buf, size_t blen)
  82. {
  83. struct Curl_cfilter *cf = s;
  84. struct ssl_connect_data *connssl = cf->ctx;
  85. struct gtls_ssl_backend_data *backend =
  86. (struct gtls_ssl_backend_data *)connssl->backend;
  87. struct Curl_easy *data = CF_DATA_CURRENT(cf);
  88. ssize_t nwritten;
  89. CURLcode result;
  90. DEBUGASSERT(data);
  91. nwritten = Curl_conn_cf_send(cf->next, data, buf, blen, &result);
  92. CURL_TRC_CF(data, cf, "gtls_push(len=%zu) -> %zd, err=%d",
  93. blen, nwritten, result);
  94. backend->gtls.io_result = result;
  95. if(nwritten < 0) {
  96. gnutls_transport_set_errno(backend->gtls.session,
  97. (CURLE_AGAIN == result)? EAGAIN : EINVAL);
  98. nwritten = -1;
  99. }
  100. return nwritten;
  101. }
  102. static ssize_t gtls_pull(void *s, void *buf, size_t blen)
  103. {
  104. struct Curl_cfilter *cf = s;
  105. struct ssl_connect_data *connssl = cf->ctx;
  106. struct gtls_ssl_backend_data *backend =
  107. (struct gtls_ssl_backend_data *)connssl->backend;
  108. struct Curl_easy *data = CF_DATA_CURRENT(cf);
  109. ssize_t nread;
  110. CURLcode result;
  111. DEBUGASSERT(data);
  112. if(!backend->gtls.shared_creds->trust_setup) {
  113. result = Curl_gtls_client_trust_setup(cf, data, &backend->gtls);
  114. if(result) {
  115. gnutls_transport_set_errno(backend->gtls.session, EINVAL);
  116. backend->gtls.io_result = result;
  117. return -1;
  118. }
  119. }
  120. nread = Curl_conn_cf_recv(cf->next, data, buf, blen, &result);
  121. CURL_TRC_CF(data, cf, "glts_pull(len=%zu) -> %zd, err=%d",
  122. blen, nread, result);
  123. backend->gtls.io_result = result;
  124. if(nread < 0) {
  125. gnutls_transport_set_errno(backend->gtls.session,
  126. (CURLE_AGAIN == result)? EAGAIN : EINVAL);
  127. nread = -1;
  128. }
  129. else if(nread == 0)
  130. connssl->peer_closed = TRUE;
  131. return nread;
  132. }
  133. /* gtls_init()
  134. *
  135. * Global GnuTLS init, called from Curl_ssl_init(). This calls functions that
  136. * are not thread-safe and thus this function itself is not thread-safe and
  137. * must only be called from within curl_global_init() to keep the thread
  138. * situation under control!
  139. */
  140. static int gtls_init(void)
  141. {
  142. int ret = 1;
  143. if(!gtls_inited) {
  144. ret = gnutls_global_init()?0:1;
  145. #ifdef GTLSDEBUG
  146. gnutls_global_set_log_function(tls_log_func);
  147. gnutls_global_set_log_level(2);
  148. #endif
  149. gtls_inited = TRUE;
  150. }
  151. return ret;
  152. }
  153. static void gtls_cleanup(void)
  154. {
  155. if(gtls_inited) {
  156. gnutls_global_deinit();
  157. gtls_inited = FALSE;
  158. }
  159. }
  160. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  161. static void showtime(struct Curl_easy *data,
  162. const char *text,
  163. time_t stamp)
  164. {
  165. struct tm buffer;
  166. const struct tm *tm = &buffer;
  167. char str[96];
  168. CURLcode result = Curl_gmtime(stamp, &buffer);
  169. if(result)
  170. return;
  171. msnprintf(str,
  172. sizeof(str),
  173. " %s: %s, %02d %s %4d %02d:%02d:%02d GMT",
  174. text,
  175. Curl_wkday[tm->tm_wday?tm->tm_wday-1:6],
  176. tm->tm_mday,
  177. Curl_month[tm->tm_mon],
  178. tm->tm_year + 1900,
  179. tm->tm_hour,
  180. tm->tm_min,
  181. tm->tm_sec);
  182. infof(data, "%s", str);
  183. }
  184. #endif
  185. static gnutls_datum_t load_file(const char *file)
  186. {
  187. FILE *f;
  188. gnutls_datum_t loaded_file = { NULL, 0 };
  189. long filelen;
  190. void *ptr;
  191. f = fopen(file, "rb");
  192. if(!f)
  193. return loaded_file;
  194. if(fseek(f, 0, SEEK_END) != 0
  195. || (filelen = ftell(f)) < 0
  196. || fseek(f, 0, SEEK_SET) != 0
  197. || !(ptr = malloc((size_t)filelen)))
  198. goto out;
  199. if(fread(ptr, 1, (size_t)filelen, f) < (size_t)filelen) {
  200. free(ptr);
  201. goto out;
  202. }
  203. loaded_file.data = ptr;
  204. loaded_file.size = (unsigned int)filelen;
  205. out:
  206. fclose(f);
  207. return loaded_file;
  208. }
  209. static void unload_file(gnutls_datum_t data)
  210. {
  211. free(data.data);
  212. }
  213. /* this function does a SSL/TLS (re-)handshake */
  214. static CURLcode handshake(struct Curl_cfilter *cf,
  215. struct Curl_easy *data,
  216. bool duringconnect,
  217. bool nonblocking)
  218. {
  219. struct ssl_connect_data *connssl = cf->ctx;
  220. struct gtls_ssl_backend_data *backend =
  221. (struct gtls_ssl_backend_data *)connssl->backend;
  222. gnutls_session_t session;
  223. curl_socket_t sockfd = Curl_conn_cf_get_socket(cf, data);
  224. DEBUGASSERT(backend);
  225. session = backend->gtls.session;
  226. connssl->connecting_state = ssl_connect_2;
  227. for(;;) {
  228. timediff_t timeout_ms;
  229. int rc;
  230. /* check allowed time left */
  231. timeout_ms = Curl_timeleft(data, NULL, duringconnect);
  232. if(timeout_ms < 0) {
  233. /* no need to continue if time already is up */
  234. failf(data, "SSL connection timeout");
  235. return CURLE_OPERATION_TIMEDOUT;
  236. }
  237. /* if ssl is expecting something, check if it is available. */
  238. if(connssl->io_need) {
  239. int what;
  240. curl_socket_t writefd = (connssl->io_need & CURL_SSL_IO_NEED_SEND)?
  241. sockfd:CURL_SOCKET_BAD;
  242. curl_socket_t readfd = (connssl->io_need & CURL_SSL_IO_NEED_RECV)?
  243. sockfd:CURL_SOCKET_BAD;
  244. what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
  245. nonblocking?0:
  246. timeout_ms?timeout_ms:1000);
  247. if(what < 0) {
  248. /* fatal error */
  249. failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
  250. return CURLE_SSL_CONNECT_ERROR;
  251. }
  252. else if(0 == what) {
  253. if(nonblocking)
  254. return CURLE_OK;
  255. else if(timeout_ms) {
  256. /* timeout */
  257. failf(data, "SSL connection timeout at %ld", (long)timeout_ms);
  258. return CURLE_OPERATION_TIMEDOUT;
  259. }
  260. }
  261. /* socket is readable or writable */
  262. }
  263. connssl->io_need = CURL_SSL_IO_NEED_NONE;
  264. backend->gtls.io_result = CURLE_OK;
  265. rc = gnutls_handshake(session);
  266. if(!backend->gtls.shared_creds->trust_setup) {
  267. /* After having send off the ClientHello, we prepare the trust
  268. * store to verify the coming certificate from the server */
  269. CURLcode result = Curl_gtls_client_trust_setup(cf, data, &backend->gtls);
  270. if(result)
  271. return result;
  272. }
  273. if((rc == GNUTLS_E_AGAIN) || (rc == GNUTLS_E_INTERRUPTED)) {
  274. connssl->io_need =
  275. gnutls_record_get_direction(session)?
  276. CURL_SSL_IO_NEED_SEND:CURL_SSL_IO_NEED_RECV;
  277. continue;
  278. }
  279. else if((rc < 0) && !gnutls_error_is_fatal(rc)) {
  280. const char *strerr = NULL;
  281. if(rc == GNUTLS_E_WARNING_ALERT_RECEIVED) {
  282. gnutls_alert_description_t alert = gnutls_alert_get(session);
  283. strerr = gnutls_alert_get_name(alert);
  284. }
  285. if(!strerr)
  286. strerr = gnutls_strerror(rc);
  287. infof(data, "gnutls_handshake() warning: %s", strerr);
  288. continue;
  289. }
  290. else if((rc < 0) && backend->gtls.io_result) {
  291. return backend->gtls.io_result;
  292. }
  293. else if(rc < 0) {
  294. const char *strerr = NULL;
  295. if(rc == GNUTLS_E_FATAL_ALERT_RECEIVED) {
  296. gnutls_alert_description_t alert = gnutls_alert_get(session);
  297. strerr = gnutls_alert_get_name(alert);
  298. }
  299. if(!strerr)
  300. strerr = gnutls_strerror(rc);
  301. failf(data, "gnutls_handshake() failed: %s", strerr);
  302. return CURLE_SSL_CONNECT_ERROR;
  303. }
  304. /* Reset our connect state machine */
  305. connssl->connecting_state = ssl_connect_1;
  306. return CURLE_OK;
  307. }
  308. }
  309. static gnutls_x509_crt_fmt_t do_file_type(const char *type)
  310. {
  311. if(!type || !type[0])
  312. return GNUTLS_X509_FMT_PEM;
  313. if(strcasecompare(type, "PEM"))
  314. return GNUTLS_X509_FMT_PEM;
  315. if(strcasecompare(type, "DER"))
  316. return GNUTLS_X509_FMT_DER;
  317. return GNUTLS_X509_FMT_PEM; /* default to PEM */
  318. }
  319. #define GNUTLS_CIPHERS "NORMAL:-ARCFOUR-128:-CTYPE-ALL:+CTYPE-X509"
  320. /* If GnuTLS was compiled without support for SRP it will error out if SRP is
  321. requested in the priority string, so treat it specially
  322. */
  323. #define GNUTLS_SRP "+SRP"
  324. static CURLcode
  325. set_ssl_version_min_max(struct Curl_easy *data,
  326. struct ssl_peer *peer,
  327. struct ssl_primary_config *conn_config,
  328. const char **prioritylist,
  329. const char *tls13support)
  330. {
  331. long ssl_version = conn_config->version;
  332. long ssl_version_max = conn_config->version_max;
  333. if((ssl_version == CURL_SSLVERSION_DEFAULT) ||
  334. (ssl_version == CURL_SSLVERSION_TLSv1))
  335. ssl_version = CURL_SSLVERSION_TLSv1_0;
  336. if(ssl_version_max == CURL_SSLVERSION_MAX_NONE)
  337. ssl_version_max = CURL_SSLVERSION_MAX_DEFAULT;
  338. if(peer->transport == TRNSPRT_QUIC) {
  339. if((ssl_version_max != CURL_SSLVERSION_MAX_DEFAULT) &&
  340. (ssl_version_max < CURL_SSLVERSION_MAX_TLSv1_3)) {
  341. failf(data, "QUIC needs at least TLS version 1.3");
  342. return CURLE_SSL_CONNECT_ERROR;
  343. }
  344. *prioritylist = QUIC_PRIORITY;
  345. return CURLE_OK;
  346. }
  347. if(!tls13support) {
  348. /* If the running GnuTLS does not support TLS 1.3, we must not specify a
  349. prioritylist involving that since it will make GnuTLS return an en
  350. error back at us */
  351. if((ssl_version_max == CURL_SSLVERSION_MAX_TLSv1_3) ||
  352. (ssl_version_max == CURL_SSLVERSION_MAX_DEFAULT)) {
  353. ssl_version_max = CURL_SSLVERSION_MAX_TLSv1_2;
  354. }
  355. }
  356. else if(ssl_version_max == CURL_SSLVERSION_MAX_DEFAULT) {
  357. ssl_version_max = CURL_SSLVERSION_MAX_TLSv1_3;
  358. }
  359. switch(ssl_version | ssl_version_max) {
  360. case CURL_SSLVERSION_TLSv1_0 | CURL_SSLVERSION_MAX_TLSv1_0:
  361. *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:"
  362. "+VERS-TLS1.0";
  363. return CURLE_OK;
  364. case CURL_SSLVERSION_TLSv1_0 | CURL_SSLVERSION_MAX_TLSv1_1:
  365. *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:"
  366. "+VERS-TLS1.1:+VERS-TLS1.0";
  367. return CURLE_OK;
  368. case CURL_SSLVERSION_TLSv1_0 | CURL_SSLVERSION_MAX_TLSv1_2:
  369. *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:"
  370. "+VERS-TLS1.2:+VERS-TLS1.1:+VERS-TLS1.0";
  371. return CURLE_OK;
  372. case CURL_SSLVERSION_TLSv1_1 | CURL_SSLVERSION_MAX_TLSv1_1:
  373. *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:"
  374. "+VERS-TLS1.1";
  375. return CURLE_OK;
  376. case CURL_SSLVERSION_TLSv1_1 | CURL_SSLVERSION_MAX_TLSv1_2:
  377. *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:"
  378. "+VERS-TLS1.2:+VERS-TLS1.1";
  379. return CURLE_OK;
  380. case CURL_SSLVERSION_TLSv1_2 | CURL_SSLVERSION_MAX_TLSv1_2:
  381. *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:"
  382. "+VERS-TLS1.2";
  383. return CURLE_OK;
  384. case CURL_SSLVERSION_TLSv1_3 | CURL_SSLVERSION_MAX_TLSv1_3:
  385. *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:"
  386. "+VERS-TLS1.3";
  387. return CURLE_OK;
  388. case CURL_SSLVERSION_TLSv1_0 | CURL_SSLVERSION_MAX_TLSv1_3:
  389. *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0";
  390. return CURLE_OK;
  391. case CURL_SSLVERSION_TLSv1_1 | CURL_SSLVERSION_MAX_TLSv1_3:
  392. *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:"
  393. "+VERS-TLS1.3:+VERS-TLS1.2:+VERS-TLS1.1";
  394. return CURLE_OK;
  395. case CURL_SSLVERSION_TLSv1_2 | CURL_SSLVERSION_MAX_TLSv1_3:
  396. *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:"
  397. "+VERS-TLS1.3:+VERS-TLS1.2";
  398. return CURLE_OK;
  399. }
  400. failf(data, "GnuTLS: cannot set ssl protocol");
  401. return CURLE_SSL_CONNECT_ERROR;
  402. }
  403. CURLcode Curl_gtls_shared_creds_create(struct Curl_easy *data,
  404. struct gtls_shared_creds **pcreds)
  405. {
  406. struct gtls_shared_creds *shared;
  407. int rc;
  408. *pcreds = NULL;
  409. shared = calloc(1, sizeof(*shared));
  410. if(!shared)
  411. return CURLE_OUT_OF_MEMORY;
  412. rc = gnutls_certificate_allocate_credentials(&shared->creds);
  413. if(rc != GNUTLS_E_SUCCESS) {
  414. failf(data, "gnutls_cert_all_cred() failed: %s", gnutls_strerror(rc));
  415. free(shared);
  416. return CURLE_SSL_CONNECT_ERROR;
  417. }
  418. shared->refcount = 1;
  419. shared->time = Curl_now();
  420. *pcreds = shared;
  421. return CURLE_OK;
  422. }
  423. CURLcode Curl_gtls_shared_creds_up_ref(struct gtls_shared_creds *creds)
  424. {
  425. DEBUGASSERT(creds);
  426. if(creds->refcount < SIZE_T_MAX) {
  427. ++creds->refcount;
  428. return CURLE_OK;
  429. }
  430. return CURLE_BAD_FUNCTION_ARGUMENT;
  431. }
  432. void Curl_gtls_shared_creds_free(struct gtls_shared_creds **pcreds)
  433. {
  434. struct gtls_shared_creds *shared = *pcreds;
  435. *pcreds = NULL;
  436. if(shared) {
  437. --shared->refcount;
  438. if(!shared->refcount) {
  439. gnutls_certificate_free_credentials(shared->creds);
  440. free(shared->CAfile);
  441. free(shared);
  442. }
  443. }
  444. }
  445. static CURLcode gtls_populate_creds(struct Curl_cfilter *cf,
  446. struct Curl_easy *data,
  447. gnutls_certificate_credentials_t creds)
  448. {
  449. struct ssl_primary_config *config = Curl_ssl_cf_get_primary_config(cf);
  450. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  451. int rc;
  452. if(config->verifypeer) {
  453. bool imported_native_ca = false;
  454. if(ssl_config->native_ca_store) {
  455. rc = gnutls_certificate_set_x509_system_trust(creds);
  456. if(rc < 0)
  457. infof(data, "error reading native ca store (%s), continuing anyway",
  458. gnutls_strerror(rc));
  459. else {
  460. infof(data, "found %d certificates in native ca store", rc);
  461. if(rc > 0)
  462. imported_native_ca = true;
  463. }
  464. }
  465. if(config->CAfile) {
  466. /* set the trusted CA cert bundle file */
  467. gnutls_certificate_set_verify_flags(creds,
  468. GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT);
  469. rc = gnutls_certificate_set_x509_trust_file(creds,
  470. config->CAfile,
  471. GNUTLS_X509_FMT_PEM);
  472. if(rc < 0) {
  473. infof(data, "error reading ca cert file %s (%s)%s",
  474. config->CAfile, gnutls_strerror(rc),
  475. (imported_native_ca ? ", continuing anyway" : ""));
  476. if(!imported_native_ca) {
  477. ssl_config->certverifyresult = rc;
  478. return CURLE_SSL_CACERT_BADFILE;
  479. }
  480. }
  481. else
  482. infof(data, "found %d certificates in %s", rc, config->CAfile);
  483. }
  484. if(config->CApath) {
  485. /* set the trusted CA cert directory */
  486. rc = gnutls_certificate_set_x509_trust_dir(creds, config->CApath,
  487. GNUTLS_X509_FMT_PEM);
  488. if(rc < 0) {
  489. infof(data, "error reading ca cert file %s (%s)%s",
  490. config->CApath, gnutls_strerror(rc),
  491. (imported_native_ca ? ", continuing anyway" : ""));
  492. if(!imported_native_ca) {
  493. ssl_config->certverifyresult = rc;
  494. return CURLE_SSL_CACERT_BADFILE;
  495. }
  496. }
  497. else
  498. infof(data, "found %d certificates in %s", rc, config->CApath);
  499. }
  500. }
  501. if(config->CRLfile) {
  502. /* set the CRL list file */
  503. rc = gnutls_certificate_set_x509_crl_file(creds, config->CRLfile,
  504. GNUTLS_X509_FMT_PEM);
  505. if(rc < 0) {
  506. failf(data, "error reading crl file %s (%s)",
  507. config->CRLfile, gnutls_strerror(rc));
  508. return CURLE_SSL_CRL_BADFILE;
  509. }
  510. else
  511. infof(data, "found %d CRL in %s", rc, config->CRLfile);
  512. }
  513. return CURLE_OK;
  514. }
  515. /* key to use at `multi->proto_hash` */
  516. #define MPROTO_GTLS_X509_KEY "tls:gtls:x509:share"
  517. static bool gtls_shared_creds_expired(const struct Curl_easy *data,
  518. const struct gtls_shared_creds *sc)
  519. {
  520. const struct ssl_general_config *cfg = &data->set.general_ssl;
  521. struct curltime now = Curl_now();
  522. timediff_t elapsed_ms = Curl_timediff(now, sc->time);
  523. timediff_t timeout_ms = cfg->ca_cache_timeout * (timediff_t)1000;
  524. if(timeout_ms < 0)
  525. return false;
  526. return elapsed_ms >= timeout_ms;
  527. }
  528. static bool gtls_shared_creds_different(struct Curl_cfilter *cf,
  529. const struct gtls_shared_creds *sc)
  530. {
  531. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  532. if(!sc->CAfile || !conn_config->CAfile)
  533. return sc->CAfile != conn_config->CAfile;
  534. return strcmp(sc->CAfile, conn_config->CAfile);
  535. }
  536. static struct gtls_shared_creds*
  537. gtls_get_cached_creds(struct Curl_cfilter *cf, struct Curl_easy *data)
  538. {
  539. struct gtls_shared_creds *shared_creds;
  540. if(data->multi) {
  541. shared_creds = Curl_hash_pick(&data->multi->proto_hash,
  542. (void *)MPROTO_GTLS_X509_KEY,
  543. sizeof(MPROTO_GTLS_X509_KEY)-1);
  544. if(shared_creds && shared_creds->creds &&
  545. !gtls_shared_creds_expired(data, shared_creds) &&
  546. !gtls_shared_creds_different(cf, shared_creds)) {
  547. return shared_creds;
  548. }
  549. }
  550. return NULL;
  551. }
  552. static void gtls_shared_creds_hash_free(void *key, size_t key_len, void *p)
  553. {
  554. struct gtls_shared_creds *sc = p;
  555. DEBUGASSERT(key_len == (sizeof(MPROTO_GTLS_X509_KEY)-1));
  556. DEBUGASSERT(!memcmp(MPROTO_GTLS_X509_KEY, key, key_len));
  557. (void)key;
  558. (void)key_len;
  559. Curl_gtls_shared_creds_free(&sc); /* down reference */
  560. }
  561. static void gtls_set_cached_creds(struct Curl_cfilter *cf,
  562. struct Curl_easy *data,
  563. struct gtls_shared_creds *sc)
  564. {
  565. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  566. DEBUGASSERT(sc);
  567. DEBUGASSERT(sc->creds);
  568. DEBUGASSERT(!sc->CAfile);
  569. DEBUGASSERT(sc->refcount == 1);
  570. if(!data->multi)
  571. return;
  572. if(conn_config->CAfile) {
  573. sc->CAfile = strdup(conn_config->CAfile);
  574. if(!sc->CAfile)
  575. return;
  576. }
  577. if(Curl_gtls_shared_creds_up_ref(sc))
  578. return;
  579. if(!Curl_hash_add2(&data->multi->proto_hash,
  580. (void *)MPROTO_GTLS_X509_KEY,
  581. sizeof(MPROTO_GTLS_X509_KEY)-1,
  582. sc, gtls_shared_creds_hash_free)) {
  583. Curl_gtls_shared_creds_free(&sc); /* down reference again */
  584. return;
  585. }
  586. }
  587. CURLcode Curl_gtls_client_trust_setup(struct Curl_cfilter *cf,
  588. struct Curl_easy *data,
  589. struct gtls_ctx *gtls)
  590. {
  591. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  592. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  593. struct gtls_shared_creds *cached_creds = NULL;
  594. bool cache_criteria_met;
  595. CURLcode result;
  596. int rc;
  597. /* Consider the X509 store cacheable if it comes exclusively from a CAfile,
  598. or no source is provided and we are falling back to OpenSSL's built-in
  599. default. */
  600. cache_criteria_met = (data->set.general_ssl.ca_cache_timeout != 0) &&
  601. conn_config->verifypeer &&
  602. !conn_config->CApath &&
  603. !conn_config->ca_info_blob &&
  604. !ssl_config->primary.CRLfile &&
  605. !ssl_config->native_ca_store &&
  606. !conn_config->clientcert; /* GnuTLS adds client cert to its credentials! */
  607. if(cache_criteria_met)
  608. cached_creds = gtls_get_cached_creds(cf, data);
  609. if(cached_creds && !Curl_gtls_shared_creds_up_ref(cached_creds)) {
  610. CURL_TRC_CF(data, cf, "using shared trust anchors and CRLs");
  611. Curl_gtls_shared_creds_free(&gtls->shared_creds);
  612. gtls->shared_creds = cached_creds;
  613. rc = gnutls_credentials_set(gtls->session, GNUTLS_CRD_CERTIFICATE,
  614. gtls->shared_creds->creds);
  615. if(rc != GNUTLS_E_SUCCESS) {
  616. failf(data, "gnutls_credentials_set() failed: %s", gnutls_strerror(rc));
  617. return CURLE_SSL_CONNECT_ERROR;
  618. }
  619. }
  620. else {
  621. CURL_TRC_CF(data, cf, "loading trust anchors and CRLs");
  622. result = gtls_populate_creds(cf, data, gtls->shared_creds->creds);
  623. if(result)
  624. return result;
  625. gtls->shared_creds->trust_setup = TRUE;
  626. if(cache_criteria_met)
  627. gtls_set_cached_creds(cf, data, gtls->shared_creds);
  628. }
  629. return CURLE_OK;
  630. }
  631. static void gtls_sessionid_free(void *sessionid, size_t idsize)
  632. {
  633. (void)idsize;
  634. free(sessionid);
  635. }
  636. static CURLcode gtls_update_session_id(struct Curl_cfilter *cf,
  637. struct Curl_easy *data,
  638. gnutls_session_t session)
  639. {
  640. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  641. struct ssl_connect_data *connssl = cf->ctx;
  642. CURLcode result = CURLE_OK;
  643. if(ssl_config->primary.cache_session) {
  644. /* we always unconditionally get the session id here, as even if we
  645. already got it from the cache and asked to use it in the connection, it
  646. might've been rejected and then a new one is in use now and we need to
  647. detect that. */
  648. void *connect_sessionid;
  649. size_t connect_idsize = 0;
  650. /* get the session ID data size */
  651. gnutls_session_get_data(session, NULL, &connect_idsize);
  652. connect_sessionid = malloc(connect_idsize); /* get a buffer for it */
  653. if(!connect_sessionid) {
  654. return CURLE_OUT_OF_MEMORY;
  655. }
  656. else {
  657. /* extract session ID to the allocated buffer */
  658. gnutls_session_get_data(session, connect_sessionid, &connect_idsize);
  659. CURL_TRC_CF(data, cf, "get session id (len=%zu) and store in cache",
  660. connect_idsize);
  661. Curl_ssl_sessionid_lock(data);
  662. /* store this session id, takes ownership */
  663. result = Curl_ssl_set_sessionid(cf, data, &connssl->peer,
  664. connect_sessionid, connect_idsize,
  665. gtls_sessionid_free);
  666. Curl_ssl_sessionid_unlock(data);
  667. }
  668. }
  669. return result;
  670. }
  671. static int gtls_handshake_cb(gnutls_session_t session, unsigned int htype,
  672. unsigned when, unsigned int incoming,
  673. const gnutls_datum_t *msg)
  674. {
  675. struct Curl_cfilter *cf = gnutls_session_get_ptr(session);
  676. (void)msg;
  677. (void)incoming;
  678. if(when) { /* after message has been processed */
  679. struct Curl_easy *data = CF_DATA_CURRENT(cf);
  680. if(data) {
  681. CURL_TRC_CF(data, cf, "handshake: %s message type %d",
  682. incoming? "incoming" : "outgoing", htype);
  683. switch(htype) {
  684. case GNUTLS_HANDSHAKE_NEW_SESSION_TICKET: {
  685. gtls_update_session_id(cf, data, session);
  686. break;
  687. }
  688. default:
  689. break;
  690. }
  691. }
  692. }
  693. return 0;
  694. }
  695. static CURLcode gtls_client_init(struct Curl_cfilter *cf,
  696. struct Curl_easy *data,
  697. struct ssl_peer *peer,
  698. struct gtls_ctx *gtls)
  699. {
  700. struct ssl_primary_config *config = Curl_ssl_cf_get_primary_config(cf);
  701. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  702. unsigned int init_flags;
  703. int rc;
  704. bool sni = TRUE; /* default is SNI enabled */
  705. const char *prioritylist;
  706. const char *err = NULL;
  707. const char *tls13support;
  708. CURLcode result;
  709. if(!gtls_inited)
  710. gtls_init();
  711. if(config->version == CURL_SSLVERSION_SSLv2) {
  712. failf(data, "GnuTLS does not support SSLv2");
  713. return CURLE_SSL_CONNECT_ERROR;
  714. }
  715. else if(config->version == CURL_SSLVERSION_SSLv3)
  716. sni = FALSE; /* SSLv3 has no SNI */
  717. /* allocate a shared creds struct */
  718. result = Curl_gtls_shared_creds_create(data, &gtls->shared_creds);
  719. if(result)
  720. return result;
  721. #ifdef USE_GNUTLS_SRP
  722. if(config->username && Curl_auth_allowed_to_host(data)) {
  723. infof(data, "Using TLS-SRP username: %s", config->username);
  724. rc = gnutls_srp_allocate_client_credentials(&gtls->srp_client_cred);
  725. if(rc != GNUTLS_E_SUCCESS) {
  726. failf(data, "gnutls_srp_allocate_client_cred() failed: %s",
  727. gnutls_strerror(rc));
  728. return CURLE_OUT_OF_MEMORY;
  729. }
  730. rc = gnutls_srp_set_client_credentials(gtls->srp_client_cred,
  731. config->username,
  732. config->password);
  733. if(rc != GNUTLS_E_SUCCESS) {
  734. failf(data, "gnutls_srp_set_client_cred() failed: %s",
  735. gnutls_strerror(rc));
  736. return CURLE_BAD_FUNCTION_ARGUMENT;
  737. }
  738. }
  739. #endif
  740. ssl_config->certverifyresult = 0;
  741. /* Initialize TLS session as a client */
  742. init_flags = GNUTLS_CLIENT;
  743. #if defined(GNUTLS_FORCE_CLIENT_CERT)
  744. init_flags |= GNUTLS_FORCE_CLIENT_CERT;
  745. #endif
  746. #if defined(GNUTLS_NO_TICKETS)
  747. /* Disable TLS session tickets */
  748. init_flags |= GNUTLS_NO_TICKETS;
  749. #endif
  750. rc = gnutls_init(&gtls->session, init_flags);
  751. if(rc != GNUTLS_E_SUCCESS) {
  752. failf(data, "gnutls_init() failed: %d", rc);
  753. return CURLE_SSL_CONNECT_ERROR;
  754. }
  755. if(sni && peer->sni) {
  756. if(gnutls_server_name_set(gtls->session, GNUTLS_NAME_DNS,
  757. peer->sni, strlen(peer->sni)) < 0) {
  758. failf(data, "Failed to set SNI");
  759. return CURLE_SSL_CONNECT_ERROR;
  760. }
  761. }
  762. /* Use default priorities */
  763. rc = gnutls_set_default_priority(gtls->session);
  764. if(rc != GNUTLS_E_SUCCESS)
  765. return CURLE_SSL_CONNECT_ERROR;
  766. /* "In GnuTLS 3.6.5, TLS 1.3 is enabled by default" */
  767. tls13support = gnutls_check_version("3.6.5");
  768. /* Ensure +SRP comes at the *end* of all relevant strings so that it can be
  769. * removed if a runtime error indicates that SRP is not supported by this
  770. * GnuTLS version */
  771. if(config->version == CURL_SSLVERSION_SSLv2 ||
  772. config->version == CURL_SSLVERSION_SSLv3) {
  773. failf(data, "GnuTLS does not support SSLv2 or SSLv3");
  774. return CURLE_SSL_CONNECT_ERROR;
  775. }
  776. if(config->version == CURL_SSLVERSION_TLSv1_3) {
  777. if(!tls13support) {
  778. failf(data, "This GnuTLS installation does not support TLS 1.3");
  779. return CURLE_SSL_CONNECT_ERROR;
  780. }
  781. }
  782. /* At this point we know we have a supported TLS version, so set it */
  783. result = set_ssl_version_min_max(data, peer,
  784. config, &prioritylist, tls13support);
  785. if(result)
  786. return result;
  787. #ifdef USE_GNUTLS_SRP
  788. /* Only add SRP to the cipher list if SRP is requested. Otherwise
  789. * GnuTLS will disable TLS 1.3 support. */
  790. if(config->username) {
  791. char *prioritysrp = aprintf("%s:" GNUTLS_SRP, prioritylist);
  792. if(!prioritysrp)
  793. return CURLE_OUT_OF_MEMORY;
  794. rc = gnutls_priority_set_direct(gtls->session, prioritysrp, &err);
  795. free(prioritysrp);
  796. if((rc == GNUTLS_E_INVALID_REQUEST) && err) {
  797. infof(data, "This GnuTLS does not support SRP");
  798. }
  799. }
  800. else {
  801. #endif
  802. infof(data, "GnuTLS ciphers: %s", prioritylist);
  803. rc = gnutls_priority_set_direct(gtls->session, prioritylist, &err);
  804. #ifdef USE_GNUTLS_SRP
  805. }
  806. #endif
  807. if(rc != GNUTLS_E_SUCCESS) {
  808. failf(data, "Error %d setting GnuTLS cipher list starting with %s",
  809. rc, err);
  810. return CURLE_SSL_CONNECT_ERROR;
  811. }
  812. if(config->clientcert) {
  813. if(!gtls->shared_creds->trust_setup) {
  814. result = Curl_gtls_client_trust_setup(cf, data, gtls);
  815. if(result)
  816. return result;
  817. }
  818. if(ssl_config->key_passwd) {
  819. const unsigned int supported_key_encryption_algorithms =
  820. GNUTLS_PKCS_USE_PKCS12_3DES | GNUTLS_PKCS_USE_PKCS12_ARCFOUR |
  821. GNUTLS_PKCS_USE_PKCS12_RC2_40 | GNUTLS_PKCS_USE_PBES2_3DES |
  822. GNUTLS_PKCS_USE_PBES2_AES_128 | GNUTLS_PKCS_USE_PBES2_AES_192 |
  823. GNUTLS_PKCS_USE_PBES2_AES_256;
  824. rc = gnutls_certificate_set_x509_key_file2(
  825. gtls->shared_creds->creds,
  826. config->clientcert,
  827. ssl_config->key ? ssl_config->key : config->clientcert,
  828. do_file_type(ssl_config->cert_type),
  829. ssl_config->key_passwd,
  830. supported_key_encryption_algorithms);
  831. if(rc != GNUTLS_E_SUCCESS) {
  832. failf(data,
  833. "error reading X.509 potentially-encrypted key file: %s",
  834. gnutls_strerror(rc));
  835. return CURLE_SSL_CONNECT_ERROR;
  836. }
  837. }
  838. else {
  839. if(gnutls_certificate_set_x509_key_file(
  840. gtls->shared_creds->creds,
  841. config->clientcert,
  842. ssl_config->key ? ssl_config->key : config->clientcert,
  843. do_file_type(ssl_config->cert_type) ) !=
  844. GNUTLS_E_SUCCESS) {
  845. failf(data, "error reading X.509 key or certificate file");
  846. return CURLE_SSL_CONNECT_ERROR;
  847. }
  848. }
  849. }
  850. #ifdef USE_GNUTLS_SRP
  851. /* put the credentials to the current session */
  852. if(config->username) {
  853. rc = gnutls_credentials_set(gtls->session, GNUTLS_CRD_SRP,
  854. gtls->srp_client_cred);
  855. if(rc != GNUTLS_E_SUCCESS) {
  856. failf(data, "gnutls_credentials_set() failed: %s", gnutls_strerror(rc));
  857. return CURLE_SSL_CONNECT_ERROR;
  858. }
  859. }
  860. else
  861. #endif
  862. {
  863. rc = gnutls_credentials_set(gtls->session, GNUTLS_CRD_CERTIFICATE,
  864. gtls->shared_creds->creds);
  865. if(rc != GNUTLS_E_SUCCESS) {
  866. failf(data, "gnutls_credentials_set() failed: %s", gnutls_strerror(rc));
  867. return CURLE_SSL_CONNECT_ERROR;
  868. }
  869. }
  870. if(config->verifystatus) {
  871. rc = gnutls_ocsp_status_request_enable_client(gtls->session,
  872. NULL, 0, NULL);
  873. if(rc != GNUTLS_E_SUCCESS) {
  874. failf(data, "gnutls_ocsp_status_request_enable_client() failed: %d", rc);
  875. return CURLE_SSL_CONNECT_ERROR;
  876. }
  877. }
  878. return CURLE_OK;
  879. }
  880. static int keylog_callback(gnutls_session_t session, const char *label,
  881. const gnutls_datum_t *secret)
  882. {
  883. gnutls_datum_t crandom;
  884. gnutls_datum_t srandom;
  885. gnutls_session_get_random(session, &crandom, &srandom);
  886. if(crandom.size != 32) {
  887. return -1;
  888. }
  889. Curl_tls_keylog_write(label, crandom.data, secret->data, secret->size);
  890. return 0;
  891. }
  892. CURLcode Curl_gtls_ctx_init(struct gtls_ctx *gctx,
  893. struct Curl_cfilter *cf,
  894. struct Curl_easy *data,
  895. struct ssl_peer *peer,
  896. const unsigned char *alpn, size_t alpn_len,
  897. Curl_gtls_ctx_setup_cb *cb_setup,
  898. void *cb_user_data,
  899. void *ssl_user_data)
  900. {
  901. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  902. CURLcode result;
  903. DEBUGASSERT(gctx);
  904. result = gtls_client_init(cf, data, peer, gctx);
  905. if(result)
  906. return result;
  907. gnutls_session_set_ptr(gctx->session, ssl_user_data);
  908. if(cb_setup) {
  909. result = cb_setup(cf, data, cb_user_data);
  910. if(result)
  911. return result;
  912. }
  913. /* Open the file if a TLS or QUIC backend has not done this before. */
  914. Curl_tls_keylog_open();
  915. if(Curl_tls_keylog_enabled()) {
  916. gnutls_session_set_keylog_function(gctx->session, keylog_callback);
  917. }
  918. /* convert the ALPN string from our arguments to a list of strings
  919. * that gnutls wants and will convert internally back to this very
  920. * string for sending to the server. nice. */
  921. if(alpn && alpn_len) {
  922. gnutls_datum_t alpns[5];
  923. size_t i, alen = alpn_len;
  924. unsigned char *s = (unsigned char *)alpn;
  925. unsigned char slen;
  926. for(i = 0; (i < ARRAYSIZE(alpns)) && alen; ++i) {
  927. slen = s[0];
  928. if(slen >= alen)
  929. return CURLE_FAILED_INIT;
  930. alpns[i].data = s + 1;
  931. alpns[i].size = slen;
  932. s += slen + 1;
  933. alen -= (size_t)slen + 1;
  934. }
  935. if(alen) /* not all alpn chars used, wrong format or too many */
  936. return CURLE_FAILED_INIT;
  937. if(i && gnutls_alpn_set_protocols(gctx->session,
  938. alpns, (unsigned int)i,
  939. GNUTLS_ALPN_MANDATORY)) {
  940. failf(data, "failed setting ALPN");
  941. return CURLE_SSL_CONNECT_ERROR;
  942. }
  943. }
  944. /* This might be a reconnect, so we check for a session ID in the cache
  945. to speed up things */
  946. if(conn_config->cache_session) {
  947. void *ssl_sessionid;
  948. size_t ssl_idsize;
  949. Curl_ssl_sessionid_lock(data);
  950. if(!Curl_ssl_getsessionid(cf, data, peer, &ssl_sessionid, &ssl_idsize)) {
  951. /* we got a session id, use it! */
  952. int rc;
  953. rc = gnutls_session_set_data(gctx->session, ssl_sessionid, ssl_idsize);
  954. if(rc < 0)
  955. infof(data, "SSL failed to set session ID");
  956. else
  957. infof(data, "SSL reusing session ID (size=%zu)", ssl_idsize);
  958. }
  959. Curl_ssl_sessionid_unlock(data);
  960. }
  961. return CURLE_OK;
  962. }
  963. static CURLcode
  964. gtls_connect_step1(struct Curl_cfilter *cf, struct Curl_easy *data)
  965. {
  966. struct ssl_connect_data *connssl = cf->ctx;
  967. struct gtls_ssl_backend_data *backend =
  968. (struct gtls_ssl_backend_data *)connssl->backend;
  969. struct alpn_proto_buf proto;
  970. CURLcode result;
  971. DEBUGASSERT(backend);
  972. DEBUGASSERT(ssl_connect_1 == connssl->connecting_state);
  973. if(connssl->state == ssl_connection_complete)
  974. /* to make us tolerant against being called more than once for the
  975. same connection */
  976. return CURLE_OK;
  977. memset(&proto, 0, sizeof(proto));
  978. if(connssl->alpn) {
  979. result = Curl_alpn_to_proto_buf(&proto, connssl->alpn);
  980. if(result) {
  981. failf(data, "Error determining ALPN");
  982. return CURLE_SSL_CONNECT_ERROR;
  983. }
  984. }
  985. result = Curl_gtls_ctx_init(&backend->gtls, cf, data, &connssl->peer,
  986. proto.data, proto.len, NULL, NULL, cf);
  987. if(result)
  988. return result;
  989. gnutls_handshake_set_hook_function(backend->gtls.session,
  990. GNUTLS_HANDSHAKE_ANY, GNUTLS_HOOK_POST,
  991. gtls_handshake_cb);
  992. /* register callback functions and handle to send and receive data. */
  993. gnutls_transport_set_ptr(backend->gtls.session, cf);
  994. gnutls_transport_set_push_function(backend->gtls.session, gtls_push);
  995. gnutls_transport_set_pull_function(backend->gtls.session, gtls_pull);
  996. return CURLE_OK;
  997. }
  998. static CURLcode pkp_pin_peer_pubkey(struct Curl_easy *data,
  999. gnutls_x509_crt_t cert,
  1000. const char *pinnedpubkey)
  1001. {
  1002. /* Scratch */
  1003. size_t len1 = 0, len2 = 0;
  1004. unsigned char *buff1 = NULL;
  1005. gnutls_pubkey_t key = NULL;
  1006. /* Result is returned to caller */
  1007. CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
  1008. /* if a path was not specified, do not pin */
  1009. if(!pinnedpubkey)
  1010. return CURLE_OK;
  1011. if(!cert)
  1012. return result;
  1013. do {
  1014. int ret;
  1015. /* Begin Gyrations to get the public key */
  1016. gnutls_pubkey_init(&key);
  1017. ret = gnutls_pubkey_import_x509(key, cert, 0);
  1018. if(ret < 0)
  1019. break; /* failed */
  1020. ret = gnutls_pubkey_export(key, GNUTLS_X509_FMT_DER, NULL, &len1);
  1021. if(ret != GNUTLS_E_SHORT_MEMORY_BUFFER || len1 == 0)
  1022. break; /* failed */
  1023. buff1 = malloc(len1);
  1024. if(!buff1)
  1025. break; /* failed */
  1026. len2 = len1;
  1027. ret = gnutls_pubkey_export(key, GNUTLS_X509_FMT_DER, buff1, &len2);
  1028. if(ret < 0 || len1 != len2)
  1029. break; /* failed */
  1030. /* End Gyrations */
  1031. /* The one good exit point */
  1032. result = Curl_pin_peer_pubkey(data, pinnedpubkey, buff1, len1);
  1033. } while(0);
  1034. if(key)
  1035. gnutls_pubkey_deinit(key);
  1036. Curl_safefree(buff1);
  1037. return result;
  1038. }
  1039. CURLcode
  1040. Curl_gtls_verifyserver(struct Curl_easy *data,
  1041. gnutls_session_t session,
  1042. struct ssl_primary_config *config,
  1043. struct ssl_config_data *ssl_config,
  1044. struct ssl_peer *peer,
  1045. const char *pinned_key)
  1046. {
  1047. unsigned int cert_list_size;
  1048. const gnutls_datum_t *chainp;
  1049. unsigned int verify_status = 0;
  1050. gnutls_x509_crt_t x509_cert, x509_issuer;
  1051. gnutls_datum_t issuerp;
  1052. gnutls_datum_t certfields;
  1053. char certname[65] = ""; /* limited to 64 chars by ASN.1 */
  1054. size_t size;
  1055. time_t certclock;
  1056. int rc;
  1057. CURLcode result = CURLE_OK;
  1058. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  1059. const char *ptr;
  1060. int algo;
  1061. unsigned int bits;
  1062. gnutls_protocol_t version = gnutls_protocol_get_version(session);
  1063. #endif
  1064. long * const certverifyresult = &ssl_config->certverifyresult;
  1065. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  1066. /* the name of the cipher suite used, e.g. ECDHE_RSA_AES_256_GCM_SHA384. */
  1067. ptr = gnutls_cipher_suite_get_name(gnutls_kx_get(session),
  1068. gnutls_cipher_get(session),
  1069. gnutls_mac_get(session));
  1070. infof(data, "SSL connection using %s / %s",
  1071. gnutls_protocol_get_name(version), ptr);
  1072. #endif
  1073. /* This function will return the peer's raw certificate (chain) as sent by
  1074. the peer. These certificates are in raw format (DER encoded for
  1075. X.509). In case of a X.509 then a certificate list may be present. The
  1076. first certificate in the list is the peer's certificate, following the
  1077. issuer's certificate, then the issuer's issuer etc. */
  1078. chainp = gnutls_certificate_get_peers(session, &cert_list_size);
  1079. if(!chainp) {
  1080. if(config->verifypeer ||
  1081. config->verifyhost ||
  1082. config->issuercert) {
  1083. #ifdef USE_GNUTLS_SRP
  1084. if(ssl_config->primary.username && !config->verifypeer &&
  1085. gnutls_cipher_get(session)) {
  1086. /* no peer cert, but auth is ok if we have SRP user and cipher and no
  1087. peer verify */
  1088. }
  1089. else {
  1090. #endif
  1091. failf(data, "failed to get server cert");
  1092. *certverifyresult = GNUTLS_E_NO_CERTIFICATE_FOUND;
  1093. return CURLE_PEER_FAILED_VERIFICATION;
  1094. #ifdef USE_GNUTLS_SRP
  1095. }
  1096. #endif
  1097. }
  1098. infof(data, " common name: WARNING could not obtain");
  1099. }
  1100. if(data->set.ssl.certinfo && chainp) {
  1101. unsigned int i;
  1102. result = Curl_ssl_init_certinfo(data, (int)cert_list_size);
  1103. if(result)
  1104. return result;
  1105. for(i = 0; i < cert_list_size; i++) {
  1106. const char *beg = (const char *) chainp[i].data;
  1107. const char *end = beg + chainp[i].size;
  1108. result = Curl_extract_certinfo(data, (int)i, beg, end);
  1109. if(result)
  1110. return result;
  1111. }
  1112. }
  1113. if(config->verifypeer) {
  1114. /* This function will try to verify the peer's certificate and return its
  1115. status (trusted, invalid etc.). The value of status should be one or
  1116. more of the gnutls_certificate_status_t enumerated elements bitwise
  1117. or'd. To avoid denial of service attacks some default upper limits
  1118. regarding the certificate key size and chain size are set. To override
  1119. them use gnutls_certificate_set_verify_limits(). */
  1120. rc = gnutls_certificate_verify_peers2(session, &verify_status);
  1121. if(rc < 0) {
  1122. failf(data, "server cert verify failed: %d", rc);
  1123. *certverifyresult = rc;
  1124. return CURLE_SSL_CONNECT_ERROR;
  1125. }
  1126. *certverifyresult = verify_status;
  1127. /* verify_status is a bitmask of gnutls_certificate_status bits */
  1128. if(verify_status & GNUTLS_CERT_INVALID) {
  1129. if(config->verifypeer) {
  1130. failf(data, "server certificate verification failed. CAfile: %s "
  1131. "CRLfile: %s", config->CAfile ? config->CAfile:
  1132. "none",
  1133. ssl_config->primary.CRLfile ?
  1134. ssl_config->primary.CRLfile : "none");
  1135. return CURLE_PEER_FAILED_VERIFICATION;
  1136. }
  1137. else
  1138. infof(data, " server certificate verification FAILED");
  1139. }
  1140. else
  1141. infof(data, " server certificate verification OK");
  1142. }
  1143. else
  1144. infof(data, " server certificate verification SKIPPED");
  1145. if(config->verifystatus) {
  1146. if(gnutls_ocsp_status_request_is_checked(session, 0) == 0) {
  1147. gnutls_datum_t status_request;
  1148. gnutls_ocsp_resp_t ocsp_resp;
  1149. gnutls_ocsp_cert_status_t status;
  1150. gnutls_x509_crl_reason_t reason;
  1151. rc = gnutls_ocsp_status_request_get(session, &status_request);
  1152. infof(data, " server certificate status verification FAILED");
  1153. if(rc == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) {
  1154. failf(data, "No OCSP response received");
  1155. return CURLE_SSL_INVALIDCERTSTATUS;
  1156. }
  1157. if(rc < 0) {
  1158. failf(data, "Invalid OCSP response received");
  1159. return CURLE_SSL_INVALIDCERTSTATUS;
  1160. }
  1161. gnutls_ocsp_resp_init(&ocsp_resp);
  1162. rc = gnutls_ocsp_resp_import(ocsp_resp, &status_request);
  1163. if(rc < 0) {
  1164. failf(data, "Invalid OCSP response received");
  1165. return CURLE_SSL_INVALIDCERTSTATUS;
  1166. }
  1167. (void)gnutls_ocsp_resp_get_single(ocsp_resp, 0, NULL, NULL, NULL, NULL,
  1168. &status, NULL, NULL, NULL, &reason);
  1169. switch(status) {
  1170. case GNUTLS_OCSP_CERT_GOOD:
  1171. break;
  1172. case GNUTLS_OCSP_CERT_REVOKED: {
  1173. const char *crl_reason;
  1174. switch(reason) {
  1175. default:
  1176. case GNUTLS_X509_CRLREASON_UNSPECIFIED:
  1177. crl_reason = "unspecified reason";
  1178. break;
  1179. case GNUTLS_X509_CRLREASON_KEYCOMPROMISE:
  1180. crl_reason = "private key compromised";
  1181. break;
  1182. case GNUTLS_X509_CRLREASON_CACOMPROMISE:
  1183. crl_reason = "CA compromised";
  1184. break;
  1185. case GNUTLS_X509_CRLREASON_AFFILIATIONCHANGED:
  1186. crl_reason = "affiliation has changed";
  1187. break;
  1188. case GNUTLS_X509_CRLREASON_SUPERSEDED:
  1189. crl_reason = "certificate superseded";
  1190. break;
  1191. case GNUTLS_X509_CRLREASON_CESSATIONOFOPERATION:
  1192. crl_reason = "operation has ceased";
  1193. break;
  1194. case GNUTLS_X509_CRLREASON_CERTIFICATEHOLD:
  1195. crl_reason = "certificate is on hold";
  1196. break;
  1197. case GNUTLS_X509_CRLREASON_REMOVEFROMCRL:
  1198. crl_reason = "will be removed from delta CRL";
  1199. break;
  1200. case GNUTLS_X509_CRLREASON_PRIVILEGEWITHDRAWN:
  1201. crl_reason = "privilege withdrawn";
  1202. break;
  1203. case GNUTLS_X509_CRLREASON_AACOMPROMISE:
  1204. crl_reason = "AA compromised";
  1205. break;
  1206. }
  1207. failf(data, "Server certificate was revoked: %s", crl_reason);
  1208. break;
  1209. }
  1210. default:
  1211. case GNUTLS_OCSP_CERT_UNKNOWN:
  1212. failf(data, "Server certificate status is unknown");
  1213. break;
  1214. }
  1215. gnutls_ocsp_resp_deinit(ocsp_resp);
  1216. return CURLE_SSL_INVALIDCERTSTATUS;
  1217. }
  1218. else
  1219. infof(data, " server certificate status verification OK");
  1220. }
  1221. else
  1222. infof(data, " server certificate status verification SKIPPED");
  1223. /* initialize an X.509 certificate structure. */
  1224. gnutls_x509_crt_init(&x509_cert);
  1225. if(chainp)
  1226. /* convert the given DER or PEM encoded Certificate to the native
  1227. gnutls_x509_crt_t format */
  1228. gnutls_x509_crt_import(x509_cert, chainp, GNUTLS_X509_FMT_DER);
  1229. if(config->issuercert) {
  1230. gnutls_x509_crt_init(&x509_issuer);
  1231. issuerp = load_file(config->issuercert);
  1232. gnutls_x509_crt_import(x509_issuer, &issuerp, GNUTLS_X509_FMT_PEM);
  1233. rc = (int)gnutls_x509_crt_check_issuer(x509_cert, x509_issuer);
  1234. gnutls_x509_crt_deinit(x509_issuer);
  1235. unload_file(issuerp);
  1236. if(rc <= 0) {
  1237. failf(data, "server certificate issuer check failed (IssuerCert: %s)",
  1238. config->issuercert?config->issuercert:"none");
  1239. gnutls_x509_crt_deinit(x509_cert);
  1240. return CURLE_SSL_ISSUER_ERROR;
  1241. }
  1242. infof(data, " server certificate issuer check OK (Issuer Cert: %s)",
  1243. config->issuercert?config->issuercert:"none");
  1244. }
  1245. size = sizeof(certname);
  1246. rc = gnutls_x509_crt_get_dn_by_oid(x509_cert, GNUTLS_OID_X520_COMMON_NAME,
  1247. 0, /* the first and only one */
  1248. FALSE,
  1249. certname,
  1250. &size);
  1251. if(rc) {
  1252. infof(data, "error fetching CN from cert:%s",
  1253. gnutls_strerror(rc));
  1254. }
  1255. /* This function will check if the given certificate's subject matches the
  1256. given hostname. This is a basic implementation of the matching described
  1257. in RFC2818 (HTTPS), which takes into account wildcards, and the subject
  1258. alternative name PKIX extension. Returns non zero on success, and zero on
  1259. failure. */
  1260. /* This function does not handle trailing dots, so if we have an SNI name
  1261. use that and fallback to the hostname only if there is no SNI (like for
  1262. IP addresses) */
  1263. rc = (int)gnutls_x509_crt_check_hostname(x509_cert,
  1264. peer->sni ? peer->sni :
  1265. peer->hostname);
  1266. #if GNUTLS_VERSION_NUMBER < 0x030306
  1267. /* Before 3.3.6, gnutls_x509_crt_check_hostname() did not check IP
  1268. addresses. */
  1269. if(!rc) {
  1270. #ifdef USE_IPV6
  1271. #define use_addr in6_addr
  1272. #else
  1273. #define use_addr in_addr
  1274. #endif
  1275. unsigned char addrbuf[sizeof(struct use_addr)];
  1276. size_t addrlen = 0;
  1277. if(Curl_inet_pton(AF_INET, peer->hostname, addrbuf) > 0)
  1278. addrlen = 4;
  1279. #ifdef USE_IPV6
  1280. else if(Curl_inet_pton(AF_INET6, peer->hostname, addrbuf) > 0)
  1281. addrlen = 16;
  1282. #endif
  1283. if(addrlen) {
  1284. unsigned char certaddr[sizeof(struct use_addr)];
  1285. int i;
  1286. for(i = 0; ; i++) {
  1287. size_t certaddrlen = sizeof(certaddr);
  1288. int ret = gnutls_x509_crt_get_subject_alt_name(x509_cert, i, certaddr,
  1289. &certaddrlen, NULL);
  1290. /* If this happens, it was not an IP address. */
  1291. if(ret == GNUTLS_E_SHORT_MEMORY_BUFFER)
  1292. continue;
  1293. if(ret < 0)
  1294. break;
  1295. if(ret != GNUTLS_SAN_IPADDRESS)
  1296. continue;
  1297. if(certaddrlen == addrlen && !memcmp(addrbuf, certaddr, addrlen)) {
  1298. rc = 1;
  1299. break;
  1300. }
  1301. }
  1302. }
  1303. }
  1304. #endif
  1305. if(!rc) {
  1306. if(config->verifyhost) {
  1307. failf(data, "SSL: certificate subject name (%s) does not match "
  1308. "target hostname '%s'", certname, peer->dispname);
  1309. gnutls_x509_crt_deinit(x509_cert);
  1310. return CURLE_PEER_FAILED_VERIFICATION;
  1311. }
  1312. else
  1313. infof(data, " common name: %s (does not match '%s')",
  1314. certname, peer->dispname);
  1315. }
  1316. else
  1317. infof(data, " common name: %s (matched)", certname);
  1318. /* Check for time-based validity */
  1319. certclock = gnutls_x509_crt_get_expiration_time(x509_cert);
  1320. if(certclock == (time_t)-1) {
  1321. if(config->verifypeer) {
  1322. failf(data, "server cert expiration date verify failed");
  1323. *certverifyresult = GNUTLS_CERT_EXPIRED;
  1324. gnutls_x509_crt_deinit(x509_cert);
  1325. return CURLE_SSL_CONNECT_ERROR;
  1326. }
  1327. else
  1328. infof(data, " server certificate expiration date verify FAILED");
  1329. }
  1330. else {
  1331. if(certclock < time(NULL)) {
  1332. if(config->verifypeer) {
  1333. failf(data, "server certificate expiration date has passed.");
  1334. *certverifyresult = GNUTLS_CERT_EXPIRED;
  1335. gnutls_x509_crt_deinit(x509_cert);
  1336. return CURLE_PEER_FAILED_VERIFICATION;
  1337. }
  1338. else
  1339. infof(data, " server certificate expiration date FAILED");
  1340. }
  1341. else
  1342. infof(data, " server certificate expiration date OK");
  1343. }
  1344. certclock = gnutls_x509_crt_get_activation_time(x509_cert);
  1345. if(certclock == (time_t)-1) {
  1346. if(config->verifypeer) {
  1347. failf(data, "server cert activation date verify failed");
  1348. *certverifyresult = GNUTLS_CERT_NOT_ACTIVATED;
  1349. gnutls_x509_crt_deinit(x509_cert);
  1350. return CURLE_SSL_CONNECT_ERROR;
  1351. }
  1352. else
  1353. infof(data, " server certificate activation date verify FAILED");
  1354. }
  1355. else {
  1356. if(certclock > time(NULL)) {
  1357. if(config->verifypeer) {
  1358. failf(data, "server certificate not activated yet.");
  1359. *certverifyresult = GNUTLS_CERT_NOT_ACTIVATED;
  1360. gnutls_x509_crt_deinit(x509_cert);
  1361. return CURLE_PEER_FAILED_VERIFICATION;
  1362. }
  1363. else
  1364. infof(data, " server certificate activation date FAILED");
  1365. }
  1366. else
  1367. infof(data, " server certificate activation date OK");
  1368. }
  1369. if(pinned_key) {
  1370. result = pkp_pin_peer_pubkey(data, x509_cert, pinned_key);
  1371. if(result != CURLE_OK) {
  1372. failf(data, "SSL: public key does not match pinned public key");
  1373. gnutls_x509_crt_deinit(x509_cert);
  1374. return result;
  1375. }
  1376. }
  1377. /* Show:
  1378. - subject
  1379. - start date
  1380. - expire date
  1381. - common name
  1382. - issuer
  1383. */
  1384. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  1385. /* public key algorithm's parameters */
  1386. algo = gnutls_x509_crt_get_pk_algorithm(x509_cert, &bits);
  1387. infof(data, " certificate public key: %s",
  1388. gnutls_pk_algorithm_get_name((gnutls_pk_algorithm_t)algo));
  1389. /* version of the X.509 certificate. */
  1390. infof(data, " certificate version: #%d",
  1391. gnutls_x509_crt_get_version(x509_cert));
  1392. rc = gnutls_x509_crt_get_dn2(x509_cert, &certfields);
  1393. if(rc)
  1394. infof(data, "Failed to get certificate name");
  1395. else {
  1396. infof(data, " subject: %s", certfields.data);
  1397. certclock = gnutls_x509_crt_get_activation_time(x509_cert);
  1398. showtime(data, "start date", certclock);
  1399. certclock = gnutls_x509_crt_get_expiration_time(x509_cert);
  1400. showtime(data, "expire date", certclock);
  1401. gnutls_free(certfields.data);
  1402. }
  1403. rc = gnutls_x509_crt_get_issuer_dn2(x509_cert, &certfields);
  1404. if(rc)
  1405. infof(data, "Failed to get certificate issuer");
  1406. else {
  1407. infof(data, " issuer: %s", certfields.data);
  1408. gnutls_free(certfields.data);
  1409. }
  1410. #endif
  1411. gnutls_x509_crt_deinit(x509_cert);
  1412. return result;
  1413. }
  1414. static CURLcode gtls_verifyserver(struct Curl_cfilter *cf,
  1415. struct Curl_easy *data,
  1416. gnutls_session_t session)
  1417. {
  1418. struct ssl_connect_data *connssl = cf->ctx;
  1419. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  1420. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  1421. #ifndef CURL_DISABLE_PROXY
  1422. const char *pinned_key = Curl_ssl_cf_is_proxy(cf)?
  1423. data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY]:
  1424. data->set.str[STRING_SSL_PINNEDPUBLICKEY];
  1425. #else
  1426. const char *pinned_key = data->set.str[STRING_SSL_PINNEDPUBLICKEY];
  1427. #endif
  1428. CURLcode result;
  1429. result = Curl_gtls_verifyserver(data, session, conn_config, ssl_config,
  1430. &connssl->peer, pinned_key);
  1431. if(result)
  1432. goto out;
  1433. if(connssl->alpn) {
  1434. gnutls_datum_t proto;
  1435. int rc;
  1436. rc = gnutls_alpn_get_selected_protocol(session, &proto);
  1437. if(rc == 0)
  1438. Curl_alpn_set_negotiated(cf, data, proto.data, proto.size);
  1439. else
  1440. Curl_alpn_set_negotiated(cf, data, NULL, 0);
  1441. }
  1442. /* Only on TLSv1.2 or lower do we have the session id now. For
  1443. * TLSv1.3 we get it via a SESSION_TICKET message that arrives later. */
  1444. if(gnutls_protocol_get_version(session) < GNUTLS_TLS1_3)
  1445. result = gtls_update_session_id(cf, data, session);
  1446. out:
  1447. return result;
  1448. }
  1449. /*
  1450. * This function is called after the TCP connect has completed. Setup the TLS
  1451. * layer and do all necessary magic.
  1452. */
  1453. /* We use connssl->connecting_state to keep track of the connection status;
  1454. there are three states: 'ssl_connect_1' (not started yet or complete),
  1455. 'ssl_connect_2' (doing handshake with the server), and
  1456. 'ssl_connect_3' (verifying and getting stats).
  1457. */
  1458. static CURLcode
  1459. gtls_connect_common(struct Curl_cfilter *cf,
  1460. struct Curl_easy *data,
  1461. bool nonblocking,
  1462. bool *done)
  1463. {
  1464. struct ssl_connect_data *connssl = cf->ctx;
  1465. CURLcode rc;
  1466. CURLcode result = CURLE_OK;
  1467. /* Initiate the connection, if not already done */
  1468. if(ssl_connect_1 == connssl->connecting_state) {
  1469. rc = gtls_connect_step1(cf, data);
  1470. if(rc) {
  1471. result = rc;
  1472. goto out;
  1473. }
  1474. }
  1475. rc = handshake(cf, data, TRUE, nonblocking);
  1476. if(rc) {
  1477. /* handshake() sets its own error message with failf() */
  1478. result = rc;
  1479. goto out;
  1480. }
  1481. /* Finish connecting once the handshake is done */
  1482. if(ssl_connect_1 == connssl->connecting_state) {
  1483. struct gtls_ssl_backend_data *backend =
  1484. (struct gtls_ssl_backend_data *)connssl->backend;
  1485. gnutls_session_t session;
  1486. DEBUGASSERT(backend);
  1487. session = backend->gtls.session;
  1488. rc = gtls_verifyserver(cf, data, session);
  1489. if(rc) {
  1490. result = rc;
  1491. goto out;
  1492. }
  1493. connssl->state = ssl_connection_complete;
  1494. }
  1495. out:
  1496. *done = ssl_connect_1 == connssl->connecting_state;
  1497. return result;
  1498. }
  1499. static CURLcode gtls_connect_nonblocking(struct Curl_cfilter *cf,
  1500. struct Curl_easy *data,
  1501. bool *done)
  1502. {
  1503. return gtls_connect_common(cf, data, TRUE, done);
  1504. }
  1505. static CURLcode gtls_connect(struct Curl_cfilter *cf,
  1506. struct Curl_easy *data)
  1507. {
  1508. CURLcode result;
  1509. bool done = FALSE;
  1510. result = gtls_connect_common(cf, data, FALSE, &done);
  1511. if(result)
  1512. return result;
  1513. DEBUGASSERT(done);
  1514. return CURLE_OK;
  1515. }
  1516. static bool gtls_data_pending(struct Curl_cfilter *cf,
  1517. const struct Curl_easy *data)
  1518. {
  1519. struct ssl_connect_data *ctx = cf->ctx;
  1520. struct gtls_ssl_backend_data *backend;
  1521. (void)data;
  1522. DEBUGASSERT(ctx && ctx->backend);
  1523. backend = (struct gtls_ssl_backend_data *)ctx->backend;
  1524. if(backend->gtls.session &&
  1525. 0 != gnutls_record_check_pending(backend->gtls.session))
  1526. return TRUE;
  1527. return FALSE;
  1528. }
  1529. static ssize_t gtls_send(struct Curl_cfilter *cf,
  1530. struct Curl_easy *data,
  1531. const void *mem,
  1532. size_t len,
  1533. CURLcode *curlcode)
  1534. {
  1535. struct ssl_connect_data *connssl = cf->ctx;
  1536. struct gtls_ssl_backend_data *backend =
  1537. (struct gtls_ssl_backend_data *)connssl->backend;
  1538. ssize_t rc;
  1539. (void)data;
  1540. DEBUGASSERT(backend);
  1541. backend->gtls.io_result = CURLE_OK;
  1542. rc = gnutls_record_send(backend->gtls.session, mem, len);
  1543. if(rc < 0) {
  1544. *curlcode = (rc == GNUTLS_E_AGAIN)?
  1545. CURLE_AGAIN :
  1546. (backend->gtls.io_result? backend->gtls.io_result : CURLE_SEND_ERROR);
  1547. rc = -1;
  1548. }
  1549. return rc;
  1550. }
  1551. /*
  1552. * This function is called to shut down the SSL layer but keep the
  1553. * socket open (CCC - Clear Command Channel)
  1554. */
  1555. static CURLcode gtls_shutdown(struct Curl_cfilter *cf,
  1556. struct Curl_easy *data,
  1557. bool send_shutdown, bool *done)
  1558. {
  1559. struct ssl_connect_data *connssl = cf->ctx;
  1560. struct gtls_ssl_backend_data *backend =
  1561. (struct gtls_ssl_backend_data *)connssl->backend;
  1562. char buf[1024];
  1563. CURLcode result = CURLE_OK;
  1564. ssize_t nread;
  1565. size_t i;
  1566. DEBUGASSERT(backend);
  1567. if(!backend->gtls.session || cf->shutdown) {
  1568. *done = TRUE;
  1569. goto out;
  1570. }
  1571. connssl->io_need = CURL_SSL_IO_NEED_NONE;
  1572. *done = FALSE;
  1573. if(!backend->gtls.sent_shutdown) {
  1574. /* do this only once */
  1575. backend->gtls.sent_shutdown = TRUE;
  1576. if(send_shutdown) {
  1577. int ret = gnutls_bye(backend->gtls.session, GNUTLS_SHUT_RDWR);
  1578. if((ret == GNUTLS_E_AGAIN) || (ret == GNUTLS_E_INTERRUPTED)) {
  1579. CURL_TRC_CF(data, cf, "SSL shutdown, gnutls_bye EAGAIN");
  1580. connssl->io_need = gnutls_record_get_direction(backend->gtls.session)?
  1581. CURL_SSL_IO_NEED_SEND : CURL_SSL_IO_NEED_RECV;
  1582. result = CURLE_OK;
  1583. goto out;
  1584. }
  1585. if(ret != GNUTLS_E_SUCCESS) {
  1586. CURL_TRC_CF(data, cf, "SSL shutdown, gnutls_bye error: '%s'(%d)",
  1587. gnutls_strerror((int)ret), (int)ret);
  1588. result = CURLE_RECV_ERROR;
  1589. goto out;
  1590. }
  1591. }
  1592. }
  1593. /* SSL should now have started the shutdown from our side. Since it
  1594. * was not complete, we are lacking the close notify from the server. */
  1595. for(i = 0; i < 10; ++i) {
  1596. nread = gnutls_record_recv(backend->gtls.session, buf, sizeof(buf));
  1597. if(nread <= 0)
  1598. break;
  1599. }
  1600. if(nread > 0) {
  1601. /* still data coming in? */
  1602. }
  1603. else if(nread == 0) {
  1604. /* We got the close notify alert and are done. */
  1605. *done = TRUE;
  1606. }
  1607. else if((nread == GNUTLS_E_AGAIN) || (nread == GNUTLS_E_INTERRUPTED)) {
  1608. connssl->io_need = gnutls_record_get_direction(backend->gtls.session)?
  1609. CURL_SSL_IO_NEED_SEND : CURL_SSL_IO_NEED_RECV;
  1610. }
  1611. else {
  1612. CURL_TRC_CF(data, cf, "SSL shutdown, error: '%s'(%d)",
  1613. gnutls_strerror((int)nread), (int)nread);
  1614. result = CURLE_RECV_ERROR;
  1615. }
  1616. out:
  1617. cf->shutdown = (result || *done);
  1618. return result;
  1619. }
  1620. static void gtls_close(struct Curl_cfilter *cf,
  1621. struct Curl_easy *data)
  1622. {
  1623. struct ssl_connect_data *connssl = cf->ctx;
  1624. struct gtls_ssl_backend_data *backend =
  1625. (struct gtls_ssl_backend_data *)connssl->backend;
  1626. (void) data;
  1627. DEBUGASSERT(backend);
  1628. CURL_TRC_CF(data, cf, "close");
  1629. if(backend->gtls.session) {
  1630. gnutls_deinit(backend->gtls.session);
  1631. backend->gtls.session = NULL;
  1632. }
  1633. if(backend->gtls.shared_creds) {
  1634. Curl_gtls_shared_creds_free(&backend->gtls.shared_creds);
  1635. }
  1636. #ifdef USE_GNUTLS_SRP
  1637. if(backend->gtls.srp_client_cred) {
  1638. gnutls_srp_free_client_credentials(backend->gtls.srp_client_cred);
  1639. backend->gtls.srp_client_cred = NULL;
  1640. }
  1641. #endif
  1642. }
  1643. static ssize_t gtls_recv(struct Curl_cfilter *cf,
  1644. struct Curl_easy *data,
  1645. char *buf,
  1646. size_t buffersize,
  1647. CURLcode *curlcode)
  1648. {
  1649. struct ssl_connect_data *connssl = cf->ctx;
  1650. struct gtls_ssl_backend_data *backend =
  1651. (struct gtls_ssl_backend_data *)connssl->backend;
  1652. ssize_t ret;
  1653. (void)data;
  1654. DEBUGASSERT(backend);
  1655. backend->gtls.io_result = CURLE_OK;
  1656. ret = gnutls_record_recv(backend->gtls.session, buf, buffersize);
  1657. if((ret == GNUTLS_E_AGAIN) || (ret == GNUTLS_E_INTERRUPTED)) {
  1658. *curlcode = CURLE_AGAIN;
  1659. ret = -1;
  1660. goto out;
  1661. }
  1662. if(ret == GNUTLS_E_REHANDSHAKE) {
  1663. /* BLOCKING call, this is bad but a work-around for now. Fixing this "the
  1664. proper way" takes a whole lot of work. */
  1665. CURLcode result = handshake(cf, data, FALSE, FALSE);
  1666. if(result)
  1667. /* handshake() writes error message on its own */
  1668. *curlcode = result;
  1669. else
  1670. *curlcode = CURLE_AGAIN; /* then return as if this was a wouldblock */
  1671. ret = -1;
  1672. goto out;
  1673. }
  1674. if(ret < 0) {
  1675. failf(data, "GnuTLS recv error (%d): %s",
  1676. (int)ret, gnutls_strerror((int)ret));
  1677. *curlcode = backend->gtls.io_result?
  1678. backend->gtls.io_result : CURLE_RECV_ERROR;
  1679. ret = -1;
  1680. goto out;
  1681. }
  1682. out:
  1683. return ret;
  1684. }
  1685. static size_t gtls_version(char *buffer, size_t size)
  1686. {
  1687. return msnprintf(buffer, size, "GnuTLS/%s", gnutls_check_version(NULL));
  1688. }
  1689. /* data might be NULL! */
  1690. static CURLcode gtls_random(struct Curl_easy *data,
  1691. unsigned char *entropy, size_t length)
  1692. {
  1693. int rc;
  1694. (void)data;
  1695. rc = gnutls_rnd(GNUTLS_RND_RANDOM, entropy, length);
  1696. return rc?CURLE_FAILED_INIT:CURLE_OK;
  1697. }
  1698. static CURLcode gtls_sha256sum(const unsigned char *tmp, /* input */
  1699. size_t tmplen,
  1700. unsigned char *sha256sum, /* output */
  1701. size_t sha256len)
  1702. {
  1703. struct sha256_ctx SHA256pw;
  1704. sha256_init(&SHA256pw);
  1705. sha256_update(&SHA256pw, (unsigned int)tmplen, tmp);
  1706. sha256_digest(&SHA256pw, (unsigned int)sha256len, sha256sum);
  1707. return CURLE_OK;
  1708. }
  1709. static bool gtls_cert_status_request(void)
  1710. {
  1711. return TRUE;
  1712. }
  1713. static void *gtls_get_internals(struct ssl_connect_data *connssl,
  1714. CURLINFO info UNUSED_PARAM)
  1715. {
  1716. struct gtls_ssl_backend_data *backend =
  1717. (struct gtls_ssl_backend_data *)connssl->backend;
  1718. (void)info;
  1719. DEBUGASSERT(backend);
  1720. return backend->gtls.session;
  1721. }
  1722. const struct Curl_ssl Curl_ssl_gnutls = {
  1723. { CURLSSLBACKEND_GNUTLS, "gnutls" }, /* info */
  1724. SSLSUPP_CA_PATH |
  1725. SSLSUPP_CERTINFO |
  1726. SSLSUPP_PINNEDPUBKEY |
  1727. SSLSUPP_HTTPS_PROXY |
  1728. SSLSUPP_CA_CACHE,
  1729. sizeof(struct gtls_ssl_backend_data),
  1730. gtls_init, /* init */
  1731. gtls_cleanup, /* cleanup */
  1732. gtls_version, /* version */
  1733. Curl_none_check_cxn, /* check_cxn */
  1734. gtls_shutdown, /* shutdown */
  1735. gtls_data_pending, /* data_pending */
  1736. gtls_random, /* random */
  1737. gtls_cert_status_request, /* cert_status_request */
  1738. gtls_connect, /* connect */
  1739. gtls_connect_nonblocking, /* connect_nonblocking */
  1740. Curl_ssl_adjust_pollset, /* adjust_pollset */
  1741. gtls_get_internals, /* get_internals */
  1742. gtls_close, /* close_one */
  1743. Curl_none_close_all, /* close_all */
  1744. Curl_none_set_engine, /* set_engine */
  1745. Curl_none_set_engine_default, /* set_engine_default */
  1746. Curl_none_engines_list, /* engines_list */
  1747. Curl_none_false_start, /* false_start */
  1748. gtls_sha256sum, /* sha256sum */
  1749. NULL, /* associate_connection */
  1750. NULL, /* disassociate_connection */
  1751. gtls_recv, /* recv decrypted data */
  1752. gtls_send, /* send data to encrypt */
  1753. };
  1754. #endif /* USE_GNUTLS */