gtls.c 50 KB

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