gtls.c 51 KB

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