gtls.c 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062
  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, FALSE, &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 gnutls_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. gnutls_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. #if defined(GNUTLS_NO_STATUS_REQUEST)
  751. if(!config->verifystatus)
  752. /* Disable the "status_request" TLS extension, enabled by default since
  753. GnuTLS 3.8.0. */
  754. init_flags |= GNUTLS_NO_STATUS_REQUEST;
  755. #endif
  756. rc = gnutls_init(&gtls->session, init_flags);
  757. if(rc != GNUTLS_E_SUCCESS) {
  758. failf(data, "gnutls_init() failed: %d", rc);
  759. return CURLE_SSL_CONNECT_ERROR;
  760. }
  761. if(sni && peer->sni) {
  762. if(gnutls_server_name_set(gtls->session, GNUTLS_NAME_DNS,
  763. peer->sni, strlen(peer->sni)) < 0) {
  764. failf(data, "Failed to set SNI");
  765. return CURLE_SSL_CONNECT_ERROR;
  766. }
  767. }
  768. /* Use default priorities */
  769. rc = gnutls_set_default_priority(gtls->session);
  770. if(rc != GNUTLS_E_SUCCESS)
  771. return CURLE_SSL_CONNECT_ERROR;
  772. /* "In GnuTLS 3.6.5, TLS 1.3 is enabled by default" */
  773. tls13support = gnutls_check_version("3.6.5");
  774. /* Ensure +SRP comes at the *end* of all relevant strings so that it can be
  775. * removed if a runtime error indicates that SRP is not supported by this
  776. * GnuTLS version */
  777. if(config->version == CURL_SSLVERSION_SSLv2 ||
  778. config->version == CURL_SSLVERSION_SSLv3) {
  779. failf(data, "GnuTLS does not support SSLv2 or SSLv3");
  780. return CURLE_SSL_CONNECT_ERROR;
  781. }
  782. if(config->version == CURL_SSLVERSION_TLSv1_3) {
  783. if(!tls13support) {
  784. failf(data, "This GnuTLS installation does not support TLS 1.3");
  785. return CURLE_SSL_CONNECT_ERROR;
  786. }
  787. }
  788. /* At this point we know we have a supported TLS version, so set it */
  789. result = gnutls_set_ssl_version_min_max(data, peer,
  790. config, &prioritylist, tls13support);
  791. if(result)
  792. return result;
  793. #ifdef USE_GNUTLS_SRP
  794. /* Only add SRP to the cipher list if SRP is requested. Otherwise
  795. * GnuTLS will disable TLS 1.3 support. */
  796. if(config->username) {
  797. char *prioritysrp = aprintf("%s:" GNUTLS_SRP, prioritylist);
  798. if(!prioritysrp)
  799. return CURLE_OUT_OF_MEMORY;
  800. rc = gnutls_priority_set_direct(gtls->session, prioritysrp, &err);
  801. free(prioritysrp);
  802. if((rc == GNUTLS_E_INVALID_REQUEST) && err) {
  803. infof(data, "This GnuTLS does not support SRP");
  804. }
  805. }
  806. else {
  807. #endif
  808. infof(data, "GnuTLS ciphers: %s", prioritylist);
  809. rc = gnutls_priority_set_direct(gtls->session, prioritylist, &err);
  810. #ifdef USE_GNUTLS_SRP
  811. }
  812. #endif
  813. if(rc != GNUTLS_E_SUCCESS) {
  814. failf(data, "Error %d setting GnuTLS cipher list starting with %s",
  815. rc, err);
  816. return CURLE_SSL_CONNECT_ERROR;
  817. }
  818. if(config->clientcert) {
  819. if(!gtls->shared_creds->trust_setup) {
  820. result = Curl_gtls_client_trust_setup(cf, data, gtls);
  821. if(result)
  822. return result;
  823. }
  824. if(ssl_config->cert_type && strcasecompare(ssl_config->cert_type, "P12")) {
  825. rc = gnutls_certificate_set_x509_simple_pkcs12_file(
  826. gtls->shared_creds->creds, config->clientcert, GNUTLS_X509_FMT_DER,
  827. ssl_config->key_passwd ? ssl_config->key_passwd : "");
  828. if(rc != GNUTLS_E_SUCCESS) {
  829. failf(data,
  830. "error reading X.509 potentially-encrypted key or certificate "
  831. "file: %s",
  832. gnutls_strerror(rc));
  833. return CURLE_SSL_CONNECT_ERROR;
  834. }
  835. }
  836. else if(ssl_config->key_passwd) {
  837. const unsigned int supported_key_encryption_algorithms =
  838. GNUTLS_PKCS_USE_PKCS12_3DES | GNUTLS_PKCS_USE_PKCS12_ARCFOUR |
  839. GNUTLS_PKCS_USE_PKCS12_RC2_40 | GNUTLS_PKCS_USE_PBES2_3DES |
  840. GNUTLS_PKCS_USE_PBES2_AES_128 | GNUTLS_PKCS_USE_PBES2_AES_192 |
  841. GNUTLS_PKCS_USE_PBES2_AES_256;
  842. rc = gnutls_certificate_set_x509_key_file2(
  843. gtls->shared_creds->creds,
  844. config->clientcert,
  845. ssl_config->key ? ssl_config->key : config->clientcert,
  846. gnutls_do_file_type(ssl_config->cert_type),
  847. ssl_config->key_passwd,
  848. supported_key_encryption_algorithms);
  849. if(rc != GNUTLS_E_SUCCESS) {
  850. failf(data,
  851. "error reading X.509 potentially-encrypted key file: %s",
  852. gnutls_strerror(rc));
  853. return CURLE_SSL_CONNECT_ERROR;
  854. }
  855. }
  856. else {
  857. if(gnutls_certificate_set_x509_key_file(
  858. gtls->shared_creds->creds,
  859. config->clientcert,
  860. ssl_config->key ? ssl_config->key : config->clientcert,
  861. gnutls_do_file_type(ssl_config->cert_type) ) !=
  862. GNUTLS_E_SUCCESS) {
  863. failf(data, "error reading X.509 key or certificate file");
  864. return CURLE_SSL_CONNECT_ERROR;
  865. }
  866. }
  867. }
  868. #ifdef USE_GNUTLS_SRP
  869. /* put the credentials to the current session */
  870. if(config->username) {
  871. rc = gnutls_credentials_set(gtls->session, GNUTLS_CRD_SRP,
  872. gtls->srp_client_cred);
  873. if(rc != GNUTLS_E_SUCCESS) {
  874. failf(data, "gnutls_credentials_set() failed: %s", gnutls_strerror(rc));
  875. return CURLE_SSL_CONNECT_ERROR;
  876. }
  877. }
  878. else
  879. #endif
  880. {
  881. rc = gnutls_credentials_set(gtls->session, GNUTLS_CRD_CERTIFICATE,
  882. gtls->shared_creds->creds);
  883. if(rc != GNUTLS_E_SUCCESS) {
  884. failf(data, "gnutls_credentials_set() failed: %s", gnutls_strerror(rc));
  885. return CURLE_SSL_CONNECT_ERROR;
  886. }
  887. }
  888. if(config->verifystatus) {
  889. rc = gnutls_ocsp_status_request_enable_client(gtls->session,
  890. NULL, 0, NULL);
  891. if(rc != GNUTLS_E_SUCCESS) {
  892. failf(data, "gnutls_ocsp_status_request_enable_client() failed: %d", rc);
  893. return CURLE_SSL_CONNECT_ERROR;
  894. }
  895. }
  896. return CURLE_OK;
  897. }
  898. static int keylog_callback(gnutls_session_t session, const char *label,
  899. const gnutls_datum_t *secret)
  900. {
  901. gnutls_datum_t crandom;
  902. gnutls_datum_t srandom;
  903. gnutls_session_get_random(session, &crandom, &srandom);
  904. if(crandom.size != 32) {
  905. return -1;
  906. }
  907. Curl_tls_keylog_write(label, crandom.data, secret->data, secret->size);
  908. return 0;
  909. }
  910. CURLcode Curl_gtls_ctx_init(struct gtls_ctx *gctx,
  911. struct Curl_cfilter *cf,
  912. struct Curl_easy *data,
  913. struct ssl_peer *peer,
  914. const unsigned char *alpn, size_t alpn_len,
  915. Curl_gtls_ctx_setup_cb *cb_setup,
  916. void *cb_user_data,
  917. void *ssl_user_data)
  918. {
  919. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  920. CURLcode result;
  921. DEBUGASSERT(gctx);
  922. result = gtls_client_init(cf, data, peer, gctx);
  923. if(result)
  924. return result;
  925. gnutls_session_set_ptr(gctx->session, ssl_user_data);
  926. if(cb_setup) {
  927. result = cb_setup(cf, data, cb_user_data);
  928. if(result)
  929. return result;
  930. }
  931. /* Open the file if a TLS or QUIC backend has not done this before. */
  932. Curl_tls_keylog_open();
  933. if(Curl_tls_keylog_enabled()) {
  934. gnutls_session_set_keylog_function(gctx->session, keylog_callback);
  935. }
  936. /* convert the ALPN string from our arguments to a list of strings
  937. * that gnutls wants and will convert internally back to this very
  938. * string for sending to the server. nice. */
  939. if(alpn && alpn_len) {
  940. gnutls_datum_t alpns[5];
  941. size_t i, alen = alpn_len;
  942. unsigned char *s = (unsigned char *)alpn;
  943. unsigned char slen;
  944. for(i = 0; (i < ARRAYSIZE(alpns)) && alen; ++i) {
  945. slen = s[0];
  946. if(slen >= alen)
  947. return CURLE_FAILED_INIT;
  948. alpns[i].data = s + 1;
  949. alpns[i].size = slen;
  950. s += slen + 1;
  951. alen -= (size_t)slen + 1;
  952. }
  953. if(alen) /* not all alpn chars used, wrong format or too many */
  954. return CURLE_FAILED_INIT;
  955. if(i && gnutls_alpn_set_protocols(gctx->session,
  956. alpns, (unsigned int)i,
  957. GNUTLS_ALPN_MANDATORY)) {
  958. failf(data, "failed setting ALPN");
  959. return CURLE_SSL_CONNECT_ERROR;
  960. }
  961. }
  962. /* This might be a reconnect, so we check for a session ID in the cache
  963. to speed up things */
  964. if(conn_config->cache_session) {
  965. void *ssl_sessionid;
  966. size_t ssl_idsize;
  967. Curl_ssl_sessionid_lock(data);
  968. if(!Curl_ssl_getsessionid(cf, data, peer, &ssl_sessionid, &ssl_idsize)) {
  969. /* we got a session id, use it! */
  970. int rc;
  971. rc = gnutls_session_set_data(gctx->session, ssl_sessionid, ssl_idsize);
  972. if(rc < 0)
  973. infof(data, "SSL failed to set session ID");
  974. else
  975. infof(data, "SSL reusing session ID (size=%zu)", ssl_idsize);
  976. }
  977. Curl_ssl_sessionid_unlock(data);
  978. }
  979. return CURLE_OK;
  980. }
  981. static CURLcode
  982. gtls_connect_step1(struct Curl_cfilter *cf, struct Curl_easy *data)
  983. {
  984. struct ssl_connect_data *connssl = cf->ctx;
  985. struct gtls_ssl_backend_data *backend =
  986. (struct gtls_ssl_backend_data *)connssl->backend;
  987. struct alpn_proto_buf proto;
  988. CURLcode result;
  989. DEBUGASSERT(backend);
  990. DEBUGASSERT(ssl_connect_1 == connssl->connecting_state);
  991. if(connssl->state == ssl_connection_complete)
  992. /* to make us tolerant against being called more than once for the
  993. same connection */
  994. return CURLE_OK;
  995. memset(&proto, 0, sizeof(proto));
  996. if(connssl->alpn) {
  997. result = Curl_alpn_to_proto_buf(&proto, connssl->alpn);
  998. if(result) {
  999. failf(data, "Error determining ALPN");
  1000. return CURLE_SSL_CONNECT_ERROR;
  1001. }
  1002. }
  1003. result = Curl_gtls_ctx_init(&backend->gtls, cf, data, &connssl->peer,
  1004. proto.data, proto.len, NULL, NULL, cf);
  1005. if(result)
  1006. return result;
  1007. gnutls_handshake_set_hook_function(backend->gtls.session,
  1008. GNUTLS_HANDSHAKE_ANY, GNUTLS_HOOK_POST,
  1009. gtls_handshake_cb);
  1010. /* register callback functions and handle to send and receive data. */
  1011. gnutls_transport_set_ptr(backend->gtls.session, cf);
  1012. gnutls_transport_set_push_function(backend->gtls.session, gtls_push);
  1013. gnutls_transport_set_pull_function(backend->gtls.session, gtls_pull);
  1014. return CURLE_OK;
  1015. }
  1016. static CURLcode pkp_pin_peer_pubkey(struct Curl_easy *data,
  1017. gnutls_x509_crt_t cert,
  1018. const char *pinnedpubkey)
  1019. {
  1020. /* Scratch */
  1021. size_t len1 = 0, len2 = 0;
  1022. unsigned char *buff1 = NULL;
  1023. gnutls_pubkey_t key = NULL;
  1024. /* Result is returned to caller */
  1025. CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
  1026. /* if a path was not specified, do not pin */
  1027. if(!pinnedpubkey)
  1028. return CURLE_OK;
  1029. if(!cert)
  1030. return result;
  1031. do {
  1032. int ret;
  1033. /* Begin Gyrations to get the public key */
  1034. gnutls_pubkey_init(&key);
  1035. ret = gnutls_pubkey_import_x509(key, cert, 0);
  1036. if(ret < 0)
  1037. break; /* failed */
  1038. ret = gnutls_pubkey_export(key, GNUTLS_X509_FMT_DER, NULL, &len1);
  1039. if(ret != GNUTLS_E_SHORT_MEMORY_BUFFER || len1 == 0)
  1040. break; /* failed */
  1041. buff1 = malloc(len1);
  1042. if(!buff1)
  1043. break; /* failed */
  1044. len2 = len1;
  1045. ret = gnutls_pubkey_export(key, GNUTLS_X509_FMT_DER, buff1, &len2);
  1046. if(ret < 0 || len1 != len2)
  1047. break; /* failed */
  1048. /* End Gyrations */
  1049. /* The one good exit point */
  1050. result = Curl_pin_peer_pubkey(data, pinnedpubkey, buff1, len1);
  1051. } while(0);
  1052. if(key)
  1053. gnutls_pubkey_deinit(key);
  1054. Curl_safefree(buff1);
  1055. return result;
  1056. }
  1057. CURLcode
  1058. Curl_gtls_verifyserver(struct Curl_easy *data,
  1059. gnutls_session_t session,
  1060. struct ssl_primary_config *config,
  1061. struct ssl_config_data *ssl_config,
  1062. struct ssl_peer *peer,
  1063. const char *pinned_key)
  1064. {
  1065. unsigned int cert_list_size;
  1066. const gnutls_datum_t *chainp;
  1067. unsigned int verify_status = 0;
  1068. gnutls_x509_crt_t x509_cert, x509_issuer;
  1069. gnutls_datum_t issuerp;
  1070. gnutls_datum_t certfields;
  1071. char certname[65] = ""; /* limited to 64 chars by ASN.1 */
  1072. size_t size;
  1073. time_t certclock;
  1074. int rc;
  1075. CURLcode result = CURLE_OK;
  1076. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  1077. const char *ptr;
  1078. int algo;
  1079. unsigned int bits;
  1080. gnutls_protocol_t version = gnutls_protocol_get_version(session);
  1081. #endif
  1082. long * const certverifyresult = &ssl_config->certverifyresult;
  1083. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  1084. /* the name of the cipher suite used, e.g. ECDHE_RSA_AES_256_GCM_SHA384. */
  1085. ptr = gnutls_cipher_suite_get_name(gnutls_kx_get(session),
  1086. gnutls_cipher_get(session),
  1087. gnutls_mac_get(session));
  1088. infof(data, "SSL connection using %s / %s",
  1089. gnutls_protocol_get_name(version), ptr);
  1090. #endif
  1091. /* This function will return the peer's raw certificate (chain) as sent by
  1092. the peer. These certificates are in raw format (DER encoded for
  1093. X.509). In case of a X.509 then a certificate list may be present. The
  1094. first certificate in the list is the peer's certificate, following the
  1095. issuer's certificate, then the issuer's issuer etc. */
  1096. chainp = gnutls_certificate_get_peers(session, &cert_list_size);
  1097. if(!chainp) {
  1098. if(config->verifypeer ||
  1099. config->verifyhost ||
  1100. config->issuercert) {
  1101. #ifdef USE_GNUTLS_SRP
  1102. if(ssl_config->primary.username && !config->verifypeer &&
  1103. gnutls_cipher_get(session)) {
  1104. /* no peer cert, but auth is ok if we have SRP user and cipher and no
  1105. peer verify */
  1106. }
  1107. else {
  1108. #endif
  1109. failf(data, "failed to get server cert");
  1110. *certverifyresult = GNUTLS_E_NO_CERTIFICATE_FOUND;
  1111. return CURLE_PEER_FAILED_VERIFICATION;
  1112. #ifdef USE_GNUTLS_SRP
  1113. }
  1114. #endif
  1115. }
  1116. infof(data, " common name: WARNING could not obtain");
  1117. }
  1118. if(data->set.ssl.certinfo && chainp) {
  1119. unsigned int i;
  1120. result = Curl_ssl_init_certinfo(data, (int)cert_list_size);
  1121. if(result)
  1122. return result;
  1123. for(i = 0; i < cert_list_size; i++) {
  1124. const char *beg = (const char *) chainp[i].data;
  1125. const char *end = beg + chainp[i].size;
  1126. result = Curl_extract_certinfo(data, (int)i, beg, end);
  1127. if(result)
  1128. return result;
  1129. }
  1130. }
  1131. if(config->verifypeer) {
  1132. /* This function will try to verify the peer's certificate and return its
  1133. status (trusted, invalid etc.). The value of status should be one or
  1134. more of the gnutls_certificate_status_t enumerated elements bitwise
  1135. or'd. To avoid denial of service attacks some default upper limits
  1136. regarding the certificate key size and chain size are set. To override
  1137. them use gnutls_certificate_set_verify_limits(). */
  1138. rc = gnutls_certificate_verify_peers2(session, &verify_status);
  1139. if(rc < 0) {
  1140. failf(data, "server cert verify failed: %d", rc);
  1141. *certverifyresult = rc;
  1142. return CURLE_SSL_CONNECT_ERROR;
  1143. }
  1144. *certverifyresult = verify_status;
  1145. /* verify_status is a bitmask of gnutls_certificate_status bits */
  1146. if(verify_status & GNUTLS_CERT_INVALID) {
  1147. if(config->verifypeer) {
  1148. const char *cause = "certificate error, no details available";
  1149. if(verify_status & GNUTLS_CERT_EXPIRED)
  1150. cause = "certificate has expired";
  1151. else if(verify_status & GNUTLS_CERT_SIGNER_NOT_FOUND)
  1152. cause = "certificate signer not trusted";
  1153. else if(verify_status & GNUTLS_CERT_INSECURE_ALGORITHM)
  1154. cause = "certificate uses insecure algorithm";
  1155. else if(verify_status & GNUTLS_CERT_INVALID_OCSP_STATUS)
  1156. cause = "attached OCSP status response is invalid";
  1157. failf(data, "server verification failed: %s. (CAfile: %s "
  1158. "CRLfile: %s)", cause,
  1159. config->CAfile ? config->CAfile : "none",
  1160. ssl_config->primary.CRLfile ?
  1161. ssl_config->primary.CRLfile : "none");
  1162. return CURLE_PEER_FAILED_VERIFICATION;
  1163. }
  1164. else
  1165. infof(data, " server certificate verification FAILED");
  1166. }
  1167. else
  1168. infof(data, " server certificate verification OK");
  1169. }
  1170. else
  1171. infof(data, " server certificate verification SKIPPED");
  1172. if(config->verifystatus) {
  1173. gnutls_datum_t status_request;
  1174. gnutls_ocsp_resp_t ocsp_resp;
  1175. gnutls_ocsp_cert_status_t status;
  1176. gnutls_x509_crl_reason_t reason;
  1177. rc = gnutls_ocsp_status_request_get(session, &status_request);
  1178. if(rc == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) {
  1179. failf(data, "No OCSP response received");
  1180. return CURLE_SSL_INVALIDCERTSTATUS;
  1181. }
  1182. if(rc < 0) {
  1183. failf(data, "Invalid OCSP response received");
  1184. return CURLE_SSL_INVALIDCERTSTATUS;
  1185. }
  1186. gnutls_ocsp_resp_init(&ocsp_resp);
  1187. rc = gnutls_ocsp_resp_import(ocsp_resp, &status_request);
  1188. if(rc < 0) {
  1189. failf(data, "Invalid OCSP response received");
  1190. return CURLE_SSL_INVALIDCERTSTATUS;
  1191. }
  1192. (void)gnutls_ocsp_resp_get_single(ocsp_resp, 0, NULL, NULL, NULL, NULL,
  1193. &status, NULL, NULL, NULL, &reason);
  1194. switch(status) {
  1195. case GNUTLS_OCSP_CERT_GOOD:
  1196. break;
  1197. case GNUTLS_OCSP_CERT_REVOKED: {
  1198. const char *crl_reason;
  1199. switch(reason) {
  1200. default:
  1201. case GNUTLS_X509_CRLREASON_UNSPECIFIED:
  1202. crl_reason = "unspecified reason";
  1203. break;
  1204. case GNUTLS_X509_CRLREASON_KEYCOMPROMISE:
  1205. crl_reason = "private key compromised";
  1206. break;
  1207. case GNUTLS_X509_CRLREASON_CACOMPROMISE:
  1208. crl_reason = "CA compromised";
  1209. break;
  1210. case GNUTLS_X509_CRLREASON_AFFILIATIONCHANGED:
  1211. crl_reason = "affiliation has changed";
  1212. break;
  1213. case GNUTLS_X509_CRLREASON_SUPERSEDED:
  1214. crl_reason = "certificate superseded";
  1215. break;
  1216. case GNUTLS_X509_CRLREASON_CESSATIONOFOPERATION:
  1217. crl_reason = "operation has ceased";
  1218. break;
  1219. case GNUTLS_X509_CRLREASON_CERTIFICATEHOLD:
  1220. crl_reason = "certificate is on hold";
  1221. break;
  1222. case GNUTLS_X509_CRLREASON_REMOVEFROMCRL:
  1223. crl_reason = "will be removed from delta CRL";
  1224. break;
  1225. case GNUTLS_X509_CRLREASON_PRIVILEGEWITHDRAWN:
  1226. crl_reason = "privilege withdrawn";
  1227. break;
  1228. case GNUTLS_X509_CRLREASON_AACOMPROMISE:
  1229. crl_reason = "AA compromised";
  1230. break;
  1231. }
  1232. failf(data, "Server certificate was revoked: %s", crl_reason);
  1233. break;
  1234. }
  1235. default:
  1236. case GNUTLS_OCSP_CERT_UNKNOWN:
  1237. failf(data, "Server certificate status is unknown");
  1238. break;
  1239. }
  1240. gnutls_ocsp_resp_deinit(ocsp_resp);
  1241. if(status != GNUTLS_OCSP_CERT_GOOD)
  1242. return CURLE_SSL_INVALIDCERTSTATUS;
  1243. }
  1244. else
  1245. infof(data, " server certificate status verification SKIPPED");
  1246. /* initialize an X.509 certificate structure. */
  1247. gnutls_x509_crt_init(&x509_cert);
  1248. if(chainp)
  1249. /* convert the given DER or PEM encoded Certificate to the native
  1250. gnutls_x509_crt_t format */
  1251. gnutls_x509_crt_import(x509_cert, chainp, GNUTLS_X509_FMT_DER);
  1252. if(config->issuercert) {
  1253. gnutls_x509_crt_init(&x509_issuer);
  1254. issuerp = load_file(config->issuercert);
  1255. gnutls_x509_crt_import(x509_issuer, &issuerp, GNUTLS_X509_FMT_PEM);
  1256. rc = (int)gnutls_x509_crt_check_issuer(x509_cert, x509_issuer);
  1257. gnutls_x509_crt_deinit(x509_issuer);
  1258. unload_file(issuerp);
  1259. if(rc <= 0) {
  1260. failf(data, "server certificate issuer check failed (IssuerCert: %s)",
  1261. config->issuercert ? config->issuercert : "none");
  1262. gnutls_x509_crt_deinit(x509_cert);
  1263. return CURLE_SSL_ISSUER_ERROR;
  1264. }
  1265. infof(data, " server certificate issuer check OK (Issuer Cert: %s)",
  1266. config->issuercert ? config->issuercert : "none");
  1267. }
  1268. size = sizeof(certname);
  1269. rc = gnutls_x509_crt_get_dn_by_oid(x509_cert, GNUTLS_OID_X520_COMMON_NAME,
  1270. 0, /* the first and only one */
  1271. FALSE,
  1272. certname,
  1273. &size);
  1274. if(rc) {
  1275. infof(data, "error fetching CN from cert:%s",
  1276. gnutls_strerror(rc));
  1277. }
  1278. /* This function will check if the given certificate's subject matches the
  1279. given hostname. This is a basic implementation of the matching described
  1280. in RFC2818 (HTTPS), which takes into account wildcards, and the subject
  1281. alternative name PKIX extension. Returns non zero on success, and zero on
  1282. failure. */
  1283. /* This function does not handle trailing dots, so if we have an SNI name
  1284. use that and fallback to the hostname only if there is no SNI (like for
  1285. IP addresses) */
  1286. rc = (int)gnutls_x509_crt_check_hostname(x509_cert,
  1287. peer->sni ? peer->sni :
  1288. peer->hostname);
  1289. #if GNUTLS_VERSION_NUMBER < 0x030306
  1290. /* Before 3.3.6, gnutls_x509_crt_check_hostname() did not check IP
  1291. addresses. */
  1292. if(!rc) {
  1293. #ifdef USE_IPV6
  1294. #define use_addr in6_addr
  1295. #else
  1296. #define use_addr in_addr
  1297. #endif
  1298. unsigned char addrbuf[sizeof(struct use_addr)];
  1299. size_t addrlen = 0;
  1300. if(Curl_inet_pton(AF_INET, peer->hostname, addrbuf) > 0)
  1301. addrlen = 4;
  1302. #ifdef USE_IPV6
  1303. else if(Curl_inet_pton(AF_INET6, peer->hostname, addrbuf) > 0)
  1304. addrlen = 16;
  1305. #endif
  1306. if(addrlen) {
  1307. unsigned char certaddr[sizeof(struct use_addr)];
  1308. int i;
  1309. for(i = 0; ; i++) {
  1310. size_t certaddrlen = sizeof(certaddr);
  1311. int ret = gnutls_x509_crt_get_subject_alt_name(x509_cert, i, certaddr,
  1312. &certaddrlen, NULL);
  1313. /* If this happens, it was not an IP address. */
  1314. if(ret == GNUTLS_E_SHORT_MEMORY_BUFFER)
  1315. continue;
  1316. if(ret < 0)
  1317. break;
  1318. if(ret != GNUTLS_SAN_IPADDRESS)
  1319. continue;
  1320. if(certaddrlen == addrlen && !memcmp(addrbuf, certaddr, addrlen)) {
  1321. rc = 1;
  1322. break;
  1323. }
  1324. }
  1325. }
  1326. }
  1327. #endif
  1328. if(!rc) {
  1329. if(config->verifyhost) {
  1330. failf(data, "SSL: certificate subject name (%s) does not match "
  1331. "target hostname '%s'", certname, peer->dispname);
  1332. gnutls_x509_crt_deinit(x509_cert);
  1333. return CURLE_PEER_FAILED_VERIFICATION;
  1334. }
  1335. else
  1336. infof(data, " common name: %s (does not match '%s')",
  1337. certname, peer->dispname);
  1338. }
  1339. else
  1340. infof(data, " common name: %s (matched)", certname);
  1341. /* Check for time-based validity */
  1342. certclock = gnutls_x509_crt_get_expiration_time(x509_cert);
  1343. if(certclock == (time_t)-1) {
  1344. if(config->verifypeer) {
  1345. failf(data, "server cert expiration date verify failed");
  1346. *certverifyresult = GNUTLS_CERT_EXPIRED;
  1347. gnutls_x509_crt_deinit(x509_cert);
  1348. return CURLE_SSL_CONNECT_ERROR;
  1349. }
  1350. else
  1351. infof(data, " server certificate expiration date verify FAILED");
  1352. }
  1353. else {
  1354. if(certclock < time(NULL)) {
  1355. if(config->verifypeer) {
  1356. failf(data, "server certificate expiration date has passed.");
  1357. *certverifyresult = GNUTLS_CERT_EXPIRED;
  1358. gnutls_x509_crt_deinit(x509_cert);
  1359. return CURLE_PEER_FAILED_VERIFICATION;
  1360. }
  1361. else
  1362. infof(data, " server certificate expiration date FAILED");
  1363. }
  1364. else
  1365. infof(data, " server certificate expiration date OK");
  1366. }
  1367. certclock = gnutls_x509_crt_get_activation_time(x509_cert);
  1368. if(certclock == (time_t)-1) {
  1369. if(config->verifypeer) {
  1370. failf(data, "server cert activation date verify failed");
  1371. *certverifyresult = GNUTLS_CERT_NOT_ACTIVATED;
  1372. gnutls_x509_crt_deinit(x509_cert);
  1373. return CURLE_SSL_CONNECT_ERROR;
  1374. }
  1375. else
  1376. infof(data, " server certificate activation date verify FAILED");
  1377. }
  1378. else {
  1379. if(certclock > time(NULL)) {
  1380. if(config->verifypeer) {
  1381. failf(data, "server certificate not activated yet.");
  1382. *certverifyresult = GNUTLS_CERT_NOT_ACTIVATED;
  1383. gnutls_x509_crt_deinit(x509_cert);
  1384. return CURLE_PEER_FAILED_VERIFICATION;
  1385. }
  1386. else
  1387. infof(data, " server certificate activation date FAILED");
  1388. }
  1389. else
  1390. infof(data, " server certificate activation date OK");
  1391. }
  1392. if(pinned_key) {
  1393. result = pkp_pin_peer_pubkey(data, x509_cert, pinned_key);
  1394. if(result != CURLE_OK) {
  1395. failf(data, "SSL: public key does not match pinned public key");
  1396. gnutls_x509_crt_deinit(x509_cert);
  1397. return result;
  1398. }
  1399. }
  1400. /* Show:
  1401. - subject
  1402. - start date
  1403. - expire date
  1404. - common name
  1405. - issuer
  1406. */
  1407. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  1408. /* public key algorithm's parameters */
  1409. algo = gnutls_x509_crt_get_pk_algorithm(x509_cert, &bits);
  1410. infof(data, " certificate public key: %s",
  1411. gnutls_pk_algorithm_get_name((gnutls_pk_algorithm_t)algo));
  1412. /* version of the X.509 certificate. */
  1413. infof(data, " certificate version: #%d",
  1414. gnutls_x509_crt_get_version(x509_cert));
  1415. rc = gnutls_x509_crt_get_dn2(x509_cert, &certfields);
  1416. if(rc)
  1417. infof(data, "Failed to get certificate name");
  1418. else {
  1419. infof(data, " subject: %s", certfields.data);
  1420. certclock = gnutls_x509_crt_get_activation_time(x509_cert);
  1421. showtime(data, "start date", certclock);
  1422. certclock = gnutls_x509_crt_get_expiration_time(x509_cert);
  1423. showtime(data, "expire date", certclock);
  1424. gnutls_free(certfields.data);
  1425. }
  1426. rc = gnutls_x509_crt_get_issuer_dn2(x509_cert, &certfields);
  1427. if(rc)
  1428. infof(data, "Failed to get certificate issuer");
  1429. else {
  1430. infof(data, " issuer: %s", certfields.data);
  1431. gnutls_free(certfields.data);
  1432. }
  1433. #endif
  1434. gnutls_x509_crt_deinit(x509_cert);
  1435. return result;
  1436. }
  1437. static CURLcode gtls_verifyserver(struct Curl_cfilter *cf,
  1438. struct Curl_easy *data,
  1439. gnutls_session_t session)
  1440. {
  1441. struct ssl_connect_data *connssl = cf->ctx;
  1442. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  1443. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  1444. #ifndef CURL_DISABLE_PROXY
  1445. const char *pinned_key = Curl_ssl_cf_is_proxy(cf) ?
  1446. data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY] :
  1447. data->set.str[STRING_SSL_PINNEDPUBLICKEY];
  1448. #else
  1449. const char *pinned_key = data->set.str[STRING_SSL_PINNEDPUBLICKEY];
  1450. #endif
  1451. CURLcode result;
  1452. result = Curl_gtls_verifyserver(data, session, conn_config, ssl_config,
  1453. &connssl->peer, pinned_key);
  1454. if(result)
  1455. goto out;
  1456. if(connssl->alpn) {
  1457. gnutls_datum_t proto;
  1458. int rc;
  1459. rc = gnutls_alpn_get_selected_protocol(session, &proto);
  1460. if(rc == 0)
  1461. Curl_alpn_set_negotiated(cf, data, proto.data, proto.size);
  1462. else
  1463. Curl_alpn_set_negotiated(cf, data, NULL, 0);
  1464. }
  1465. /* Only on TLSv1.2 or lower do we have the session id now. For
  1466. * TLSv1.3 we get it via a SESSION_TICKET message that arrives later. */
  1467. if(gnutls_protocol_get_version(session) < GNUTLS_TLS1_3)
  1468. result = gtls_update_session_id(cf, data, session);
  1469. out:
  1470. return result;
  1471. }
  1472. /*
  1473. * This function is called after the TCP connect has completed. Setup the TLS
  1474. * layer and do all necessary magic.
  1475. */
  1476. /* We use connssl->connecting_state to keep track of the connection status;
  1477. there are three states: 'ssl_connect_1' (not started yet or complete),
  1478. 'ssl_connect_2' (doing handshake with the server), and
  1479. 'ssl_connect_3' (verifying and getting stats).
  1480. */
  1481. static CURLcode
  1482. gtls_connect_common(struct Curl_cfilter *cf,
  1483. struct Curl_easy *data,
  1484. bool nonblocking,
  1485. bool *done)
  1486. {
  1487. struct ssl_connect_data *connssl = cf->ctx;
  1488. CURLcode rc;
  1489. CURLcode result = CURLE_OK;
  1490. /* Initiate the connection, if not already done */
  1491. if(ssl_connect_1 == connssl->connecting_state) {
  1492. rc = gtls_connect_step1(cf, data);
  1493. if(rc) {
  1494. result = rc;
  1495. goto out;
  1496. }
  1497. }
  1498. rc = handshake(cf, data, TRUE, nonblocking);
  1499. if(rc) {
  1500. /* handshake() sets its own error message with failf() */
  1501. result = rc;
  1502. goto out;
  1503. }
  1504. /* Finish connecting once the handshake is done */
  1505. if(ssl_connect_1 == connssl->connecting_state) {
  1506. struct gtls_ssl_backend_data *backend =
  1507. (struct gtls_ssl_backend_data *)connssl->backend;
  1508. gnutls_session_t session;
  1509. DEBUGASSERT(backend);
  1510. session = backend->gtls.session;
  1511. rc = gtls_verifyserver(cf, data, session);
  1512. if(rc) {
  1513. result = rc;
  1514. goto out;
  1515. }
  1516. connssl->state = ssl_connection_complete;
  1517. }
  1518. out:
  1519. *done = ssl_connect_1 == connssl->connecting_state;
  1520. return result;
  1521. }
  1522. static CURLcode gtls_connect_nonblocking(struct Curl_cfilter *cf,
  1523. struct Curl_easy *data,
  1524. bool *done)
  1525. {
  1526. return gtls_connect_common(cf, data, TRUE, done);
  1527. }
  1528. static CURLcode gtls_connect(struct Curl_cfilter *cf,
  1529. struct Curl_easy *data)
  1530. {
  1531. CURLcode result;
  1532. bool done = FALSE;
  1533. result = gtls_connect_common(cf, data, FALSE, &done);
  1534. if(result)
  1535. return result;
  1536. DEBUGASSERT(done);
  1537. return CURLE_OK;
  1538. }
  1539. static bool gtls_data_pending(struct Curl_cfilter *cf,
  1540. const struct Curl_easy *data)
  1541. {
  1542. struct ssl_connect_data *ctx = cf->ctx;
  1543. struct gtls_ssl_backend_data *backend;
  1544. (void)data;
  1545. DEBUGASSERT(ctx && ctx->backend);
  1546. backend = (struct gtls_ssl_backend_data *)ctx->backend;
  1547. if(backend->gtls.session &&
  1548. 0 != gnutls_record_check_pending(backend->gtls.session))
  1549. return TRUE;
  1550. return FALSE;
  1551. }
  1552. static ssize_t gtls_send(struct Curl_cfilter *cf,
  1553. struct Curl_easy *data,
  1554. const void *buf,
  1555. size_t blen,
  1556. CURLcode *curlcode)
  1557. {
  1558. struct ssl_connect_data *connssl = cf->ctx;
  1559. struct gtls_ssl_backend_data *backend =
  1560. (struct gtls_ssl_backend_data *)connssl->backend;
  1561. ssize_t rc;
  1562. size_t nwritten, total_written = 0;
  1563. (void)data;
  1564. DEBUGASSERT(backend);
  1565. while(blen) {
  1566. backend->gtls.io_result = CURLE_OK;
  1567. rc = gnutls_record_send(backend->gtls.session, buf, blen);
  1568. if(rc < 0) {
  1569. if(total_written && (rc == GNUTLS_E_AGAIN)) {
  1570. *curlcode = CURLE_OK;
  1571. rc = (ssize_t)total_written;
  1572. goto out;
  1573. }
  1574. *curlcode = (rc == GNUTLS_E_AGAIN) ?
  1575. CURLE_AGAIN :
  1576. (backend->gtls.io_result ? backend->gtls.io_result : CURLE_SEND_ERROR);
  1577. rc = -1;
  1578. goto out;
  1579. }
  1580. nwritten = (size_t)rc;
  1581. total_written += nwritten;
  1582. DEBUGASSERT(nwritten <= blen);
  1583. buf = (char *)buf + nwritten;
  1584. blen -= nwritten;
  1585. }
  1586. rc = total_written;
  1587. out:
  1588. return rc;
  1589. }
  1590. /*
  1591. * This function is called to shut down the SSL layer but keep the
  1592. * socket open (CCC - Clear Command Channel)
  1593. */
  1594. static CURLcode gtls_shutdown(struct Curl_cfilter *cf,
  1595. struct Curl_easy *data,
  1596. bool send_shutdown, bool *done)
  1597. {
  1598. struct ssl_connect_data *connssl = cf->ctx;
  1599. struct gtls_ssl_backend_data *backend =
  1600. (struct gtls_ssl_backend_data *)connssl->backend;
  1601. char buf[1024];
  1602. CURLcode result = CURLE_OK;
  1603. ssize_t nread;
  1604. size_t i;
  1605. DEBUGASSERT(backend);
  1606. if(!backend->gtls.session || cf->shutdown) {
  1607. *done = TRUE;
  1608. goto out;
  1609. }
  1610. connssl->io_need = CURL_SSL_IO_NEED_NONE;
  1611. *done = FALSE;
  1612. if(!backend->gtls.sent_shutdown) {
  1613. /* do this only once */
  1614. backend->gtls.sent_shutdown = TRUE;
  1615. if(send_shutdown) {
  1616. int ret = gnutls_bye(backend->gtls.session, GNUTLS_SHUT_RDWR);
  1617. if((ret == GNUTLS_E_AGAIN) || (ret == GNUTLS_E_INTERRUPTED)) {
  1618. CURL_TRC_CF(data, cf, "SSL shutdown, gnutls_bye EAGAIN");
  1619. connssl->io_need = gnutls_record_get_direction(backend->gtls.session) ?
  1620. CURL_SSL_IO_NEED_SEND : CURL_SSL_IO_NEED_RECV;
  1621. backend->gtls.sent_shutdown = FALSE;
  1622. result = CURLE_OK;
  1623. goto out;
  1624. }
  1625. if(ret != GNUTLS_E_SUCCESS) {
  1626. CURL_TRC_CF(data, cf, "SSL shutdown, gnutls_bye error: '%s'(%d)",
  1627. gnutls_strerror((int)ret), (int)ret);
  1628. result = CURLE_RECV_ERROR;
  1629. goto out;
  1630. }
  1631. }
  1632. }
  1633. /* SSL should now have started the shutdown from our side. Since it
  1634. * was not complete, we are lacking the close notify from the server. */
  1635. for(i = 0; i < 10; ++i) {
  1636. nread = gnutls_record_recv(backend->gtls.session, buf, sizeof(buf));
  1637. if(nread <= 0)
  1638. break;
  1639. }
  1640. if(nread > 0) {
  1641. /* still data coming in? */
  1642. }
  1643. else if(nread == 0) {
  1644. /* We got the close notify alert and are done. */
  1645. *done = TRUE;
  1646. }
  1647. else if((nread == GNUTLS_E_AGAIN) || (nread == GNUTLS_E_INTERRUPTED)) {
  1648. connssl->io_need = gnutls_record_get_direction(backend->gtls.session) ?
  1649. CURL_SSL_IO_NEED_SEND : CURL_SSL_IO_NEED_RECV;
  1650. }
  1651. else {
  1652. CURL_TRC_CF(data, cf, "SSL shutdown, error: '%s'(%d)",
  1653. gnutls_strerror((int)nread), (int)nread);
  1654. result = CURLE_RECV_ERROR;
  1655. }
  1656. out:
  1657. cf->shutdown = (result || *done);
  1658. return result;
  1659. }
  1660. static void gtls_close(struct Curl_cfilter *cf,
  1661. struct Curl_easy *data)
  1662. {
  1663. struct ssl_connect_data *connssl = cf->ctx;
  1664. struct gtls_ssl_backend_data *backend =
  1665. (struct gtls_ssl_backend_data *)connssl->backend;
  1666. (void) data;
  1667. DEBUGASSERT(backend);
  1668. CURL_TRC_CF(data, cf, "close");
  1669. if(backend->gtls.session) {
  1670. gnutls_deinit(backend->gtls.session);
  1671. backend->gtls.session = NULL;
  1672. }
  1673. if(backend->gtls.shared_creds) {
  1674. Curl_gtls_shared_creds_free(&backend->gtls.shared_creds);
  1675. }
  1676. #ifdef USE_GNUTLS_SRP
  1677. if(backend->gtls.srp_client_cred) {
  1678. gnutls_srp_free_client_credentials(backend->gtls.srp_client_cred);
  1679. backend->gtls.srp_client_cred = NULL;
  1680. }
  1681. #endif
  1682. }
  1683. static ssize_t gtls_recv(struct Curl_cfilter *cf,
  1684. struct Curl_easy *data,
  1685. char *buf,
  1686. size_t buffersize,
  1687. CURLcode *curlcode)
  1688. {
  1689. struct ssl_connect_data *connssl = cf->ctx;
  1690. struct gtls_ssl_backend_data *backend =
  1691. (struct gtls_ssl_backend_data *)connssl->backend;
  1692. ssize_t ret;
  1693. (void)data;
  1694. DEBUGASSERT(backend);
  1695. backend->gtls.io_result = CURLE_OK;
  1696. ret = gnutls_record_recv(backend->gtls.session, buf, buffersize);
  1697. if((ret == GNUTLS_E_AGAIN) || (ret == GNUTLS_E_INTERRUPTED)) {
  1698. *curlcode = CURLE_AGAIN;
  1699. ret = -1;
  1700. goto out;
  1701. }
  1702. if(ret == GNUTLS_E_REHANDSHAKE) {
  1703. /* BLOCKING call, this is bad but a work-around for now. Fixing this "the
  1704. proper way" takes a whole lot of work. */
  1705. CURLcode result = handshake(cf, data, FALSE, FALSE);
  1706. if(result)
  1707. /* handshake() writes error message on its own */
  1708. *curlcode = result;
  1709. else
  1710. *curlcode = CURLE_AGAIN; /* then return as if this was a wouldblock */
  1711. ret = -1;
  1712. goto out;
  1713. }
  1714. if(ret < 0) {
  1715. failf(data, "GnuTLS recv error (%d): %s",
  1716. (int)ret, gnutls_strerror((int)ret));
  1717. *curlcode = backend->gtls.io_result ?
  1718. backend->gtls.io_result : CURLE_RECV_ERROR;
  1719. ret = -1;
  1720. goto out;
  1721. }
  1722. out:
  1723. return ret;
  1724. }
  1725. static size_t gtls_version(char *buffer, size_t size)
  1726. {
  1727. return msnprintf(buffer, size, "GnuTLS/%s", gnutls_check_version(NULL));
  1728. }
  1729. /* data might be NULL! */
  1730. static CURLcode gtls_random(struct Curl_easy *data,
  1731. unsigned char *entropy, size_t length)
  1732. {
  1733. int rc;
  1734. (void)data;
  1735. rc = gnutls_rnd(GNUTLS_RND_RANDOM, entropy, length);
  1736. return rc ? CURLE_FAILED_INIT : CURLE_OK;
  1737. }
  1738. static CURLcode gtls_sha256sum(const unsigned char *tmp, /* input */
  1739. size_t tmplen,
  1740. unsigned char *sha256sum, /* output */
  1741. size_t sha256len)
  1742. {
  1743. struct sha256_ctx SHA256pw;
  1744. sha256_init(&SHA256pw);
  1745. sha256_update(&SHA256pw, (unsigned int)tmplen, tmp);
  1746. sha256_digest(&SHA256pw, (unsigned int)sha256len, sha256sum);
  1747. return CURLE_OK;
  1748. }
  1749. static bool gtls_cert_status_request(void)
  1750. {
  1751. return TRUE;
  1752. }
  1753. static void *gtls_get_internals(struct ssl_connect_data *connssl,
  1754. CURLINFO info UNUSED_PARAM)
  1755. {
  1756. struct gtls_ssl_backend_data *backend =
  1757. (struct gtls_ssl_backend_data *)connssl->backend;
  1758. (void)info;
  1759. DEBUGASSERT(backend);
  1760. return backend->gtls.session;
  1761. }
  1762. const struct Curl_ssl Curl_ssl_gnutls = {
  1763. { CURLSSLBACKEND_GNUTLS, "gnutls" }, /* info */
  1764. SSLSUPP_CA_PATH |
  1765. SSLSUPP_CERTINFO |
  1766. SSLSUPP_PINNEDPUBKEY |
  1767. SSLSUPP_HTTPS_PROXY |
  1768. SSLSUPP_CA_CACHE,
  1769. sizeof(struct gtls_ssl_backend_data),
  1770. gtls_init, /* init */
  1771. gtls_cleanup, /* cleanup */
  1772. gtls_version, /* version */
  1773. Curl_none_check_cxn, /* check_cxn */
  1774. gtls_shutdown, /* shutdown */
  1775. gtls_data_pending, /* data_pending */
  1776. gtls_random, /* random */
  1777. gtls_cert_status_request, /* cert_status_request */
  1778. gtls_connect, /* connect */
  1779. gtls_connect_nonblocking, /* connect_nonblocking */
  1780. Curl_ssl_adjust_pollset, /* adjust_pollset */
  1781. gtls_get_internals, /* get_internals */
  1782. gtls_close, /* close_one */
  1783. Curl_none_close_all, /* close_all */
  1784. Curl_none_set_engine, /* set_engine */
  1785. Curl_none_set_engine_default, /* set_engine_default */
  1786. Curl_none_engines_list, /* engines_list */
  1787. Curl_none_false_start, /* false_start */
  1788. gtls_sha256sum, /* sha256sum */
  1789. NULL, /* associate_connection */
  1790. NULL, /* disassociate_connection */
  1791. gtls_recv, /* recv decrypted data */
  1792. gtls_send, /* send data to encrypt */
  1793. NULL, /* get_channel_binding */
  1794. };
  1795. #endif /* USE_GNUTLS */