2
0

gtls.c 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666
  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: don't 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 "gtls.h"
  42. #include "vtls.h"
  43. #include "vtls_int.h"
  44. #include "vauth/vauth.h"
  45. #include "parsedate.h"
  46. #include "connect.h" /* for the connect timeout */
  47. #include "select.h"
  48. #include "strcase.h"
  49. #include "warnless.h"
  50. #include "x509asn1.h"
  51. #include "multiif.h"
  52. #include "curl_printf.h"
  53. #include "curl_memory.h"
  54. /* The last #include file should be: */
  55. #include "memdebug.h"
  56. /* Enable GnuTLS debugging by defining GTLSDEBUG */
  57. /*#define GTLSDEBUG */
  58. #ifdef GTLSDEBUG
  59. static void tls_log_func(int level, const char *str)
  60. {
  61. fprintf(stderr, "|<%d>| %s", level, str);
  62. }
  63. #endif
  64. static bool gtls_inited = FALSE;
  65. #if !defined(GNUTLS_VERSION_NUMBER) || (GNUTLS_VERSION_NUMBER < 0x03010a)
  66. #error "too old GnuTLS version"
  67. #endif
  68. # include <gnutls/ocsp.h>
  69. struct ssl_backend_data {
  70. struct gtls_instance gtls;
  71. };
  72. static ssize_t gtls_push(void *s, const void *buf, size_t blen)
  73. {
  74. struct Curl_cfilter *cf = s;
  75. struct ssl_connect_data *connssl = cf->ctx;
  76. struct Curl_easy *data = CF_DATA_CURRENT(cf);
  77. ssize_t nwritten;
  78. CURLcode result;
  79. DEBUGASSERT(data);
  80. nwritten = Curl_conn_cf_send(cf->next, data, buf, blen, &result);
  81. if(nwritten < 0) {
  82. gnutls_transport_set_errno(connssl->backend->gtls.session,
  83. (CURLE_AGAIN == result)? EAGAIN : EINVAL);
  84. nwritten = -1;
  85. }
  86. return nwritten;
  87. }
  88. static ssize_t gtls_pull(void *s, void *buf, size_t blen)
  89. {
  90. struct Curl_cfilter *cf = s;
  91. struct ssl_connect_data *connssl = cf->ctx;
  92. struct Curl_easy *data = CF_DATA_CURRENT(cf);
  93. ssize_t nread;
  94. CURLcode result;
  95. DEBUGASSERT(data);
  96. nread = Curl_conn_cf_recv(cf->next, data, buf, blen, &result);
  97. if(nread < 0) {
  98. gnutls_transport_set_errno(connssl->backend->gtls.session,
  99. (CURLE_AGAIN == result)? EAGAIN : EINVAL);
  100. nread = -1;
  101. }
  102. return nread;
  103. }
  104. /* gtls_init()
  105. *
  106. * Global GnuTLS init, called from Curl_ssl_init(). This calls functions that
  107. * are not thread-safe and thus this function itself is not thread-safe and
  108. * must only be called from within curl_global_init() to keep the thread
  109. * situation under control!
  110. */
  111. static int gtls_init(void)
  112. {
  113. int ret = 1;
  114. if(!gtls_inited) {
  115. ret = gnutls_global_init()?0:1;
  116. #ifdef GTLSDEBUG
  117. gnutls_global_set_log_function(tls_log_func);
  118. gnutls_global_set_log_level(2);
  119. #endif
  120. gtls_inited = TRUE;
  121. }
  122. return ret;
  123. }
  124. static void gtls_cleanup(void)
  125. {
  126. if(gtls_inited) {
  127. gnutls_global_deinit();
  128. gtls_inited = FALSE;
  129. }
  130. }
  131. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  132. static void showtime(struct Curl_easy *data,
  133. const char *text,
  134. time_t stamp)
  135. {
  136. struct tm buffer;
  137. const struct tm *tm = &buffer;
  138. char str[96];
  139. CURLcode result = Curl_gmtime(stamp, &buffer);
  140. if(result)
  141. return;
  142. msnprintf(str,
  143. sizeof(str),
  144. " %s: %s, %02d %s %4d %02d:%02d:%02d GMT",
  145. text,
  146. Curl_wkday[tm->tm_wday?tm->tm_wday-1:6],
  147. tm->tm_mday,
  148. Curl_month[tm->tm_mon],
  149. tm->tm_year + 1900,
  150. tm->tm_hour,
  151. tm->tm_min,
  152. tm->tm_sec);
  153. infof(data, "%s", str);
  154. }
  155. #endif
  156. static gnutls_datum_t load_file(const char *file)
  157. {
  158. FILE *f;
  159. gnutls_datum_t loaded_file = { NULL, 0 };
  160. long filelen;
  161. void *ptr;
  162. f = fopen(file, "rb");
  163. if(!f)
  164. return loaded_file;
  165. if(fseek(f, 0, SEEK_END) != 0
  166. || (filelen = ftell(f)) < 0
  167. || fseek(f, 0, SEEK_SET) != 0
  168. || !(ptr = malloc((size_t)filelen)))
  169. goto out;
  170. if(fread(ptr, 1, (size_t)filelen, f) < (size_t)filelen) {
  171. free(ptr);
  172. goto out;
  173. }
  174. loaded_file.data = ptr;
  175. loaded_file.size = (unsigned int)filelen;
  176. out:
  177. fclose(f);
  178. return loaded_file;
  179. }
  180. static void unload_file(gnutls_datum_t data)
  181. {
  182. free(data.data);
  183. }
  184. /* this function does a SSL/TLS (re-)handshake */
  185. static CURLcode handshake(struct Curl_cfilter *cf,
  186. struct Curl_easy *data,
  187. bool duringconnect,
  188. bool nonblocking)
  189. {
  190. struct ssl_connect_data *connssl = cf->ctx;
  191. struct ssl_backend_data *backend = connssl->backend;
  192. gnutls_session_t session;
  193. curl_socket_t sockfd = Curl_conn_cf_get_socket(cf, data);
  194. DEBUGASSERT(backend);
  195. session = backend->gtls.session;
  196. for(;;) {
  197. timediff_t timeout_ms;
  198. int rc;
  199. /* check allowed time left */
  200. timeout_ms = Curl_timeleft(data, NULL, duringconnect);
  201. if(timeout_ms < 0) {
  202. /* no need to continue if time already is up */
  203. failf(data, "SSL connection timeout");
  204. return CURLE_OPERATION_TIMEDOUT;
  205. }
  206. /* if ssl is expecting something, check if it's available. */
  207. if(connssl->connecting_state == ssl_connect_2_reading
  208. || connssl->connecting_state == ssl_connect_2_writing) {
  209. int what;
  210. curl_socket_t writefd = ssl_connect_2_writing ==
  211. connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
  212. curl_socket_t readfd = ssl_connect_2_reading ==
  213. connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
  214. what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
  215. nonblocking?0:
  216. timeout_ms?timeout_ms:1000);
  217. if(what < 0) {
  218. /* fatal error */
  219. failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
  220. return CURLE_SSL_CONNECT_ERROR;
  221. }
  222. else if(0 == what) {
  223. if(nonblocking)
  224. return CURLE_OK;
  225. else if(timeout_ms) {
  226. /* timeout */
  227. failf(data, "SSL connection timeout at %ld", (long)timeout_ms);
  228. return CURLE_OPERATION_TIMEDOUT;
  229. }
  230. }
  231. /* socket is readable or writable */
  232. }
  233. rc = gnutls_handshake(session);
  234. if((rc == GNUTLS_E_AGAIN) || (rc == GNUTLS_E_INTERRUPTED)) {
  235. connssl->connecting_state =
  236. gnutls_record_get_direction(session)?
  237. ssl_connect_2_writing:ssl_connect_2_reading;
  238. continue;
  239. }
  240. else if((rc < 0) && !gnutls_error_is_fatal(rc)) {
  241. const char *strerr = NULL;
  242. if(rc == GNUTLS_E_WARNING_ALERT_RECEIVED) {
  243. int alert = gnutls_alert_get(session);
  244. strerr = gnutls_alert_get_name(alert);
  245. }
  246. if(!strerr)
  247. strerr = gnutls_strerror(rc);
  248. infof(data, "gnutls_handshake() warning: %s", strerr);
  249. continue;
  250. }
  251. else if(rc < 0) {
  252. const char *strerr = NULL;
  253. if(rc == GNUTLS_E_FATAL_ALERT_RECEIVED) {
  254. int alert = gnutls_alert_get(session);
  255. strerr = gnutls_alert_get_name(alert);
  256. }
  257. if(!strerr)
  258. strerr = gnutls_strerror(rc);
  259. failf(data, "gnutls_handshake() failed: %s", strerr);
  260. return CURLE_SSL_CONNECT_ERROR;
  261. }
  262. /* Reset our connect state machine */
  263. connssl->connecting_state = ssl_connect_1;
  264. return CURLE_OK;
  265. }
  266. }
  267. static gnutls_x509_crt_fmt_t do_file_type(const char *type)
  268. {
  269. if(!type || !type[0])
  270. return GNUTLS_X509_FMT_PEM;
  271. if(strcasecompare(type, "PEM"))
  272. return GNUTLS_X509_FMT_PEM;
  273. if(strcasecompare(type, "DER"))
  274. return GNUTLS_X509_FMT_DER;
  275. return GNUTLS_X509_FMT_PEM; /* default to PEM */
  276. }
  277. #define GNUTLS_CIPHERS "NORMAL:-ARCFOUR-128:-CTYPE-ALL:+CTYPE-X509"
  278. /* If GnuTLS was compiled without support for SRP it will error out if SRP is
  279. requested in the priority string, so treat it specially
  280. */
  281. #define GNUTLS_SRP "+SRP"
  282. static CURLcode
  283. set_ssl_version_min_max(struct Curl_easy *data,
  284. struct ssl_primary_config *conn_config,
  285. const char **prioritylist,
  286. const char *tls13support)
  287. {
  288. long ssl_version = conn_config->version;
  289. long ssl_version_max = conn_config->version_max;
  290. if((ssl_version == CURL_SSLVERSION_DEFAULT) ||
  291. (ssl_version == CURL_SSLVERSION_TLSv1))
  292. ssl_version = CURL_SSLVERSION_TLSv1_0;
  293. if(ssl_version_max == CURL_SSLVERSION_MAX_NONE)
  294. ssl_version_max = CURL_SSLVERSION_MAX_DEFAULT;
  295. if(!tls13support) {
  296. /* If the running GnuTLS doesn't support TLS 1.3, we must not specify a
  297. prioritylist involving that since it will make GnuTLS return an en
  298. error back at us */
  299. if((ssl_version_max == CURL_SSLVERSION_MAX_TLSv1_3) ||
  300. (ssl_version_max == CURL_SSLVERSION_MAX_DEFAULT)) {
  301. ssl_version_max = CURL_SSLVERSION_MAX_TLSv1_2;
  302. }
  303. }
  304. else if(ssl_version_max == CURL_SSLVERSION_MAX_DEFAULT) {
  305. ssl_version_max = CURL_SSLVERSION_MAX_TLSv1_3;
  306. }
  307. switch(ssl_version | ssl_version_max) {
  308. case CURL_SSLVERSION_TLSv1_0 | CURL_SSLVERSION_MAX_TLSv1_0:
  309. *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:"
  310. "+VERS-TLS1.0";
  311. return CURLE_OK;
  312. case CURL_SSLVERSION_TLSv1_0 | CURL_SSLVERSION_MAX_TLSv1_1:
  313. *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:"
  314. "+VERS-TLS1.1:+VERS-TLS1.0";
  315. return CURLE_OK;
  316. case CURL_SSLVERSION_TLSv1_0 | CURL_SSLVERSION_MAX_TLSv1_2:
  317. *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:"
  318. "+VERS-TLS1.2:+VERS-TLS1.1:+VERS-TLS1.0";
  319. return CURLE_OK;
  320. case CURL_SSLVERSION_TLSv1_1 | CURL_SSLVERSION_MAX_TLSv1_1:
  321. *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:"
  322. "+VERS-TLS1.1";
  323. return CURLE_OK;
  324. case CURL_SSLVERSION_TLSv1_1 | CURL_SSLVERSION_MAX_TLSv1_2:
  325. *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:"
  326. "+VERS-TLS1.2:+VERS-TLS1.1";
  327. return CURLE_OK;
  328. case CURL_SSLVERSION_TLSv1_2 | CURL_SSLVERSION_MAX_TLSv1_2:
  329. *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:"
  330. "+VERS-TLS1.2";
  331. return CURLE_OK;
  332. case CURL_SSLVERSION_TLSv1_3 | CURL_SSLVERSION_MAX_TLSv1_3:
  333. *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:"
  334. "+VERS-TLS1.3";
  335. return CURLE_OK;
  336. case CURL_SSLVERSION_TLSv1_0 | CURL_SSLVERSION_MAX_TLSv1_3:
  337. *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0";
  338. return CURLE_OK;
  339. case CURL_SSLVERSION_TLSv1_1 | CURL_SSLVERSION_MAX_TLSv1_3:
  340. *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:"
  341. "+VERS-TLS1.3:+VERS-TLS1.2:+VERS-TLS1.1";
  342. return CURLE_OK;
  343. case CURL_SSLVERSION_TLSv1_2 | CURL_SSLVERSION_MAX_TLSv1_3:
  344. *prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:"
  345. "+VERS-TLS1.3:+VERS-TLS1.2";
  346. return CURLE_OK;
  347. }
  348. failf(data, "GnuTLS: cannot set ssl protocol");
  349. return CURLE_SSL_CONNECT_ERROR;
  350. }
  351. CURLcode gtls_client_init(struct Curl_easy *data,
  352. struct ssl_primary_config *config,
  353. struct ssl_config_data *ssl_config,
  354. const char *hostname,
  355. struct gtls_instance *gtls,
  356. long *pverifyresult)
  357. {
  358. unsigned int init_flags;
  359. int rc;
  360. bool sni = TRUE; /* default is SNI enabled */
  361. #ifdef ENABLE_IPV6
  362. struct in6_addr addr;
  363. #else
  364. struct in_addr addr;
  365. #endif
  366. const char *prioritylist;
  367. const char *err = NULL;
  368. const char *tls13support;
  369. CURLcode result;
  370. if(!gtls_inited)
  371. gtls_init();
  372. *pverifyresult = 0;
  373. if(config->version == CURL_SSLVERSION_SSLv2) {
  374. failf(data, "GnuTLS does not support SSLv2");
  375. return CURLE_SSL_CONNECT_ERROR;
  376. }
  377. else if(config->version == CURL_SSLVERSION_SSLv3)
  378. sni = FALSE; /* SSLv3 has no SNI */
  379. /* allocate a cred struct */
  380. rc = gnutls_certificate_allocate_credentials(&gtls->cred);
  381. if(rc != GNUTLS_E_SUCCESS) {
  382. failf(data, "gnutls_cert_all_cred() failed: %s", gnutls_strerror(rc));
  383. return CURLE_SSL_CONNECT_ERROR;
  384. }
  385. #ifdef USE_GNUTLS_SRP
  386. if(config->username && Curl_auth_allowed_to_host(data)) {
  387. infof(data, "Using TLS-SRP username: %s", config->username);
  388. rc = gnutls_srp_allocate_client_credentials(&gtls->srp_client_cred);
  389. if(rc != GNUTLS_E_SUCCESS) {
  390. failf(data, "gnutls_srp_allocate_client_cred() failed: %s",
  391. gnutls_strerror(rc));
  392. return CURLE_OUT_OF_MEMORY;
  393. }
  394. rc = gnutls_srp_set_client_credentials(gtls->srp_client_cred,
  395. config->username,
  396. config->password);
  397. if(rc != GNUTLS_E_SUCCESS) {
  398. failf(data, "gnutls_srp_set_client_cred() failed: %s",
  399. gnutls_strerror(rc));
  400. return CURLE_BAD_FUNCTION_ARGUMENT;
  401. }
  402. }
  403. #endif
  404. if(config->CAfile) {
  405. /* set the trusted CA cert bundle file */
  406. gnutls_certificate_set_verify_flags(gtls->cred,
  407. GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT);
  408. rc = gnutls_certificate_set_x509_trust_file(gtls->cred,
  409. config->CAfile,
  410. GNUTLS_X509_FMT_PEM);
  411. if(rc < 0) {
  412. infof(data, "error reading ca cert file %s (%s)",
  413. config->CAfile, gnutls_strerror(rc));
  414. if(config->verifypeer) {
  415. *pverifyresult = rc;
  416. return CURLE_SSL_CACERT_BADFILE;
  417. }
  418. }
  419. else
  420. infof(data, "found %d certificates in %s", rc, config->CAfile);
  421. }
  422. if(config->CApath) {
  423. /* set the trusted CA cert directory */
  424. rc = gnutls_certificate_set_x509_trust_dir(gtls->cred,
  425. config->CApath,
  426. GNUTLS_X509_FMT_PEM);
  427. if(rc < 0) {
  428. infof(data, "error reading ca cert file %s (%s)",
  429. config->CApath, gnutls_strerror(rc));
  430. if(config->verifypeer) {
  431. *pverifyresult = rc;
  432. return CURLE_SSL_CACERT_BADFILE;
  433. }
  434. }
  435. else
  436. infof(data, "found %d certificates in %s", rc, config->CApath);
  437. }
  438. #ifdef CURL_CA_FALLBACK
  439. /* use system ca certificate store as fallback */
  440. if(config->verifypeer && !(config->CAfile || config->CApath)) {
  441. /* this ignores errors on purpose */
  442. gnutls_certificate_set_x509_system_trust(gtls->cred);
  443. }
  444. #endif
  445. if(config->CRLfile) {
  446. /* set the CRL list file */
  447. rc = gnutls_certificate_set_x509_crl_file(gtls->cred,
  448. config->CRLfile,
  449. GNUTLS_X509_FMT_PEM);
  450. if(rc < 0) {
  451. failf(data, "error reading crl file %s (%s)",
  452. config->CRLfile, gnutls_strerror(rc));
  453. return CURLE_SSL_CRL_BADFILE;
  454. }
  455. else
  456. infof(data, "found %d CRL in %s", rc, config->CRLfile);
  457. }
  458. /* Initialize TLS session as a client */
  459. init_flags = GNUTLS_CLIENT;
  460. #if defined(GNUTLS_FORCE_CLIENT_CERT)
  461. init_flags |= GNUTLS_FORCE_CLIENT_CERT;
  462. #endif
  463. #if defined(GNUTLS_NO_TICKETS)
  464. /* Disable TLS session tickets */
  465. init_flags |= GNUTLS_NO_TICKETS;
  466. #endif
  467. rc = gnutls_init(&gtls->session, init_flags);
  468. if(rc != GNUTLS_E_SUCCESS) {
  469. failf(data, "gnutls_init() failed: %d", rc);
  470. return CURLE_SSL_CONNECT_ERROR;
  471. }
  472. if((0 == Curl_inet_pton(AF_INET, hostname, &addr)) &&
  473. #ifdef ENABLE_IPV6
  474. (0 == Curl_inet_pton(AF_INET6, hostname, &addr)) &&
  475. #endif
  476. sni) {
  477. size_t snilen;
  478. char *snihost = Curl_ssl_snihost(data, hostname, &snilen);
  479. if(!snihost || gnutls_server_name_set(gtls->session, GNUTLS_NAME_DNS,
  480. snihost, snilen) < 0) {
  481. failf(data, "Failed to set SNI");
  482. return CURLE_SSL_CONNECT_ERROR;
  483. }
  484. }
  485. /* Use default priorities */
  486. rc = gnutls_set_default_priority(gtls->session);
  487. if(rc != GNUTLS_E_SUCCESS)
  488. return CURLE_SSL_CONNECT_ERROR;
  489. /* "In GnuTLS 3.6.5, TLS 1.3 is enabled by default" */
  490. tls13support = gnutls_check_version("3.6.5");
  491. /* Ensure +SRP comes at the *end* of all relevant strings so that it can be
  492. * removed if a run-time error indicates that SRP is not supported by this
  493. * GnuTLS version */
  494. if(config->version == CURL_SSLVERSION_SSLv2 ||
  495. config->version == CURL_SSLVERSION_SSLv3) {
  496. failf(data, "GnuTLS does not support SSLv2 or SSLv3");
  497. return CURLE_SSL_CONNECT_ERROR;
  498. }
  499. if(config->version == CURL_SSLVERSION_TLSv1_3) {
  500. if(!tls13support) {
  501. failf(data, "This GnuTLS installation does not support TLS 1.3");
  502. return CURLE_SSL_CONNECT_ERROR;
  503. }
  504. }
  505. /* At this point we know we have a supported TLS version, so set it */
  506. result = set_ssl_version_min_max(data, config, &prioritylist, tls13support);
  507. if(result)
  508. return result;
  509. #ifdef USE_GNUTLS_SRP
  510. /* Only add SRP to the cipher list if SRP is requested. Otherwise
  511. * GnuTLS will disable TLS 1.3 support. */
  512. if(config->username) {
  513. size_t len = strlen(prioritylist);
  514. char *prioritysrp = malloc(len + sizeof(GNUTLS_SRP) + 1);
  515. if(!prioritysrp)
  516. return CURLE_OUT_OF_MEMORY;
  517. strcpy(prioritysrp, prioritylist);
  518. strcpy(prioritysrp + len, ":" GNUTLS_SRP);
  519. rc = gnutls_priority_set_direct(gtls->session, prioritysrp, &err);
  520. free(prioritysrp);
  521. if((rc == GNUTLS_E_INVALID_REQUEST) && err) {
  522. infof(data, "This GnuTLS does not support SRP");
  523. }
  524. }
  525. else {
  526. #endif
  527. infof(data, "GnuTLS ciphers: %s", prioritylist);
  528. rc = gnutls_priority_set_direct(gtls->session, prioritylist, &err);
  529. #ifdef USE_GNUTLS_SRP
  530. }
  531. #endif
  532. if(rc != GNUTLS_E_SUCCESS) {
  533. failf(data, "Error %d setting GnuTLS cipher list starting with %s",
  534. rc, err);
  535. return CURLE_SSL_CONNECT_ERROR;
  536. }
  537. if(config->clientcert) {
  538. if(ssl_config->key_passwd) {
  539. const unsigned int supported_key_encryption_algorithms =
  540. GNUTLS_PKCS_USE_PKCS12_3DES | GNUTLS_PKCS_USE_PKCS12_ARCFOUR |
  541. GNUTLS_PKCS_USE_PKCS12_RC2_40 | GNUTLS_PKCS_USE_PBES2_3DES |
  542. GNUTLS_PKCS_USE_PBES2_AES_128 | GNUTLS_PKCS_USE_PBES2_AES_192 |
  543. GNUTLS_PKCS_USE_PBES2_AES_256;
  544. rc = gnutls_certificate_set_x509_key_file2(
  545. gtls->cred,
  546. config->clientcert,
  547. ssl_config->key ? ssl_config->key : config->clientcert,
  548. do_file_type(ssl_config->cert_type),
  549. ssl_config->key_passwd,
  550. supported_key_encryption_algorithms);
  551. if(rc != GNUTLS_E_SUCCESS) {
  552. failf(data,
  553. "error reading X.509 potentially-encrypted key file: %s",
  554. gnutls_strerror(rc));
  555. return CURLE_SSL_CONNECT_ERROR;
  556. }
  557. }
  558. else {
  559. if(gnutls_certificate_set_x509_key_file(
  560. gtls->cred,
  561. config->clientcert,
  562. ssl_config->key ? ssl_config->key : config->clientcert,
  563. do_file_type(ssl_config->cert_type) ) !=
  564. GNUTLS_E_SUCCESS) {
  565. failf(data, "error reading X.509 key or certificate file");
  566. return CURLE_SSL_CONNECT_ERROR;
  567. }
  568. }
  569. }
  570. #ifdef USE_GNUTLS_SRP
  571. /* put the credentials to the current session */
  572. if(config->username) {
  573. rc = gnutls_credentials_set(gtls->session, GNUTLS_CRD_SRP,
  574. gtls->srp_client_cred);
  575. if(rc != GNUTLS_E_SUCCESS) {
  576. failf(data, "gnutls_credentials_set() failed: %s", gnutls_strerror(rc));
  577. return CURLE_SSL_CONNECT_ERROR;
  578. }
  579. }
  580. else
  581. #endif
  582. {
  583. rc = gnutls_credentials_set(gtls->session, GNUTLS_CRD_CERTIFICATE,
  584. gtls->cred);
  585. if(rc != GNUTLS_E_SUCCESS) {
  586. failf(data, "gnutls_credentials_set() failed: %s", gnutls_strerror(rc));
  587. return CURLE_SSL_CONNECT_ERROR;
  588. }
  589. }
  590. if(config->verifystatus) {
  591. rc = gnutls_ocsp_status_request_enable_client(gtls->session,
  592. NULL, 0, NULL);
  593. if(rc != GNUTLS_E_SUCCESS) {
  594. failf(data, "gnutls_ocsp_status_request_enable_client() failed: %d", rc);
  595. return CURLE_SSL_CONNECT_ERROR;
  596. }
  597. }
  598. return CURLE_OK;
  599. }
  600. static CURLcode
  601. gtls_connect_step1(struct Curl_cfilter *cf, struct Curl_easy *data)
  602. {
  603. struct ssl_connect_data *connssl = cf->ctx;
  604. struct ssl_backend_data *backend = connssl->backend;
  605. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  606. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  607. long * const pverifyresult = &ssl_config->certverifyresult;
  608. CURLcode result;
  609. DEBUGASSERT(backend);
  610. if(connssl->state == ssl_connection_complete)
  611. /* to make us tolerant against being called more than once for the
  612. same connection */
  613. return CURLE_OK;
  614. result = gtls_client_init(data, conn_config, ssl_config,
  615. connssl->hostname,
  616. &backend->gtls, pverifyresult);
  617. if(result)
  618. return result;
  619. if(connssl->alpn) {
  620. struct alpn_proto_buf proto;
  621. gnutls_datum_t alpn[ALPN_ENTRIES_MAX];
  622. size_t i;
  623. for(i = 0; i < connssl->alpn->count; ++i) {
  624. alpn[i].data = (unsigned char *)connssl->alpn->entries[i];
  625. alpn[i].size = (unsigned)strlen(connssl->alpn->entries[i]);
  626. }
  627. if(gnutls_alpn_set_protocols(backend->gtls.session, alpn,
  628. (unsigned)connssl->alpn->count, 0)) {
  629. failf(data, "failed setting ALPN");
  630. return CURLE_SSL_CONNECT_ERROR;
  631. }
  632. Curl_alpn_to_proto_str(&proto, connssl->alpn);
  633. infof(data, VTLS_INFOF_ALPN_OFFER_1STR, proto.data);
  634. }
  635. /* This might be a reconnect, so we check for a session ID in the cache
  636. to speed up things */
  637. if(conn_config->sessionid) {
  638. void *ssl_sessionid;
  639. size_t ssl_idsize;
  640. Curl_ssl_sessionid_lock(data);
  641. if(!Curl_ssl_getsessionid(cf, data, &ssl_sessionid, &ssl_idsize)) {
  642. /* we got a session id, use it! */
  643. gnutls_session_set_data(backend->gtls.session,
  644. ssl_sessionid, ssl_idsize);
  645. /* Informational message */
  646. infof(data, "SSL re-using session ID");
  647. }
  648. Curl_ssl_sessionid_unlock(data);
  649. }
  650. /* register callback functions and handle to send and receive data. */
  651. gnutls_transport_set_ptr(backend->gtls.session, cf);
  652. gnutls_transport_set_push_function(backend->gtls.session, gtls_push);
  653. gnutls_transport_set_pull_function(backend->gtls.session, gtls_pull);
  654. return CURLE_OK;
  655. }
  656. static CURLcode pkp_pin_peer_pubkey(struct Curl_easy *data,
  657. gnutls_x509_crt_t cert,
  658. const char *pinnedpubkey)
  659. {
  660. /* Scratch */
  661. size_t len1 = 0, len2 = 0;
  662. unsigned char *buff1 = NULL;
  663. gnutls_pubkey_t key = NULL;
  664. /* Result is returned to caller */
  665. CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
  666. /* if a path wasn't specified, don't pin */
  667. if(!pinnedpubkey)
  668. return CURLE_OK;
  669. if(!cert)
  670. return result;
  671. do {
  672. int ret;
  673. /* Begin Gyrations to get the public key */
  674. gnutls_pubkey_init(&key);
  675. ret = gnutls_pubkey_import_x509(key, cert, 0);
  676. if(ret < 0)
  677. break; /* failed */
  678. ret = gnutls_pubkey_export(key, GNUTLS_X509_FMT_DER, NULL, &len1);
  679. if(ret != GNUTLS_E_SHORT_MEMORY_BUFFER || len1 == 0)
  680. break; /* failed */
  681. buff1 = malloc(len1);
  682. if(!buff1)
  683. break; /* failed */
  684. len2 = len1;
  685. ret = gnutls_pubkey_export(key, GNUTLS_X509_FMT_DER, buff1, &len2);
  686. if(ret < 0 || len1 != len2)
  687. break; /* failed */
  688. /* End Gyrations */
  689. /* The one good exit point */
  690. result = Curl_pin_peer_pubkey(data, pinnedpubkey, buff1, len1);
  691. } while(0);
  692. if(key)
  693. gnutls_pubkey_deinit(key);
  694. Curl_safefree(buff1);
  695. return result;
  696. }
  697. CURLcode
  698. Curl_gtls_verifyserver(struct Curl_easy *data,
  699. gnutls_session_t session,
  700. struct ssl_primary_config *config,
  701. struct ssl_config_data *ssl_config,
  702. const char *hostname,
  703. const char *dispname,
  704. const char *pinned_key)
  705. {
  706. unsigned int cert_list_size;
  707. const gnutls_datum_t *chainp;
  708. unsigned int verify_status = 0;
  709. gnutls_x509_crt_t x509_cert, x509_issuer;
  710. gnutls_datum_t issuerp;
  711. gnutls_datum_t certfields;
  712. char certname[65] = ""; /* limited to 64 chars by ASN.1 */
  713. size_t size;
  714. time_t certclock;
  715. const char *ptr;
  716. int rc;
  717. CURLcode result = CURLE_OK;
  718. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  719. unsigned int algo;
  720. unsigned int bits;
  721. gnutls_protocol_t version = gnutls_protocol_get_version(session);
  722. #endif
  723. long * const certverifyresult = &ssl_config->certverifyresult;
  724. /* the name of the cipher suite used, e.g. ECDHE_RSA_AES_256_GCM_SHA384. */
  725. ptr = gnutls_cipher_suite_get_name(gnutls_kx_get(session),
  726. gnutls_cipher_get(session),
  727. gnutls_mac_get(session));
  728. infof(data, "SSL connection using %s / %s",
  729. gnutls_protocol_get_name(version), ptr);
  730. /* This function will return the peer's raw certificate (chain) as sent by
  731. the peer. These certificates are in raw format (DER encoded for
  732. X.509). In case of a X.509 then a certificate list may be present. The
  733. first certificate in the list is the peer's certificate, following the
  734. issuer's certificate, then the issuer's issuer etc. */
  735. chainp = gnutls_certificate_get_peers(session, &cert_list_size);
  736. if(!chainp) {
  737. if(config->verifypeer ||
  738. config->verifyhost ||
  739. config->issuercert) {
  740. #ifdef USE_GNUTLS_SRP
  741. if(ssl_config->primary.username && !config->verifypeer &&
  742. gnutls_cipher_get(session)) {
  743. /* no peer cert, but auth is ok if we have SRP user and cipher and no
  744. peer verify */
  745. }
  746. else {
  747. #endif
  748. failf(data, "failed to get server cert");
  749. *certverifyresult = GNUTLS_E_NO_CERTIFICATE_FOUND;
  750. return CURLE_PEER_FAILED_VERIFICATION;
  751. #ifdef USE_GNUTLS_SRP
  752. }
  753. #endif
  754. }
  755. infof(data, " common name: WARNING couldn't obtain");
  756. }
  757. if(data->set.ssl.certinfo && chainp) {
  758. unsigned int i;
  759. result = Curl_ssl_init_certinfo(data, cert_list_size);
  760. if(result)
  761. return result;
  762. for(i = 0; i < cert_list_size; i++) {
  763. const char *beg = (const char *) chainp[i].data;
  764. const char *end = beg + chainp[i].size;
  765. result = Curl_extract_certinfo(data, i, beg, end);
  766. if(result)
  767. return result;
  768. }
  769. }
  770. if(config->verifypeer) {
  771. /* This function will try to verify the peer's certificate and return its
  772. status (trusted, invalid etc.). The value of status should be one or
  773. more of the gnutls_certificate_status_t enumerated elements bitwise
  774. or'd. To avoid denial of service attacks some default upper limits
  775. regarding the certificate key size and chain size are set. To override
  776. them use gnutls_certificate_set_verify_limits(). */
  777. rc = gnutls_certificate_verify_peers2(session, &verify_status);
  778. if(rc < 0) {
  779. failf(data, "server cert verify failed: %d", rc);
  780. *certverifyresult = rc;
  781. return CURLE_SSL_CONNECT_ERROR;
  782. }
  783. *certverifyresult = verify_status;
  784. /* verify_status is a bitmask of gnutls_certificate_status bits */
  785. if(verify_status & GNUTLS_CERT_INVALID) {
  786. if(config->verifypeer) {
  787. failf(data, "server certificate verification failed. CAfile: %s "
  788. "CRLfile: %s", config->CAfile ? config->CAfile:
  789. "none",
  790. ssl_config->primary.CRLfile ?
  791. ssl_config->primary.CRLfile : "none");
  792. return CURLE_PEER_FAILED_VERIFICATION;
  793. }
  794. else
  795. infof(data, " server certificate verification FAILED");
  796. }
  797. else
  798. infof(data, " server certificate verification OK");
  799. }
  800. else
  801. infof(data, " server certificate verification SKIPPED");
  802. if(config->verifystatus) {
  803. if(gnutls_ocsp_status_request_is_checked(session, 0) == 0) {
  804. gnutls_datum_t status_request;
  805. gnutls_ocsp_resp_t ocsp_resp;
  806. gnutls_ocsp_cert_status_t status;
  807. gnutls_x509_crl_reason_t reason;
  808. rc = gnutls_ocsp_status_request_get(session, &status_request);
  809. infof(data, " server certificate status verification FAILED");
  810. if(rc == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) {
  811. failf(data, "No OCSP response received");
  812. return CURLE_SSL_INVALIDCERTSTATUS;
  813. }
  814. if(rc < 0) {
  815. failf(data, "Invalid OCSP response received");
  816. return CURLE_SSL_INVALIDCERTSTATUS;
  817. }
  818. gnutls_ocsp_resp_init(&ocsp_resp);
  819. rc = gnutls_ocsp_resp_import(ocsp_resp, &status_request);
  820. if(rc < 0) {
  821. failf(data, "Invalid OCSP response received");
  822. return CURLE_SSL_INVALIDCERTSTATUS;
  823. }
  824. (void)gnutls_ocsp_resp_get_single(ocsp_resp, 0, NULL, NULL, NULL, NULL,
  825. &status, NULL, NULL, NULL, &reason);
  826. switch(status) {
  827. case GNUTLS_OCSP_CERT_GOOD:
  828. break;
  829. case GNUTLS_OCSP_CERT_REVOKED: {
  830. const char *crl_reason;
  831. switch(reason) {
  832. default:
  833. case GNUTLS_X509_CRLREASON_UNSPECIFIED:
  834. crl_reason = "unspecified reason";
  835. break;
  836. case GNUTLS_X509_CRLREASON_KEYCOMPROMISE:
  837. crl_reason = "private key compromised";
  838. break;
  839. case GNUTLS_X509_CRLREASON_CACOMPROMISE:
  840. crl_reason = "CA compromised";
  841. break;
  842. case GNUTLS_X509_CRLREASON_AFFILIATIONCHANGED:
  843. crl_reason = "affiliation has changed";
  844. break;
  845. case GNUTLS_X509_CRLREASON_SUPERSEDED:
  846. crl_reason = "certificate superseded";
  847. break;
  848. case GNUTLS_X509_CRLREASON_CESSATIONOFOPERATION:
  849. crl_reason = "operation has ceased";
  850. break;
  851. case GNUTLS_X509_CRLREASON_CERTIFICATEHOLD:
  852. crl_reason = "certificate is on hold";
  853. break;
  854. case GNUTLS_X509_CRLREASON_REMOVEFROMCRL:
  855. crl_reason = "will be removed from delta CRL";
  856. break;
  857. case GNUTLS_X509_CRLREASON_PRIVILEGEWITHDRAWN:
  858. crl_reason = "privilege withdrawn";
  859. break;
  860. case GNUTLS_X509_CRLREASON_AACOMPROMISE:
  861. crl_reason = "AA compromised";
  862. break;
  863. }
  864. failf(data, "Server certificate was revoked: %s", crl_reason);
  865. break;
  866. }
  867. default:
  868. case GNUTLS_OCSP_CERT_UNKNOWN:
  869. failf(data, "Server certificate status is unknown");
  870. break;
  871. }
  872. gnutls_ocsp_resp_deinit(ocsp_resp);
  873. return CURLE_SSL_INVALIDCERTSTATUS;
  874. }
  875. else
  876. infof(data, " server certificate status verification OK");
  877. }
  878. else
  879. infof(data, " server certificate status verification SKIPPED");
  880. /* initialize an X.509 certificate structure. */
  881. gnutls_x509_crt_init(&x509_cert);
  882. if(chainp)
  883. /* convert the given DER or PEM encoded Certificate to the native
  884. gnutls_x509_crt_t format */
  885. gnutls_x509_crt_import(x509_cert, chainp, GNUTLS_X509_FMT_DER);
  886. if(config->issuercert) {
  887. gnutls_x509_crt_init(&x509_issuer);
  888. issuerp = load_file(config->issuercert);
  889. gnutls_x509_crt_import(x509_issuer, &issuerp, GNUTLS_X509_FMT_PEM);
  890. rc = gnutls_x509_crt_check_issuer(x509_cert, x509_issuer);
  891. gnutls_x509_crt_deinit(x509_issuer);
  892. unload_file(issuerp);
  893. if(rc <= 0) {
  894. failf(data, "server certificate issuer check failed (IssuerCert: %s)",
  895. config->issuercert?config->issuercert:"none");
  896. gnutls_x509_crt_deinit(x509_cert);
  897. return CURLE_SSL_ISSUER_ERROR;
  898. }
  899. infof(data, " server certificate issuer check OK (Issuer Cert: %s)",
  900. config->issuercert?config->issuercert:"none");
  901. }
  902. size = sizeof(certname);
  903. rc = gnutls_x509_crt_get_dn_by_oid(x509_cert, GNUTLS_OID_X520_COMMON_NAME,
  904. 0, /* the first and only one */
  905. FALSE,
  906. certname,
  907. &size);
  908. if(rc) {
  909. infof(data, "error fetching CN from cert:%s",
  910. gnutls_strerror(rc));
  911. }
  912. /* This function will check if the given certificate's subject matches the
  913. given hostname. This is a basic implementation of the matching described
  914. in RFC2818 (HTTPS), which takes into account wildcards, and the subject
  915. alternative name PKIX extension. Returns non zero on success, and zero on
  916. failure. */
  917. rc = gnutls_x509_crt_check_hostname(x509_cert, hostname);
  918. #if GNUTLS_VERSION_NUMBER < 0x030306
  919. /* Before 3.3.6, gnutls_x509_crt_check_hostname() didn't check IP
  920. addresses. */
  921. if(!rc) {
  922. #ifdef ENABLE_IPV6
  923. #define use_addr in6_addr
  924. #else
  925. #define use_addr in_addr
  926. #endif
  927. unsigned char addrbuf[sizeof(struct use_addr)];
  928. size_t addrlen = 0;
  929. if(Curl_inet_pton(AF_INET, hostname, addrbuf) > 0)
  930. addrlen = 4;
  931. #ifdef ENABLE_IPV6
  932. else if(Curl_inet_pton(AF_INET6, hostname, addrbuf) > 0)
  933. addrlen = 16;
  934. #endif
  935. if(addrlen) {
  936. unsigned char certaddr[sizeof(struct use_addr)];
  937. int i;
  938. for(i = 0; ; i++) {
  939. size_t certaddrlen = sizeof(certaddr);
  940. int ret = gnutls_x509_crt_get_subject_alt_name(x509_cert, i, certaddr,
  941. &certaddrlen, NULL);
  942. /* If this happens, it wasn't an IP address. */
  943. if(ret == GNUTLS_E_SHORT_MEMORY_BUFFER)
  944. continue;
  945. if(ret < 0)
  946. break;
  947. if(ret != GNUTLS_SAN_IPADDRESS)
  948. continue;
  949. if(certaddrlen == addrlen && !memcmp(addrbuf, certaddr, addrlen)) {
  950. rc = 1;
  951. break;
  952. }
  953. }
  954. }
  955. }
  956. #endif
  957. if(!rc) {
  958. if(config->verifyhost) {
  959. failf(data, "SSL: certificate subject name (%s) does not match "
  960. "target host name '%s'", certname, dispname);
  961. gnutls_x509_crt_deinit(x509_cert);
  962. return CURLE_PEER_FAILED_VERIFICATION;
  963. }
  964. else
  965. infof(data, " common name: %s (does not match '%s')",
  966. certname, dispname);
  967. }
  968. else
  969. infof(data, " common name: %s (matched)", certname);
  970. /* Check for time-based validity */
  971. certclock = gnutls_x509_crt_get_expiration_time(x509_cert);
  972. if(certclock == (time_t)-1) {
  973. if(config->verifypeer) {
  974. failf(data, "server cert expiration date verify failed");
  975. *certverifyresult = GNUTLS_CERT_EXPIRED;
  976. gnutls_x509_crt_deinit(x509_cert);
  977. return CURLE_SSL_CONNECT_ERROR;
  978. }
  979. else
  980. infof(data, " server certificate expiration date verify FAILED");
  981. }
  982. else {
  983. if(certclock < time(NULL)) {
  984. if(config->verifypeer) {
  985. failf(data, "server certificate expiration date has passed.");
  986. *certverifyresult = GNUTLS_CERT_EXPIRED;
  987. gnutls_x509_crt_deinit(x509_cert);
  988. return CURLE_PEER_FAILED_VERIFICATION;
  989. }
  990. else
  991. infof(data, " server certificate expiration date FAILED");
  992. }
  993. else
  994. infof(data, " server certificate expiration date OK");
  995. }
  996. certclock = gnutls_x509_crt_get_activation_time(x509_cert);
  997. if(certclock == (time_t)-1) {
  998. if(config->verifypeer) {
  999. failf(data, "server cert activation date verify failed");
  1000. *certverifyresult = GNUTLS_CERT_NOT_ACTIVATED;
  1001. gnutls_x509_crt_deinit(x509_cert);
  1002. return CURLE_SSL_CONNECT_ERROR;
  1003. }
  1004. else
  1005. infof(data, " server certificate activation date verify FAILED");
  1006. }
  1007. else {
  1008. if(certclock > time(NULL)) {
  1009. if(config->verifypeer) {
  1010. failf(data, "server certificate not activated yet.");
  1011. *certverifyresult = GNUTLS_CERT_NOT_ACTIVATED;
  1012. gnutls_x509_crt_deinit(x509_cert);
  1013. return CURLE_PEER_FAILED_VERIFICATION;
  1014. }
  1015. else
  1016. infof(data, " server certificate activation date FAILED");
  1017. }
  1018. else
  1019. infof(data, " server certificate activation date OK");
  1020. }
  1021. if(pinned_key) {
  1022. result = pkp_pin_peer_pubkey(data, x509_cert, pinned_key);
  1023. if(result != CURLE_OK) {
  1024. failf(data, "SSL: public key does not match pinned public key");
  1025. gnutls_x509_crt_deinit(x509_cert);
  1026. return result;
  1027. }
  1028. }
  1029. /* Show:
  1030. - subject
  1031. - start date
  1032. - expire date
  1033. - common name
  1034. - issuer
  1035. */
  1036. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  1037. /* public key algorithm's parameters */
  1038. algo = gnutls_x509_crt_get_pk_algorithm(x509_cert, &bits);
  1039. infof(data, " certificate public key: %s",
  1040. gnutls_pk_algorithm_get_name(algo));
  1041. /* version of the X.509 certificate. */
  1042. infof(data, " certificate version: #%d",
  1043. gnutls_x509_crt_get_version(x509_cert));
  1044. rc = gnutls_x509_crt_get_dn2(x509_cert, &certfields);
  1045. if(rc)
  1046. infof(data, "Failed to get certificate name");
  1047. else {
  1048. infof(data, " subject: %s", certfields.data);
  1049. certclock = gnutls_x509_crt_get_activation_time(x509_cert);
  1050. showtime(data, "start date", certclock);
  1051. certclock = gnutls_x509_crt_get_expiration_time(x509_cert);
  1052. showtime(data, "expire date", certclock);
  1053. gnutls_free(certfields.data);
  1054. }
  1055. rc = gnutls_x509_crt_get_issuer_dn2(x509_cert, &certfields);
  1056. if(rc)
  1057. infof(data, "Failed to get certificate issuer");
  1058. else {
  1059. infof(data, " issuer: %s", certfields.data);
  1060. gnutls_free(certfields.data);
  1061. }
  1062. #endif
  1063. gnutls_x509_crt_deinit(x509_cert);
  1064. return result;
  1065. }
  1066. static CURLcode gtls_verifyserver(struct Curl_cfilter *cf,
  1067. struct Curl_easy *data,
  1068. gnutls_session_t session)
  1069. {
  1070. struct ssl_connect_data *connssl = cf->ctx;
  1071. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  1072. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  1073. const char *pinned_key = Curl_ssl_cf_is_proxy(cf)?
  1074. data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY]:
  1075. data->set.str[STRING_SSL_PINNEDPUBLICKEY];
  1076. CURLcode result;
  1077. result = Curl_gtls_verifyserver(data, session, conn_config, ssl_config,
  1078. connssl->hostname, connssl->dispname,
  1079. pinned_key);
  1080. if(result)
  1081. goto out;
  1082. if(cf->conn->bits.tls_enable_alpn) {
  1083. gnutls_datum_t proto;
  1084. int rc;
  1085. rc = gnutls_alpn_get_selected_protocol(session, &proto);
  1086. if(rc == 0)
  1087. Curl_alpn_set_negotiated(cf, data, proto.data, proto.size);
  1088. else
  1089. Curl_alpn_set_negotiated(cf, data, NULL, 0);
  1090. }
  1091. if(ssl_config->primary.sessionid) {
  1092. /* we always unconditionally get the session id here, as even if we
  1093. already got it from the cache and asked to use it in the connection, it
  1094. might've been rejected and then a new one is in use now and we need to
  1095. detect that. */
  1096. void *connect_sessionid;
  1097. size_t connect_idsize = 0;
  1098. /* get the session ID data size */
  1099. gnutls_session_get_data(session, NULL, &connect_idsize);
  1100. connect_sessionid = malloc(connect_idsize); /* get a buffer for it */
  1101. if(connect_sessionid) {
  1102. bool incache;
  1103. bool added = FALSE;
  1104. void *ssl_sessionid;
  1105. /* extract session ID to the allocated buffer */
  1106. gnutls_session_get_data(session, connect_sessionid, &connect_idsize);
  1107. Curl_ssl_sessionid_lock(data);
  1108. incache = !(Curl_ssl_getsessionid(cf, data, &ssl_sessionid, NULL));
  1109. if(incache) {
  1110. /* there was one before in the cache, so instead of risking that the
  1111. previous one was rejected, we just kill that and store the new */
  1112. Curl_ssl_delsessionid(data, ssl_sessionid);
  1113. }
  1114. /* store this session id */
  1115. result = Curl_ssl_addsessionid(cf, data, connect_sessionid,
  1116. connect_idsize, &added);
  1117. Curl_ssl_sessionid_unlock(data);
  1118. if(!added)
  1119. free(connect_sessionid);
  1120. if(result) {
  1121. result = CURLE_OUT_OF_MEMORY;
  1122. }
  1123. }
  1124. else
  1125. result = CURLE_OUT_OF_MEMORY;
  1126. }
  1127. out:
  1128. return result;
  1129. }
  1130. /*
  1131. * This function is called after the TCP connect has completed. Setup the TLS
  1132. * layer and do all necessary magic.
  1133. */
  1134. /* We use connssl->connecting_state to keep track of the connection status;
  1135. there are three states: 'ssl_connect_1' (not started yet or complete),
  1136. 'ssl_connect_2_reading' (waiting for data from server), and
  1137. 'ssl_connect_2_writing' (waiting to be able to write).
  1138. */
  1139. static CURLcode
  1140. gtls_connect_common(struct Curl_cfilter *cf,
  1141. struct Curl_easy *data,
  1142. bool nonblocking,
  1143. bool *done)
  1144. {
  1145. struct ssl_connect_data *connssl = cf->ctx;
  1146. int rc;
  1147. CURLcode result = CURLE_OK;
  1148. /* Initiate the connection, if not already done */
  1149. if(ssl_connect_1 == connssl->connecting_state) {
  1150. rc = gtls_connect_step1(cf, data);
  1151. if(rc) {
  1152. result = rc;
  1153. goto out;
  1154. }
  1155. }
  1156. rc = handshake(cf, data, TRUE, nonblocking);
  1157. if(rc) {
  1158. /* handshake() sets its own error message with failf() */
  1159. result = rc;
  1160. goto out;
  1161. }
  1162. /* Finish connecting once the handshake is done */
  1163. if(ssl_connect_1 == connssl->connecting_state) {
  1164. struct ssl_backend_data *backend = connssl->backend;
  1165. gnutls_session_t session;
  1166. DEBUGASSERT(backend);
  1167. session = backend->gtls.session;
  1168. rc = gtls_verifyserver(cf, data, session);
  1169. if(rc) {
  1170. result = rc;
  1171. goto out;
  1172. }
  1173. connssl->state = ssl_connection_complete;
  1174. }
  1175. out:
  1176. *done = ssl_connect_1 == connssl->connecting_state;
  1177. return result;
  1178. }
  1179. static CURLcode gtls_connect_nonblocking(struct Curl_cfilter *cf,
  1180. struct Curl_easy *data,
  1181. bool *done)
  1182. {
  1183. return gtls_connect_common(cf, data, TRUE, done);
  1184. }
  1185. static CURLcode gtls_connect(struct Curl_cfilter *cf,
  1186. struct Curl_easy *data)
  1187. {
  1188. CURLcode result;
  1189. bool done = FALSE;
  1190. result = gtls_connect_common(cf, data, FALSE, &done);
  1191. if(result)
  1192. return result;
  1193. DEBUGASSERT(done);
  1194. return CURLE_OK;
  1195. }
  1196. static bool gtls_data_pending(struct Curl_cfilter *cf,
  1197. const struct Curl_easy *data)
  1198. {
  1199. struct ssl_connect_data *ctx = cf->ctx;
  1200. (void)data;
  1201. DEBUGASSERT(ctx && ctx->backend);
  1202. if(ctx->backend->gtls.session &&
  1203. 0 != gnutls_record_check_pending(ctx->backend->gtls.session))
  1204. return TRUE;
  1205. return FALSE;
  1206. }
  1207. static ssize_t gtls_send(struct Curl_cfilter *cf,
  1208. struct Curl_easy *data,
  1209. const void *mem,
  1210. size_t len,
  1211. CURLcode *curlcode)
  1212. {
  1213. struct ssl_connect_data *connssl = cf->ctx;
  1214. struct ssl_backend_data *backend = connssl->backend;
  1215. ssize_t rc;
  1216. (void)data;
  1217. DEBUGASSERT(backend);
  1218. rc = gnutls_record_send(backend->gtls.session, mem, len);
  1219. if(rc < 0) {
  1220. *curlcode = (rc == GNUTLS_E_AGAIN)
  1221. ? CURLE_AGAIN
  1222. : CURLE_SEND_ERROR;
  1223. rc = -1;
  1224. }
  1225. return rc;
  1226. }
  1227. static void gtls_close(struct Curl_cfilter *cf,
  1228. struct Curl_easy *data)
  1229. {
  1230. struct ssl_connect_data *connssl = cf->ctx;
  1231. struct ssl_backend_data *backend = connssl->backend;
  1232. (void) data;
  1233. DEBUGASSERT(backend);
  1234. if(backend->gtls.session) {
  1235. char buf[32];
  1236. /* Maybe the server has already sent a close notify alert.
  1237. Read it to avoid an RST on the TCP connection. */
  1238. (void)gnutls_record_recv(backend->gtls.session, buf, sizeof(buf));
  1239. gnutls_bye(backend->gtls.session, GNUTLS_SHUT_WR);
  1240. gnutls_deinit(backend->gtls.session);
  1241. backend->gtls.session = NULL;
  1242. }
  1243. if(backend->gtls.cred) {
  1244. gnutls_certificate_free_credentials(backend->gtls.cred);
  1245. backend->gtls.cred = NULL;
  1246. }
  1247. #ifdef USE_GNUTLS_SRP
  1248. if(backend->gtls.srp_client_cred) {
  1249. gnutls_srp_free_client_credentials(backend->gtls.srp_client_cred);
  1250. backend->gtls.srp_client_cred = NULL;
  1251. }
  1252. #endif
  1253. }
  1254. /*
  1255. * This function is called to shut down the SSL layer but keep the
  1256. * socket open (CCC - Clear Command Channel)
  1257. */
  1258. static int gtls_shutdown(struct Curl_cfilter *cf,
  1259. struct Curl_easy *data)
  1260. {
  1261. struct ssl_connect_data *connssl = cf->ctx;
  1262. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  1263. struct ssl_backend_data *backend = connssl->backend;
  1264. int retval = 0;
  1265. DEBUGASSERT(backend);
  1266. #ifndef CURL_DISABLE_FTP
  1267. /* This has only been tested on the proftpd server, and the mod_tls code
  1268. sends a close notify alert without waiting for a close notify alert in
  1269. response. Thus we wait for a close notify alert from the server, but
  1270. we do not send one. Let's hope other servers do the same... */
  1271. if(data->set.ftp_ccc == CURLFTPSSL_CCC_ACTIVE)
  1272. gnutls_bye(backend->gtls.session, GNUTLS_SHUT_WR);
  1273. #endif
  1274. if(backend->gtls.session) {
  1275. ssize_t result;
  1276. bool done = FALSE;
  1277. char buf[120];
  1278. while(!done) {
  1279. int what = SOCKET_READABLE(Curl_conn_cf_get_socket(cf, data),
  1280. SSL_SHUTDOWN_TIMEOUT);
  1281. if(what > 0) {
  1282. /* Something to read, let's do it and hope that it is the close
  1283. notify alert from the server */
  1284. result = gnutls_record_recv(backend->gtls.session,
  1285. buf, sizeof(buf));
  1286. switch(result) {
  1287. case 0:
  1288. /* This is the expected response. There was no data but only
  1289. the close notify alert */
  1290. done = TRUE;
  1291. break;
  1292. case GNUTLS_E_AGAIN:
  1293. case GNUTLS_E_INTERRUPTED:
  1294. infof(data, "GNUTLS_E_AGAIN || GNUTLS_E_INTERRUPTED");
  1295. break;
  1296. default:
  1297. retval = -1;
  1298. done = TRUE;
  1299. break;
  1300. }
  1301. }
  1302. else if(0 == what) {
  1303. /* timeout */
  1304. failf(data, "SSL shutdown timeout");
  1305. done = TRUE;
  1306. }
  1307. else {
  1308. /* anything that gets here is fatally bad */
  1309. failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
  1310. retval = -1;
  1311. done = TRUE;
  1312. }
  1313. }
  1314. gnutls_deinit(backend->gtls.session);
  1315. }
  1316. gnutls_certificate_free_credentials(backend->gtls.cred);
  1317. #ifdef USE_GNUTLS_SRP
  1318. if(ssl_config->primary.username)
  1319. gnutls_srp_free_client_credentials(backend->gtls.srp_client_cred);
  1320. #endif
  1321. backend->gtls.cred = NULL;
  1322. backend->gtls.session = NULL;
  1323. return retval;
  1324. }
  1325. static ssize_t gtls_recv(struct Curl_cfilter *cf,
  1326. struct Curl_easy *data,
  1327. char *buf,
  1328. size_t buffersize,
  1329. CURLcode *curlcode)
  1330. {
  1331. struct ssl_connect_data *connssl = cf->ctx;
  1332. struct ssl_backend_data *backend = connssl->backend;
  1333. ssize_t ret;
  1334. (void)data;
  1335. DEBUGASSERT(backend);
  1336. ret = gnutls_record_recv(backend->gtls.session, buf, buffersize);
  1337. if((ret == GNUTLS_E_AGAIN) || (ret == GNUTLS_E_INTERRUPTED)) {
  1338. *curlcode = CURLE_AGAIN;
  1339. ret = -1;
  1340. goto out;
  1341. }
  1342. if(ret == GNUTLS_E_REHANDSHAKE) {
  1343. /* BLOCKING call, this is bad but a work-around for now. Fixing this "the
  1344. proper way" takes a whole lot of work. */
  1345. CURLcode result = handshake(cf, data, FALSE, FALSE);
  1346. if(result)
  1347. /* handshake() writes error message on its own */
  1348. *curlcode = result;
  1349. else
  1350. *curlcode = CURLE_AGAIN; /* then return as if this was a wouldblock */
  1351. ret = -1;
  1352. goto out;
  1353. }
  1354. if(ret < 0) {
  1355. failf(data, "GnuTLS recv error (%d): %s",
  1356. (int)ret, gnutls_strerror((int)ret));
  1357. *curlcode = CURLE_RECV_ERROR;
  1358. ret = -1;
  1359. goto out;
  1360. }
  1361. out:
  1362. return ret;
  1363. }
  1364. static void gtls_session_free(void *ptr)
  1365. {
  1366. free(ptr);
  1367. }
  1368. static size_t gtls_version(char *buffer, size_t size)
  1369. {
  1370. return msnprintf(buffer, size, "GnuTLS/%s", gnutls_check_version(NULL));
  1371. }
  1372. /* data might be NULL! */
  1373. static CURLcode gtls_random(struct Curl_easy *data,
  1374. unsigned char *entropy, size_t length)
  1375. {
  1376. int rc;
  1377. (void)data;
  1378. rc = gnutls_rnd(GNUTLS_RND_RANDOM, entropy, length);
  1379. return rc?CURLE_FAILED_INIT:CURLE_OK;
  1380. }
  1381. static CURLcode gtls_sha256sum(const unsigned char *tmp, /* input */
  1382. size_t tmplen,
  1383. unsigned char *sha256sum, /* output */
  1384. size_t sha256len)
  1385. {
  1386. struct sha256_ctx SHA256pw;
  1387. sha256_init(&SHA256pw);
  1388. sha256_update(&SHA256pw, (unsigned int)tmplen, tmp);
  1389. sha256_digest(&SHA256pw, (unsigned int)sha256len, sha256sum);
  1390. return CURLE_OK;
  1391. }
  1392. static bool gtls_cert_status_request(void)
  1393. {
  1394. return TRUE;
  1395. }
  1396. static void *gtls_get_internals(struct ssl_connect_data *connssl,
  1397. CURLINFO info UNUSED_PARAM)
  1398. {
  1399. struct ssl_backend_data *backend = connssl->backend;
  1400. (void)info;
  1401. DEBUGASSERT(backend);
  1402. return backend->gtls.session;
  1403. }
  1404. const struct Curl_ssl Curl_ssl_gnutls = {
  1405. { CURLSSLBACKEND_GNUTLS, "gnutls" }, /* info */
  1406. SSLSUPP_CA_PATH |
  1407. SSLSUPP_CERTINFO |
  1408. SSLSUPP_PINNEDPUBKEY |
  1409. SSLSUPP_HTTPS_PROXY,
  1410. sizeof(struct ssl_backend_data),
  1411. gtls_init, /* init */
  1412. gtls_cleanup, /* cleanup */
  1413. gtls_version, /* version */
  1414. Curl_none_check_cxn, /* check_cxn */
  1415. gtls_shutdown, /* shutdown */
  1416. gtls_data_pending, /* data_pending */
  1417. gtls_random, /* random */
  1418. gtls_cert_status_request, /* cert_status_request */
  1419. gtls_connect, /* connect */
  1420. gtls_connect_nonblocking, /* connect_nonblocking */
  1421. Curl_ssl_get_select_socks, /* getsock */
  1422. gtls_get_internals, /* get_internals */
  1423. gtls_close, /* close_one */
  1424. Curl_none_close_all, /* close_all */
  1425. gtls_session_free, /* session_free */
  1426. Curl_none_set_engine, /* set_engine */
  1427. Curl_none_set_engine_default, /* set_engine_default */
  1428. Curl_none_engines_list, /* engines_list */
  1429. Curl_none_false_start, /* false_start */
  1430. gtls_sha256sum, /* sha256sum */
  1431. NULL, /* associate_connection */
  1432. NULL, /* disassociate_connection */
  1433. NULL, /* free_multi_ssl_backend_data */
  1434. gtls_recv, /* recv decrypted data */
  1435. gtls_send, /* send data to encrypt */
  1436. };
  1437. #endif /* USE_GNUTLS */